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 0fe479f5..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 @@ -2,8 +2,10 @@ 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 @@ -141,6 +143,7 @@ internal class CodeEditorViewModel @Inject constructor( private val pendingQrKey: PendingQrKey, private val resolveQrCode: ResolveQrCodeUseCase, private val seenChanges: SeenChangesUseCase, + private val lineAuthor: LineAuthorUseCase, private val serverFeatures: ServerFeatures, savedStateHandle: SavedStateHandle, clientInstanceId: ClientInstanceId, @@ -324,7 +327,8 @@ internal class CodeEditorViewModel @Inject constructor( launch { val history = serverFeatures.has(ServerFeature.HISTORY) val revert = serverFeatures.has(ServerFeature.REVERT) - _uiState.update { it.copy(historyAvailable = history, revertAvailable = 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 @@ -517,6 +521,11 @@ internal class CodeEditorViewModel @Inject constructor( 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()) @@ -682,15 +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 -> uiState.value.documentId?.let { - _navigationEvents.send( - NavigationRequest.OpenHistory( - documentId = it, - canRestore = uiState.value.canEdit, - canRevert = uiState.value.canEdit && uiState.value.revertAvailable, - ) - ) - } + 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)) } } @@ -1278,6 +1301,9 @@ internal class CodeEditorViewModel @Inject constructor( /** 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, ) { @@ -1297,6 +1323,10 @@ internal class CodeEditorViewModel @Inject constructor( 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() @@ -1380,7 +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) : 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 { @@ -1414,6 +1449,9 @@ internal class CodeEditorViewModel @Inject constructor( /** 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 3a20d37e..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 @@ -32,6 +32,7 @@ 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 @@ -107,7 +108,12 @@ internal data class CodeEditorScreen( is CodeEditorViewModel.NavigationRequest.OpenHistory -> navigator.push( - HistoryScreen(documentId = request.documentId, canRestore = request.canRestore, canRevert = request.canRevert) + HistoryScreen( + documentId = request.documentId, + canRestore = request.canRestore, + canRevert = request.canRevert, + canRestoreSection = request.canRestoreSection, + ) ) is CodeEditorViewModel.NavigationRequest.Close -> navigator.pop() @@ -200,6 +206,13 @@ internal data class CodeEditorScreen( 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 1a1e55b4..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 @@ -266,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 = { 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/ui/HistoryViewModel.kt b/app/src/main/java/de/markusressel/mkdocseditor/feature/history/ui/HistoryViewModel.kt index 43516f5b..18821ee3 100644 --- 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 @@ -13,6 +13,8 @@ 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 @@ -38,10 +40,10 @@ internal class HistoryViewModel @Inject constructor( private var documentId: String? = null - fun initialize(documentId: String, canRestore: Boolean, canRevert: Boolean = false) { + 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) } + _uiState.update { it.copy(canRestore = canRestore, canRevert = canRevert, canRestoreSection = canRestoreSection) } launch { load() } } @@ -52,10 +54,15 @@ internal class HistoryViewModel @Inject constructor( 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) } @@ -124,6 +131,30 @@ internal class HistoryViewModel @Inject constructor( } } + /** 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 @@ -159,8 +190,14 @@ internal class HistoryViewModel @Inject constructor( /** 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 @@ -184,6 +221,7 @@ internal class HistoryViewModel @Inject constructor( val diffs: Map = emptyMap(), val canRestore: Boolean = false, val canRevert: Boolean = false, + val canRestoreSection: Boolean = false, val confirm: Confirm? = null, val working: Boolean = false, ) @@ -194,6 +232,7 @@ internal class HistoryViewModel @Inject constructor( 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 @@ -205,6 +244,8 @@ internal class HistoryViewModel @Inject constructor( /** 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/HistoryScreen.kt b/app/src/main/java/de/markusressel/mkdocseditor/feature/history/ui/compose/HistoryScreen.kt index ec9093c3..b70fb873 100644 --- 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 @@ -25,11 +25,13 @@ import de.markusressel.mkdocseditor.feature.main.data.rememberMainNavigationRequ * * @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 @@ -41,7 +43,7 @@ data class HistoryScreen( val uiState by viewModel.uiState.collectAsState() LaunchedEffect(viewModel, documentId) { - viewModel.initialize(documentId, canRestore, canRevert) + viewModel.initialize(documentId, canRestore, canRevert, canRestoreSection) } LaunchedEffect(viewModel) { @@ -63,6 +65,11 @@ data class HistoryScreen( 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() } } 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 index c65e6f9e..5b5308bd 100644 --- 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 @@ -1,6 +1,5 @@ package de.markusressel.mkdocseditor.feature.history.ui.compose -import android.text.format.DateUtils import androidx.compose.animation.animateContentSize import androidx.compose.foundation.background import androidx.compose.foundation.clickable @@ -121,6 +120,7 @@ internal fun HistoryScreenContent( 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() @@ -144,6 +144,11 @@ internal fun HistoryScreenContent( 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) }, @@ -164,6 +169,7 @@ private fun HistoryEntry( diff: DiffState?, canRestore: Boolean, canUndo: Boolean, + canRestoreSection: Boolean, onUiEvent: (UiEvent) -> Unit, ) { Column( @@ -197,7 +203,14 @@ private fun HistoryEntry( } if (expanded) { Spacer(Modifier.size(8.dp)) - EntryDiff(diff, onUiEvent) + 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)) }) { @@ -261,16 +274,12 @@ private fun summaryText(summary: HistorySummaryModel?): String? { return if (summary.headings.isEmpty()) lines else "$lines · ${summary.headings.joinToString(", ")}" } -/** within the last minute, or from a server whose clock is a little ahead, it is "just now", not "in 0 minutes" */ @Composable -private 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() -} - -@Composable -private fun EntryDiff(diff: DiffState?, onUiEvent: (UiEvent) -> Unit) { +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) @@ -279,7 +288,13 @@ private fun EntryDiff(diff: DiffState?, onUiEvent: (UiEvent) -> Unit) { 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, onClick = { onUiEvent(UiEvent.HunkClicked(hunk)) }) } + diff.hunks.forEach { hunk -> + Hunk( + hunk = hunk, + onClick = { onHunkClicked(hunk) }, + onRestoreSection = onRestoreSection?.takeIf { hunk.heading != null }?.let { { it(hunk) } }, + ) + } } } } @@ -287,7 +302,7 @@ private fun EntryDiff(diff: DiffState?, onUiEvent: (UiEvent) -> Unit) { /** inline, as Markdown source; a long line scrolls sideways instead of wrapping, so the columns stay */ @Composable -internal fun Hunk(hunk: DiffHunkModel, onClick: () -> Unit) { +internal fun Hunk(hunk: DiffHunkModel, onClick: () -> Unit, onRestoreSection: (() -> Unit)? = null) { val lines = remember(hunk) { diffLineTexts(hunk.lines) } Column( modifier = Modifier @@ -331,6 +346,16 @@ internal fun Hunk(hunk: DiffHunkModel, onClick: () -> Unit) { ) } } + 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, + ) + } + } } } 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/res/values/strings.xml b/app/src/main/res/values/strings.xml index d3412a95..07596a0d 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -470,6 +470,17 @@ 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/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/ui/HistoryViewModelTest.kt b/app/src/test/java/de/markusressel/mkdocseditor/feature/history/ui/HistoryViewModelTest.kt index 529a1bc6..a4e48641 100644 --- 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 @@ -50,6 +50,8 @@ class HistoryViewModelTest { 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() @@ -73,6 +75,16 @@ class HistoryViewModelTest { 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 @@ -167,7 +179,7 @@ class HistoryViewModelTest { assertEquals(emptyList(), restored) } - private fun conflict(body: String) = Result.error( + private fun conflict(body: String): Result = Result.error( FuelError.wrap( RuntimeException("409"), Response( @@ -216,4 +228,40 @@ class HistoryViewModelTest { 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/HistoryScreenContentTest.kt b/app/src/test/java/de/markusressel/mkdocseditor/feature/history/ui/compose/HistoryScreenContentTest.kt index d2554afb..bac073da 100644 --- 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 @@ -5,7 +5,9 @@ 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 @@ -141,4 +143,41 @@ class HistoryScreenContentTest { 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 89eaf6c9..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 @@ -231,6 +231,9 @@ object ServerFeature { /** `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 5305e99c..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,7 @@ 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 @@ -303,6 +304,16 @@ class DummyMkDocsRestClient : IMkDocsRestClient { 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/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/HistoryApi.kt b/rest/src/main/java/de/markusressel/mkdocsrestclient/history/HistoryApi.kt index c489f4b6..ecc98441 100644 --- a/rest/src/main/java/de/markusressel/mkdocsrestclient/history/HistoryApi.kt +++ b/rest/src/main/java/de/markusressel/mkdocsrestclient/history/HistoryApi.kt @@ -61,6 +61,23 @@ interface HistoryApi { /** 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( @@ -123,4 +140,19 @@ class HistoryApiImpl( 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/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) + } +}