diff --git a/app/src/main/java/de/markusressel/mkdocseditor/feature/common/data/ServerFeatures.kt b/app/src/main/java/de/markusressel/mkdocseditor/feature/common/data/ServerFeatures.kt new file mode 100644 index 00000000..8a8bfb53 --- /dev/null +++ b/app/src/main/java/de/markusressel/mkdocseditor/feature/common/data/ServerFeatures.kt @@ -0,0 +1,35 @@ +package de.markusressel.mkdocseditor.feature.common.data + +import de.markusressel.mkdocseditor.auth.domain.AuthRepository +import de.markusressel.mkdocseditor.feature.auth.common.data.AuthBackends +import de.markusressel.mkdocseditor.feature.backendconfig.common.data.toBackendRef +import timber.log.Timber +import java.util.concurrent.ConcurrentHashMap +import javax.inject.Inject +import javax.inject.Singleton + +/** + * The optional API features of the selected server (`features` of `GET /server-info/`, see `ServerFeature`). The answer + * is kept for the app's lifetime, so a page opened offline still shows what the server had once it was reached. + */ +@Singleton +internal class ServerFeatures @Inject constructor( + private val backends: AuthBackends, + private val authRepository: AuthRepository, +) { + private val known = ConcurrentHashMap>() + + /** false while the server can't be asked and has not been before */ + suspend fun has(feature: String): Boolean = feature in features() + + private suspend fun features(): Set { + val backend = backends.selected()?.toBackendRef() ?: return emptySet() + known[backend.baseUrl]?.let { return it } + return try { + authRepository.serverInfo(backend).features.toSet().also { known[backend.baseUrl] = it } + } catch (e: Exception) { + Timber.w(e, "Could not read the server features") + emptySet() + } + } +} diff --git a/app/src/main/java/de/markusressel/mkdocseditor/feature/common/ui/compose/topbar/MkDocsEditorTopAppBar.kt b/app/src/main/java/de/markusressel/mkdocseditor/feature/common/ui/compose/topbar/MkDocsEditorTopAppBar.kt index 8dd50201..42a46fad 100644 --- a/app/src/main/java/de/markusressel/mkdocseditor/feature/common/ui/compose/topbar/MkDocsEditorTopAppBar.kt +++ b/app/src/main/java/de/markusressel/mkdocseditor/feature/common/ui/compose/topbar/MkDocsEditorTopAppBar.kt @@ -133,6 +133,7 @@ fun MkDocsEditorTopAppBar( is TopAppBarAction.CodeEditor.ShareLinkAction, is TopAppBarAction.CodeEditor.ShowInBrowserAction, is TopAppBarAction.CodeEditor.QrCodesAction, + is TopAppBarAction.CodeEditor.HistoryAction, is TopAppBarAction.CodeEditor.MenuDivider, is TopAppBarAction.CodeEditor.RenameAction, is TopAppBarAction.CodeEditor.MoveAction, diff --git a/app/src/main/java/de/markusressel/mkdocseditor/feature/common/ui/compose/topbar/TopAppBarAction.kt b/app/src/main/java/de/markusressel/mkdocseditor/feature/common/ui/compose/topbar/TopAppBarAction.kt index f711d61d..251dc595 100644 --- a/app/src/main/java/de/markusressel/mkdocseditor/feature/common/ui/compose/topbar/TopAppBarAction.kt +++ b/app/src/main/java/de/markusressel/mkdocseditor/feature/common/ui/compose/topbar/TopAppBarAction.kt @@ -26,6 +26,8 @@ sealed interface TopAppBarAction { data object PageReferencesAction : CodeEditor /** the QR code stickers of the page */ data object QrCodesAction : CodeEditor + /** the revision history of the page */ + data object HistoryAction : CodeEditor /** opens the sheet with the view settings of the editor */ data object ViewSettingsAction : CodeEditor data class ConnectionAction(val indicator: ConnectionIndicator) : CodeEditor diff --git a/app/src/main/java/de/markusressel/mkdocseditor/feature/editor/ui/CodeEditorViewModel.kt b/app/src/main/java/de/markusressel/mkdocseditor/feature/editor/ui/CodeEditorViewModel.kt index 80596034..de0dc786 100644 --- a/app/src/main/java/de/markusressel/mkdocseditor/feature/editor/ui/CodeEditorViewModel.kt +++ b/app/src/main/java/de/markusressel/mkdocseditor/feature/editor/ui/CodeEditorViewModel.kt @@ -1,5 +1,14 @@ package de.markusressel.mkdocseditor.feature.editor.ui +import de.markusressel.mkdocseditor.auth.api.ServerFeature +import de.markusressel.mkdocseditor.feature.common.data.ServerFeatures +import de.markusressel.mkdocseditor.feature.history.domain.LineAuthorUseCase +import de.markusressel.mkdocseditor.feature.history.domain.SeenChangesUseCase +import de.markusressel.mkdocseditor.feature.history.domain.changeLocation +import de.markusressel.mkdocsrestclient.history.BlameBlockModel +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 @@ -133,6 +142,9 @@ internal class CodeEditorViewModel @Inject constructor( private val qrCodesSupport: QrCodesSupport, private val pendingQrKey: PendingQrKey, private val resolveQrCode: ResolveQrCodeUseCase, + private val seenChanges: SeenChangesUseCase, + private val lineAuthor: LineAuthorUseCase, + private val serverFeatures: ServerFeatures, savedStateHandle: SavedStateHandle, clientInstanceId: ClientInstanceId, moveItemUseCase: MoveItemUseCase, @@ -312,6 +324,12 @@ internal class CodeEditorViewModel @Inject constructor( } launch { _uiState.update { it.copy(qrCodesAvailable = qrCodesSupport.isSupported()) } } + launch { + val history = serverFeatures.has(ServerFeature.HISTORY) + val revert = serverFeatures.has(ServerFeature.REVERT) + val blame = serverFeatures.has(ServerFeature.BLAME) + _uiState.update { it.copy(historyAvailable = history, revertAvailable = revert, blameAvailable = blame) } + } // a key of a sticker without a page, to put on this one launch { @@ -501,6 +519,17 @@ 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.AuthorLineClicked -> showLineAuthor(event.line) + is UiEvent.LineAuthorHistoryClicked -> { + dismissCurrentDialog() + openHistory() + } + is UiEvent.ChangeHunkClicked -> { + dismissCurrentDialog() + jumpToChange(event.hunk.changeLocation()) + } is UiEvent.ItemActionClicked -> itemActions.onActionClicked( event.item, event.action, openElsewhere = uiState.value.remotePeers.isNotEmpty(), ) @@ -662,6 +691,29 @@ internal class CodeEditorViewModel @Inject constructor( is TopAppBarAction.CodeEditor.ConnectionAction -> onConnectionIconClicked(action.indicator) is TopAppBarAction.CodeEditor.PageReferencesAction -> showPageReferences() is TopAppBarAction.CodeEditor.QrCodesAction -> showQrCodes() + is TopAppBarAction.CodeEditor.HistoryAction -> openHistory() + } + } + + private suspend fun openHistory() { + val documentId = uiState.value.documentId ?: return + _navigationEvents.send( + NavigationRequest.OpenHistory( + documentId = documentId, + canRestore = uiState.value.canEdit, + canRevert = uiState.value.canEdit && uiState.value.revertAvailable, + canRestoreSection = uiState.value.canEdit && uiState.value.blameAvailable, + ) + ) + } + + /** @param line 0-based */ + private suspend fun showLineAuthor(line: Int) { + val documentId = uiState.value.documentId ?: return + when (val answer = lineAuthor(documentId, line)) { + is LineAuthorUseCase.Answer.Found -> showDialog(DialogState.LineAuthor(answer.block)) + LineAuthorUseCase.Answer.Unknown -> showMessage(context.getString(R.string.line_author_none)) + is LineAuthorUseCase.Answer.Failed -> showMessage(context.getString(answer.message)) } } @@ -837,6 +889,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) } } /** @@ -976,6 +1054,7 @@ internal class CodeEditorViewModel @Inject constructor( } override fun onCleared() { + leavePage() session.close() super.onCleared() } @@ -1215,6 +1294,18 @@ internal class CodeEditorViewModel @Inject constructor( /** whether the server has QR codes, see [QrCodesSupport] */ val qrCodesAvailable: Boolean = false, + + /** whether the server has the revision history, see [ServerFeatures] */ + val historyAvailable: Boolean = false, + + /** whether the server can undo a single change of the history */ + val revertAvailable: Boolean = false, + + /** whether the server tells who last changed each line, and can restore a single section */ + val blameAvailable: 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 @@ -1227,6 +1318,15 @@ 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() + + /** a line of the author strip, 0-based */ + data class AuthorLineClicked(val line: Int) : UiEvent() + data object LineAuthorHistoryClicked : 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() @@ -1310,6 +1410,12 @@ internal class CodeEditorViewModel @Inject constructor( sealed interface NavigationRequest { data class Login(val backendId: Long) : NavigationRequest data class OpenDocument(val documentId: String) : NavigationRequest + data class OpenHistory( + val documentId: String, + val canRestore: Boolean, + val canRevert: Boolean, + val canRestoreSection: Boolean, + ) : NavigationRequest /** leave the editor, e.g. to show a folder in the file browser */ data object Close : NavigationRequest data class ShareLink(val link: String) : NavigationRequest { @@ -1340,6 +1446,12 @@ 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 + + /** who last changed a block of lines, and when */ + data class LineAuthor(val block: BlameBlockModel) : DialogState + /** * The QR codes of the page, and adding or removing them * diff --git a/app/src/main/java/de/markusressel/mkdocseditor/feature/editor/ui/compose/AuthorHighlights.kt b/app/src/main/java/de/markusressel/mkdocseditor/feature/editor/ui/compose/AuthorHighlights.kt index f083dc82..ac4afb01 100644 --- a/app/src/main/java/de/markusressel/mkdocseditor/feature/editor/ui/compose/AuthorHighlights.kt +++ b/app/src/main/java/de/markusressel/mkdocseditor/feature/editor/ui/compose/AuthorHighlights.kt @@ -48,15 +48,19 @@ internal fun authorColor(author: String, knownColors: Map): Col * * @param lines the shares of each line * @param widthPx the width of the strip + * @param onLineTapped gets the 0-based line; false places the cursor like any tap on the bar */ internal class AuthorStripColumn( private val lines: List>, private val widthPx: Int, private val colorOf: (String) -> Color, + private val onLineTapped: (Int) -> Boolean = { false }, ) : KodeEditorGutterColumn { override fun width(lineCount: Int) = widthPx + override fun onTap(line: Int): Boolean = onLineTapped(line) + override fun DrawScope.drawCell(cell: GutterCell) { var top = 0f lines.getOrNull(cell.line)?.forEach { share -> @@ -67,6 +71,14 @@ internal class AuthorStripColumn( } } +/** [column] as it is, with [onLineTapped] for taps on it */ +internal class TappableGutterColumn( + private val column: KodeEditorGutterColumn, + private val onLineTapped: (Int) -> Boolean, +) : KodeEditorGutterColumn by column { + override fun onTap(line: Int): Boolean = onLineTapped(line) +} + /** A light marker on the text of each author */ @Composable internal fun BoxScope.AuthorMarkers( diff --git a/app/src/main/java/de/markusressel/mkdocseditor/feature/editor/ui/compose/CodeEditorLayout.kt b/app/src/main/java/de/markusressel/mkdocseditor/feature/editor/ui/compose/CodeEditorLayout.kt index 52d539d1..1f05c049 100644 --- a/app/src/main/java/de/markusressel/mkdocseditor/feature/editor/ui/compose/CodeEditorLayout.kt +++ b/app/src/main/java/de/markusressel/mkdocseditor/feature/editor/ui/compose/CodeEditorLayout.kt @@ -98,6 +98,7 @@ internal fun CodeEditorLayout( restoreToCursor: Boolean = false, changeJump: CodeEditorViewModel.ChangeJump? = null, onChangeJumpShown: (CodeEditorViewModel.ChangeJump) -> Unit = {}, + onAuthorLineClicked: ((Int) -> Unit)? = null, ) { val viewState = rememberKodeEditorViewState() val currentOnVisibleRangeChanged by rememberUpdatedState(onVisibleRangeChanged) @@ -238,13 +239,19 @@ internal fun CodeEditorLayout( val colorOf: (String) -> Color = { authorColor(it, authorColors()) } val stripWidth = with(LocalDensity.current) { AUTHOR_STRIP_WIDTH.roundToPx() } val runs = authorRuns.value + val currentOnAuthorLineClicked by rememberUpdatedState(onAuthorLineClicked) + val onGutterTapped: (Int) -> Boolean = { line -> currentOnAuthorLineClicked?.let { it(line); true } ?: false } val authorStrip = if (settings.authorHighlight != AuthorHighlightMode.Off && runs.runs.isNotEmpty()) { remember(runs, stripWidth) { - AuthorStripColumn(lineShares(state.text, runs.runs), stripWidth, colorOf) + AuthorStripColumn(lineShares(state.text, runs.runs), stripWidth, colorOf, onGutterTapped) } } else { null } + // the strip is too narrow to hit, so the line numbers next to it tell who wrote a line as well + val numbers = lineNumbers.takeIf { settings.lineNumbers }?.let { numbers -> + if (authorStrip == null) numbers else remember(numbers) { TappableGutterColumn(numbers, onGutterTapped) } + } CompositionLocalProvider( LocalTextSelectionColors provides TextSelectionColors( @@ -275,7 +282,7 @@ internal fun CodeEditorLayout( enabled = true, readOnly = readOnly, lineWrapping = settings.lineWrapping, - gutterColumns = listOfNotNull(lineNumbers.takeIf { settings.lineNumbers }, authorStrip), + gutterColumns = listOfNotNull(numbers, authorStrip), overlay = { layout -> changeHighlight?.let { ChangeHighlight(layout, it, highlightColor, { changeHighlightAlpha.value }) } if (settings.authorHighlight == AuthorHighlightMode.StripAndMarker) { diff --git a/app/src/main/java/de/markusressel/mkdocseditor/feature/editor/ui/compose/CodeEditorScreen.kt b/app/src/main/java/de/markusressel/mkdocseditor/feature/editor/ui/compose/CodeEditorScreen.kt index 1ec75558..98141b63 100644 --- a/app/src/main/java/de/markusressel/mkdocseditor/feature/editor/ui/compose/CodeEditorScreen.kt +++ b/app/src/main/java/de/markusressel/mkdocseditor/feature/editor/ui/compose/CodeEditorScreen.kt @@ -31,6 +31,9 @@ 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.LineAuthorSheet +import de.markusressel.mkdocseditor.feature.history.ui.compose.HistoryScreen import de.markusressel.mkdocseditor.feature.qr.ui.compose.PageQrCodesDialog internal data class CodeEditorScreen( @@ -103,6 +106,16 @@ internal data class CodeEditorScreen( is CodeEditorViewModel.NavigationRequest.OpenDocument -> navigator.push(CodeEditorScreen(documentId = request.documentId)) + is CodeEditorViewModel.NavigationRequest.OpenHistory -> + navigator.push( + HistoryScreen( + documentId = request.documentId, + canRestore = request.canRestore, + canRevert = request.canRevert, + canRestoreSection = request.canRestoreSection, + ) + ) + is CodeEditorViewModel.NavigationRequest.Close -> navigator.pop() is CodeEditorViewModel.NavigationRequest.ShareLink -> { @@ -187,6 +200,19 @@ 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.LineAuthor -> LineAuthorSheet( + block = dialogState.block, + onOpenHistory = { viewModel.onUiEvent(CodeEditorViewModel.UiEvent.LineAuthorHistoryClicked) } + .takeIf { uiState.historyAvailable }, + onDismiss = { viewModel.onUiEvent(CodeEditorViewModel.UiEvent.DismissDialog) }, + ) + is CodeEditorViewModel.DialogState.PageReferencesPanel -> if (tree != null && documentId != null) { PageReferencesDialog( tree = tree!!, diff --git a/app/src/main/java/de/markusressel/mkdocseditor/feature/editor/ui/compose/CodeEditorScreenContent.kt b/app/src/main/java/de/markusressel/mkdocseditor/feature/editor/ui/compose/CodeEditorScreenContent.kt index 580620f1..6f9a1885 100644 --- a/app/src/main/java/de/markusressel/mkdocseditor/feature/editor/ui/compose/CodeEditorScreenContent.kt +++ b/app/src/main/java/de/markusressel/mkdocseditor/feature/editor/ui/compose/CodeEditorScreenContent.kt @@ -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 @@ -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), @@ -258,6 +266,8 @@ internal fun CodeEditorScreenContent( // the editor goes to a change while it is shown, else the page while reading changeJump = uiState.changeJump, onChangeJumpShown = { onUiEvent(CodeEditorViewModel.UiEvent.ChangeJumpShown(it)) }, + onAuthorLineClicked = { line: Int -> onUiEvent(CodeEditorViewModel.UiEvent.AuthorLineClicked(line)) } + .takeIf { uiState.blameAvailable && uiState.documentId != null }, ) }, preview = { @@ -399,6 +409,7 @@ internal fun editorTopBarActions( listOfNotNull( viewSettings.takeIf { !viewInBar }, TopAppBarAction.CodeEditor.PageReferencesAction.takeIf { !wide }, + TopAppBarAction.CodeEditor.HistoryAction.takeIf { uiState.historyAvailable }, TopAppBarAction.CodeEditor.MenuDivider, TopAppBarAction.CodeEditor.ShareLinkAction, TopAppBarAction.CodeEditor.ShowInBrowserAction, @@ -576,6 +587,7 @@ private fun menuText(entry: TopAppBarAction.CodeEditor): String? = when (entry) TopAppBarAction.CodeEditor.ShareLinkAction -> stringResource(R.string.share_document_link) TopAppBarAction.CodeEditor.ShowInBrowserAction -> stringResource(R.string.open_in_browser) TopAppBarAction.CodeEditor.QrCodesAction -> stringResource(R.string.qr_codes_action) + TopAppBarAction.CodeEditor.HistoryAction -> stringResource(R.string.history_action) TopAppBarAction.CodeEditor.RenameAction -> stringResource(R.string.item_action_rename) TopAppBarAction.CodeEditor.MoveAction -> stringResource(R.string.item_action_move) TopAppBarAction.CodeEditor.PinAction -> stringResource(R.string.item_action_pin) diff --git a/app/src/main/java/de/markusressel/mkdocseditor/feature/history/domain/HistoryText.kt b/app/src/main/java/de/markusressel/mkdocseditor/feature/history/domain/HistoryText.kt new file mode 100644 index 00000000..8d925541 --- /dev/null +++ b/app/src/main/java/de/markusressel/mkdocseditor/feature/history/domain/HistoryText.kt @@ -0,0 +1,69 @@ +package de.markusressel.mkdocseditor.feature.history.domain + +import de.markusressel.mkdocseditor.feature.editor.domain.ChangeLocation +import de.markusressel.mkdocseditor.feature.editor.domain.ChangedLines +import de.markusressel.mkdocsrestclient.history.DiffHunkModel +import de.markusressel.mkdocsrestclient.history.DiffOp +import de.markusressel.mkdocsrestclient.history.HistoryAuthorModel +import de.markusressel.mkdocsrestclient.history.HistoryEntryModel + +/** + * Where the editor goes for a hunk: its first changed lines, found again by heading and offset as for a change of the + * feed. A backend without the offset only gives the section. + */ +internal fun DiffHunkModel.changeLocation(): ChangeLocation { + val headings = listOfNotNull(heading) + val offset = offset ?: return ChangeLocation(headings) + var line = newStart + var index = 0 + while (index < lines.size && lines[index].op == DiffOp.CONTEXT) { + line++ + index++ + } + var count = 0 + while (index < lines.size && lines[index].op != DiffOp.CONTEXT) { + if (lines[index].op == DiffOp.ADDED) count++ + index++ + } + return ChangeLocation( + headings = headings, + ranges = listOf(ChangedLines(line, count, heading, headingOccurrence, offset + (line - newStart))), + ) +} + +/** The name to show for an author: the account's current name, else the one in the commit */ +internal val HistoryAuthorModel.shownName: String + get() = displayName?.takeIf { it.isNotBlank() } ?: username.takeIf { it.isNotBlank() } ?: name + +/** All people of an entry without repeats, the author first */ +internal val HistoryEntryModel.people: List + 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>> + 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. + */ +internal val HistoryEntryModel.agentNames: List + get() = agents.map { it.name }.ifEmpty { appTokens }.distinct() + +/** + * The message of a commit when it says more than the backend's standard "Update " + */ +internal val HistoryEntryModel.notableMessage: String? + get() = message.takeUnless { it.isBlank() || it == "Update $path" } diff --git a/app/src/main/java/de/markusressel/mkdocseditor/feature/history/domain/LineAuthorUseCase.kt b/app/src/main/java/de/markusressel/mkdocseditor/feature/history/domain/LineAuthorUseCase.kt new file mode 100644 index 00000000..4eb7b434 --- /dev/null +++ b/app/src/main/java/de/markusressel/mkdocseditor/feature/history/domain/LineAuthorUseCase.kt @@ -0,0 +1,40 @@ +package de.markusressel.mkdocseditor.feature.history.domain + +import androidx.annotation.StringRes +import com.github.kittinunf.result.Result +import de.markusressel.mkdocseditor.feature.common.ui.userMessage +import de.markusressel.mkdocsrestclient.IMkDocsRestClient +import de.markusressel.mkdocsrestclient.history.BlameBlockModel +import timber.log.Timber +import javax.inject.Inject + +/** + * Who last changed a line of a page and when, from the blame of the server (`GET /document/{id}/blame/`). It is asked + * for each time, because the page changes while it is open. + */ +internal class LineAuthorUseCase @Inject constructor( + private val restClient: IMkDocsRestClient, +) { + sealed interface Answer { + /** the lines around [line] that were changed together */ + data class Found(val block: BlameBlockModel) : Answer + + /** the line is newer than the text the server knows, or nobody known wrote it */ + data object Unknown : Answer + + data class Failed(@param:StringRes val message: Int) : Answer + } + + /** @param line 0-based, as in the editor */ + suspend operator fun invoke(documentId: String, line: Int): Answer = + when (val result = restClient.getDocumentBlame(documentId)) { + is Result.Success -> result.value.blockAt(line + 1) + ?.takeIf { it.author != null } + ?.let { Answer.Found(it) } + ?: Answer.Unknown + is Result.Failure -> { + Timber.w(result.error, "blame of %s", documentId) + Answer.Failed(result.error.userMessage()) + } + } +} diff --git a/app/src/main/java/de/markusressel/mkdocseditor/feature/history/domain/SeenChangesUseCase.kt b/app/src/main/java/de/markusressel/mkdocseditor/feature/history/domain/SeenChangesUseCase.kt new file mode 100644 index 00000000..684d4181 --- /dev/null +++ b/app/src/main/java/de/markusressel/mkdocseditor/feature/history/domain/SeenChangesUseCase.kt @@ -0,0 +1,71 @@ +package de.markusressel.mkdocseditor.feature.history.domain + +import com.github.kittinunf.result.Result +import de.markusressel.mkdocseditor.auth.api.ServerFeature +import de.markusressel.mkdocseditor.auth.domain.AuthRepository +import de.markusressel.mkdocseditor.feature.common.data.ServerFeatures +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 `changes` is not asked. + */ +internal class SeenChangesUseCase @Inject constructor( + private val restClient: IMkDocsRestClient, + private val backends: AuthBackends, + private val authRepository: AuthRepository, + private val features: ServerFeatures, +) { + + /** + * 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? { + if (!features.has(ServerFeature.CHANGES)) return null + 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) { + if (!features.has(ServerFeature.CHANGES)) return + 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 diff --git a/app/src/main/java/de/markusressel/mkdocseditor/feature/history/domain/WordDiff.kt b/app/src/main/java/de/markusressel/mkdocseditor/feature/history/domain/WordDiff.kt new file mode 100644 index 00000000..713a5f40 --- /dev/null +++ b/app/src/main/java/de/markusressel/mkdocseditor/feature/history/domain/WordDiff.kt @@ -0,0 +1,100 @@ +package de.markusressel.mkdocseditor.feature.history.domain + +import de.markusressel.mkdocsrestclient.history.DiffLineModel +import de.markusressel.mkdocsrestclient.history.DiffOp + +/** A changed part of a line, as character indices, end exclusive */ +internal data class Highlight(val start: Int, val end: Int) + +/** The changed words of a removed line and of the added line that replaced it */ +internal data class WordChanges(val removed: List, val added: List) + +/** Longer lines are marked as a whole: the comparison takes the product of both lengths */ +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. 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() + val b = token.findAll(new).toList() + if (a.size > MAX_TOKENS || b.size > MAX_TOKENS) { + return WordChanges(listOfNotNull(whole(old)), listOfNotNull(whole(new))) + } + // longest common subsequence of the tokens, from the end + val lcs = Array(a.size + 1) { IntArray(b.size + 1) } + for (i in a.indices.reversed()) { + for (j in b.indices.reversed()) { + lcs[i][j] = if (a[i].value == b[j].value) lcs[i + 1][j + 1] + 1 else maxOf(lcs[i + 1][j], lcs[i][j + 1]) + } + } + val removed = mutableListOf() + val added = mutableListOf() + var i = 0 + var j = 0 + while (i < a.size || j < b.size) { + when { + i < a.size && j < b.size && a[i].value == b[j].value -> { i++; j++ } + j < b.size && (i == a.size || lcs[i][j + 1] >= lcs[i + 1][j]) -> added += b[j++].range + else -> removed += a[i++].range + } + } + 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) + +/** neighbouring tokens become one highlight */ +private fun List.merged(): List { + val result = mutableListOf() + for (range in this) { + val last = result.lastOrNull() + if (last != null && last.end == range.first) { + result[result.size - 1] = last.copy(end = range.last + 1) + } else { + result += Highlight(range.first, range.last + 1) + } + } + return result +} + +/** + * Pairs each removed line with the added line that took its place, so their changed words can be marked. A block of + * removed lines followed by a block of added lines pairs up in order; lines left over have no partner. + * + * @return the index of the partner of each line in [lines], null without one + */ +internal fun pairChangedLines(lines: List): List { + val partner = arrayOfNulls(lines.size) + var index = 0 + while (index < lines.size) { + if (lines[index].op != DiffOp.REMOVED) { + index++ + continue + } + val removedStart = index + while (index < lines.size && lines[index].op == DiffOp.REMOVED) index++ + val addedStart = index + while (index < lines.size && lines[index].op == DiffOp.ADDED) index++ + val pairs = minOf(addedStart - removedStart, index - addedStart) + for (k in 0 until pairs) { + partner[removedStart + k] = addedStart + k + partner[addedStart + k] = removedStart + k + } + } + return partner.toList() +} diff --git a/app/src/main/java/de/markusressel/mkdocseditor/feature/history/ui/HistoryViewModel.kt b/app/src/main/java/de/markusressel/mkdocseditor/feature/history/ui/HistoryViewModel.kt new file mode 100644 index 00000000..18821ee3 --- /dev/null +++ b/app/src/main/java/de/markusressel/mkdocseditor/feature/history/ui/HistoryViewModel.kt @@ -0,0 +1,251 @@ +package de.markusressel.mkdocseditor.feature.history.ui + +import androidx.annotation.StringRes +import androidx.lifecycle.ViewModel +import com.github.kittinunf.result.Result +import dagger.hilt.android.lifecycle.HiltViewModel +import de.markusressel.mkdocseditor.R +import de.markusressel.mkdocseditor.extensions.common.android.launch +import de.markusressel.mkdocseditor.feature.common.ui.userMessage +import de.markusressel.mkdocseditor.feature.editor.domain.ChangeLocation +import de.markusressel.mkdocseditor.feature.history.domain.changeLocation +import de.markusressel.mkdocsrestclient.IMkDocsRestClient +import de.markusressel.mkdocsrestclient.history.DiffHunkModel +import de.markusressel.mkdocsrestclient.history.HistoryEntryModel +import de.markusressel.mkdocsrestclient.history.RevertErrorModel +import de.markusressel.mkdocsrestclient.history.SectionNotFoundModel +import de.markusressel.mkdocsrestclient.history.SectionRestoreErrorModel +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.receiveAsFlow +import kotlinx.coroutines.flow.update +import timber.log.Timber +import javax.inject.Inject + +/** + * The revision history of a document: who changed what and when, newest first. An entry opens to the diff of its + * commit, a hunk of it opens the editor there, and editors can bring back the text of an entry. + */ +@HiltViewModel +internal class HistoryViewModel @Inject constructor( + private val restClient: IMkDocsRestClient, +) : ViewModel() { + + private val _uiState = MutableStateFlow(UiState()) + internal val uiState = _uiState.asStateFlow() + + private val _events = Channel(Channel.BUFFERED) + internal val events = _events.receiveAsFlow() + + private var documentId: String? = null + + fun initialize(documentId: String, canRestore: Boolean, canRevert: Boolean = false, canRestoreSection: Boolean = false) { + if (this.documentId != null) return + this.documentId = documentId + _uiState.update { it.copy(canRestore = canRestore, canRevert = canRevert, canRestoreSection = canRestoreSection) } + launch { load() } + } + + fun onUiEvent(event: UiEvent) { + when (event) { + is UiEvent.RetryClicked -> launch { load() } + is UiEvent.EntryClicked -> onEntryClicked(event.revision) + is UiEvent.HunkClicked -> launch { _events.send(HistoryEvent.OpenInEditor(event.hunk.changeLocation())) } + is UiEvent.RestoreClicked -> _uiState.update { it.copy(confirm = Confirm.Restore(event.entry)) } + is UiEvent.UndoClicked -> _uiState.update { it.copy(confirm = Confirm.Undo(event.entry)) } + is UiEvent.RestoreSectionClicked -> event.hunk.heading?.let { heading -> + val section = Section(heading, event.hunk.headingOccurrence.coerceAtLeast(1)) + _uiState.update { it.copy(confirm = Confirm.RestoreSection(event.entry, section)) } + } + is UiEvent.ConfirmDismissed -> _uiState.update { it.copy(confirm = null) } + is UiEvent.Confirmed -> when (val confirm = uiState.value.confirm) { + is Confirm.Restore -> launch { restore(confirm.entry) } + is Confirm.Undo -> launch { undo(confirm.entry) } + is Confirm.RestoreSection -> launch { restoreSection(confirm.entry, confirm.section) } + null -> Unit + } + is UiEvent.BackClicked -> launch { _events.send(HistoryEvent.Close) } + } + } + + private suspend fun load() { + val documentId = documentId ?: return + _uiState.update { it.copy(loading = true, problem = null) } + when (val result = restClient.getDocumentHistory(documentId)) { + // diffs stay: a revision never changes, but a new entry moves the parent of none of the old ones + is Result.Success -> _uiState.update { it.copy(loading = false, entries = result.value) } + is Result.Failure -> { + Timber.w(result.error, "history of %s", documentId) + _uiState.update { it.copy(loading = false, problem = result.error.userMessage()) } + } + } + } + + private fun onEntryClicked(revision: String) { + if (uiState.value.expanded == revision) { + _uiState.update { it.copy(expanded = null) } + return + } + _uiState.update { it.copy(expanded = revision) } + if (uiState.value.diffs[revision] !is DiffState.Loaded) launch { loadDiff(revision) } + } + + /** the diff of a commit is the one from the entry below it, the commit before on this file */ + private suspend fun loadDiff(revision: String) { + val documentId = documentId ?: return + val entries = uiState.value.entries + val index = entries.indexOfFirst { it.revision == revision } + if (index < 0) return + val parent = entries.getOrNull(index + 1) + if (parent == null) { + setDiff(revision, DiffState.FirstVersion) + return + } + setDiff(revision, DiffState.Loading) + when (val result = restClient.getDocumentRevisionDiffHunks(documentId, from = parent.revision, to = revision)) { + is Result.Success -> setDiff(revision, DiffState.Loaded(result.value.hunks)) + is Result.Failure -> { + Timber.w(result.error, "diff of %s at %s", documentId, revision) + setDiff(revision, DiffState.Failed(result.error.userMessage())) + } + } + } + + private fun setDiff(revision: String, diff: DiffState) = _uiState.update { it.copy(diffs = it.diffs + (revision to diff)) } + + private suspend fun restore(entry: HistoryEntryModel) { + val documentId = documentId ?: return + _uiState.update { it.copy(confirm = null, working = true) } + val result = restClient.restoreDocumentRevision(documentId, entry.revision) + _uiState.update { it.copy(working = false) } + when (result) { + is Result.Success -> { + _events.send(HistoryEvent.Message(R.string.history_restored)) + load() + } + is Result.Failure -> { + Timber.w(result.error, "restore of %s to %s", documentId, entry.revision) + _events.send(HistoryEvent.Message(result.error.userMessage())) + } + } + } + + /** Sets one section of the page to its text in [entry]; the rest of the page stays */ + private suspend fun restoreSection(entry: HistoryEntryModel, section: Section) { + val documentId = documentId ?: return + _uiState.update { it.copy(confirm = null, working = true) } + val result = restClient.restoreDocumentSection(documentId, entry.revision, section.heading, section.occurrence) + _uiState.update { it.copy(working = false) } + when (result) { + is Result.Success -> { + _events.send(HistoryEvent.Message(R.string.history_section_restored)) + load() + } + is Result.Failure -> { + val error = SectionRestoreErrorModel.parse(result.error.response.data) + val message = if (error?.code == SectionRestoreErrorModel.SECTION_NOT_FOUND) { + HistoryEvent.SectionMissing(section.heading, inRevision = error.details?.missingIn == SectionNotFoundModel.REVISION) + } else { + Timber.w(result.error, "restore of a section of %s to %s", documentId, entry.revision) + HistoryEvent.Message(result.error.userMessage()) + } + _events.send(message) + } + } + } + + /** Undoes the changes of one entry; later changes stay. A conflict or a change that is gone changes nothing. */ + private suspend fun undo(entry: HistoryEntryModel) { + val documentId = documentId ?: return + _uiState.update { it.copy(confirm = null, working = true) } + val result = restClient.revertDocumentRevision(documentId, entry.revision) + _uiState.update { it.copy(working = false) } + when (result) { + is Result.Success -> { + _events.send(HistoryEvent.Message(R.string.history_undone)) + load() + } + is Result.Failure -> { + val error = RevertErrorModel.parse(result.error.response.data) + val message = when (error?.code) { + RevertErrorModel.CONFLICT -> HistoryEvent.UndoConflict(error.details?.headings.orEmpty()) + RevertErrorModel.NOTHING_TO_REVERT -> HistoryEvent.Message(R.string.history_undo_nothing) + else -> { + Timber.w(result.error, "revert of %s at %s", documentId, entry.revision) + HistoryEvent.Message(result.error.userMessage()) + } + } + _events.send(message) + } + } + } + + /** an action that waits for the user to confirm it */ + internal sealed interface Confirm { + val entry: HistoryEntryModel + + /** the text of the page becomes the one of [entry] */ + data class Restore(override val entry: HistoryEntryModel) : Confirm + + /** the changes of [entry] are taken back */ + data class Undo(override val entry: HistoryEntryModel) : Confirm + + /** one section of the page becomes the one of [entry] */ + data class RestoreSection(override val entry: HistoryEntryModel, val section: Section) : Confirm + } + + /** a section of the page: its heading, the [occurrence]th one with this text */ + internal data class Section(val heading: String, val occurrence: Int) + + internal sealed interface DiffState { + data object Loading : DiffState + data class Loaded(val hunks: List) : DiffState + data class Failed(@param:StringRes val message: Int) : DiffState + + /** the commit that added the file has nothing to compare with */ + data object FirstVersion : DiffState + } + + /** + * @param expanded the revision whose diff is shown + * @param diffs by revision + * @param confirm the action the user is asked to confirm + * @param working a restore or undo is on its way + */ + internal data class UiState( + val loading: Boolean = true, + val entries: List = emptyList(), + @param:StringRes val problem: Int? = null, + val expanded: String? = null, + val diffs: Map = emptyMap(), + val canRestore: Boolean = false, + val canRevert: Boolean = false, + val canRestoreSection: Boolean = false, + val confirm: Confirm? = null, + val working: Boolean = false, + ) + + internal sealed interface UiEvent { + data object RetryClicked : UiEvent + data class EntryClicked(val revision: String) : UiEvent + data class HunkClicked(val hunk: DiffHunkModel) : UiEvent + data class RestoreClicked(val entry: HistoryEntryModel) : UiEvent + data class UndoClicked(val entry: HistoryEntryModel) : UiEvent + data class RestoreSectionClicked(val entry: HistoryEntryModel, val hunk: DiffHunkModel) : UiEvent + data object ConfirmDismissed : UiEvent + data object Confirmed : UiEvent + data object BackClicked : UiEvent + } + + internal sealed interface HistoryEvent { + data class OpenInEditor(val change: ChangeLocation) : HistoryEvent + data class Message(@param:StringRes val text: Int) : HistoryEvent + + /** later changes in these sections are in the way, null for the part above the first heading */ + data class UndoConflict(val headings: List) : HistoryEvent + /** the section is not in the text of the entry, or with [inRevision] false, not in the page anymore */ + data class SectionMissing(val heading: String, val inRevision: Boolean) : HistoryEvent + data object Close : HistoryEvent + } +} diff --git a/app/src/main/java/de/markusressel/mkdocseditor/feature/history/ui/compose/ChangesSinceSeen.kt b/app/src/main/java/de/markusressel/mkdocseditor/feature/history/ui/compose/ChangesSinceSeen.kt new file mode 100644 index 00000000..8c2bf786 --- /dev/null +++ b/app/src/main/java/de/markusressel/mkdocseditor/feature/history/ui/compose/ChangesSinceSeen.kt @@ -0,0 +1,162 @@ +package de.markusressel.mkdocseditor.feature.history.ui.compose + +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Close +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.Text +import androidx.compose.material3.rememberModalBottomSheetState +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import de.markusressel.mkdocseditor.R +import de.markusressel.mkdocseditor.feature.theme.MkDocsEditorTheme +import de.markusressel.mkdocseditor.util.compose.CombinedPreview +import de.markusressel.mkdocsrestclient.history.ChangeAuthorModel +import de.markusressel.mkdocsrestclient.history.DiffHunkModel +import de.markusressel.mkdocsrestclient.history.DiffLineModel +import de.markusressel.mkdocsrestclient.history.DiffOp +import de.markusressel.mkdocsrestclient.history.DocumentChangesModel +import de.markusressel.mkdocsrestclient.history.HistorySummaryModel +import de.markusressel.mkdocsrestclient.history.SeenMarkModel +import java.util.Date + +/** "Anna, Bob via Claude Code": each person, with the agents they changed the page with */ +@Composable +private fun authorsText(authors: List): String { + val via = stringResource(R.string.history_via) + return authors.joinToString(", ") { author -> + if (author.agents.isEmpty()) author.displayName else via.format(author.displayName, author.agents.joinToString(", ")) + } +} + +/** + * Tells on opening a page who changed it since the last visit, and where. Tapping it shows the changes. + */ +@Composable +internal fun ChangesSinceSeenBanner( + changes: DocumentChangesModel, + onClick: () -> Unit, + onDismiss: () -> Unit, +) { + val headings = changes.summary.headings + Row( + modifier = Modifier + .fillMaxWidth() + .background(MaterialTheme.colorScheme.secondaryContainer) + .clickable(onClick = onClick) + .padding(start = 12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(modifier = Modifier.weight(1f).padding(vertical = 6.dp)) { + Text( + text = stringResource(R.string.changes_since_seen_banner, authorsText(changes.authors)), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSecondaryContainer, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + if (headings.isNotEmpty()) { + Text( + text = headings.joinToString(", "), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSecondaryContainer, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } + IconButton(onClick = onDismiss) { + Icon( + imageVector = Icons.Default.Close, + contentDescription = stringResource(R.string.changes_since_seen_dismiss), + tint = MaterialTheme.colorScheme.onSecondaryContainer, + ) + } + } +} + +/** The changes since the last visit, hunk by hunk; a hunk goes to its place in the page */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +internal fun ChangesSinceSeenSheet( + changes: DocumentChangesModel, + onHunkClicked: (DiffHunkModel) -> Unit, + onDismiss: () -> Unit, +) { + ModalBottomSheet( + onDismissRequest = onDismiss, + sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true), + ) { + ChangesSinceSeenContent(changes, onHunkClicked) + } +} + +@Composable +internal fun ChangesSinceSeenContent( + changes: DocumentChangesModel, + onHunkClicked: (DiffHunkModel) -> Unit, +) { + Column( + modifier = Modifier + .fillMaxWidth() + .verticalScroll(rememberScrollState()) + .padding(horizontal = 16.dp) + .padding(bottom = 16.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + Text(text = stringResource(R.string.changes_since_seen_title), style = MaterialTheme.typography.titleMedium) + Text( + text = authorsText(changes.authors) + " · +${changes.summary.linesAdded} −${changes.summary.linesRemoved}", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + changes.hunks.forEach { hunk -> Hunk(hunk, onClick = { onHunkClicked(hunk) }) } + } +} + +@CombinedPreview +@Composable +private fun ChangesSinceSeenPreview() { + val changes = DocumentChangesModel( + since = SeenMarkModel(Date(0), "a"), + seenToken = "b", + authors = listOf( + ChangeAuthorModel(displayName = "Alice", color = "#e8590c"), + ChangeAuthorModel(displayName = "Bob", color = "#2f9e44", agents = listOf("Claude Code")), + ), + hunks = listOf( + DiffHunkModel( + heading = "Setup", headingOccurrence = 1, oldStart = 1, oldLines = 2, newStart = 1, newLines = 3, + lines = listOf( + DiffLineModel(DiffOp.CONTEXT, "# Setup"), + DiffLineModel(DiffOp.REMOVED, "Some text."), + DiffLineModel(DiffOp.ADDED, "Some better text."), + DiffLineModel(DiffOp.ADDED, "## Install"), + ), + ), + ), + summary = HistorySummaryModel(2, 1, listOf("Setup", "Install")), + ) + MkDocsEditorTheme { + Column { + ChangesSinceSeenBanner(changes, onClick = {}, onDismiss = {}) + ChangesSinceSeenContent(changes, onHunkClicked = {}) + } + } +} diff --git a/app/src/main/java/de/markusressel/mkdocseditor/feature/history/ui/compose/HistoryScreen.kt b/app/src/main/java/de/markusressel/mkdocseditor/feature/history/ui/compose/HistoryScreen.kt new file mode 100644 index 00000000..b70fb873 --- /dev/null +++ b/app/src/main/java/de/markusressel/mkdocseditor/feature/history/ui/compose/HistoryScreen.kt @@ -0,0 +1,82 @@ +package de.markusressel.mkdocseditor.feature.history.ui.compose + +import android.widget.Toast +import androidx.activity.compose.BackHandler +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.ui.platform.LocalContext +import cafe.adriel.voyager.core.screen.Screen +import cafe.adriel.voyager.hilt.getViewModel +import cafe.adriel.voyager.navigator.LocalNavigator +import cafe.adriel.voyager.navigator.currentOrThrow +import de.markusressel.mkdocseditor.R +import de.markusressel.mkdocseditor.feature.editor.ui.compose.CodeEditorScreen +import de.markusressel.mkdocseditor.feature.history.ui.HistoryViewModel +import de.markusressel.mkdocseditor.feature.history.ui.HistoryViewModel.HistoryEvent +import de.markusressel.mkdocseditor.feature.history.ui.HistoryViewModel.UiEvent +import de.markusressel.mkdocseditor.feature.main.data.MainNavigationRequests +import de.markusressel.mkdocseditor.feature.main.data.editorOf +import de.markusressel.mkdocseditor.feature.main.data.rememberMainNavigationRequests + +/** + * The revision history of a document, see [HistoryViewModel] + * + * @param canRestore whether the account may edit the document, and so bring back an old text + * @param canRevert whether it may also undo a single change, which needs `revert` on the server + * @param canRestoreSection whether it may also bring back a single section, which needs `blame` on the server + */ +data class HistoryScreen( + val documentId: String, + val canRestore: Boolean, + val canRevert: Boolean = false, + val canRestoreSection: Boolean = false, +) : Screen { + + @Composable + override fun Content() { + val navigator = LocalNavigator.currentOrThrow + val context = LocalContext.current + val requests = rememberMainNavigationRequests() + val viewModel = getViewModel() + val uiState by viewModel.uiState.collectAsState() + + LaunchedEffect(viewModel, documentId) { + viewModel.initialize(documentId, canRestore, canRevert, canRestoreSection) + } + + LaunchedEffect(viewModel) { + viewModel.events.collect { event -> + when (event) { + is HistoryEvent.OpenInEditor -> { + // the history usually opens from the editor of the document, which takes the change + val open = navigator.items.editorOf(documentId) + if (open != null) { + navigator.popUntil { it === open } + requests.handChange(MainNavigationRequests.EditorChange(open.key, event.change)) + } else { + navigator.replace(CodeEditorScreen(documentId = documentId, change = event.change)) + } + } + is HistoryEvent.Message -> Toast.makeText(context, event.text, Toast.LENGTH_LONG).show() + is HistoryEvent.UndoConflict -> { + val top = context.getString(R.string.history_page_start) + val headings = event.headings.joinToString(", ") { it ?: top } + Toast.makeText(context, context.getString(R.string.history_undo_conflict, headings), Toast.LENGTH_LONG).show() + } + is HistoryEvent.SectionMissing -> { + val text = if (event.inRevision) R.string.history_section_missing_in_version + else R.string.history_section_missing_now + Toast.makeText(context, context.getString(text, event.heading), Toast.LENGTH_LONG).show() + } + is HistoryEvent.Close -> navigator.pop() + } + } + } + + BackHandler { viewModel.onUiEvent(UiEvent.BackClicked) } + + HistoryScreenContent(uiState = uiState, onUiEvent = viewModel::onUiEvent) + } +} diff --git a/app/src/main/java/de/markusressel/mkdocseditor/feature/history/ui/compose/HistoryScreenContent.kt b/app/src/main/java/de/markusressel/mkdocseditor/feature/history/ui/compose/HistoryScreenContent.kt new file mode 100644 index 00000000..5b5308bd --- /dev/null +++ b/app/src/main/java/de/markusressel/mkdocseditor/feature/history/ui/compose/HistoryScreenContent.kt @@ -0,0 +1,419 @@ +package de.markusressel.mkdocseditor.feature.history.ui.compose + +import androidx.compose.animation.animateContentSize +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.SmartToy +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.buildAnnotatedString +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import de.markusressel.mkdocseditor.R +import de.markusressel.mkdocseditor.feature.avatar.data.Avatar +import de.markusressel.mkdocseditor.feature.avatar.ui.compose.UserAvatar +import de.markusressel.mkdocseditor.feature.common.ui.compose.TabContentScaffold +import de.markusressel.mkdocseditor.feature.common.ui.compose.topbar.MkDocsEditorTopAppBar +import de.markusressel.mkdocseditor.feature.editor.ui.compose.fallbackPeerColor +import de.markusressel.mkdocseditor.feature.editor.ui.compose.labelTextColorOn +import de.markusressel.mkdocseditor.feature.editor.ui.compose.parsePeerColor +import de.markusressel.mkdocseditor.feature.history.domain.Highlight +import de.markusressel.mkdocseditor.feature.history.domain.agentNames +import de.markusressel.mkdocseditor.feature.history.domain.notableMessage +import de.markusressel.mkdocseditor.feature.history.domain.pairChangedLines +import de.markusressel.mkdocseditor.feature.history.domain.peopleWithAgents +import de.markusressel.mkdocseditor.feature.history.domain.shownName +import de.markusressel.mkdocseditor.feature.history.domain.wordChanges +import de.markusressel.mkdocseditor.feature.history.ui.HistoryViewModel.Confirm +import de.markusressel.mkdocseditor.feature.history.ui.HistoryViewModel.DiffState +import de.markusressel.mkdocseditor.feature.history.ui.HistoryViewModel.UiEvent +import de.markusressel.mkdocseditor.feature.history.ui.HistoryViewModel.UiState +import de.markusressel.mkdocseditor.feature.theme.MkDocsEditorTheme +import de.markusressel.mkdocseditor.util.compose.CombinedPreview +import de.markusressel.mkdocsrestclient.history.DiffHunkModel +import de.markusressel.mkdocsrestclient.history.DiffLineModel +import de.markusressel.mkdocsrestclient.history.DiffOp +import de.markusressel.mkdocsrestclient.history.HistoryAgentModel +import de.markusressel.mkdocsrestclient.history.HistoryAuthorModel +import de.markusressel.mkdocsrestclient.history.HistoryEntryModel +import de.markusressel.mkdocsrestclient.history.HistorySummaryModel +import java.util.Date + +// light enough for text on top in both themes +private val AddedLine = Color(0x332DA44E) +private val AddedWords = Color(0x772DA44E) +private val RemovedLine = Color(0x33E5534B) +private val RemovedWords = Color(0x77E5534B) + +@Composable +internal fun HistoryScreenContent( + uiState: UiState, + onUiEvent: (UiEvent) -> Unit, +) { + TabContentScaffold( + topBar = { + MkDocsEditorTopAppBar( + title = stringResource(R.string.history_title), + canGoBack = true, + onBackClicked = { onUiEvent(UiEvent.BackClicked) }, + ) + }, + ) { paddingValues -> + Column(modifier = Modifier.fillMaxSize().padding(paddingValues)) { + if (uiState.loading || uiState.working) { + LinearProgressIndicator(modifier = Modifier.fillMaxWidth()) + } + val problem = uiState.problem + when { + problem != null -> Column( + modifier = Modifier.fillMaxWidth().padding(16.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + Text(stringResource(problem)) + Button(onClick = { onUiEvent(UiEvent.RetryClicked) }) { Text(stringResource(R.string.retry)) } + } + !uiState.loading && uiState.entries.isEmpty() -> Text( + modifier = Modifier.padding(16.dp), + text = stringResource(R.string.history_empty), + ) + else -> LazyColumn(modifier = Modifier.fillMaxSize()) { + items(uiState.entries, key = { it.revision }) { entry -> + HistoryEntry( + entry = entry, + expanded = uiState.expanded == entry.revision, + diff = uiState.diffs[entry.revision], + // the newest entry is the text as it is + canRestore = uiState.canRestore && entry != uiState.entries.first(), + // the oldest one created the page, which is undone by deleting it + canUndo = uiState.canRevert && entry != uiState.entries.last(), + canRestoreSection = uiState.canRestoreSection && entry != uiState.entries.first(), + onUiEvent = onUiEvent, + ) + HorizontalDivider() + } + } + } + } + } + + uiState.confirm?.let { confirm -> + val entry = confirm.entry + val (title, text, action) = when (confirm) { + is Confirm.Restore -> Triple( + stringResource(R.string.history_restore_title), + stringResource(R.string.history_restore_text, relativeTime(entry.time), entry.author.shownName), + stringResource(R.string.history_restore), + ) + // the diff of the entry is open above, so the dialog names who and when + is Confirm.Undo -> Triple( + stringResource(R.string.history_undo_title), + stringResource(R.string.history_undo_text, whoText(entry), relativeTime(entry.time)), + stringResource(R.string.history_undo), + ) + is Confirm.RestoreSection -> Triple( + stringResource(R.string.history_restore_section_title), + stringResource(R.string.history_restore_section_text, confirm.section.heading, relativeTime(entry.time)), + stringResource(R.string.history_restore), + ) + } + AlertDialog( + onDismissRequest = { onUiEvent(UiEvent.ConfirmDismissed) }, + title = { Text(title) }, + text = { Text(text) }, + confirmButton = { TextButton(onClick = { onUiEvent(UiEvent.Confirmed) }) { Text(action) } }, + dismissButton = { + TextButton(onClick = { onUiEvent(UiEvent.ConfirmDismissed) }) { Text(stringResource(android.R.string.cancel)) } + }, + ) + } +} + +@Composable +private fun HistoryEntry( + entry: HistoryEntryModel, + expanded: Boolean, + diff: DiffState?, + canRestore: Boolean, + canUndo: Boolean, + canRestoreSection: Boolean, + onUiEvent: (UiEvent) -> Unit, +) { + Column( + modifier = Modifier + .fillMaxWidth() + .animateContentSize() + .clickable { onUiEvent(UiEvent.EntryClicked(entry.revision)) } + .padding(horizontal = 16.dp, vertical = 12.dp), + ) { + Row(verticalAlignment = Alignment.CenterVertically) { + EntryAvatar(entry) + Spacer(Modifier.width(12.dp)) + Column(modifier = Modifier.weight(1f)) { + Text( + text = whoText(entry), + style = MaterialTheme.typography.titleSmall, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + Text( + text = listOfNotNull(relativeTime(entry.time), summaryText(entry.summary)).joinToString(" · "), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + entry.notableMessage?.let { + Text(text = it, style = MaterialTheme.typography.bodySmall, maxLines = 2, overflow = TextOverflow.Ellipsis) + } + } + } + if (expanded) { + Spacer(Modifier.size(8.dp)) + EntryDiff( + diff = diff, + onHunkClicked = { onUiEvent(UiEvent.HunkClicked(it)) }, + // a hunk above the first heading has no section to restore + onRestoreSection = if (canRestoreSection) { + { hunk -> onUiEvent(UiEvent.RestoreSectionClicked(entry, hunk)) } + } else null, + ) + Row(modifier = Modifier.padding(top = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + if (canUndo) { + OutlinedButton(onClick = { onUiEvent(UiEvent.UndoClicked(entry)) }) { + Text(stringResource(R.string.history_undo_action)) + } + } + if (canRestore) { + OutlinedButton(onClick = { onUiEvent(UiEvent.RestoreClicked(entry)) }) { + Text(stringResource(R.string.history_restore_action)) + } + } + } + } + } +} + +/** the author, with a robot on top when an agent made the changes */ +@Composable +private fun EntryAvatar(entry: HistoryEntryModel) { + val author = entry.author + val color = authorColor(author) + Box { + UserAvatar( + modifier = Modifier.size(36.dp), + name = author.shownName, + color = color, + avatar = Avatar.of(author.accountId, author.avatar), + ) + if (entry.agentNames.isNotEmpty()) { + Icon( + imageVector = Icons.Outlined.SmartToy, + contentDescription = null, + tint = labelTextColorOn(color), + modifier = Modifier + .align(Alignment.BottomEnd) + .size(16.dp) + .clip(CircleShape) + .background(color) + .padding(2.dp), + ) + } + } +} + +private fun authorColor(author: HistoryAuthorModel): Color = + parsePeerColor(author.color) ?: fallbackPeerColor(author.username.ifEmpty { author.name }) + +/** "Bob via Claude Code, Anna" */ +@Composable +private fun whoText(entry: HistoryEntryModel): String { + val via = stringResource(R.string.history_via) + return entry.peopleWithAgents.joinToString(", ") { (person, agents) -> + if (agents.isEmpty()) person.shownName else via.format(person.shownName, agents.joinToString(", ")) + } +} + +@Composable +private fun summaryText(summary: HistorySummaryModel?): String? { + summary ?: return null + val lines = "+${summary.linesAdded} −${summary.linesRemoved}" + return if (summary.headings.isEmpty()) lines else "$lines · ${summary.headings.joinToString(", ")}" +} + +@Composable +private fun EntryDiff( + diff: DiffState?, + onHunkClicked: (DiffHunkModel) -> Unit, + onRestoreSection: ((DiffHunkModel) -> Unit)?, +) { + when (diff) { + null, DiffState.Loading -> LinearProgressIndicator(modifier = Modifier.fillMaxWidth()) + is DiffState.Failed -> Text(stringResource(diff.message), color = MaterialTheme.colorScheme.error) + DiffState.FirstVersion -> Text(stringResource(R.string.history_first_version), style = MaterialTheme.typography.bodySmall) + is DiffState.Loaded -> if (diff.hunks.isEmpty()) { + Text(stringResource(R.string.history_no_text_changes), style = MaterialTheme.typography.bodySmall) + } else { + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + diff.hunks.forEach { hunk -> + Hunk( + hunk = hunk, + onClick = { onHunkClicked(hunk) }, + onRestoreSection = onRestoreSection?.takeIf { hunk.heading != null }?.let { { it(hunk) } }, + ) + } + } + } + } +} + +/** inline, as Markdown source; a long line scrolls sideways instead of wrapping, so the columns stay */ +@Composable +internal fun Hunk(hunk: DiffHunkModel, onClick: () -> Unit, onRestoreSection: (() -> Unit)? = null) { + val lines = remember(hunk) { diffLineTexts(hunk.lines) } + Column( + modifier = Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(8.dp)) + .background(MaterialTheme.colorScheme.surfaceContainer), + ) { + Row( + modifier = Modifier.fillMaxWidth().clickable(onClick = onClick).padding(horizontal = 8.dp, vertical = 6.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + modifier = Modifier.weight(1f), + text = hunk.heading ?: stringResource(R.string.history_page_start), + style = MaterialTheme.typography.labelLarge, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Text( + text = stringResource(R.string.history_open_in_editor), + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.primary, + ) + } + Column(modifier = Modifier.fillMaxWidth().horizontalScroll(rememberScrollState())) { + lines.forEachIndexed { index, text -> + val op = hunk.lines[index].op + Text( + modifier = Modifier + .background( + when (op) { + DiffOp.ADDED -> AddedLine + DiffOp.REMOVED -> RemovedLine + DiffOp.CONTEXT -> Color.Transparent + } + ) + .padding(horizontal = 8.dp), + text = text, + style = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Monospace), + softWrap = false, + ) + } + } + if (onRestoreSection != null) { + // names the section, because the hunk can reach into the next one + TextButton(modifier = Modifier.align(Alignment.End), onClick = onRestoreSection) { + Text( + text = stringResource(R.string.history_restore_section_action, hunk.heading.orEmpty()), + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } + } +} + +/** each line with its sign, and in a pair of a removed and an added line the changed words marked */ +private fun diffLineTexts(lines: List): List { + val partners = pairChangedLines(lines) + return lines.mapIndexed { index, line -> + val sign = when (line.op) { + DiffOp.ADDED -> "+ " + DiffOp.REMOVED -> "− " + DiffOp.CONTEXT -> " " + } + val highlights: List = partners[index]?.let { partner -> + when (line.op) { + DiffOp.REMOVED -> wordChanges(line.text, lines[partner].text).removed + DiffOp.ADDED -> wordChanges(lines[partner].text, line.text).added + DiffOp.CONTEXT -> emptyList() + } + }.orEmpty() + val color = if (line.op == DiffOp.ADDED) AddedWords else RemovedWords + buildAnnotatedString { + append(sign) + append(line.text) + highlights.forEach { addStyle(SpanStyle(background = color), sign.length + it.start, sign.length + it.end) } + } + } +} + +@CombinedPreview +@Composable +private fun HistoryScreenContentPreview() { + val anna = HistoryAuthorModel("anna", "anna@mkdocseditor.invalid", "anna", "a1", "Anna", "#1971c2") + val entries = listOf( + HistoryEntryModel( + revision = "b", time = Date(), author = anna, message = "Update guide/setup.md", path = "guide/setup.md", + agents = listOf(HistoryAgentModel("Claude Code", "a1")), summary = HistorySummaryModel(2, 1, listOf("Install")), + ), + HistoryEntryModel( + revision = "a", time = Date(0), author = HistoryAuthorModel("Test", "test@example.com"), message = "Initial", + path = "guide/setup.md", + ), + ) + val hunk = DiffHunkModel( + heading = "Install", headingOccurrence = 1, oldStart = 3, oldLines = 2, newStart = 3, newLines = 3, + lines = listOf( + DiffLineModel(DiffOp.CONTEXT, "## Install"), + DiffLineModel(DiffOp.REMOVED, "Install the app on your phone."), + DiffLineModel(DiffOp.ADDED, "Install the new app on the phone."), + DiffLineModel(DiffOp.ADDED, "Then sign in."), + ), + ) + MkDocsEditorTheme { + HistoryScreenContent( + uiState = UiState( + loading = false, entries = entries, expanded = "b", diffs = mapOf("b" to DiffState.Loaded(listOf(hunk))), + canRestore = true, canRevert = true, + ), + onUiEvent = {}, + ) + } +} diff --git a/app/src/main/java/de/markusressel/mkdocseditor/feature/history/ui/compose/LineAuthorSheet.kt b/app/src/main/java/de/markusressel/mkdocseditor/feature/history/ui/compose/LineAuthorSheet.kt new file mode 100644 index 00000000..2c69abfa --- /dev/null +++ b/app/src/main/java/de/markusressel/mkdocseditor/feature/history/ui/compose/LineAuthorSheet.kt @@ -0,0 +1,125 @@ +package de.markusressel.mkdocseditor.feature.history.ui.compose + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.rememberModalBottomSheetState +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import de.markusressel.mkdocseditor.R +import de.markusressel.mkdocseditor.feature.avatar.data.Avatar +import de.markusressel.mkdocseditor.feature.avatar.ui.compose.UserAvatar +import de.markusressel.mkdocseditor.feature.editor.ui.compose.fallbackPeerColor +import de.markusressel.mkdocseditor.feature.editor.ui.compose.parsePeerColor +import de.markusressel.mkdocseditor.feature.theme.MkDocsEditorTheme +import de.markusressel.mkdocseditor.util.compose.CombinedPreview +import de.markusressel.mkdocsrestclient.dashboard.FeedAuthorModel +import de.markusressel.mkdocsrestclient.history.BlameBlockModel +import java.util.Date + +/** the backend's message for an edit without one of its own, which tells nothing */ +private val STANDARD_MESSAGE = Regex("Update .+\\.md") + +/** Who last changed the lines around a tapped line of the author strip, and when */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +internal fun LineAuthorSheet( + block: BlameBlockModel, + onOpenHistory: (() -> Unit)?, + onDismiss: () -> Unit, +) { + ModalBottomSheet( + onDismissRequest = onDismiss, + sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true), + ) { + LineAuthorContent(block, onOpenHistory) + } +} + +/** @param onOpenHistory null on a server without the history */ +@Composable +internal fun LineAuthorContent( + block: BlameBlockModel, + onOpenHistory: (() -> Unit)?, +) { + val author = block.author + Column( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp) + .padding(bottom = 16.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + Text( + text = if (block.start == block.end) stringResource(R.string.line_author_title_line, block.start) + else stringResource(R.string.line_author_title_lines, block.start, block.end), + style = MaterialTheme.typography.titleMedium, + ) + Row(verticalAlignment = Alignment.CenterVertically) { + if (author != null) { + UserAvatar( + modifier = Modifier.size(36.dp), + name = author.displayName, + color = parsePeerColor(author.color) ?: fallbackPeerColor(author.username ?: author.displayName), + avatar = Avatar.of(author.accountId, author.avatar), + ) + Spacer(Modifier.width(12.dp)) + } + Column(modifier = Modifier.weight(1f)) { + val name = author?.displayName ?: stringResource(R.string.line_author_unknown) + Text( + text = if (block.agents.isEmpty()) name + else stringResource(R.string.history_via, name, block.agents.joinToString(", ")), + style = MaterialTheme.typography.titleSmall, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + val time = block.time + Text( + // pending lines are newer than the last commit, so they have no time yet + text = if (block.pending || time == null) stringResource(R.string.line_author_pending) else relativeTime(time), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + block.message?.takeUnless { it.isBlank() || STANDARD_MESSAGE.matches(it) }?.let { + Text(text = it, style = MaterialTheme.typography.bodySmall, maxLines = 3, overflow = TextOverflow.Ellipsis) + } + } + } + if (onOpenHistory != null) { + TextButton(modifier = Modifier.align(Alignment.End), onClick = onOpenHistory) { + Text(stringResource(R.string.history_action)) + } + } + } +} + +@CombinedPreview +@Composable +private fun LineAuthorPreview() { + MkDocsEditorTheme { + LineAuthorContent( + block = BlameBlockModel( + start = 7, end = 9, revision = "415bd17be867d776b13a5d71b8d38132aab1a171", time = Date(), + message = "Restore section \"Install\" of guide/setup.md to bde4a3c", + author = FeedAuthorModel(accountId = "a2", username = "bob", displayName = "Bob", color = "#2f9e44"), + agents = listOf("Claude Code"), + ), + onOpenHistory = {}, + ) + } +} diff --git a/app/src/main/java/de/markusressel/mkdocseditor/feature/history/ui/compose/RelativeTime.kt b/app/src/main/java/de/markusressel/mkdocseditor/feature/history/ui/compose/RelativeTime.kt new file mode 100644 index 00000000..44e1b8e9 --- /dev/null +++ b/app/src/main/java/de/markusressel/mkdocseditor/feature/history/ui/compose/RelativeTime.kt @@ -0,0 +1,15 @@ +package de.markusressel.mkdocseditor.feature.history.ui.compose + +import android.text.format.DateUtils +import androidx.compose.runtime.Composable +import androidx.compose.ui.res.stringResource +import de.markusressel.mkdocseditor.R +import java.util.Date + +/** within the last minute, or from a server whose clock is a little ahead, it is "just now", not "in 0 minutes" */ +@Composable +internal fun relativeTime(time: Date): String { + val now = System.currentTimeMillis() + if (now - time.time < DateUtils.MINUTE_IN_MILLIS) return stringResource(R.string.history_just_now) + return DateUtils.getRelativeTimeSpanString(time.time, now, DateUtils.MINUTE_IN_MILLIS).toString() +} diff --git a/app/src/main/java/de/markusressel/mkdocseditor/feature/qr/data/QrCodesSupport.kt b/app/src/main/java/de/markusressel/mkdocseditor/feature/qr/data/QrCodesSupport.kt index cf441f01..026c8d29 100644 --- a/app/src/main/java/de/markusressel/mkdocseditor/feature/qr/data/QrCodesSupport.kt +++ b/app/src/main/java/de/markusressel/mkdocseditor/feature/qr/data/QrCodesSupport.kt @@ -1,34 +1,13 @@ package de.markusressel.mkdocseditor.feature.qr.data import de.markusressel.mkdocseditor.auth.api.ServerFeature -import de.markusressel.mkdocseditor.auth.domain.AuthRepository -import de.markusressel.mkdocseditor.feature.auth.common.data.AuthBackends -import de.markusressel.mkdocseditor.feature.backendconfig.common.data.toBackendRef -import timber.log.Timber -import java.util.concurrent.ConcurrentHashMap +import de.markusressel.mkdocseditor.feature.common.data.ServerFeatures import javax.inject.Inject -import javax.inject.Singleton -/** - * Whether the selected server has QR codes (`qr-codes` in its features). The answer is kept for the app's lifetime, - * so a page opened offline still shows the menu entry once the server was reached. - */ -@Singleton +/** Whether the selected server has QR codes (`qr-codes` in its features), see [ServerFeatures] */ internal class QrCodesSupport @Inject constructor( - private val backends: AuthBackends, - private val authRepository: AuthRepository, + private val features: ServerFeatures, ) { - private val known = ConcurrentHashMap() - /** false while the server can't be asked and has not been before */ - suspend fun isSupported(): Boolean { - val backend = backends.selected()?.toBackendRef() ?: return false - known[backend.baseUrl]?.let { return it } - return try { - (ServerFeature.QR_CODES in authRepository.serverInfo(backend).features).also { known[backend.baseUrl] = it } - } catch (e: Exception) { - Timber.w(e, "Could not read the server features") - false - } - } + suspend fun isSupported(): Boolean = features.has(ServerFeature.QR_CODES) } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index c83f6b7e..07596a0d 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -449,4 +449,39 @@ “%1$s” has this code. Remove it there first. Can\'t ask the server whether another page has this code. Try again with a connection. + History + History + This page has no history yet. + %1$s via %2$s + The first version of this page. + The text did not change. + Top of the page + Open + Restore this version + Restore this version? + The page gets the text it had %1$s, after the change of %2$s. Everyone sees it as an edit, which can be undone. + Restore + Version restored + just now + Undo this change + Undo this change? + The change of %1$s from %2$s is taken back. Later changes stay. Everyone sees it as an edit, which can be undone. + Undo + Change undone + This change is not in the page anymore. + Can\'t undo: later changes in %1$s are in the way. + Restore “%1$s” + Restore this section? + “%1$s” and its subsections go back to how they were %2$s. The rest of the page stays. + Section restored + “%1$s” is not in this version. + “%1$s” is no longer in the page. Restore the whole version instead. + Line %1$d + Lines %1$d–%2$d + Unknown + Not saved in the history yet + Nobody known changed this line yet + Changed by %1$s since you were here + Changes since your last visit + Hide diff --git a/app/src/test/java/de/markusressel/mkdocseditor/feature/editor/ui/compose/EditorTopBarActionsTest.kt b/app/src/test/java/de/markusressel/mkdocseditor/feature/editor/ui/compose/EditorTopBarActionsTest.kt index cd951b69..e756493e 100644 --- a/app/src/test/java/de/markusressel/mkdocseditor/feature/editor/ui/compose/EditorTopBarActionsTest.kt +++ b/app/src/test/java/de/markusressel/mkdocseditor/feature/editor/ui/compose/EditorTopBarActionsTest.kt @@ -12,7 +12,7 @@ import kotlin.test.assertTrue class EditorTopBarActionsTest { - private val editing = CodeEditorViewModel.UiState(editModeActive = true) + private val editing = CodeEditorViewModel.UiState(editModeActive = true, historyAvailable = true) /** a phone in portrait */ private val phone = 411 @@ -63,8 +63,8 @@ class EditorTopBarActionsTest { assertTrue(TopAppBarAction.CodeEditor.PageReferencesAction in actions) val menu = menuOf(actions) assertTrue(TopAppBarAction.CodeEditor.ViewSettingsAction !in menu && TopAppBarAction.CodeEditor.PageReferencesAction !in menu) - // no divider without a group before it - assertEquals(TopAppBarAction.CodeEditor.ShareLinkAction, menu.first()) + // the history stays in the menu, it opens a screen of its own + assertEquals(TopAppBarAction.CodeEditor.HistoryAction, menu.first()) } @Test @@ -82,6 +82,7 @@ class EditorTopBarActionsTest { val actionsOnly = setOf( TopAppBarAction.CodeEditor.ViewSettingsAction, TopAppBarAction.CodeEditor.PageReferencesAction, + TopAppBarAction.CodeEditor.HistoryAction, TopAppBarAction.CodeEditor.MenuDivider, TopAppBarAction.CodeEditor.ShareLinkAction, TopAppBarAction.CodeEditor.ShowInBrowserAction, @@ -98,6 +99,15 @@ class EditorTopBarActionsTest { } } + @Test + fun `the history is in the menu only when the server has it`() { + val without = menuOf(editorTopBarActions(editing.copy(historyAvailable = false), SplitMode.Off, widthDp = phone)) + val with = menuOf(editorTopBarActions(editing, SplitMode.Off, widthDp = phone)) + + assertTrue(TopAppBarAction.CodeEditor.HistoryAction !in without) + assertTrue(TopAppBarAction.CodeEditor.HistoryAction in with) + } + @Test fun `the page can be renamed, moved, pinned and deleted from the menu, last`() { val menu = menuOf(editorTopBarActions(CodeEditorViewModel.UiState(), SplitMode.Off, widthDp = phone)) diff --git a/app/src/test/java/de/markusressel/mkdocseditor/feature/history/domain/HistoryTextTest.kt b/app/src/test/java/de/markusressel/mkdocseditor/feature/history/domain/HistoryTextTest.kt new file mode 100644 index 00000000..dac36329 --- /dev/null +++ b/app/src/test/java/de/markusressel/mkdocseditor/feature/history/domain/HistoryTextTest.kt @@ -0,0 +1,93 @@ +package de.markusressel.mkdocseditor.feature.history.domain + +import de.markusressel.mkdocseditor.feature.editor.domain.ChangeLocation +import de.markusressel.mkdocseditor.feature.editor.domain.ChangedLines +import de.markusressel.mkdocsrestclient.history.DiffHunkModel +import de.markusressel.mkdocsrestclient.history.DiffLineModel +import de.markusressel.mkdocsrestclient.history.DiffOp +import de.markusressel.mkdocsrestclient.history.HistoryAgentModel +import de.markusressel.mkdocsrestclient.history.HistoryAuthorModel +import de.markusressel.mkdocsrestclient.history.HistoryEntryModel +import java.util.Date +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull + +class HistoryTextTest { + + private fun hunk(vararg ops: DiffOp, offset: Int? = 4) = DiffHunkModel( + heading = "Setup", + headingOccurrence = 2, + oldStart = 10, + oldLines = ops.count { it != DiffOp.ADDED }, + newStart = 12, + newLines = ops.count { it != DiffOp.REMOVED }, + lines = ops.map { DiffLineModel(it, "x") }, + offset = offset, + ) + + @Test + fun `a hunk opens the editor at its first added lines, relative to its heading`() { + val location = hunk(DiffOp.CONTEXT, DiffOp.CONTEXT, DiffOp.REMOVED, DiffOp.ADDED, DiffOp.ADDED, DiffOp.CONTEXT).changeLocation() + + assertEquals(ChangeLocation(listOf("Setup"), ranges = listOf(ChangedLines(14, 2, "Setup", 2, 6))), location) + } + + @Test + fun `a hunk that only removed lines opens at the place they were`() { + val location = hunk(DiffOp.CONTEXT, DiffOp.REMOVED, DiffOp.CONTEXT).changeLocation() + + assertEquals(listOf(ChangedLines(13, 0, "Setup", 2, 5)), location.ranges) + } + + @Test + fun `without an offset the editor opens at the section`() { + assertEquals(ChangeLocation(listOf("Setup")), hunk(DiffOp.ADDED, offset = null).changeLocation()) + } + + private fun author(name: String, accountId: String = "", displayName: String? = null) = + HistoryAuthorModel(name = name, email = "$name@mkdocseditor.invalid", username = name, accountId = accountId, displayName = displayName) + + private fun entry( + author: HistoryAuthorModel = author("anna", "a1"), + coAuthors: List = emptyList(), + message: String = "Update guide/setup.md", + appTokens: List = emptyList(), + agents: List = emptyList(), + ) = HistoryEntryModel("r", Date(0), author, coAuthors, message, "guide/setup.md", appTokens, agents) + + @Test + fun `an author shows the name of the account, else the one of the commit`() { + assertEquals("Anna", author("anna", "a1", displayName = "Anna").shownName) + assertEquals("anna", author("anna", "a1", displayName = " ").shownName) + assertEquals("Test", HistoryAuthorModel(name = "Test", email = "test@example.com").shownName) + } + + @Test + fun `a co-author who is also the author shows once`() { + val anna = author("anna", "a1") + assertEquals(listOf("anna", "bob"), entry(anna, listOf(author("bob", "a2"), anna)).people.map { it.shownName }) + } + + @Test + fun `agents come from the agents list, else from the token names`() { + assertEquals(listOf("Claude Code"), entry(agents = listOf(HistoryAgentModel("Claude Code", "a1"))).agentNames) + assertEquals(listOf("Claude Code"), entry(appTokens = listOf("Claude Code")).agentNames) + } + + @Test + fun `an agent goes with its own person, one of an unknown person or without account with the author`() { + val bob = author("bob", "a2") + val agents = listOf(HistoryAgentModel("Claude Code", "a2"), HistoryAgentModel("Script", "a9")) + val withAgents = entry(author("anna", "a1"), listOf(bob), agents = agents).peopleWithAgents + + assertEquals(listOf("anna" to listOf("Script"), "bob" to listOf("Claude Code")), withAgents.map { (p, a) -> p.shownName to a }) + assertEquals(listOf("Claude Code"), entry(appTokens = listOf("Claude Code")).peopleWithAgents.single().second) + } + + @Test + fun `the standard message of an edit is left out, others are shown`() { + assertNull(entry().notableMessage) + assertEquals("Restore guide/setup.md to 9d8af8092333", entry(message = "Restore guide/setup.md to 9d8af8092333").notableMessage) + } +} diff --git a/app/src/test/java/de/markusressel/mkdocseditor/feature/history/domain/LineAuthorUseCaseTest.kt b/app/src/test/java/de/markusressel/mkdocseditor/feature/history/domain/LineAuthorUseCaseTest.kt new file mode 100644 index 00000000..185ce8e7 --- /dev/null +++ b/app/src/test/java/de/markusressel/mkdocseditor/feature/history/domain/LineAuthorUseCaseTest.kt @@ -0,0 +1,48 @@ +package de.markusressel.mkdocseditor.feature.history.domain + +import com.github.kittinunf.fuel.core.FuelError +import com.github.kittinunf.fuel.core.Response +import com.github.kittinunf.result.Result +import de.markusressel.mkdocseditor.R +import de.markusressel.mkdocsrestclient.DummyMkDocsRestClient +import de.markusressel.mkdocsrestclient.IMkDocsRestClient +import de.markusressel.mkdocsrestclient.dashboard.FeedAuthorModel +import de.markusressel.mkdocsrestclient.history.BlameBlockModel +import de.markusressel.mkdocsrestclient.history.BlameModel +import kotlinx.coroutines.test.runTest +import java.net.URL +import kotlin.test.Test +import kotlin.test.assertEquals + +class LineAuthorUseCaseTest { + + private val bob = FeedAuthorModel(accountId = "a2", username = "bob", displayName = "Bob", color = "#2f9e44") + private val committed = BlameBlockModel(start = 1, end = 3, revision = "r1", author = bob) + private val nobody = BlameBlockModel(start = 4, end = 4, pending = true, author = null) + private var answer: Result = + Result.success(BlameModel(revision = "h", lines = 4, blocks = listOf(committed, nobody))) + + private val client = object : IMkDocsRestClient by DummyMkDocsRestClient() { + override suspend fun getDocumentBlame(documentId: String): Result = answer + } + private val lineAuthor = LineAuthorUseCase(client) + + @Test + fun `the editor's first line is the first line of the blame`() = runTest { + assertEquals(LineAuthorUseCase.Answer.Found(committed), lineAuthor("d1", 0)) + assertEquals(LineAuthorUseCase.Answer.Found(committed), lineAuthor("d1", 2)) + } + + @Test + fun `a line nobody known wrote, or newer than the blame, is unknown`() = runTest { + assertEquals(LineAuthorUseCase.Answer.Unknown, lineAuthor("d1", 3)) + assertEquals(LineAuthorUseCase.Answer.Unknown, lineAuthor("d1", 4)) + } + + @Test + fun `a failed request says why`() = runTest { + answer = Result.error(FuelError.wrap(RuntimeException("404"), Response(URL("http://localhost/"), statusCode = 404))) + + assertEquals(LineAuthorUseCase.Answer.Failed(R.string.error_not_found), lineAuthor("d1", 0)) + } +} diff --git a/app/src/test/java/de/markusressel/mkdocseditor/feature/history/domain/SeenChangesUseCaseTest.kt b/app/src/test/java/de/markusressel/mkdocseditor/feature/history/domain/SeenChangesUseCaseTest.kt new file mode 100644 index 00000000..b4692380 --- /dev/null +++ b/app/src/test/java/de/markusressel/mkdocseditor/feature/history/domain/SeenChangesUseCaseTest.kt @@ -0,0 +1,136 @@ +package de.markusressel.mkdocseditor.feature.history.domain + +import com.github.kittinunf.fuel.core.FuelError +import com.github.kittinunf.fuel.core.Response +import com.github.kittinunf.result.Result +import de.markusressel.mkdocseditor.auth.FakeAuthApi +import de.markusressel.mkdocseditor.auth.InMemoryTokenStore +import de.markusressel.mkdocseditor.auth.api.ServerFeature +import de.markusressel.mkdocseditor.auth.api.ServerInfo +import de.markusressel.mkdocseditor.auth.domain.AuthRepository +import de.markusressel.mkdocseditor.feature.common.data.ServerFeatures +import de.markusressel.mkdocseditor.auth.token.AuthSession +import de.markusressel.mkdocseditor.feature.auth.FakeAuthBackends +import de.markusressel.mkdocseditor.feature.auth.backendConfig +import de.markusressel.mkdocsrestclient.DummyMkDocsRestClient +import de.markusressel.mkdocsrestclient.IMkDocsRestClient +import de.markusressel.mkdocsrestclient.history.ChangeAuthorModel +import de.markusressel.mkdocsrestclient.history.DiffHunkModel +import de.markusressel.mkdocsrestclient.history.DocumentChangesModel +import de.markusressel.mkdocsrestclient.history.SeenMarkModel +import de.markusressel.mkdocsrestclient.history.SeenModel +import kotlinx.coroutines.test.runTest +import java.net.URL +import java.util.Date +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull + +class SeenChangesUseCaseTest { + + private val hunk = DiffHunkModel(heading = "Setup", oldStart = 1, oldLines = 1, newStart = 1, newLines = 1) + private val alice = ChangeAuthorModel(accountId = "a1", username = "alice", displayName = "Alice") + private val carol = ChangeAuthorModel(accountId = "a3", username = "carol", displayName = "Carol") + + private var answer: Result = Result.success(changes(listOf(alice))) + private val seen = mutableListOf() + + private fun changes(authors: List, since: SeenMarkModel? = SeenMarkModel(Date(0), "old")) = + DocumentChangesModel(since = since, seenToken = "now", authors = authors, hunks = if (authors.isEmpty()) emptyList() else listOf(hunk)) + + private val client = object : IMkDocsRestClient by DummyMkDocsRestClient() { + override suspend fun getDocumentChanges(documentId: String, since: String?) = answer + + override suspend fun putDocumentSeen(documentId: String, seenToken: String): Result { + seen += seenToken + return Result.success(SeenModel(Date(), seenToken)) + } + } + + private var serverFeatures = listOf(ServerFeature.CHANGES) + private val backends = FakeAuthBackends().apply { + configs += backendConfig(1) + selectedId = 1 + } + private val authRepository = AuthRepository( + InMemoryTokenStore().apply { put(1, AuthSession("t", null, "carol")) }, + { FakeAuthApi().apply { onServerInfo = { ServerInfo(name = "Wiki", features = serverFeatures) } } }, + deviceName = "Pixel 8", + ) + private val useCase = SeenChangesUseCase(client, backends, authRepository, ServerFeatures(backends, authRepository)) + + @Test + fun `changes of someone else are told, and the page counts as seen with the token of the answer`() = runTest { + val changes = useCase.open("d1") + + assertEquals(listOf(alice), changes?.authors) + assertEquals(listOf("now"), seen) + } + + @Test + fun `the own edits are no news, those of an own agent are`() = runTest { + answer = Result.success(changes(listOf(carol))) + assertNull(useCase.open("d1")) + + answer = Result.success(changes(listOf(carol.copy(agents = listOf("Claude Code"))))) + assertEquals("Claude Code", useCase.open("d1")?.authors?.single()?.agents?.single()) + } + + @Test + fun `the account itself is left out of the names, next to someone else`() = runTest { + answer = Result.success(changes(listOf(carol, alice))) + + assertEquals(listOf(alice), useCase.open("d1")?.authors) + } + + @Test + fun `a page seen for the first time has no news, but is marked`() = runTest { + answer = Result.success(DocumentChangesModel(since = null, seenToken = "now")) + + assertNull(useCase.open("d1")) + assertEquals(listOf("now"), seen) + } + + @Test + fun `an unchanged page has no news`() = runTest { + answer = Result.success(changes(emptyList())) + + assertNull(useCase.open("d1")) + } + + @Test + fun `a server without the endpoint tells nothing and marks nothing`() = runTest { + answer = Result.error(FuelError.wrap(RuntimeException("404"), Response(URL("http://localhost/"), statusCode = 404))) + + assertNull(useCase.open("d1")) + useCase.leave("d1") + assertEquals(emptyList(), seen) + } + + @Test + fun `a server without the changes feature is not asked`() = runTest { + serverFeatures = emptyList() + var asked = false + val useCase = SeenChangesUseCase( + object : IMkDocsRestClient by client { + override suspend fun getDocumentChanges(documentId: String, since: String?): Result { + asked = true + return answer + } + }, + backends, authRepository, ServerFeatures(backends, authRepository), + ) + + assertNull(useCase.open("d1")) + useCase.leave("d1") + assertEquals(false, asked) + assertEquals(emptyList(), seen) + } + + @Test + fun `leaving the page marks it as it is now`() = runTest { + useCase.leave("d1") + + assertEquals(listOf("now"), seen) + } +} diff --git a/app/src/test/java/de/markusressel/mkdocseditor/feature/history/domain/WordDiffTest.kt b/app/src/test/java/de/markusressel/mkdocseditor/feature/history/domain/WordDiffTest.kt new file mode 100644 index 00000000..f82dee76 --- /dev/null +++ b/app/src/test/java/de/markusressel/mkdocseditor/feature/history/domain/WordDiffTest.kt @@ -0,0 +1,42 @@ +package de.markusressel.mkdocseditor.feature.history.domain + +import de.markusressel.mkdocsrestclient.history.DiffLineModel +import de.markusressel.mkdocsrestclient.history.DiffOp +import kotlin.test.Test +import kotlin.test.assertEquals + +class WordDiffTest { + + @Test + fun `only the changed words of a line are marked`() { + val changes = wordChanges("Install the app on your phone.", "Install the new app on the phone.") + + assertEquals(listOf(Highlight(19, 23)), changes.removed) + assertEquals(listOf(Highlight(12, 16), Highlight(23, 26)), changes.added) + } + + @Test + fun `lines with little in common get no marks`() { + assertEquals(WordChanges(emptyList(), emptyList()), wordChanges("Then reboot.", "Wait for it to finish.")) + assertEquals(listOf(Highlight(5, 12)), wordChanges("Some text.", "Some better text.").added) + } + + @Test + fun `an emptied line is marked as a whole`() { + assertEquals(WordChanges(listOf(Highlight(0, 3)), emptyList()), wordChanges("abc", "")) + } + + @Test + fun `removed lines pair with the added lines after them, in order`() { + val lines = listOf( + DiffLineModel(DiffOp.CONTEXT, "a"), + DiffLineModel(DiffOp.REMOVED, "b"), + DiffLineModel(DiffOp.REMOVED, "c"), + DiffLineModel(DiffOp.ADDED, "B"), + DiffLineModel(DiffOp.CONTEXT, "d"), + DiffLineModel(DiffOp.ADDED, "e"), + ) + + assertEquals(listOf(null, 3, null, 1, null, null), pairChangedLines(lines)) + } +} diff --git a/app/src/test/java/de/markusressel/mkdocseditor/feature/history/ui/HistoryViewModelTest.kt b/app/src/test/java/de/markusressel/mkdocseditor/feature/history/ui/HistoryViewModelTest.kt new file mode 100644 index 00000000..a4e48641 --- /dev/null +++ b/app/src/test/java/de/markusressel/mkdocseditor/feature/history/ui/HistoryViewModelTest.kt @@ -0,0 +1,267 @@ +package de.markusressel.mkdocseditor.feature.history.ui + +import com.github.kittinunf.fuel.core.FuelError +import com.github.kittinunf.fuel.core.Response +import com.github.kittinunf.fuel.core.requests.DefaultBody +import com.github.kittinunf.result.Result +import de.markusressel.mkdocseditor.R +import de.markusressel.mkdocseditor.feature.editor.domain.ChangeLocation +import de.markusressel.mkdocseditor.feature.history.ui.HistoryViewModel.DiffState +import de.markusressel.mkdocseditor.feature.history.ui.HistoryViewModel.HistoryEvent +import de.markusressel.mkdocseditor.feature.history.ui.HistoryViewModel.UiEvent +import de.markusressel.mkdocsrestclient.DummyMkDocsRestClient +import de.markusressel.mkdocsrestclient.IMkDocsRestClient +import de.markusressel.mkdocsrestclient.history.DiffHunkModel +import de.markusressel.mkdocsrestclient.history.DiffLineModel +import de.markusressel.mkdocsrestclient.history.DiffOp +import de.markusressel.mkdocsrestclient.history.HistoryAuthorModel +import de.markusressel.mkdocsrestclient.history.HistoryDiffModel +import de.markusressel.mkdocsrestclient.history.HistoryEntryModel +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.test.setMain +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import java.io.ByteArrayInputStream +import java.net.URL +import java.util.Date +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull + +@OptIn(ExperimentalCoroutinesApi::class) +class HistoryViewModelTest { + + private val anna = HistoryAuthorModel("anna", "anna@mkdocseditor.invalid", "anna", "a1") + private fun entry(revision: String) = HistoryEntryModel(revision, Date(0), anna, emptyList(), "Update a.md", "a.md") + + private val hunk = DiffHunkModel( + heading = "Setup", headingOccurrence = 1, oldStart = 3, oldLines = 1, newStart = 3, newLines = 1, + lines = listOf(DiffLineModel(DiffOp.REMOVED, "a"), DiffLineModel(DiffOp.ADDED, "b")), + ) + + private var history: Result, FuelError> = Result.success(listOf(entry("c"), entry("b"), entry("a"))) + private val diffRequests = mutableListOf>() + private val restored = mutableListOf() + private val reverted = mutableListOf() + private var revertAnswer: Result = Result.success(entry("d")) + private val restoredSections = mutableListOf>() + private var sectionAnswer: Result = Result.success("") + private var historyRequests = 0 + private val events = mutableListOf() + + private val client = object : IMkDocsRestClient by DummyMkDocsRestClient() { + override suspend fun getDocumentHistory(documentId: String, limit: Int): Result, FuelError> { + historyRequests++ + return history + } + + override suspend fun getDocumentRevisionDiffHunks(documentId: String, from: String, to: String): Result { + diffRequests += from to to + return Result.success(HistoryDiffModel(from, to, listOf(hunk))) + } + + override suspend fun revertDocumentRevision(documentId: String, revision: String): Result { + reverted += revision + return revertAnswer + } + + override suspend fun restoreDocumentRevision(documentId: String, revision: String): Result { + restored += revision + return Result.success("") + } + + override suspend fun restoreDocumentSection( + documentId: String, + revision: String, + heading: String, + headingOccurrence: Int, + ): Result { + restoredSections += Triple(revision, heading, headingOccurrence) + return sectionAnswer + } + } + + @BeforeEach + fun setUp() = Dispatchers.setMain(UnconfinedTestDispatcher()) + + @AfterEach + fun tearDown() = Dispatchers.resetMain() + + private fun TestScope.viewModel(canRestore: Boolean = true) = HistoryViewModel(client).also { viewModel -> + backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { viewModel.events.collect { events += it } } + viewModel.initialize("d1", canRestore, canRevert = true) + } + + @Test + fun `the history of the document is listed newest first`() = runTest { + val viewModel = viewModel() + + assertEquals(listOf("c", "b", "a"), viewModel.uiState.value.entries.map { it.revision }) + assertEquals(false, viewModel.uiState.value.loading) + } + + @Test + fun `a history that fails to load says why and loads again on retry`() = runTest { + history = Result.error(FuelError.wrap(RuntimeException("404"), Response(URL("http://localhost/"), statusCode = 404))) + val viewModel = viewModel() + assertEquals(R.string.error_not_found, viewModel.uiState.value.problem) + + history = Result.success(listOf(entry("a"))) + viewModel.onUiEvent(UiEvent.RetryClicked) + + assertNull(viewModel.uiState.value.problem) + assertEquals(listOf("a"), viewModel.uiState.value.entries.map { it.revision }) + } + + @Test + fun `an entry shows the diff from the commit before it, and closes on a second tap`() = runTest { + val viewModel = viewModel() + + viewModel.onUiEvent(UiEvent.EntryClicked("b")) + + assertEquals(listOf("a" to "b"), diffRequests) + assertEquals(DiffState.Loaded(listOf(hunk)), viewModel.uiState.value.diffs["b"]) + assertEquals("b", viewModel.uiState.value.expanded) + + viewModel.onUiEvent(UiEvent.EntryClicked("b")) + viewModel.onUiEvent(UiEvent.EntryClicked("b")) + + assertEquals(1, diffRequests.size, "a loaded diff is not asked for again") + } + + @Test + fun `the first version has nothing to compare with`() = runTest { + val viewModel = viewModel() + + viewModel.onUiEvent(UiEvent.EntryClicked("a")) + + assertEquals(DiffState.FirstVersion, viewModel.uiState.value.diffs["a"]) + assertEquals(emptyList(), diffRequests) + } + + @Test + fun `a hunk opens the editor at its section`() = runTest { + val viewModel = viewModel() + + viewModel.onUiEvent(UiEvent.HunkClicked(hunk)) + + assertEquals(listOf(HistoryEvent.OpenInEditor(ChangeLocation(listOf("Setup")))), events) + } + + @Test + fun `a version comes back only after confirming, and the history reloads`() = runTest { + val viewModel = viewModel() + viewModel.onUiEvent(UiEvent.RestoreClicked(entry("b"))) + assertEquals(emptyList(), restored) + + viewModel.onUiEvent(UiEvent.Confirmed) + + assertEquals(listOf("b"), restored) + assertNull(viewModel.uiState.value.confirm) + assertEquals(2, historyRequests) + assertEquals(listOf(HistoryEvent.Message(R.string.history_restored)), events) + } + + @Test + fun `a dismissed restore changes nothing`() = runTest { + val viewModel = viewModel() + viewModel.onUiEvent(UiEvent.RestoreClicked(entry("b"))) + + viewModel.onUiEvent(UiEvent.ConfirmDismissed) + viewModel.onUiEvent(UiEvent.Confirmed) + + assertEquals(emptyList(), restored) + } + + private fun conflict(body: String): Result = Result.error( + FuelError.wrap( + RuntimeException("409"), + Response( + url = URL("http://localhost/"), + statusCode = 409, + body = DefaultBody.from({ ByteArrayInputStream(body.toByteArray()) }, { body.length.toLong() }), + ), + ) + ) + + @Test + fun `a change is undone after confirming, and the history reloads`() = runTest { + val viewModel = viewModel() + viewModel.onUiEvent(UiEvent.UndoClicked(entry("b"))) + assertEquals(emptyList(), reverted) + + viewModel.onUiEvent(UiEvent.Confirmed) + + assertEquals(listOf("b"), reverted) + assertEquals(emptyList(), restored) + assertEquals(2, historyRequests) + assertEquals(listOf(HistoryEvent.Message(R.string.history_undone)), events) + } + + @Test + fun `an undo in the way of later changes names their sections`() = runTest { + // the answer of a real backend (MkDocsEditor-Backend#99) + revertAnswer = conflict( + """{"name":"Conflict","code":"revert-conflict","message":"later edits changed the same lines, edit the document by hand",""" + + """"details":{"conflicts":[{"heading":"Setup","headingOccurrence":1,"line":3}],"headings":["Setup"]}}""" + ) + val viewModel = viewModel() + viewModel.onUiEvent(UiEvent.UndoClicked(entry("b"))) + viewModel.onUiEvent(UiEvent.Confirmed) + + assertEquals(listOf(HistoryEvent.UndoConflict(listOf("Setup"))), events) + assertEquals(1, historyRequests) + } + + @Test + fun `an undo of a change that is gone says so`() = runTest { + revertAnswer = conflict("""{"name":"Conflict","code":"nothing-to-revert","message":"the change of this revision is not in the document anymore"}""") + val viewModel = viewModel() + viewModel.onUiEvent(UiEvent.UndoClicked(entry("b"))) + viewModel.onUiEvent(UiEvent.Confirmed) + + assertEquals(listOf(HistoryEvent.Message(R.string.history_undo_nothing)), events) + } + + @Test + fun `a section comes back after confirming, and the history reloads`() = runTest { + val viewModel = viewModel() + viewModel.onUiEvent(UiEvent.RestoreSectionClicked(entry("b"), hunk.copy(headingOccurrence = 2))) + + assertEquals(emptyList(), restoredSections, "not before confirming") + viewModel.onUiEvent(UiEvent.Confirmed) + + assertEquals(listOf(Triple("b", "Setup", 2)), restoredSections) + assertEquals(emptyList(), restored) + assertEquals(2, historyRequests) + assertEquals(listOf(HistoryEvent.Message(R.string.history_section_restored)), events) + } + + @Test + fun `a hunk above the first heading has no section to restore`() = runTest { + val viewModel = viewModel() + viewModel.onUiEvent(UiEvent.RestoreSectionClicked(entry("b"), hunk.copy(heading = null))) + + assertNull(viewModel.uiState.value.confirm) + } + + @Test + fun `a section that is gone from the page says so`() = runTest { + // the answer of a real backend (MkDocsEditor-Backend#101) has "revision" here, the other case is "current" + sectionAnswer = conflict( + """{"name":"Conflict","code":"section-not-found","message":"the document has no such section","details":{"in":"current"}}""" + ) + val viewModel = viewModel() + viewModel.onUiEvent(UiEvent.RestoreSectionClicked(entry("b"), hunk)) + viewModel.onUiEvent(UiEvent.Confirmed) + + assertEquals(listOf(HistoryEvent.SectionMissing("Setup", inRevision = false)), events) + assertEquals(1, historyRequests) + } +} diff --git a/app/src/test/java/de/markusressel/mkdocseditor/feature/history/ui/compose/ChangesSinceSeenTest.kt b/app/src/test/java/de/markusressel/mkdocseditor/feature/history/ui/compose/ChangesSinceSeenTest.kt new file mode 100644 index 00000000..c0c7fb12 --- /dev/null +++ b/app/src/test/java/de/markusressel/mkdocseditor/feature/history/ui/compose/ChangesSinceSeenTest.kt @@ -0,0 +1,53 @@ +package de.markusressel.mkdocseditor.feature.history.ui.compose + +import android.app.Application +import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.test.onNodeWithContentDescription +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.test.ext.junit.runners.AndroidJUnit4 +import de.markusressel.mkdocseditor.feature.theme.MkDocsEditorTheme +import de.markusressel.mkdocsrestclient.history.ChangeAuthorModel +import de.markusressel.mkdocsrestclient.history.DocumentChangesModel +import de.markusressel.mkdocsrestclient.history.HistorySummaryModel +import de.markusressel.mkdocsrestclient.history.SeenMarkModel +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.annotation.Config +import java.util.Date +import kotlin.test.assertEquals + +@RunWith(AndroidJUnit4::class) +@Config(application = Application::class, sdk = [36]) +class ChangesSinceSeenTest { + + @get:Rule + val composeRule = createComposeRule() + + private val changes = DocumentChangesModel( + since = SeenMarkModel(Date(0), "a"), + seenToken = "b", + authors = listOf( + ChangeAuthorModel(displayName = "Alice"), + ChangeAuthorModel(displayName = "Bob", agents = listOf("Claude Code")), + ), + summary = HistorySummaryModel(2, 1, listOf("Setup", "Install")), + ) + + @Test + fun `the banner names who changed the page and where, and opens or hides`() { + val clicks = mutableListOf() + composeRule.setContent { + MkDocsEditorTheme { + ChangesSinceSeenBanner(changes, onClick = { clicks += "open" }, onDismiss = { clicks += "hide" }) + } + } + + composeRule.onNodeWithText("Changed by Alice, Bob via Claude Code since you were here").performClick() + composeRule.onNodeWithText("Setup, Install").assertExists() + composeRule.onNodeWithContentDescription("Hide").performClick() + + assertEquals(listOf("open", "hide"), clicks) + } +} diff --git a/app/src/test/java/de/markusressel/mkdocseditor/feature/history/ui/compose/HistoryScreenContentTest.kt b/app/src/test/java/de/markusressel/mkdocseditor/feature/history/ui/compose/HistoryScreenContentTest.kt new file mode 100644 index 00000000..bac073da --- /dev/null +++ b/app/src/test/java/de/markusressel/mkdocseditor/feature/history/ui/compose/HistoryScreenContentTest.kt @@ -0,0 +1,183 @@ +package de.markusressel.mkdocseditor.feature.history.ui.compose + +import android.app.Application +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.semantics.SemanticsActions +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performSemanticsAction +import androidx.test.ext.junit.runners.AndroidJUnit4 +import cafe.adriel.voyager.core.screen.Screen +import cafe.adriel.voyager.navigator.Navigator +import de.markusressel.mkdocseditor.feature.history.ui.HistoryViewModel.DiffState +import de.markusressel.mkdocseditor.feature.history.ui.HistoryViewModel.UiEvent +import de.markusressel.mkdocseditor.feature.history.ui.HistoryViewModel.UiState +import de.markusressel.mkdocseditor.feature.theme.MkDocsEditorTheme +import de.markusressel.mkdocsrestclient.history.DiffHunkModel +import de.markusressel.mkdocsrestclient.history.DiffLineModel +import de.markusressel.mkdocsrestclient.history.DiffOp +import de.markusressel.mkdocsrestclient.history.HistoryAgentModel +import de.markusressel.mkdocsrestclient.history.HistoryAuthorModel +import de.markusressel.mkdocsrestclient.history.HistoryEntryModel +import de.markusressel.mkdocsrestclient.history.HistorySummaryModel +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.annotation.Config +import java.util.Date +import kotlin.test.assertEquals + +@RunWith(AndroidJUnit4::class) +@Config(application = Application::class, sdk = [36]) +class HistoryScreenContentTest { + + @get:Rule + val composeRule = createComposeRule() + + private val anna = HistoryAuthorModel("anna", "anna@mkdocseditor.invalid", "anna", "a1", "Anna", "#1971c2") + private val bob = HistoryAuthorModel("bob", "bob@mkdocseditor.invalid", "bob", "a2", "Bob") + private val hunk = DiffHunkModel( + heading = "Install", headingOccurrence = 1, oldStart = 3, oldLines = 1, newStart = 3, newLines = 1, + lines = listOf(DiffLineModel(DiffOp.REMOVED, "old line"), DiffLineModel(DiffOp.ADDED, "new line")), + ) + private val entries = listOf( + HistoryEntryModel( + revision = "b", time = Date(), author = anna, coAuthors = listOf(bob), message = "Update a.md", path = "a.md", + agents = listOf(HistoryAgentModel("Claude Code", "a2")), summary = HistorySummaryModel(1, 1, listOf("Install")), + ), + HistoryEntryModel(revision = "a", time = Date(0), author = anna, message = "Restore a.md to 0123456789ab", path = "a.md"), + ) + + /** the top bar goes back through the navigator, so the content needs one */ + @Composable + private fun Shown(content: @Composable () -> Unit) { + val screen = remember { + object : Screen { + override val key = "history" + + @Composable + override fun Content() = MkDocsEditorTheme { content() } + } + } + Navigator(screen) + } + + @Test + fun `an entry names its people and agents, its changes and an unusual message`() { + composeRule.setContent { + Shown { HistoryScreenContent(UiState(loading = false, entries = entries), onUiEvent = {}) } + } + + composeRule.onNodeWithText("Anna, Bob via Claude Code").assertExists() + composeRule.onNodeWithText("Anna via Claude Code, Bob").assertDoesNotExist() + composeRule.onNodeWithText("+1 −1 · Install", substring = true).assertExists() + composeRule.onNodeWithText("Restore a.md to 0123456789ab").assertExists() + composeRule.onNodeWithText("Update a.md").assertDoesNotExist() + } + + @Test + fun `an open entry shows its hunks, and a hunk opens the editor`() { + val events = mutableListOf() + composeRule.setContent { + Shown { + HistoryScreenContent( + UiState(loading = false, entries = entries, expanded = "a", diffs = mapOf("a" to DiffState.Loaded(listOf(hunk))), canRestore = true), + onUiEvent = { events += it }, + ) + } + } + + composeRule.onNodeWithText("+ new line").assertExists() + composeRule.onNodeWithText("− old line").assertExists() + composeRule.onNodeWithText("Install").performClick() + composeRule.onNodeWithText("Restore this version").performClick() + + assertEquals(listOf(UiEvent.HunkClicked(hunk), UiEvent.RestoreClicked(entries[1])), events) + } + + @Test + fun `editors on a server with revert can undo a change, but not the first version`() { + val events = mutableListOf() + composeRule.setContent { + Shown { + HistoryScreenContent( + UiState( + loading = false, entries = entries, expanded = "b", + diffs = mapOf("b" to DiffState.Loaded(listOf(hunk)), "a" to DiffState.FirstVersion), canRevert = true, + ), + onUiEvent = { events += it }, + ) + } + } + + composeRule.onNodeWithText("Undo this change").performClick() + assertEquals(listOf(UiEvent.UndoClicked(entries[0])), events) + } + + @Test + fun `the first version can not be undone`() { + composeRule.setContent { + Shown { + HistoryScreenContent( + UiState(loading = false, entries = entries, expanded = "a", diffs = mapOf("a" to DiffState.FirstVersion), canRevert = true), + onUiEvent = {}, + ) + } + } + + composeRule.onNodeWithText("Undo this change").assertDoesNotExist() + } + + @Test + fun `the newest entry can not be restored, it is the text as it is`() { + composeRule.setContent { + Shown { + HistoryScreenContent( + UiState(loading = false, entries = entries, expanded = "b", diffs = mapOf("b" to DiffState.Loaded(listOf(hunk))), canRestore = true), + onUiEvent = {}, + ) + } + } + + composeRule.onNodeWithText("Restore this version").assertDoesNotExist() + } + + @Test + fun `a hunk of an older version can restore its section, but not above the first heading`() { + val top = hunk.copy(heading = null, lines = listOf(DiffLineModel(DiffOp.ADDED, "intro"))) + val older = entries + HistoryEntryModel(revision = "0", time = Date(0), author = anna, message = "Initial", path = "a.md") + val events = mutableListOf() + composeRule.setContent { + Shown { + HistoryScreenContent( + UiState( + loading = false, entries = older, expanded = "a", + diffs = mapOf("a" to DiffState.Loaded(listOf(top, hunk))), canRestoreSection = true, + ), + onUiEvent = { events += it }, + ) + } + } + + // below the small test window, so clicked through its semantics + composeRule.onNodeWithText("Restore “Install”").performSemanticsAction(SemanticsActions.OnClick) + assertEquals(listOf(UiEvent.RestoreSectionClicked(older[1], hunk)), events) + composeRule.onNodeWithText("Restore “”").assertDoesNotExist() + } + + @Test + fun `the newest entry has no section to restore`() { + composeRule.setContent { + Shown { + HistoryScreenContent( + UiState(loading = false, entries = entries, expanded = "b", diffs = mapOf("b" to DiffState.Loaded(listOf(hunk))), canRestoreSection = true), + onUiEvent = {}, + ) + } + } + + composeRule.onNodeWithText("Restore “Install”").assertDoesNotExist() + } +} diff --git a/app/src/test/java/de/markusressel/mkdocseditor/feature/history/ui/compose/LineAuthorSheetTest.kt b/app/src/test/java/de/markusressel/mkdocseditor/feature/history/ui/compose/LineAuthorSheetTest.kt new file mode 100644 index 00000000..717035d4 --- /dev/null +++ b/app/src/test/java/de/markusressel/mkdocseditor/feature/history/ui/compose/LineAuthorSheetTest.kt @@ -0,0 +1,61 @@ +package de.markusressel.mkdocseditor.feature.history.ui.compose + +import android.app.Application +import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.test.ext.junit.runners.AndroidJUnit4 +import de.markusressel.mkdocseditor.feature.theme.MkDocsEditorTheme +import de.markusressel.mkdocsrestclient.dashboard.FeedAuthorModel +import de.markusressel.mkdocsrestclient.history.BlameBlockModel +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.annotation.Config +import java.util.Date +import kotlin.test.assertEquals + +@RunWith(AndroidJUnit4::class) +@Config(application = Application::class, sdk = [36]) +class LineAuthorSheetTest { + + @get:Rule + val composeRule = createComposeRule() + + private val bob = FeedAuthorModel(accountId = "a2", username = "bob", displayName = "Bob", color = "#2f9e44") + + @Test + fun `committed lines name their author, the time and a message of its own`() { + var historyOpened = 0 + val block = BlameBlockModel( + start = 7, end = 9, revision = "r", time = Date(), message = "Restore section \"Install\" of a.md to bde4a3c", + author = bob, + ) + composeRule.setContent { MkDocsEditorTheme { LineAuthorContent(block, onOpenHistory = { historyOpened++ }) } } + + composeRule.onNodeWithText("Lines 7–9").assertExists() + composeRule.onNodeWithText("Bob").assertExists() + composeRule.onNodeWithText("just now").assertExists() + composeRule.onNodeWithText("Restore section \"Install\" of a.md to bde4a3c").assertExists() + composeRule.onNodeWithText("History").performClick() + assertEquals(1, historyOpened) + } + + @Test + fun `pending lines of an agent have no time, and the standard message is left out`() { + val pending = BlameBlockModel(start = 12, end = 12, pending = true, author = bob, agents = listOf("Claude Code")) + val standard = BlameBlockModel(start = 1, end = 1, revision = "r", time = Date(0), message = "Update guide/setup.md", author = bob) + composeRule.setContent { + MkDocsEditorTheme { + LineAuthorContent(pending, onOpenHistory = null) + LineAuthorContent(standard, onOpenHistory = null) + } + } + + composeRule.onNodeWithText("Line 12").assertExists() + composeRule.onNodeWithText("Bob via Claude Code").assertExists() + composeRule.onNodeWithText("Not saved in the history yet").assertExists() + composeRule.onNodeWithText("Update guide/setup.md").assertDoesNotExist() + composeRule.onNodeWithText("History").assertDoesNotExist() + } +} diff --git a/auth/src/main/java/de/markusressel/mkdocseditor/auth/api/Models.kt b/auth/src/main/java/de/markusressel/mkdocseditor/auth/api/Models.kt index e157dee0..14097ebe 100644 --- a/auth/src/main/java/de/markusressel/mkdocseditor/auth/api/Models.kt +++ b/auth/src/main/java/de/markusressel/mkdocseditor/auth/api/Models.kt @@ -222,6 +222,18 @@ object ServerFeature { const val AVATARS = "avatars" const val PUSH = "push" const val QR_CODES = "qr-codes" + + /** `GET /document/{id}/changes/` and `PUT /document/{id}/seen/` */ + const val CHANGES = "changes" + + /** the revision history with summaries, agents and diffs as JSON; needs git on the server */ + const val HISTORY = "history" + + /** `POST /document/{id}/history/{revision}/revert/` */ + const val REVERT = "revert" + + /** `GET /document/{id}/blame/` and the restore of a single section */ + const val BLAME = "blame" } /** POST /auth/access-requests/. The token is only shown once. */ diff --git a/rest/src/main/java/de/markusressel/mkdocsrestclient/DummyMkDocsRestClient.kt b/rest/src/main/java/de/markusressel/mkdocsrestclient/DummyMkDocsRestClient.kt index 252a831d..4609c98f 100644 --- a/rest/src/main/java/de/markusressel/mkdocsrestclient/DummyMkDocsRestClient.kt +++ b/rest/src/main/java/de/markusressel/mkdocsrestclient/DummyMkDocsRestClient.kt @@ -3,6 +3,11 @@ package de.markusressel.mkdocsrestclient import de.markusressel.mkdocsrestclient.dashboard.FeedPageModel +import de.markusressel.mkdocsrestclient.history.BlameModel +import de.markusressel.mkdocsrestclient.history.DocumentChangesModel +import de.markusressel.mkdocsrestclient.history.HistoryDiffModel +import de.markusressel.mkdocsrestclient.history.SeenModel +import de.markusressel.mkdocsrestclient.history.HistoryEntryModel import de.markusressel.mkdocsrestclient.dashboard.PinScope import de.markusressel.mkdocsrestclient.dashboard.PinsModel import de.markusressel.mkdocsrestclient.reference.AuthorshipModel @@ -275,6 +280,40 @@ class DummyMkDocsRestClient : IMkDocsRestClient { override suspend fun getFeed(before: String?, limit: Int): Result = Result.success(FeedPageModel()) + override suspend fun getDocumentHistory(documentId: String, limit: Int): Result, FuelError> = + Result.success(emptyList()) + + override suspend fun getDocumentRevisionContent(documentId: String, revision: String): Result = + Result.success("") + + override suspend fun getDocumentRevisionDiff(documentId: String, from: String, to: String): Result = + Result.success("") + + override suspend fun getDocumentRevisionDiffHunks(documentId: String, from: String, to: String): Result = + Result.success(HistoryDiffModel(from, to)) + + override suspend fun getDocumentChanges(documentId: String, since: String?): Result = + Result.success(DocumentChangesModel(seenToken = "")) + + override suspend fun putDocumentSeen(documentId: String, seenToken: String): Result = + Result.success(SeenModel(Date(), seenToken)) + + override suspend fun revertDocumentRevision(documentId: String, revision: String): Result = + Result.error(FuelError.wrap(UnsupportedOperationException())) + + override suspend fun restoreDocumentRevision(documentId: String, revision: String): Result = + Result.success("") + + override suspend fun restoreDocumentSection( + documentId: String, + revision: String, + heading: String, + headingOccurrence: Int, + ): Result = Result.success("") + + override suspend fun getDocumentBlame(documentId: String): Result = + Result.success(BlameModel(revision = "", lines = 0)) + override suspend fun getQrCode(key: String, scan: Boolean): Result = Result.error(FuelError.wrap(UnsupportedOperationException("not in the demo"))) diff --git a/rest/src/main/java/de/markusressel/mkdocsrestclient/IMkDocsRestClient.kt b/rest/src/main/java/de/markusressel/mkdocsrestclient/IMkDocsRestClient.kt index c5463eea..cccbbe25 100644 --- a/rest/src/main/java/de/markusressel/mkdocsrestclient/IMkDocsRestClient.kt +++ b/rest/src/main/java/de/markusressel/mkdocsrestclient/IMkDocsRestClient.kt @@ -4,6 +4,7 @@ import com.github.kittinunf.fuel.core.FuelError import com.github.kittinunf.result.Result import de.markusressel.mkdocsrestclient.dashboard.DashboardApi import de.markusressel.mkdocsrestclient.document.DocumentApi +import de.markusressel.mkdocsrestclient.history.HistoryApi import de.markusressel.mkdocsrestclient.mkdocs.MkDocsApi import de.markusressel.mkdocsrestclient.qr.QrCodeApi import de.markusressel.mkdocsrestclient.reference.ReferenceApi @@ -11,7 +12,8 @@ import de.markusressel.mkdocsrestclient.resource.ResourceApi import de.markusressel.mkdocsrestclient.section.SectionApi import de.markusressel.mkdocsrestclient.section.SectionModel -interface IMkDocsRestClient : MkDocsApi, SectionApi, DocumentApi, ResourceApi, ReferenceApi, DashboardApi, QrCodeApi { +interface IMkDocsRestClient : MkDocsApi, SectionApi, DocumentApi, ResourceApi, ReferenceApi, DashboardApi, QrCodeApi, + HistoryApi { /** * Check if the server is alive and reachable diff --git a/rest/src/main/java/de/markusressel/mkdocsrestclient/MkDocsRestClient.kt b/rest/src/main/java/de/markusressel/mkdocsrestclient/MkDocsRestClient.kt index 87994de7..0dd9b082 100644 --- a/rest/src/main/java/de/markusressel/mkdocsrestclient/MkDocsRestClient.kt +++ b/rest/src/main/java/de/markusressel/mkdocsrestclient/MkDocsRestClient.kt @@ -7,6 +7,8 @@ import de.markusressel.mkdocsrestclient.dashboard.DashboardApi import de.markusressel.mkdocsrestclient.dashboard.DashboardApiImpl import de.markusressel.mkdocsrestclient.document.DocumentApi import de.markusressel.mkdocsrestclient.document.DocumentApiImpl +import de.markusressel.mkdocsrestclient.history.HistoryApi +import de.markusressel.mkdocsrestclient.history.HistoryApiImpl import de.markusressel.mkdocsrestclient.mkdocs.MkDocsApi import de.markusressel.mkdocsrestclient.mkdocs.MkDocsApiImpl import de.markusressel.mkdocsrestclient.qr.QrCodeApi @@ -33,6 +35,7 @@ class MkDocsRestClient constructor( referenceApi: ReferenceApi = ReferenceApiImpl(requestManager), dashboardApi: DashboardApi = DashboardApiImpl(requestManager), qrCodeApi: QrCodeApi = QrCodeApiImpl(requestManager), + historyApi: HistoryApi = HistoryApiImpl(requestManager), ) : IMkDocsRestClient, MkDocsApi by mkDocsApi, SectionApi by sectionApi, @@ -40,7 +43,8 @@ class MkDocsRestClient constructor( ResourceApi by resourceApi, ReferenceApi by referenceApi, DashboardApi by dashboardApi, - QrCodeApi by qrCodeApi { + QrCodeApi by qrCodeApi, + HistoryApi by historyApi { override suspend fun isHostAlive(): Result { return requestManager.doStatusRequest("/alive/", Method.GET) diff --git a/rest/src/main/java/de/markusressel/mkdocsrestclient/history/BlameModels.kt b/rest/src/main/java/de/markusressel/mkdocsrestclient/history/BlameModels.kt new file mode 100644 index 00000000..8d600ae4 --- /dev/null +++ b/rest/src/main/java/de/markusressel/mkdocsrestclient/history/BlameModels.kt @@ -0,0 +1,81 @@ +package de.markusressel.mkdocsrestclient.history + +import com.squareup.moshi.Json +import com.squareup.moshi.JsonClass +import com.squareup.moshi.Moshi +import de.markusressel.mkdocsrestclient.dashboard.FeedAuthorModel +import java.util.Date + +/** + * Who last changed each line of a document, from `GET /document/{id}/blame/` + * + * @param revision the revision of the text the blame belongs to, a seen token; it may be a little behind the live text + * @param lines the line count of that text + * @param blocks consecutive lines of the same commit, or pending lines of the same account and agent, in text order + */ +@JsonClass(generateAdapter = true) +data class BlameModel( + val revision: String, + val lines: Int, + val blocks: List = emptyList(), +) { + /** @param line 1-based */ + fun blockAt(line: Int): BlameBlockModel? = blocks.firstOrNull { line in it.start..it.end } +} + +/** + * @param start the first line, 1-based + * @param end the last line, inclusive + * @param pending lines not committed yet; they have no [revision], [time] or [message] + * @param author the commit's author, for pending lines the one who wrote most of them; null if nobody known did + * @param agents the names of the app tokens (AI agents) the lines were written with + */ +@JsonClass(generateAdapter = true) +data class BlameBlockModel( + val start: Int, + val end: Int, + val pending: Boolean = false, + val revision: String? = null, + val time: Date? = null, + val message: String? = null, + val author: FeedAuthorModel? = null, + val agents: List = emptyList(), +) + +/** The body of a section restore: the section of the heading at its [headingOccurrence], 1 for the first */ +@JsonClass(generateAdapter = true) +data class SectionRestoreRequestModel( + val heading: String, + val headingOccurrence: Int, +) + +/** The error body of a section restore that changed nothing */ +@JsonClass(generateAdapter = true) +data class SectionRestoreErrorModel( + val code: String? = null, + val details: SectionNotFoundModel? = null, +) { + companion object { + const val SECTION_NOT_FOUND = "section-not-found" + + private val adapter by lazy { Moshi.Builder().build().adapter(SectionRestoreErrorModel::class.java) } + + /** the error in a response body, null when the body is not one */ + fun parse(body: ByteArray): SectionRestoreErrorModel? = try { + adapter.fromJson(String(body, Charsets.UTF_8)) + } catch (e: Exception) { + null + } + } +} + +/** @param missingIn which text has no such section: [REVISION] or [CURRENT] */ +@JsonClass(generateAdapter = true) +data class SectionNotFoundModel( + @Json(name = "in") val missingIn: String? = null, +) { + companion object { + const val REVISION = "revision" + const val CURRENT = "current" + } +} diff --git a/rest/src/main/java/de/markusressel/mkdocsrestclient/history/ChangesModels.kt b/rest/src/main/java/de/markusressel/mkdocsrestclient/history/ChangesModels.kt new file mode 100644 index 00000000..2de2cb37 --- /dev/null +++ b/rest/src/main/java/de/markusressel/mkdocsrestclient/history/ChangesModels.kt @@ -0,0 +1,63 @@ +package de.markusressel.mkdocsrestclient.history + +import com.squareup.moshi.JsonClass +import java.util.Date + +/** + * What changed in a document since the signed in account last looked, from `GET /document/{id}/changes/` + * + * @param since when the account last looked, null if it never did: then there are no hunks + * @param seenToken the text this answer is about, to send to `PUT /document/{id}/seen/` once it was shown + * @param hunks against the live text, empty if nothing changed + */ +@JsonClass(generateAdapter = true) +data class DocumentChangesModel( + val since: SeenMarkModel? = null, + val seenToken: String, + val authors: List = emptyList(), + val hunks: List = emptyList(), + val summary: HistorySummaryModel = HistorySummaryModel(), +) { + override fun toString() = "DocumentChangesModel(since=${since?.time}, authors=${authors.size}, hunks=${hunks.size})" +} + +/** The last look of the account at a document */ +@JsonClass(generateAdapter = true) +data class SeenMarkModel( + val time: Date, + val seenToken: String, +) { + override fun toString() = "SeenMarkModel(time=$time)" +} + +/** + * Someone who changed the document, with the current name, color and picture of the account, like in the feed + * + * @param agents the names of the app tokens this account changed the document with + */ +@JsonClass(generateAdapter = true) +data class ChangeAuthorModel( + val accountId: String? = null, + val username: String? = null, + val displayName: String, + val color: String? = null, + val avatar: String? = null, + val agents: List = emptyList(), +) + +/** `PUT /document/{id}/seen/` */ +@JsonClass(generateAdapter = true) +data class SeenRequestModel( + val seenToken: String, +) { + override fun toString() = "SeenRequestModel" +} + +/** The answer of `PUT /document/{id}/seen/` */ +@JsonClass(generateAdapter = true) +data class SeenModel( + val seenAt: Date, + val seenToken: String, +) { + override fun toString() = "SeenModel(seenAt=$seenAt)" +} diff --git a/rest/src/main/java/de/markusressel/mkdocsrestclient/history/HistoryApi.kt b/rest/src/main/java/de/markusressel/mkdocsrestclient/history/HistoryApi.kt new file mode 100644 index 00000000..ecc98441 --- /dev/null +++ b/rest/src/main/java/de/markusressel/mkdocsrestclient/history/HistoryApi.kt @@ -0,0 +1,158 @@ +package de.markusressel.mkdocsrestclient.history + +import com.github.kittinunf.fuel.core.FuelError +import com.github.kittinunf.fuel.core.Method +import com.github.kittinunf.result.Result +import com.github.kittinunf.result.map +import de.markusressel.mkdocsrestclient.RequestKind +import de.markusressel.mkdocsrestclient.RequestManager + +/** Names the live text of a document in a diff */ +const val REVISION_CURRENT = "current" + +/** + * The revision history of a document, from the git history of its file. A backend without `git.enabled` answers 404. + */ +interface HistoryApi { + + /** + * @param limit 1 to 1000 + * @return the commits that touched the document, newest first + */ + suspend fun getDocumentHistory(documentId: String, limit: Int = 100): Result, FuelError> + + /** @return the text of the document at [revision] */ + suspend fun getDocumentRevisionContent(documentId: String, revision: String): Result + + /** + * @param from a revision or [REVISION_CURRENT] + * @param to a revision or [REVISION_CURRENT] + * @return a unified diff, empty if both texts are equal + */ + suspend fun getDocumentRevisionDiff( + documentId: String, + from: String, + to: String = REVISION_CURRENT, + ): Result + + /** The same as [getDocumentRevisionDiff], as hunks with the heading of each one */ + suspend fun getDocumentRevisionDiffHunks( + documentId: String, + from: String, + to: String = REVISION_CURRENT, + ): Result + + /** + * @param since a seen token, null for the last look of the signed in account + * @return what changed since then; a token the document no longer knows answers 409 `unknown-revision` + */ + suspend fun getDocumentChanges(documentId: String, since: String? = null): Result + + /** Marks the text of [seenToken] as seen by the signed in account. A token the document no longer knows answers 409. */ + suspend fun putDocumentSeen(documentId: String, seenToken: String): Result + + /** + * Undoes the changes of one commit in the live text; later changes stay. Editors, admins and write tokens only. + * + * @return the entry of the revert commit. A 409 `revert-conflict` (see [RevertErrorModel]) or `nothing-to-revert` + * changes nothing, 400 is the commit that created the file. + */ + suspend fun revertDocumentRevision(documentId: String, revision: String): Result + + /** Sets the live text to the one of [revision], as an edit of the signed in account. Editors and admins only. */ + suspend fun restoreDocumentRevision(documentId: String, revision: String): Result + + /** + * Sets one section of the live text to the one of [revision]: the heading and the lines below it up to the next + * heading of the same or a higher level. Editors and admins only. A 409 `section-not-found` (see + * [SectionRestoreErrorModel]) changes nothing. + * + * @param headingOccurrence which of the headings with this text, 1 for the first + */ + suspend fun restoreDocumentSection( + documentId: String, + revision: String, + heading: String, + headingOccurrence: Int, + ): Result + + /** @return who last changed each line of the live text */ + suspend fun getDocumentBlame(documentId: String): Result +} + +class HistoryApiImpl( + private val requestManager: RequestManager, +) : HistoryApi { + + override suspend fun getDocumentHistory(documentId: String, limit: Int): Result, FuelError> = + requestManager.doRequest>( + url = "/document/$documentId/history/", + urlParameters = listOf("limit" to limit), + method = Method.GET, + ).map { it.toList() } + + override suspend fun getDocumentRevisionContent(documentId: String, revision: String): Result = + requestManager.doRequest(url = "/document/$documentId/history/$revision/content/", method = Method.GET) + + override suspend fun getDocumentRevisionDiff(documentId: String, from: String, to: String): Result = + requestManager.doRequest( + url = "/document/$documentId/history/diff/", + urlParameters = listOf("from" to from, "to" to to), + method = Method.GET, + ) + + override suspend fun getDocumentRevisionDiffHunks( + documentId: String, + from: String, + to: String, + ): Result = + requestManager.doRequest( + url = "/document/$documentId/history/diff/", + urlParameters = listOf("from" to from, "to" to to, "format" to "json"), + method = Method.GET, + ) + + override suspend fun getDocumentChanges(documentId: String, since: String?): Result = + requestManager.doRequest( + url = "/document/$documentId/changes/", + urlParameters = listOfNotNull(since?.let { "since" to it }), + method = Method.GET, + ) + + override suspend fun putDocumentSeen(documentId: String, seenToken: String): Result = + requestManager.doJsonRequest( + url = "/document/$documentId/seen/", + method = Method.PUT, + jsonData = SeenRequestModel(seenToken), + kind = RequestKind.Quick, + ) + + override suspend fun revertDocumentRevision(documentId: String, revision: String): Result = + requestManager.doRequest( + url = "/document/$documentId/history/$revision/revert/", + method = Method.POST, + kind = RequestKind.LongAction, + ) + + override suspend fun restoreDocumentRevision(documentId: String, revision: String): Result = + requestManager.doRequest( + url = "/document/$documentId/history/$revision/restore/", + method = Method.POST, + kind = RequestKind.LongAction, + ) + + override suspend fun restoreDocumentSection( + documentId: String, + revision: String, + heading: String, + headingOccurrence: Int, + ): Result = + requestManager.doJsonRequest( + url = "/document/$documentId/history/$revision/restore/", + method = Method.POST, + jsonData = SectionRestoreRequestModel(heading, headingOccurrence), + ) + + override suspend fun getDocumentBlame(documentId: String): Result = + requestManager.doRequest(url = "/document/$documentId/blame/", method = Method.GET) +} diff --git a/rest/src/main/java/de/markusressel/mkdocsrestclient/history/HistoryModels.kt b/rest/src/main/java/de/markusressel/mkdocsrestclient/history/HistoryModels.kt new file mode 100644 index 00000000..6e3c9f09 --- /dev/null +++ b/rest/src/main/java/de/markusressel/mkdocsrestclient/history/HistoryModels.kt @@ -0,0 +1,143 @@ +package de.markusressel.mkdocsrestclient.history + +import com.squareup.moshi.Json +import com.squareup.moshi.JsonClass +import com.squareup.moshi.Moshi +import java.util.Date + +/** + * An author of a commit. The backend sends empty strings, not null, for an author who is not an account, like the + * initial import. + * + * @param username the current username of the account + * @param displayName the current name of the account, like in the feed; null from a backend before it + * @param avatar the version of the profile picture, null without one + */ +@JsonClass(generateAdapter = true) +data class HistoryAuthorModel( + val name: String, + val email: String, + val username: String = "", + val accountId: String = "", + val displayName: String? = null, + val color: String? = null, + val avatar: String? = null, +) { + val isAccount: Boolean get() = accountId.isNotEmpty() +} + +/** + * A commit that touched a document, from `GET /document/{id}/history/` + * + * @param revision the full commit hash + * @param path the path of the file in that commit, which differs from today's after a rename + * @param appTokens the names of the app tokens (AI agents) the changes were made with + */ +@JsonClass(generateAdapter = true) +data class HistoryEntryModel( + val revision: String, + val time: Date, + val author: HistoryAuthorModel, + val coAuthors: List = emptyList(), + val message: String, + val path: String, + val appTokens: List = emptyList(), + /** the AI agents the changes were made with, with the account each one belongs to */ + val agents: List = emptyList(), + /** null from a backend before it */ + val summary: HistorySummaryModel? = null, +) + +/** An AI agent that changed a document, with an app token of [accountId] */ +@JsonClass(generateAdapter = true) +data class HistoryAgentModel( + /** the name of the app token */ + val name: String, + val accountId: String = "", +) + +/** @param headings the headings of the changed sections, as in the feed */ +@JsonClass(generateAdapter = true) +data class HistorySummaryModel( + val linesAdded: Int = 0, + val linesRemoved: Int = 0, + val headings: List = emptyList(), +) + +/** `GET /document/{id}/history/diff/?format=json` */ +@JsonClass(generateAdapter = true) +data class HistoryDiffModel( + val from: String, + val to: String, + val hunks: List = emptyList(), +) + +/** + * Changed lines with up to 3 unchanged ones around them + * + * @param heading the heading of the section, as in the feed: computed on the new text, and for lines that were only + * removed the heading above where they were. Null before the first heading. + * @param headingOccurrence which of the headings with this text, from 1 + * @param oldStart the first line in the old text, from 1 + * @param offset [newStart] minus the line of [heading], or [newStart] - 1 without one, as in the feed; null from a + * backend before it + */ +@JsonClass(generateAdapter = true) +data class DiffHunkModel( + val heading: String? = null, + val headingOccurrence: Int = 0, + val oldStart: Int, + val oldLines: Int, + val newStart: Int, + val newLines: Int, + val lines: List = emptyList(), + val offset: Int? = null, +) + +@JsonClass(generateAdapter = true) +data class DiffLineModel( + val op: DiffOp, + val text: String, +) + +enum class DiffOp { + @Json(name = " ") + CONTEXT, + + @Json(name = "-") + REMOVED, + + @Json(name = "+") + ADDED, +} + +/** + * The error body of a revert that changed nothing + * + * @param code `revert-conflict` when later changes touched the same lines, `nothing-to-revert` when the change is gone + */ +@JsonClass(generateAdapter = true) +data class RevertErrorModel( + val code: String? = null, + val details: RevertConflictModel? = null, +) { + companion object { + const val CONFLICT = "revert-conflict" + const val NOTHING_TO_REVERT = "nothing-to-revert" + + private val adapter by lazy { Moshi.Builder().build().adapter(RevertErrorModel::class.java) } + + /** the error in a response body, null when the body is not one */ + fun parse(body: ByteArray): RevertErrorModel? = try { + adapter.fromJson(String(body, Charsets.UTF_8)) + } catch (e: Exception) { + null + } + } +} + +/** @param headings the distinct headings of the sections where later changes are in the way */ +@JsonClass(generateAdapter = true) +data class RevertConflictModel( + val headings: List = emptyList(), +) diff --git a/rest/src/test/java/de/markusressel/mkdocsrestclient/history/BlameModelsTest.kt b/rest/src/test/java/de/markusressel/mkdocsrestclient/history/BlameModelsTest.kt new file mode 100644 index 00000000..6d995211 --- /dev/null +++ b/rest/src/test/java/de/markusressel/mkdocsrestclient/history/BlameModelsTest.kt @@ -0,0 +1,66 @@ +package de.markusressel.mkdocsrestclient.history + +import de.markusressel.mkdocsrestclient.toEntity +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** Real answers of a backend with blame and section restore (MkDocsEditor-Backend#101), the blame shortened */ +class BlameModelsTest { + + private val blame = """ + {"revision":"80ad3763823b0f9963237b665ff4cfaa69a042a1ea42d771e8bb30230bb5aea2","lines":12,"blocks":[ + {"start":1,"end":2,"pending":false,"revision":"bde4a3ccafc50e7cc80407b00afe242e438f7d98","time":"2026-11-14T03:10:43Z", + "message":"Initial","author":{"displayName":"Test","color":"#1971c2","avatar":null},"agents":[]}, + {"start":3,"end":3,"pending":false,"revision":"ef16954b863aa386884140a04a5321cb5422706a","time":"2026-11-14T03:37:00Z", + "message":"Revert f5be247d069c on guide/setup.md", + "author":{"accountId":"e4dheissqqro4keaag5e6f2qhq","username":"anna","displayName":"Anna","color":"#1971c2","avatar":null},"agents":[]}, + {"start":8,"end":8,"pending":true,"revision":null,"time":null,"message":null, + "author":{"displayName":"Server","color":"#868e96","avatar":null},"agents":[]}, + {"start":12,"end":12,"pending":true,"revision":null,"time":null,"message":null, + "author":{"accountId":"xdumn6fjdax2tjxiebt53aqymu","username":"bob","displayName":"Bob","color":"#2f9e44","avatar":null}, + "agents":["Claude Code"]}]} + """.trimIndent().toEntity() + + @Test + fun `a committed block has its commit`() { + val block = blame.blockAt(3)!! + + assertEquals("ef16954b863aa386884140a04a5321cb5422706a", block.revision) + assertEquals("anna", block.author?.username) + assertEquals(1794627420000, block.time?.time) + } + + @Test + fun `the author of the initial import is no account`() { + assertNull(blame.blockAt(2)!!.author?.accountId) + assertEquals("Test", blame.blockAt(1)!!.author?.displayName) + } + + @Test + fun `pending lines have no commit but their agent`() { + val block = blame.blockAt(12)!! + + assertTrue(block.pending) + assertNull(block.revision) + assertNull(block.time) + assertEquals(listOf("Claude Code"), block.agents) + } + + @Test + fun `lines between the blocks belong to none`() { + assertNull(blame.blockAt(5)) + assertNull(blame.blockAt(13)) + } + + @Test + fun `a section restore names the text without the section`() { + val body = """{"name":"Conflict","code":"section-not-found","message":"the revision has no such section","details":{"in":"revision"}}""" + + val error = SectionRestoreErrorModel.parse(body.toByteArray()) + + assertEquals(SectionRestoreErrorModel.SECTION_NOT_FOUND, error?.code) + assertEquals(SectionNotFoundModel.REVISION, error?.details?.missingIn) + } +} diff --git a/rest/src/test/java/de/markusressel/mkdocsrestclient/history/ChangesModelsTest.kt b/rest/src/test/java/de/markusressel/mkdocsrestclient/history/ChangesModelsTest.kt new file mode 100644 index 00000000..9df4c9fe --- /dev/null +++ b/rest/src/test/java/de/markusressel/mkdocsrestclient/history/ChangesModelsTest.kt @@ -0,0 +1,44 @@ +package de.markusressel.mkdocsrestclient.history + +import de.markusressel.mkdocsrestclient.reference.ApiErrorModel +import de.markusressel.mkdocsrestclient.toEntity +import java.time.Instant +import java.util.Date +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull + +/** Real answers of a backend with B2: Carol saw the page, then Alice added a section and Bob's token changed a line */ +class ChangesModelsTest { + + @Test + fun `changes since the last look are read with their authors, agents and hunks`() { + val changes = """ + {"since":{"time":"2026-11-14T03:00:24.962Z","seenToken":"ab181433912a1fe6082d0247c32d137940b7bd532f841748418ffa06af8b11d2"},"seenToken":"b62168b4464c85c3b78186f3af9f4d83c12361060c7087a7753ce26851115a3b","authors":[{"accountId":"5y7wrjicdbpk5b3lo7xzewblee","username":"alice","displayName":"alice","color":"#e8590c","avatar":null,"agents":[]},{"accountId":"nogzraprjnjhwib3z42cub4qia","username":"bob","displayName":"bob","color":"#2f9e44","avatar":null,"agents":["Claude Code"]}],"hunks":[{"heading":"Setup","headingOccurrence":1,"offset":0,"oldStart":1,"oldLines":3,"newStart":1,"newLines":7,"lines":[{"op":" ","text":"# Setup"},{"op":" ","text":""},{"op":"-","text":"Some text."},{"op":"+","text":"Some better text."},{"op":"+","text":""},{"op":"+","text":"## Install"},{"op":"+","text":""},{"op":"+","text":"Run the installer."}]}],"summary":{"linesAdded":5,"linesRemoved":1,"headings":["Setup","Install"]}} + """.trimIndent().toEntity() + + assertEquals(Date.from(Instant.parse("2026-11-14T03:00:24.962Z")), changes.since?.time) + assertEquals("b62168b4464c85c3b78186f3af9f4d83c12361060c7087a7753ce26851115a3b", changes.seenToken) + assertEquals(listOf("alice", "bob"), changes.authors.map { it.username }) + assertEquals(listOf("Claude Code"), changes.authors[1].agents) + assertEquals(8, changes.hunks.single().lines.size) + assertEquals(HistorySummaryModel(5, 1, listOf("Setup", "Install")), changes.summary) + } + + @Test + fun `a page that never was seen has no since and no hunks`() { + val changes = """ + {"since":null,"seenToken":"b62168b4","authors":[],"hunks":[],"summary":{"linesAdded":0,"linesRemoved":0,"headings":[]}} + """.trimIndent().toEntity() + + assertNull(changes.since) + assertEquals(emptyList(), changes.hunks) + } + + @Test + fun `a token the document no longer knows is told apart by its code`() { + val body = """{"name":"Conflict","code":"unknown-revision","message":"the document does not know this revision, get the changes again"}""" + + assertEquals("unknown-revision", ApiErrorModel.parse(body.toByteArray())?.code) + } +} diff --git a/rest/src/test/java/de/markusressel/mkdocsrestclient/history/HistoryModelsTest.kt b/rest/src/test/java/de/markusressel/mkdocsrestclient/history/HistoryModelsTest.kt new file mode 100644 index 00000000..3a4a717c --- /dev/null +++ b/rest/src/test/java/de/markusressel/mkdocsrestclient/history/HistoryModelsTest.kt @@ -0,0 +1,113 @@ +package de.markusressel.mkdocsrestclient.history + +import de.markusressel.mkdocsrestclient.toEntity +import java.time.Instant +import java.util.Date +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class HistoryModelsTest { + + /** the answer of a real backend (TestHistory setup in MkDocsEditor-Backend), only the account ids changed */ + private val history = """ + [ + { + "revision": "bfc59905fcb742f8160345f1047b33056386ff17", + "time": "2026-11-14T03:45:33+01:00", + "author": { + "name": "alice", + "email": "alice@mkdocseditor.invalid", + "username": "alice", + "accountId": "a1" + }, + "coAuthors": [ + { + "name": "bob", + "email": "bob@mkdocseditor.invalid", + "username": "bob", + "accountId": "a2" + } + ], + "message": "Update guide/setup.md", + "path": "guide/setup.md", + "appTokens": ["Claude Code"] + }, + { + "revision": "9d8af80923338d9e86ebbdf016f547b96089cc07", + "time": "2026-11-14T03:45:32+01:00", + "author": { + "name": "Test", + "email": "test@example.com", + "username": "", + "accountId": "" + }, + "coAuthors": [], + "message": "Initial", + "path": "guide/setup.md", + "appTokens": [] + } + ] + """.trimIndent() + + @Test + fun `a history of the backend is read with all its fields`() { + val entries = history.toEntity>().toList() + + val update = entries[0] + assertEquals("bfc59905fcb742f8160345f1047b33056386ff17", update.revision) + assertEquals(Date.from(Instant.parse("2026-11-14T02:45:33Z")), update.time) + assertEquals("alice", update.author.username) + assertTrue(update.author.isAccount) + assertEquals(listOf("bob"), update.coAuthors.map { it.username }) + assertEquals(listOf("Claude Code"), update.appTokens) + assertEquals("guide/setup.md", update.path) + } + + @Test + fun `an author who is not an account comes with empty strings`() { + val initial = history.toEntity>()[1] + + assertFalse(initial.author.isAccount) + assertEquals("", initial.author.username) + assertEquals(emptyList(), initial.coAuthors) + assertEquals(emptyList(), initial.appTokens) + } + + /** a real answer of a backend with B1: Alice added an Install section, then Bob's token "Claude Code" changed two lines */ + @Test + fun `a structured diff is read with the heading and offset of each hunk`() { + val diff = """ + {"from":"61939a9de3616d776742b10f2cafd2357eae53ae","to":"837116f685b782ae635c9cb38dd53842d0f67506","hunks":[{"heading":"Setup","headingOccurrence":1,"offset":0,"oldStart":1,"oldLines":8,"newStart":1,"newLines":8,"lines":[{"op":" ","text":"# Setup"},{"op":" ","text":""},{"op":"-","text":"Some text."},{"op":"+","text":"Some better text."},{"op":" ","text":""},{"op":" ","text":"## Install"},{"op":" ","text":""},{"op":" ","text":"Run the installer."},{"op":"-","text":"Then reboot."},{"op":"+","text":"Then reboot twice."}]}]} + """.trimIndent().toEntity() + + val hunk = diff.hunks.single() + assertEquals("Setup", hunk.heading) + assertEquals(1, hunk.headingOccurrence) + assertEquals(0, hunk.offset) + assertEquals(8, hunk.newLines) + assertEquals(DiffLineModel(DiffOp.REMOVED, "Some text."), hunk.lines[2]) + assertEquals(DiffLineModel(DiffOp.ADDED, "Some better text."), hunk.lines[3]) + assertEquals(DiffOp.CONTEXT, hunk.lines[1].op) + } + + @Test + fun `an entry of a backend with B1 has display data, agents and a summary`() { + val entry = """ + {"revision":"837116f685b782ae635c9cb38dd53842d0f67506","time":"2026-11-14T04:10:00+01:00", + "author":{"name":"bob","email":"bob@mkdocseditor.invalid","username":"bob","accountId":"45sqchh6te3waahhswaf573gyi","displayName":"bob","color":"#2f9e44","avatar":null}, + "coAuthors":[{"name":"Test","email":"test@example.com","username":"","accountId":"","displayName":"Test","color":"#1971c2","avatar":null}], + "message":"Update guide/setup.md","path":"guide/setup.md", + "appTokens":["Claude Code"],"agents":[{"name":"Claude Code","accountId":"45sqchh6te3waahhswaf573gyi"}], + "summary":{"linesAdded":2,"linesRemoved":2,"headings":["Setup","Install"]}} + """.trimIndent().toEntity() + + assertEquals("#2f9e44", entry.author.color) + assertEquals(null, entry.author.avatar) + assertEquals("Test", entry.coAuthors.single().displayName) + assertFalse(entry.coAuthors.single().isAccount) + assertEquals(listOf(HistoryAgentModel("Claude Code", "45sqchh6te3waahhswaf573gyi")), entry.agents) + assertEquals(HistorySummaryModel(2, 2, listOf("Setup", "Install")), entry.summary) + } +} diff --git a/rest/src/test/java/de/markusressel/mkdocsrestclient/history/RevertModelsTest.kt b/rest/src/test/java/de/markusressel/mkdocsrestclient/history/RevertModelsTest.kt new file mode 100644 index 00000000..626f49f4 --- /dev/null +++ b/rest/src/test/java/de/markusressel/mkdocsrestclient/history/RevertModelsTest.kt @@ -0,0 +1,46 @@ +package de.markusressel.mkdocsrestclient.history + +import de.markusressel.mkdocsrestclient.toEntity +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull + +/** Real answers of a backend with revert (MkDocsEditor-Backend#99) */ +class RevertModelsTest { + + @Test + fun `a revert answers with the entry of its commit`() { + val entry = """ + {"revision":"ef16954b863aa386884140a04a5321cb5422706a","time":"2026-11-14T04:37:00+01:00", + "author":{"name":"Anna","email":"anna@mkdocseditor.invalid","username":"anna","accountId":"e4dheissqqro4keaag5e6f2qhq","displayName":"Anna","color":"#1971c2","avatar":null}, + "coAuthors":[],"message":"Revert f5be247d069c on guide/setup.md","path":"guide/setup.md","appTokens":[],"agents":[], + "summary":{"linesAdded":5,"linesRemoved":1,"headings":["Setup","Install","Troubleshooting"]}} + """.trimIndent().toEntity() + + assertEquals("Revert f5be247d069c on guide/setup.md", entry.message) + assertEquals("anna", entry.author.username) + } + + @Test + fun `a conflict names the headings where later edits are in the way`() { + val body = """ + {"name":"Conflict","code":"revert-conflict","message":"later edits changed the same lines, edit the document by hand", + "details":{"conflicts":[{"heading":"Setup","headingOccurrence":1,"line":3}],"headings":["Setup"]}} + """.trimIndent() + + val error = RevertErrorModel.parse(body.toByteArray()) + + assertEquals(RevertErrorModel.CONFLICT, error?.code) + assertEquals(listOf("Setup"), error?.details?.headings) + } + + @Test + fun `a change that is gone already has no details`() { + val body = """{"name":"Conflict","code":"nothing-to-revert","message":"the change of this revision is not in the document anymore"}""" + + val error = RevertErrorModel.parse(body.toByteArray()) + + assertEquals(RevertErrorModel.NOTHING_TO_REVERT, error?.code) + assertNull(error?.details) + } +}