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
@@ -0,0 +1,35 @@
package de.markusressel.mkdocseditor.feature.common.data

import de.markusressel.mkdocseditor.auth.domain.AuthRepository
import de.markusressel.mkdocseditor.feature.auth.common.data.AuthBackends
import de.markusressel.mkdocseditor.feature.backendconfig.common.data.toBackendRef
import timber.log.Timber
import java.util.concurrent.ConcurrentHashMap
import javax.inject.Inject
import javax.inject.Singleton

/**
* The optional API features of the selected server (`features` of `GET /server-info/`, see `ServerFeature`). The answer
* is kept for the app's lifetime, so a page opened offline still shows what the server had once it was reached.
*/
@Singleton
internal class ServerFeatures @Inject constructor(
private val backends: AuthBackends,
private val authRepository: AuthRepository,
) {
private val known = ConcurrentHashMap<String, Set<String>>()

/** false while the server can't be asked and has not been before */
suspend fun has(feature: String): Boolean = feature in features()

private suspend fun features(): Set<String> {
val backend = backends.selected()?.toBackendRef() ?: return emptySet()
known[backend.baseUrl]?.let { return it }
return try {
authRepository.serverInfo(backend).features.toSet().also { known[backend.baseUrl] = it }
} catch (e: Exception) {
Timber.w(e, "Could not read the server features")
emptySet()
}
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
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.SeenChangesUseCase
import de.markusressel.mkdocseditor.feature.history.domain.changeLocation
import de.markusressel.mkdocsrestclient.history.DiffHunkModel
Expand Down Expand Up @@ -139,6 +141,7 @@ internal class CodeEditorViewModel @Inject constructor(
private val pendingQrKey: PendingQrKey,
private val resolveQrCode: ResolveQrCodeUseCase,
private val seenChanges: SeenChangesUseCase,
private val serverFeatures: ServerFeatures,
savedStateHandle: SavedStateHandle,
clientInstanceId: ClientInstanceId,
moveItemUseCase: MoveItemUseCase,
Expand Down Expand Up @@ -318,6 +321,11 @@ internal class CodeEditorViewModel @Inject constructor(
}

launch { _uiState.update { it.copy(qrCodesAvailable = qrCodesSupport.isSupported()) } }
launch {
val history = serverFeatures.has(ServerFeature.HISTORY)
val revert = serverFeatures.has(ServerFeature.REVERT)
_uiState.update { it.copy(historyAvailable = history, revertAvailable = revert) }
}

// a key of a sticker without a page, to put on this one
launch {
Expand Down Expand Up @@ -675,7 +683,13 @@ internal class CodeEditorViewModel @Inject constructor(
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))
_navigationEvents.send(
NavigationRequest.OpenHistory(
documentId = it,
canRestore = uiState.value.canEdit,
canRevert = uiState.value.canEdit && uiState.value.revertAvailable,
)
)
}
}
}
Expand Down Expand Up @@ -1258,6 +1272,12 @@ internal class CodeEditorViewModel @Inject constructor(
/** whether the server has QR codes, see [QrCodesSupport] */
val qrCodesAvailable: Boolean = false,

/** whether the server has the revision history, see [ServerFeatures] */
val historyAvailable: Boolean = false,

/** whether the server can undo a single change of the history */
val revertAvailable: Boolean = false,

/** what others changed since the user last looked at the page, null if nothing; see [SeenChangesUseCase] */
val changesSinceSeen: DocumentChangesModel? = null,
) {
Expand Down Expand Up @@ -1360,7 +1380,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
data class OpenHistory(val documentId: String, val canRestore: Boolean, val canRevert: 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 @@ -106,7 +106,9 @@ internal data class CodeEditorScreen(
navigator.push(CodeEditorScreen(documentId = request.documentId))

is CodeEditorViewModel.NavigationRequest.OpenHistory ->
navigator.push(HistoryScreen(documentId = request.documentId, canRestore = request.canRestore))
navigator.push(
HistoryScreen(documentId = request.documentId, canRestore = request.canRestore, canRevert = request.canRevert)
)

is CodeEditorViewModel.NavigationRequest.Close -> navigator.pop()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -407,7 +407,7 @@ internal fun editorTopBarActions(
listOfNotNull(
viewSettings.takeIf { !viewInBar },
TopAppBarAction.CodeEditor.PageReferencesAction.takeIf { !wide },
TopAppBarAction.CodeEditor.HistoryAction,
TopAppBarAction.CodeEditor.HistoryAction.takeIf { uiState.historyAvailable },
TopAppBarAction.CodeEditor.MenuDivider,
TopAppBarAction.CodeEditor.ShareLinkAction,
TopAppBarAction.CodeEditor.ShowInBrowserAction,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package de.markusressel.mkdocseditor.feature.history.domain

import com.github.kittinunf.result.Result
import de.markusressel.mkdocseditor.auth.api.ServerFeature
import de.markusressel.mkdocseditor.auth.domain.AuthRepository
import de.markusressel.mkdocseditor.feature.common.data.ServerFeatures
import de.markusressel.mkdocseditor.feature.auth.common.data.AuthBackends
import de.markusressel.mkdocsrestclient.IMkDocsRestClient
import de.markusressel.mkdocsrestclient.history.ChangeAuthorModel
Expand All @@ -12,12 +14,13 @@ import javax.inject.Inject

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

/**
Expand All @@ -28,6 +31,7 @@ internal class SeenChangesUseCase @Inject constructor(
* seen, nothing changed, only the account itself changed it, or the server can't say
*/
suspend fun open(documentId: String): DocumentChangesModel? {
if (!features.has(ServerFeature.CHANGES)) return null
val changes = changes(documentId) ?: return null
markSeen(documentId, changes.seenToken)
if (changes.since == null || changes.hunks.isEmpty()) return null
Expand All @@ -38,6 +42,7 @@ internal class SeenChangesUseCase @Inject constructor(

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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import de.markusressel.mkdocseditor.feature.history.domain.changeLocation
import de.markusressel.mkdocsrestclient.IMkDocsRestClient
import de.markusressel.mkdocsrestclient.history.DiffHunkModel
import de.markusressel.mkdocsrestclient.history.HistoryEntryModel
import de.markusressel.mkdocsrestclient.history.RevertErrorModel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
Expand All @@ -37,10 +38,10 @@ internal class HistoryViewModel @Inject constructor(

private var documentId: String? = null

fun initialize(documentId: String, canRestore: Boolean) {
fun initialize(documentId: String, canRestore: Boolean, canRevert: Boolean = false) {
if (this.documentId != null) return
this.documentId = documentId
_uiState.update { it.copy(canRestore = canRestore) }
_uiState.update { it.copy(canRestore = canRestore, canRevert = canRevert) }
launch { load() }
}

Expand All @@ -49,9 +50,14 @@ internal class HistoryViewModel @Inject constructor(
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.RestoreClicked -> _uiState.update { it.copy(confirm = Confirm.Restore(event.entry)) }
is UiEvent.UndoClicked -> _uiState.update { it.copy(confirm = Confirm.Undo(event.entry)) }
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) }
null -> Unit
}
is UiEvent.BackClicked -> launch { _events.send(HistoryEvent.Close) }
}
}
Expand Down Expand Up @@ -101,12 +107,11 @@ internal class HistoryViewModel @Inject constructor(

private fun setDiff(revision: String, diff: DiffState) = _uiState.update { it.copy(diffs = it.diffs + (revision to diff)) }

private suspend fun restore() {
private suspend fun restore(entry: HistoryEntryModel) {
val documentId = documentId ?: return
val entry = uiState.value.confirmRestore ?: return
_uiState.update { it.copy(confirmRestore = null, restoring = true) }
_uiState.update { it.copy(confirm = null, working = true) }
val result = restClient.restoreDocumentRevision(documentId, entry.revision)
_uiState.update { it.copy(restoring = false) }
_uiState.update { it.copy(working = false) }
when (result) {
is Result.Success -> {
_events.send(HistoryEvent.Message(R.string.history_restored))
Expand All @@ -119,6 +124,43 @@ internal class HistoryViewModel @Inject constructor(
}
}

/** Undoes the changes of one entry; later changes stay. A conflict or a change that is gone changes nothing. */
private suspend fun undo(entry: HistoryEntryModel) {
val documentId = documentId ?: return
_uiState.update { it.copy(confirm = null, working = true) }
val result = restClient.revertDocumentRevision(documentId, entry.revision)
_uiState.update { it.copy(working = false) }
when (result) {
is Result.Success -> {
_events.send(HistoryEvent.Message(R.string.history_undone))
load()
}
is Result.Failure -> {
val error = RevertErrorModel.parse(result.error.response.data)
val message = when (error?.code) {
RevertErrorModel.CONFLICT -> HistoryEvent.UndoConflict(error.details?.headings.orEmpty())
RevertErrorModel.NOTHING_TO_REVERT -> HistoryEvent.Message(R.string.history_undo_nothing)
else -> {
Timber.w(result.error, "revert of %s at %s", documentId, entry.revision)
HistoryEvent.Message(result.error.userMessage())
}
}
_events.send(message)
}
}
}

/** an action that waits for the user to confirm it */
internal sealed interface Confirm {
val entry: HistoryEntryModel

/** the text of the page becomes the one of [entry] */
data class Restore(override val entry: HistoryEntryModel) : Confirm

/** the changes of [entry] are taken back */
data class Undo(override val entry: HistoryEntryModel) : Confirm
}

internal sealed interface DiffState {
data object Loading : DiffState
data class Loaded(val hunks: List<DiffHunkModel>) : DiffState
Expand All @@ -131,7 +173,8 @@ internal class HistoryViewModel @Inject constructor(
/**
* @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
* @param confirm the action the user is asked to confirm
* @param working a restore or undo is on its way
*/
internal data class UiState(
val loading: Boolean = true,
Expand All @@ -140,23 +183,28 @@ internal class HistoryViewModel @Inject constructor(
val expanded: String? = null,
val diffs: Map<String, DiffState> = emptyMap(),
val canRestore: Boolean = false,
val confirmRestore: HistoryEntryModel? = null,
val restoring: Boolean = false,
val canRevert: Boolean = false,
val confirm: Confirm? = null,
val working: Boolean = false,
)

internal sealed interface UiEvent {
data object RetryClicked : UiEvent
data class EntryClicked(val revision: String) : UiEvent
data class HunkClicked(val hunk: DiffHunkModel) : UiEvent
data class RestoreClicked(val entry: HistoryEntryModel) : UiEvent
data object RestoreDismissed : UiEvent
data object RestoreConfirmed : UiEvent
data class UndoClicked(val entry: HistoryEntryModel) : UiEvent
data object ConfirmDismissed : UiEvent
data object Confirmed : UiEvent
data object BackClicked : UiEvent
}

internal sealed interface HistoryEvent {
data class OpenInEditor(val change: ChangeLocation) : HistoryEvent
data class Message(@param:StringRes val text: Int) : HistoryEvent

/** later changes in these sections are in the way, null for the part above the first heading */
data class UndoConflict(val headings: List<String?>) : HistoryEvent
data object Close : HistoryEvent
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import cafe.adriel.voyager.core.screen.Screen
import cafe.adriel.voyager.hilt.getViewModel
import cafe.adriel.voyager.navigator.LocalNavigator
import cafe.adriel.voyager.navigator.currentOrThrow
import de.markusressel.mkdocseditor.R
import de.markusressel.mkdocseditor.feature.editor.ui.compose.CodeEditorScreen
import de.markusressel.mkdocseditor.feature.history.ui.HistoryViewModel
import de.markusressel.mkdocseditor.feature.history.ui.HistoryViewModel.HistoryEvent
Expand All @@ -23,10 +24,12 @@ import de.markusressel.mkdocseditor.feature.main.data.rememberMainNavigationRequ
* The revision history of a document, see [HistoryViewModel]
*
* @param canRestore whether the account may edit the document, and so bring back an old text
* @param canRevert whether it may also undo a single change, which needs `revert` on the server
*/
data class HistoryScreen(
val documentId: String,
val canRestore: Boolean,
val canRevert: Boolean = false,
) : Screen {

@Composable
Expand All @@ -38,7 +41,7 @@ data class HistoryScreen(
val uiState by viewModel.uiState.collectAsState()

LaunchedEffect(viewModel, documentId) {
viewModel.initialize(documentId, canRestore)
viewModel.initialize(documentId, canRestore, canRevert)
}

LaunchedEffect(viewModel) {
Expand All @@ -55,6 +58,11 @@ data class HistoryScreen(
}
}
is HistoryEvent.Message -> Toast.makeText(context, event.text, Toast.LENGTH_LONG).show()
is HistoryEvent.UndoConflict -> {
val top = context.getString(R.string.history_page_start)
val headings = event.headings.joinToString(", ") { it ?: top }
Toast.makeText(context, context.getString(R.string.history_undo_conflict, headings), Toast.LENGTH_LONG).show()
}
is HistoryEvent.Close -> navigator.pop()
}
}
Expand Down
Loading
Loading