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..ce61e8fa 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 @@ -662,6 +662,9 @@ 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(it, canRestore = uiState.value.canEdit)) + } } } @@ -1310,6 +1313,7 @@ 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) : 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 { 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..61e72236 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,7 @@ import de.markusressel.mkdocseditor.feature.editor.ui.compose.picker.ResourcePic import androidx.compose.ui.res.stringResource import de.markusressel.mkdocseditor.R import de.markusressel.mkdocseditor.feature.qr.domain.QrLink +import de.markusressel.mkdocseditor.feature.history.ui.compose.HistoryScreen import de.markusressel.mkdocseditor.feature.qr.ui.compose.PageQrCodesDialog internal data class CodeEditorScreen( @@ -103,6 +104,9 @@ 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)) + is CodeEditorViewModel.NavigationRequest.Close -> navigator.pop() is CodeEditorViewModel.NavigationRequest.ShareLink -> { 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..74bb4ec8 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 @@ -399,6 +399,7 @@ internal fun editorTopBarActions( listOfNotNull( viewSettings.takeIf { !viewInBar }, TopAppBarAction.CodeEditor.PageReferencesAction.takeIf { !wide }, + TopAppBarAction.CodeEditor.HistoryAction, TopAppBarAction.CodeEditor.MenuDivider, TopAppBarAction.CodeEditor.ShareLinkAction, TopAppBarAction.CodeEditor.ShowInBrowserAction, @@ -576,6 +577,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..36ad44b6 --- /dev/null +++ b/app/src/main/java/de/markusressel/mkdocseditor/feature/history/domain/HistoryText.kt @@ -0,0 +1,52 @@ +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 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/WordDiff.kt b/app/src/main/java/de/markusressel/mkdocseditor/feature/history/domain/WordDiff.kt new file mode 100644 index 00000000..53f73b0a --- /dev/null +++ b/app/src/main/java/de/markusressel/mkdocseditor/feature/history/domain/WordDiff.kt @@ -0,0 +1,89 @@ +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]""") + +/** + * 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. + */ +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 + } + } + return WordChanges(removed.merged(), added.merged()) +} + +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..907d35a7 --- /dev/null +++ b/app/src/main/java/de/markusressel/mkdocseditor/feature/history/ui/HistoryViewModel.kt @@ -0,0 +1,162 @@ +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 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) { + if (this.documentId != null) return + this.documentId = documentId + _uiState.update { it.copy(canRestore = canRestore) } + 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(confirmRestore = event.entry) } + is UiEvent.RestoreDismissed -> _uiState.update { it.copy(confirmRestore = null) } + is UiEvent.RestoreConfirmed -> launch { restore() } + 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() { + val documentId = documentId ?: return + val entry = uiState.value.confirmRestore ?: return + _uiState.update { it.copy(confirmRestore = null, restoring = true) } + val result = restClient.restoreDocumentRevision(documentId, entry.revision) + _uiState.update { it.copy(restoring = 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())) + } + } + } + + 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 confirmRestore the entry whose text is about to come back, while the user confirms it + */ + 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 confirmRestore: HistoryEntryModel? = null, + val restoring: 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 object RestoreDismissed : UiEvent + data object RestoreConfirmed : 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 + 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 new file mode 100644 index 00000000..66d39627 --- /dev/null +++ b/app/src/main/java/de/markusressel/mkdocseditor/feature/history/ui/compose/HistoryScreen.kt @@ -0,0 +1,67 @@ +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.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 + */ +data class HistoryScreen( + val documentId: String, + val canRestore: Boolean, +) : 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) + } + + 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.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..943a0dd2 --- /dev/null +++ b/app/src/main/java/de/markusressel/mkdocseditor/feature/history/ui/compose/HistoryScreenContent.kt @@ -0,0 +1,370 @@ +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 +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.people +import de.markusressel.mkdocseditor.feature.history.domain.shownName +import de.markusressel.mkdocseditor.feature.history.domain.wordChanges +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.restoring) { + 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(), + onUiEvent = onUiEvent, + ) + HorizontalDivider() + } + } + } + } + } + + uiState.confirmRestore?.let { entry -> + AlertDialog( + onDismissRequest = { onUiEvent(UiEvent.RestoreDismissed) }, + title = { Text(stringResource(R.string.history_restore_title)) }, + text = { Text(stringResource(R.string.history_restore_text, relativeTime(entry.time), entry.author.shownName)) }, + confirmButton = { + TextButton(onClick = { onUiEvent(UiEvent.RestoreConfirmed) }) { Text(stringResource(R.string.history_restore)) } + }, + dismissButton = { + TextButton(onClick = { onUiEvent(UiEvent.RestoreDismissed) }) { Text(stringResource(android.R.string.cancel)) } + }, + ) + } +} + +@Composable +private fun HistoryEntry( + entry: HistoryEntryModel, + expanded: Boolean, + diff: DiffState?, + canRestore: 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, onUiEvent) + if (canRestore) { + OutlinedButton( + modifier = Modifier.padding(top = 8.dp), + 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 }) + +/** "Anna, Bob via Claude Code" */ +@Composable +private fun whoText(entry: HistoryEntryModel): String { + val people = entry.people.joinToString(", ") { it.shownName } + val agents = entry.agentNames + return if (agents.isEmpty()) people else stringResource(R.string.history_via, people, 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 relativeTime(time: Date): String = DateUtils.getRelativeTimeSpanString( + time.time, + System.currentTimeMillis(), + DateUtils.MINUTE_IN_MILLIS, +).toString() + +@Composable +private fun EntryDiff(diff: DiffState?, onUiEvent: (UiEvent) -> 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, onClick = { onUiEvent(UiEvent.HunkClicked(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) { + 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, + ) + } + } + } +} + +/** 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, + ), + onUiEvent = {}, + ) + } +} diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index c83f6b7e..fbdd437f 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -449,4 +449,17 @@ “%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 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..6fcb2254 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 @@ -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, 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..e0abd775 --- /dev/null +++ b/app/src/test/java/de/markusressel/mkdocseditor/feature/history/domain/HistoryTextTest.kt @@ -0,0 +1,83 @@ +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 `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/WordDiffTest.kt b/app/src/test/java/de/markusressel/mkdocseditor/feature/history/domain/WordDiffTest.kt new file mode 100644 index 00000000..1b39ed44 --- /dev/null +++ b/app/src/test/java/de/markusressel/mkdocseditor/feature/history/domain/WordDiffTest.kt @@ -0,0 +1,36 @@ +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 `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..aba8227c --- /dev/null +++ b/app/src/test/java/de/markusressel/mkdocseditor/feature/history/ui/HistoryViewModelTest.kt @@ -0,0 +1,160 @@ +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.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.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 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 restoreDocumentRevision(documentId: String, revision: String): Result { + restored += revision + return Result.success("") + } + } + + @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) + } + + @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.RestoreConfirmed) + + assertEquals(listOf("b"), restored) + assertNull(viewModel.uiState.value.confirmRestore) + 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.RestoreDismissed) + viewModel.onUiEvent(UiEvent.RestoreConfirmed) + + assertEquals(emptyList(), restored) + } +} 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..2ca06360 --- /dev/null +++ b/app/src/test/java/de/markusressel/mkdocseditor/feature/history/ui/compose/HistoryScreenContentTest.kt @@ -0,0 +1,110 @@ +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.test.performClick +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", "a1")), 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("+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 `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() + } +} diff --git a/rest/src/main/java/de/markusressel/mkdocsrestclient/DummyMkDocsRestClient.kt b/rest/src/main/java/de/markusressel/mkdocsrestclient/DummyMkDocsRestClient.kt index 7a62e9a0..e8f3ea9f 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.HistoryDiffModel import de.markusressel.mkdocsrestclient.history.HistoryEntryModel import de.markusressel.mkdocsrestclient.dashboard.PinScope import de.markusressel.mkdocsrestclient.dashboard.PinsModel @@ -285,6 +286,9 @@ class DummyMkDocsRestClient : IMkDocsRestClient { 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 restoreDocumentRevision(documentId: String, revision: String): Result = Result.success("") 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 31480688..6717aca5 100644 --- a/rest/src/main/java/de/markusressel/mkdocsrestclient/history/HistoryApi.kt +++ b/rest/src/main/java/de/markusressel/mkdocsrestclient/history/HistoryApi.kt @@ -35,6 +35,13 @@ interface HistoryApi { 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 + /** 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 } @@ -60,6 +67,17 @@ class HistoryApiImpl( 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 restoreDocumentRevision(documentId: String, revision: String): Result = requestManager.doRequest( url = "/document/$documentId/history/$revision/restore/", diff --git a/rest/src/main/java/de/markusressel/mkdocsrestclient/history/HistoryModels.kt b/rest/src/main/java/de/markusressel/mkdocsrestclient/history/HistoryModels.kt index 44b99fae..735e4166 100644 --- a/rest/src/main/java/de/markusressel/mkdocsrestclient/history/HistoryModels.kt +++ b/rest/src/main/java/de/markusressel/mkdocsrestclient/history/HistoryModels.kt @@ -1,5 +1,6 @@ package de.markusressel.mkdocsrestclient.history +import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import java.util.Date @@ -8,6 +9,8 @@ import java.util.Date * 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( @@ -15,6 +18,9 @@ data class HistoryAuthorModel( 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() } @@ -35,4 +41,71 @@ data class HistoryEntryModel( 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, +} diff --git a/rest/src/test/java/de/markusressel/mkdocsrestclient/history/HistoryModelsTest.kt b/rest/src/test/java/de/markusressel/mkdocsrestclient/history/HistoryModelsTest.kt index 38b2daa2..3a4a717c 100644 --- a/rest/src/test/java/de/markusressel/mkdocsrestclient/history/HistoryModelsTest.kt +++ b/rest/src/test/java/de/markusressel/mkdocsrestclient/history/HistoryModelsTest.kt @@ -74,4 +74,40 @@ class HistoryModelsTest { 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) + } }