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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ fun <T : TopAppBarAction> 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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
}
}

Expand Down Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import de.markusressel.mkdocseditor.feature.editor.ui.compose.picker.ResourcePic
import androidx.compose.ui.res.stringResource
import de.markusressel.mkdocseditor.R
import de.markusressel.mkdocseditor.feature.qr.domain.QrLink
import de.markusressel.mkdocseditor.feature.history.ui.compose.HistoryScreen
import de.markusressel.mkdocseditor.feature.qr.ui.compose.PageQrCodesDialog

internal data class CodeEditorScreen(
Expand Down Expand Up @@ -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 -> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
@@ -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<HistoryAuthorModel>
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<String>
get() = agents.map { it.name }.ifEmpty { appTokens }.distinct()

/**
* The message of a commit when it says more than the backend's standard "Update <path>"
*/
internal val HistoryEntryModel.notableMessage: String?
get() = message.takeUnless { it.isBlank() || it == "Update $path" }
Original file line number Diff line number Diff line change
@@ -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<Highlight>, val added: List<Highlight>)

/** 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<IntRange>()
val added = mutableListOf<IntRange>()
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<IntRange>.merged(): List<Highlight> {
val result = mutableListOf<Highlight>()
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<DiffLineModel>): List<Int?> {
val partner = arrayOfNulls<Int>(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()
}
Original file line number Diff line number Diff line change
@@ -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<HistoryEvent>(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<DiffHunkModel>) : 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<HistoryEntryModel> = emptyList(),
@param:StringRes val problem: Int? = null,
val expanded: String? = null,
val diffs: Map<String, DiffState> = 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
}
}
Loading
Loading