Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
package de.markusressel.mkdocseditor.feature.editor.ui

import de.markusressel.mkdocseditor.feature.history.domain.SeenChangesUseCase
import de.markusressel.mkdocseditor.feature.history.domain.changeLocation
import de.markusressel.mkdocsrestclient.history.DiffHunkModel
import de.markusressel.mkdocsrestclient.history.DocumentChangesModel
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.flow.transformWhile
import de.markusressel.mkdocseditor.feature.editor.domain.ChangeLocation
import de.markusressel.mkdocsrestclient.dashboard.PinScope
Expand Down Expand Up @@ -133,6 +138,7 @@ internal class CodeEditorViewModel @Inject constructor(
private val qrCodesSupport: QrCodesSupport,
private val pendingQrKey: PendingQrKey,
private val resolveQrCode: ResolveQrCodeUseCase,
private val seenChanges: SeenChangesUseCase,
savedStateHandle: SavedStateHandle,
clientInstanceId: ClientInstanceId,
moveItemUseCase: MoveItemUseCase,
Expand Down Expand Up @@ -501,6 +507,12 @@ internal class CodeEditorViewModel @Inject constructor(
launch {
when (event) {
is UiEvent.DismissDialog -> dismissCurrentDialog()
is UiEvent.ChangesSinceSeenClicked -> uiState.value.changesSinceSeen?.let { showDialog(DialogState.ChangesSinceSeen(it)) }
is UiEvent.ChangesSinceSeenDismissed -> _uiState.update { it.copy(changesSinceSeen = null) }
is UiEvent.ChangeHunkClicked -> {
dismissCurrentDialog()
jumpToChange(event.hunk.changeLocation())
}
is UiEvent.ItemActionClicked -> itemActions.onActionClicked(
event.item, event.action, openElsewhere = uiState.value.remotePeers.isNotEmpty(),
)
Expand Down Expand Up @@ -840,6 +852,32 @@ internal class CodeEditorViewModel @Inject constructor(
*/
fun setCurrentDocumentId(documentId: String?) {
session.setDocument(documentId)
if (documentId != null && seenChangesAsked != documentId) {
seenChangesAsked = documentId
launch {
// not inside update: it runs its block again when the state changed meanwhile, and each run marks seen
val changes = seenChanges.open(documentId)
_uiState.update { it.copy(changesSinceSeen = changes) }
seenChangesOpened = true
}
}
}

/** the document whose changes since the last visit were asked for, once per editor */
private var seenChangesAsked: String? = null

/** whether the changes since the last visit are known; marking the page seen before that would swallow them */
private var seenChangesOpened = false

/**
* The page as it is now counts as seen when the user closes it, see [SeenChangesUseCase.leave]. Not on ON_STOP: the
* screen gets one while it opens.
*/
private fun leavePage() {
if (!seenChangesOpened) return
val documentId = uiState.value.documentId ?: seenChangesAsked ?: return
// after the editor is closed: it is a short request, and without it the own edits come back as news
launch(NonCancellable) { seenChanges.leave(documentId) }
}

/**
Expand Down Expand Up @@ -979,6 +1017,7 @@ internal class CodeEditorViewModel @Inject constructor(
}

override fun onCleared() {
leavePage()
session.close()
super.onCleared()
}
Expand Down Expand Up @@ -1218,6 +1257,9 @@ internal class CodeEditorViewModel @Inject constructor(

/** whether the server has QR codes, see [QrCodesSupport] */
val qrCodesAvailable: Boolean = false,

/** what others changed since the user last looked at the page, null if nothing; see [SeenChangesUseCase] */
val changesSinceSeen: DocumentChangesModel? = null,
) {
val editorShown: Boolean
get() = editModeActive || editModeOpening || readOnlyEditorShown
Expand All @@ -1230,6 +1272,11 @@ internal class CodeEditorViewModel @Inject constructor(
sealed class UiEvent {
data object DismissDialog : UiEvent()

/** the banner about the changes since the last visit */
data object ChangesSinceSeenClicked : UiEvent()
data object ChangesSinceSeenDismissed : UiEvent()
data class ChangeHunkClicked(val hunk: DiffHunkModel) : UiEvent()

data class ItemActionClicked(val item: WikiItem, val action: ItemAction) : UiEvent()
data class ItemMovePreviewRequested(val parentId: String?, val name: String?) : UiEvent()
data object ItemMoveBackClicked : UiEvent()
Expand Down Expand Up @@ -1344,6 +1391,9 @@ internal class CodeEditorViewModel @Inject constructor(
/** the view settings of the editor, as a sheet below it */
data object ViewSettings : DialogState

/** what changed since the last visit, hunk by hunk */
data class ChangesSinceSeen(val changes: DocumentChangesModel) : DialogState

/**
* The QR codes of the page, and adding or removing them
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import de.markusressel.mkdocseditor.feature.editor.ui.compose.picker.ResourcePic
import androidx.compose.ui.res.stringResource
import de.markusressel.mkdocseditor.R
import de.markusressel.mkdocseditor.feature.qr.domain.QrLink
import de.markusressel.mkdocseditor.feature.history.ui.compose.ChangesSinceSeenSheet
import de.markusressel.mkdocseditor.feature.history.ui.compose.HistoryScreen
import de.markusressel.mkdocseditor.feature.qr.ui.compose.PageQrCodesDialog

Expand Down Expand Up @@ -191,6 +192,12 @@ internal data class CodeEditorScreen(
// in the content, which knows whether a split is open
is CodeEditorViewModel.DialogState.ViewSettings -> Unit

is CodeEditorViewModel.DialogState.ChangesSinceSeen -> ChangesSinceSeenSheet(
changes = dialogState.changes,
onHunkClicked = { viewModel.onUiEvent(CodeEditorViewModel.UiEvent.ChangeHunkClicked(it)) },
onDismiss = { viewModel.onUiEvent(CodeEditorViewModel.UiEvent.DismissDialog) },
)

is CodeEditorViewModel.DialogState.PageReferencesPanel -> if (tree != null && documentId != null) {
PageReferencesDialog(
tree = tree!!,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package de.markusressel.mkdocseditor.feature.editor.ui.compose

import de.markusressel.mkdocseditor.feature.history.ui.compose.ChangesSinceSeenBanner
import de.markusressel.mkdocseditor.feature.editor.domain.AuthorRuns
import de.markusressel.mkdocseditor.feature.editor.domain.visibleSourceLines
import androidx.compose.animation.AnimatedVisibility
Expand Down Expand Up @@ -228,6 +229,13 @@ internal fun CodeEditorScreenContent(
) {
Column(modifier = Modifier.fillMaxSize()) {
EditorBanners(uiState)
uiState.changesSinceSeen?.let { changes ->
ChangesSinceSeenBanner(
changes = changes,
onClick = { onUiEvent(CodeEditorViewModel.UiEvent.ChangesSinceSeenClicked) },
onDismiss = { onUiEvent(CodeEditorViewModel.UiEvent.ChangesSinceSeenDismissed) },
)
}

EditorPanes(
modifier = Modifier.weight(1f),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,23 @@ internal val HistoryAuthorModel.shownName: String
internal val HistoryEntryModel.people: List<HistoryAuthorModel>
get() = (listOf(author) + coAuthors).distinctBy { it.accountId.ifEmpty { it.email } }

/**
* The people of an entry, each with the agents they made the changes with: "Bob via Claude Code, Anna". An agent
* without its person among them, or from a backend that only sends token names, goes with the author.
*
* @return each person with the names of their agents
*/
internal val HistoryEntryModel.peopleWithAgents: List<Pair<HistoryAuthorModel, List<String>>>
get() {
val people = people
val known = agents.filter { agent -> people.any { it.isAccount && it.accountId == agent.accountId } }
val homeless = agentNames - known.map { it.name }.toSet()
return people.mapIndexed { index, person ->
val own = known.filter { person.isAccount && it.accountId == person.accountId }.map { it.name }
person to (own + if (index == 0) homeless else emptyList()).distinct()
}
}

/**
* The names of the agents of an entry. A backend before `agents` only has the token names.
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package de.markusressel.mkdocseditor.feature.history.domain

import com.github.kittinunf.result.Result
import de.markusressel.mkdocseditor.auth.domain.AuthRepository
import de.markusressel.mkdocseditor.feature.auth.common.data.AuthBackends
import de.markusressel.mkdocsrestclient.IMkDocsRestClient
import de.markusressel.mkdocsrestclient.history.ChangeAuthorModel
import de.markusressel.mkdocsrestclient.history.DocumentChangesModel
import de.markusressel.mkdocsrestclient.reference.isUnsupportedEndpoint
import timber.log.Timber
import javax.inject.Inject

/**
* What changed in a page since the account last looked at it (`GET /document/{id}/changes/`), and marking it as seen.
* The server keeps the mark, so all devices and the web client agree. A server without it tells nothing.
*/
internal class SeenChangesUseCase @Inject constructor(
private val restClient: IMkDocsRestClient,
private val backends: AuthBackends,
private val authRepository: AuthRepository,
) {

/**
* The changes to tell about when the page opens. The page counts as seen as soon as they are shown, with the token
* of this answer, so an edit that arrives while reading stays news.
*
* @return the changes with only the authors that are news, null if there is nothing to tell: the page was never
* seen, nothing changed, only the account itself changed it, or the server can't say
*/
suspend fun open(documentId: String): DocumentChangesModel? {
val changes = changes(documentId) ?: return null
markSeen(documentId, changes.seenToken)
if (changes.since == null || changes.hunks.isEmpty()) return null
val own = ownUsername()
val others = changes.authors.filter { it.isNewsFor(own) }
return if (others.isEmpty()) null else changes.copy(authors = others)
}

/** The page as it is now counts as seen, when the account leaves it: its own edits are no news later. */
suspend fun leave(documentId: String) {
changes(documentId)?.let { markSeen(documentId, it.seenToken) }
}

private suspend fun changes(documentId: String): DocumentChangesModel? =
when (val result = restClient.getDocumentChanges(documentId)) {
is Result.Success -> result.value
is Result.Failure -> {
if (!result.error.isUnsupportedEndpoint()) Timber.w(result.error, "changes of %s", documentId)
null
}
}

/** a token the document lost in the meantime (409) needs no retry: the next visit asks again */
private suspend fun markSeen(documentId: String, seenToken: String) {
val result = restClient.putDocumentSeen(documentId, seenToken)
if (result is Result.Failure && !result.error.isUnsupportedEndpoint()) {
Timber.w(result.error, "seen of %s", documentId)
}
}

private suspend fun ownUsername(): String? = backends.selected()?.let { authRepository.session(it.id)?.username }
}

/** someone else changed the page, or an agent of the account itself did */
internal fun ChangeAuthorModel.isNewsFor(ownUsername: String?): Boolean =
agents.isNotEmpty() || ownUsername == null || username != ownUsername
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,13 @@ private const val MAX_TOKENS = 400

private val token = Regex("""\w+|\s+|[^\w\s]""")

/** Below this share of unchanged text, two lines are different lines and not one changed line */
private const val MIN_UNCHANGED_SHARE = 0.4

/**
* Which words of [old] were removed and which of [new] were added. Words, spaces and single signs count as units, so a
* change marks whole words.
* change marks whole words. Lines with little in common get no marks: the line color says enough, and marks on nearly
* every word only hide the few that stayed.
*/
internal fun wordChanges(old: String, new: String): WordChanges {
val a = token.findAll(old).toList()
Expand All @@ -42,7 +46,14 @@ internal fun wordChanges(old: String, new: String): WordChanges {
else -> removed += a[i++].range
}
}
return WordChanges(removed.merged(), added.merged())
val changes = WordChanges(removed.merged(), added.merged())
val unchanged = old.length - changes.removed.sumOf { it.end - it.start }
val longer = maxOf(old.length, new.length)
return if (longer > 0 && old.isNotEmpty() && new.isNotEmpty() && unchanged < MIN_UNCHANGED_SHARE * longer) {
WordChanges(emptyList(), emptyList())
} else {
changes
}
}

private fun whole(text: String) = if (text.isEmpty()) null else Highlight(0, text.length)
Expand Down
Loading
Loading