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
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
@@ -1,5 +1,14 @@
package de.markusressel.mkdocseditor.feature.editor.ui

import de.markusressel.mkdocseditor.auth.api.ServerFeature
import de.markusressel.mkdocseditor.feature.common.data.ServerFeatures
import de.markusressel.mkdocseditor.feature.history.domain.LineAuthorUseCase
import de.markusressel.mkdocseditor.feature.history.domain.SeenChangesUseCase
import de.markusressel.mkdocseditor.feature.history.domain.changeLocation
import de.markusressel.mkdocsrestclient.history.BlameBlockModel
import de.markusressel.mkdocsrestclient.history.DiffHunkModel
import de.markusressel.mkdocsrestclient.history.DocumentChangesModel
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.flow.transformWhile
import de.markusressel.mkdocseditor.feature.editor.domain.ChangeLocation
import de.markusressel.mkdocsrestclient.dashboard.PinScope
Expand Down Expand Up @@ -133,6 +142,9 @@ internal class CodeEditorViewModel @Inject constructor(
private val qrCodesSupport: QrCodesSupport,
private val pendingQrKey: PendingQrKey,
private val resolveQrCode: ResolveQrCodeUseCase,
private val seenChanges: SeenChangesUseCase,
private val lineAuthor: LineAuthorUseCase,
private val serverFeatures: ServerFeatures,
savedStateHandle: SavedStateHandle,
clientInstanceId: ClientInstanceId,
moveItemUseCase: MoveItemUseCase,
Expand Down Expand Up @@ -312,6 +324,12 @@ internal class CodeEditorViewModel @Inject constructor(
}

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

// a key of a sticker without a page, to put on this one
launch {
Expand Down Expand Up @@ -501,6 +519,17 @@ internal class CodeEditorViewModel @Inject constructor(
launch {
when (event) {
is UiEvent.DismissDialog -> dismissCurrentDialog()
is UiEvent.ChangesSinceSeenClicked -> uiState.value.changesSinceSeen?.let { showDialog(DialogState.ChangesSinceSeen(it)) }
is UiEvent.ChangesSinceSeenDismissed -> _uiState.update { it.copy(changesSinceSeen = null) }
is UiEvent.AuthorLineClicked -> showLineAuthor(event.line)
is UiEvent.LineAuthorHistoryClicked -> {
dismissCurrentDialog()
openHistory()
}
is UiEvent.ChangeHunkClicked -> {
dismissCurrentDialog()
jumpToChange(event.hunk.changeLocation())
}
is UiEvent.ItemActionClicked -> itemActions.onActionClicked(
event.item, event.action, openElsewhere = uiState.value.remotePeers.isNotEmpty(),
)
Expand Down Expand Up @@ -662,6 +691,29 @@ internal class CodeEditorViewModel @Inject constructor(
is TopAppBarAction.CodeEditor.ConnectionAction -> onConnectionIconClicked(action.indicator)
is TopAppBarAction.CodeEditor.PageReferencesAction -> showPageReferences()
is TopAppBarAction.CodeEditor.QrCodesAction -> showQrCodes()
is TopAppBarAction.CodeEditor.HistoryAction -> openHistory()
}
}

private suspend fun openHistory() {
val documentId = uiState.value.documentId ?: return
_navigationEvents.send(
NavigationRequest.OpenHistory(
documentId = documentId,
canRestore = uiState.value.canEdit,
canRevert = uiState.value.canEdit && uiState.value.revertAvailable,
canRestoreSection = uiState.value.canEdit && uiState.value.blameAvailable,
)
)
}

/** @param line 0-based */
private suspend fun showLineAuthor(line: Int) {
val documentId = uiState.value.documentId ?: return
when (val answer = lineAuthor(documentId, line)) {
is LineAuthorUseCase.Answer.Found -> showDialog(DialogState.LineAuthor(answer.block))
LineAuthorUseCase.Answer.Unknown -> showMessage(context.getString(R.string.line_author_none))
is LineAuthorUseCase.Answer.Failed -> showMessage(context.getString(answer.message))
}
}

Expand Down Expand Up @@ -837,6 +889,32 @@ internal class CodeEditorViewModel @Inject constructor(
*/
fun setCurrentDocumentId(documentId: String?) {
session.setDocument(documentId)
if (documentId != null && seenChangesAsked != documentId) {
seenChangesAsked = documentId
launch {
// not inside update: it runs its block again when the state changed meanwhile, and each run marks seen
val changes = seenChanges.open(documentId)
_uiState.update { it.copy(changesSinceSeen = changes) }
seenChangesOpened = true
}
}
}

/** the document whose changes since the last visit were asked for, once per editor */
private var seenChangesAsked: String? = null

/** whether the changes since the last visit are known; marking the page seen before that would swallow them */
private var seenChangesOpened = false

/**
* The page as it is now counts as seen when the user closes it, see [SeenChangesUseCase.leave]. Not on ON_STOP: the
* screen gets one while it opens.
*/
private fun leavePage() {
if (!seenChangesOpened) return
val documentId = uiState.value.documentId ?: seenChangesAsked ?: return
// after the editor is closed: it is a short request, and without it the own edits come back as news
launch(NonCancellable) { seenChanges.leave(documentId) }
}

/**
Expand Down Expand Up @@ -976,6 +1054,7 @@ internal class CodeEditorViewModel @Inject constructor(
}

override fun onCleared() {
leavePage()
session.close()
super.onCleared()
}
Expand Down Expand Up @@ -1215,6 +1294,18 @@ internal class CodeEditorViewModel @Inject constructor(

/** whether the server has QR codes, see [QrCodesSupport] */
val qrCodesAvailable: Boolean = false,

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

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

/** whether the server tells who last changed each line, and can restore a single section */
val blameAvailable: Boolean = false,

/** what others changed since the user last looked at the page, null if nothing; see [SeenChangesUseCase] */
val changesSinceSeen: DocumentChangesModel? = null,
) {
val editorShown: Boolean
get() = editModeActive || editModeOpening || readOnlyEditorShown
Expand All @@ -1227,6 +1318,15 @@ internal class CodeEditorViewModel @Inject constructor(
sealed class UiEvent {
data object DismissDialog : UiEvent()

/** the banner about the changes since the last visit */
data object ChangesSinceSeenClicked : UiEvent()
data object ChangesSinceSeenDismissed : UiEvent()
data class ChangeHunkClicked(val hunk: DiffHunkModel) : UiEvent()

/** a line of the author strip, 0-based */
data class AuthorLineClicked(val line: Int) : UiEvent()
data object LineAuthorHistoryClicked : UiEvent()

data class ItemActionClicked(val item: WikiItem, val action: ItemAction) : UiEvent()
data class ItemMovePreviewRequested(val parentId: String?, val name: String?) : UiEvent()
data object ItemMoveBackClicked : UiEvent()
Expand Down Expand Up @@ -1310,6 +1410,12 @@ internal class CodeEditorViewModel @Inject constructor(
sealed interface NavigationRequest {
data class Login(val backendId: Long) : NavigationRequest
data class OpenDocument(val documentId: String) : NavigationRequest
data class OpenHistory(
val documentId: String,
val canRestore: Boolean,
val canRevert: Boolean,
val canRestoreSection: Boolean,
) : NavigationRequest
/** leave the editor, e.g. to show a folder in the file browser */
data object Close : NavigationRequest
data class ShareLink(val link: String) : NavigationRequest {
Expand Down Expand Up @@ -1340,6 +1446,12 @@ internal class CodeEditorViewModel @Inject constructor(
/** the view settings of the editor, as a sheet below it */
data object ViewSettings : DialogState

/** what changed since the last visit, hunk by hunk */
data class ChangesSinceSeen(val changes: DocumentChangesModel) : DialogState

/** who last changed a block of lines, and when */
data class LineAuthor(val block: BlameBlockModel) : DialogState

/**
* The QR codes of the page, and adding or removing them
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,15 +48,19 @@ internal fun authorColor(author: String, knownColors: Map<String, String?>): Col
*
* @param lines the shares of each line
* @param widthPx the width of the strip
* @param onLineTapped gets the 0-based line; false places the cursor like any tap on the bar
*/
internal class AuthorStripColumn(
private val lines: List<List<LineShare>>,
private val widthPx: Int,
private val colorOf: (String) -> Color,
private val onLineTapped: (Int) -> Boolean = { false },
) : KodeEditorGutterColumn {

override fun width(lineCount: Int) = widthPx

override fun onTap(line: Int): Boolean = onLineTapped(line)

override fun DrawScope.drawCell(cell: GutterCell) {
var top = 0f
lines.getOrNull(cell.line)?.forEach { share ->
Expand All @@ -67,6 +71,14 @@ internal class AuthorStripColumn(
}
}

/** [column] as it is, with [onLineTapped] for taps on it */
internal class TappableGutterColumn(
private val column: KodeEditorGutterColumn,
private val onLineTapped: (Int) -> Boolean,
) : KodeEditorGutterColumn by column {
override fun onTap(line: Int): Boolean = onLineTapped(line)
}

/** A light marker on the text of each author */
@Composable
internal fun BoxScope.AuthorMarkers(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ internal fun CodeEditorLayout(
restoreToCursor: Boolean = false,
changeJump: CodeEditorViewModel.ChangeJump? = null,
onChangeJumpShown: (CodeEditorViewModel.ChangeJump) -> Unit = {},
onAuthorLineClicked: ((Int) -> Unit)? = null,
) {
val viewState = rememberKodeEditorViewState()
val currentOnVisibleRangeChanged by rememberUpdatedState(onVisibleRangeChanged)
Expand Down Expand Up @@ -238,13 +239,19 @@ internal fun CodeEditorLayout(
val colorOf: (String) -> Color = { authorColor(it, authorColors()) }
val stripWidth = with(LocalDensity.current) { AUTHOR_STRIP_WIDTH.roundToPx() }
val runs = authorRuns.value
val currentOnAuthorLineClicked by rememberUpdatedState(onAuthorLineClicked)
val onGutterTapped: (Int) -> Boolean = { line -> currentOnAuthorLineClicked?.let { it(line); true } ?: false }
val authorStrip = if (settings.authorHighlight != AuthorHighlightMode.Off && runs.runs.isNotEmpty()) {
remember(runs, stripWidth) {
AuthorStripColumn(lineShares(state.text, runs.runs), stripWidth, colorOf)
AuthorStripColumn(lineShares(state.text, runs.runs), stripWidth, colorOf, onGutterTapped)
}
} else {
null
}
// the strip is too narrow to hit, so the line numbers next to it tell who wrote a line as well
val numbers = lineNumbers.takeIf { settings.lineNumbers }?.let { numbers ->
if (authorStrip == null) numbers else remember(numbers) { TappableGutterColumn(numbers, onGutterTapped) }
}

CompositionLocalProvider(
LocalTextSelectionColors provides TextSelectionColors(
Expand Down Expand Up @@ -275,7 +282,7 @@ internal fun CodeEditorLayout(
enabled = true,
readOnly = readOnly,
lineWrapping = settings.lineWrapping,
gutterColumns = listOfNotNull(lineNumbers.takeIf { settings.lineNumbers }, authorStrip),
gutterColumns = listOfNotNull(numbers, authorStrip),
overlay = { layout ->
changeHighlight?.let { ChangeHighlight(layout, it, highlightColor, { changeHighlightAlpha.value }) }
if (settings.authorHighlight == AuthorHighlightMode.StripAndMarker) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ import de.markusressel.mkdocseditor.feature.editor.ui.compose.picker.ResourcePic
import androidx.compose.ui.res.stringResource
import de.markusressel.mkdocseditor.R
import de.markusressel.mkdocseditor.feature.qr.domain.QrLink
import de.markusressel.mkdocseditor.feature.history.ui.compose.ChangesSinceSeenSheet
import de.markusressel.mkdocseditor.feature.history.ui.compose.LineAuthorSheet
import de.markusressel.mkdocseditor.feature.history.ui.compose.HistoryScreen
import de.markusressel.mkdocseditor.feature.qr.ui.compose.PageQrCodesDialog

internal data class CodeEditorScreen(
Expand Down Expand Up @@ -103,6 +106,16 @@ internal data class CodeEditorScreen(
is CodeEditorViewModel.NavigationRequest.OpenDocument ->
navigator.push(CodeEditorScreen(documentId = request.documentId))

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

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

is CodeEditorViewModel.NavigationRequest.ShareLink -> {
Expand Down Expand Up @@ -187,6 +200,19 @@ internal data class CodeEditorScreen(
// in the content, which knows whether a split is open
is CodeEditorViewModel.DialogState.ViewSettings -> Unit

is CodeEditorViewModel.DialogState.ChangesSinceSeen -> ChangesSinceSeenSheet(
changes = dialogState.changes,
onHunkClicked = { viewModel.onUiEvent(CodeEditorViewModel.UiEvent.ChangeHunkClicked(it)) },
onDismiss = { viewModel.onUiEvent(CodeEditorViewModel.UiEvent.DismissDialog) },
)

is CodeEditorViewModel.DialogState.LineAuthor -> LineAuthorSheet(
block = dialogState.block,
onOpenHistory = { viewModel.onUiEvent(CodeEditorViewModel.UiEvent.LineAuthorHistoryClicked) }
.takeIf { uiState.historyAvailable },
onDismiss = { viewModel.onUiEvent(CodeEditorViewModel.UiEvent.DismissDialog) },
)

is CodeEditorViewModel.DialogState.PageReferencesPanel -> if (tree != null && documentId != null) {
PageReferencesDialog(
tree = tree!!,
Expand Down
Loading
Loading