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 @@ -328,7 +328,10 @@ internal class CodeEditorViewModel @Inject constructor(
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) }
val revertCheck = serverFeatures.has(ServerFeature.REVERT_CHECK)
_uiState.update {
it.copy(historyAvailable = history, revertAvailable = revert, blameAvailable = blame, revertCheckAvailable = revertCheck)
}
}

// a key of a sticker without a page, to put on this one
Expand Down Expand Up @@ -703,6 +706,7 @@ internal class CodeEditorViewModel @Inject constructor(
canRestore = uiState.value.canEdit,
canRevert = uiState.value.canEdit && uiState.value.revertAvailable,
canRestoreSection = uiState.value.canEdit && uiState.value.blameAvailable,
canCheckRevert = uiState.value.revertCheckAvailable,
)
)
}
Expand Down Expand Up @@ -1304,6 +1308,9 @@ internal class CodeEditorViewModel @Inject constructor(
/** whether the server tells who last changed each line, and can restore a single section */
val blameAvailable: Boolean = false,

/** whether the server tells before an undo whether it would work */
val revertCheckAvailable: 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 @@ -1415,6 +1422,7 @@ internal class CodeEditorViewModel @Inject constructor(
val canRestore: Boolean,
val canRevert: Boolean,
val canRestoreSection: Boolean,
val canCheckRevert: Boolean,
) : NavigationRequest
/** leave the editor, e.g. to show a folder in the file browser */
data object Close : NavigationRequest
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ internal data class CodeEditorScreen(
canRestore = request.canRestore,
canRevert = request.canRevert,
canRestoreSection = request.canRestoreSection,
canCheckRevert = request.canCheckRevert,
)
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,18 @@ internal class HistoryViewModel @Inject constructor(
internal val events = _events.receiveAsFlow()

private var documentId: String? = null
private var canCheckRevert = false

fun initialize(documentId: String, canRestore: Boolean, canRevert: Boolean = false, canRestoreSection: Boolean = false) {
fun initialize(
documentId: String,
canRestore: Boolean,
canRevert: Boolean = false,
canRestoreSection: Boolean = false,
canCheckRevert: Boolean = false,
) {
if (this.documentId != null) return
this.documentId = documentId
this.canCheckRevert = canCheckRevert
_uiState.update { it.copy(canRestore = canRestore, canRevert = canRevert, canRestoreSection = canRestoreSection) }
launch { load() }
}
Expand Down Expand Up @@ -74,7 +82,11 @@ internal class HistoryViewModel @Inject constructor(
_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) }
// an undo or restore changed the text, so what could be undone is asked again
is Result.Success -> {
_uiState.update { it.copy(loading = false, entries = result.value, undoChecks = emptyMap()) }
uiState.value.expanded?.let { checkUndo(it) }
}
is Result.Failure -> {
Timber.w(result.error, "history of %s", documentId)
_uiState.update { it.copy(loading = false, problem = result.error.userMessage()) }
Expand All @@ -89,8 +101,37 @@ internal class HistoryViewModel @Inject constructor(
}
_uiState.update { it.copy(expanded = revision) }
if (uiState.value.diffs[revision] !is DiffState.Loaded) launch { loadDiff(revision) }
launch { checkUndo(revision) }
}

/**
* Asks whether the change of an entry can be undone, each time it opens: others may have edited the page since.
* The oldest entry created the page and is not asked about.
*/
private suspend fun checkUndo(revision: String) {
val documentId = documentId ?: return
if (!canCheckRevert || !uiState.value.canRevert || uiState.value.entries.lastOrNull()?.revision == revision) return
setUndoCheck(revision, UndoCheck.Checking)
val check = when (val result = restClient.checkDocumentRevert(documentId, revision)) {
is Result.Success -> when {
result.value.possible -> UndoCheck.Possible
result.value.code == RevertErrorModel.CONFLICT -> UndoCheck.Conflict(result.value.details?.headings.orEmpty())
result.value.code == RevertErrorModel.NOTHING_TO_REVERT -> UndoCheck.Gone
// a reason this app doesn't know yet: the undo itself tells
else -> UndoCheck.Possible
}
is Result.Failure -> {
// the undo itself still says why it fails
Timber.w(result.error, "revert check of %s at %s", documentId, revision)
UndoCheck.Possible
}
}
setUndoCheck(revision, check)
}

private fun setUndoCheck(revision: String, check: UndoCheck) =
_uiState.update { it.copy(undoChecks = it.undoChecks + (revision to check)) }

/** 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
Expand Down Expand Up @@ -198,6 +239,18 @@ internal class HistoryViewModel @Inject constructor(
/** a section of the page: its heading, the [occurrence]th one with this text */
internal data class Section(val heading: String, val occurrence: Int)

/** whether the change of an entry can be undone now */
internal sealed interface UndoCheck {
data object Checking : UndoCheck
data object Possible : UndoCheck

/** undone already, or edited away by hand */
data object Gone : UndoCheck

/** later changes in these sections are in the way, null for the part above the first heading */
data class Conflict(val headings: List<String?>) : UndoCheck
}

internal sealed interface DiffState {
data object Loading : DiffState
data class Loaded(val hunks: List<DiffHunkModel>) : DiffState
Expand All @@ -222,6 +275,8 @@ internal class HistoryViewModel @Inject constructor(
val canRestore: Boolean = false,
val canRevert: Boolean = false,
val canRestoreSection: Boolean = false,
/** by revision; without an entry the undo is offered and tells itself whether it worked */
val undoChecks: Map<String, UndoCheck> = emptyMap(),
val confirm: Confirm? = null,
val working: Boolean = false,
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,14 @@ import de.markusressel.mkdocseditor.feature.main.data.rememberMainNavigationRequ
* @param canRestore whether the account may edit the document, and so bring back an old text
* @param canRevert whether it may also undo a single change, which needs `revert` on the server
* @param canRestoreSection whether it may also bring back a single section, which needs `blame` on the server
* @param canCheckRevert whether the server tells before an undo whether it would work (`revert-check`)
*/
data class HistoryScreen(
val documentId: String,
val canRestore: Boolean,
val canRevert: Boolean = false,
val canRestoreSection: Boolean = false,
val canCheckRevert: Boolean = false,
) : Screen {

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

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

LaunchedEffect(viewModel) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ import de.markusressel.mkdocseditor.feature.history.domain.shownName
import de.markusressel.mkdocseditor.feature.history.domain.wordChanges
import de.markusressel.mkdocseditor.feature.history.ui.HistoryViewModel.Confirm
import de.markusressel.mkdocseditor.feature.history.ui.HistoryViewModel.DiffState
import de.markusressel.mkdocseditor.feature.history.ui.HistoryViewModel.UndoCheck
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
Expand Down Expand Up @@ -120,6 +121,7 @@ internal fun HistoryScreenContent(
canRestore = uiState.canRestore && entry != uiState.entries.first(),
// the oldest one created the page, which is undone by deleting it
canUndo = uiState.canRevert && entry != uiState.entries.last(),
undoCheck = uiState.undoChecks[entry.revision],
canRestoreSection = uiState.canRestoreSection && entry != uiState.entries.first(),
onUiEvent = onUiEvent,
)
Expand Down Expand Up @@ -169,6 +171,7 @@ private fun HistoryEntry(
diff: DiffState?,
canRestore: Boolean,
canUndo: Boolean,
undoCheck: UndoCheck?,
canRestoreSection: Boolean,
onUiEvent: (UiEvent) -> Unit,
) {
Expand Down Expand Up @@ -211,9 +214,29 @@ private fun HistoryEntry(
{ hunk -> onUiEvent(UiEvent.RestoreSectionClicked(entry, hunk)) }
} else null,
)
// why the change can't be undone, instead of a button that would only say so after the tap
val undoProblem = when (undoCheck) {
UndoCheck.Gone -> stringResource(R.string.history_undo_gone)
is UndoCheck.Conflict -> {
val top = stringResource(R.string.history_page_start)
stringResource(R.string.history_undo_conflict, undoCheck.headings.joinToString(", ") { it ?: top })
}
else -> null
}.takeIf { canUndo }
if (undoProblem != null) {
Text(
modifier = Modifier.padding(top = 8.dp),
text = undoProblem,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Row(modifier = Modifier.padding(top = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
if (canUndo) {
OutlinedButton(onClick = { onUiEvent(UiEvent.UndoClicked(entry)) }) {
if (canUndo && undoProblem == null) {
OutlinedButton(
enabled = undoCheck != UndoCheck.Checking,
onClick = { onUiEvent(UiEvent.UndoClicked(entry)) },
) {
Text(stringResource(R.string.history_undo_action))
}
}
Expand Down
1 change: 1 addition & 0 deletions app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -469,6 +469,7 @@
<string name="history_undo">Undo</string>
<string name="history_undone">Change undone</string>
<string name="history_undo_nothing">This change is not in the page anymore.</string>
<string name="history_undo_gone">Can\'t undo: this change was undone already or edited away.</string>
<string name="history_undo_conflict">Can\'t undo: later changes in %1$s are in the way.</string>
<string name="history_restore_section_action">Restore “%1$s”</string>
<string name="history_restore_section_title">Restore this section?</string>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ 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 de.markusressel.mkdocsrestclient.history.RevertCheckModel
import de.markusressel.mkdocsrestclient.history.RevertConflictModel
import de.markusressel.mkdocseditor.feature.history.ui.HistoryViewModel.UndoCheck
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.launch
Expand Down Expand Up @@ -52,6 +55,8 @@ class HistoryViewModelTest {
private var revertAnswer: Result<HistoryEntryModel, FuelError> = Result.success(entry("d"))
private val restoredSections = mutableListOf<Triple<String, String, Int>>()
private var sectionAnswer: Result<String, FuelError> = Result.success("")
private var checkAnswer: Result<RevertCheckModel, FuelError> = Result.success(RevertCheckModel(possible = true))
private val checked = mutableListOf<String>()
private var historyRequests = 0
private val events = mutableListOf<HistoryEvent>()

Expand All @@ -66,6 +71,11 @@ class HistoryViewModelTest {
return Result.success(HistoryDiffModel(from, to, listOf(hunk)))
}

override suspend fun checkDocumentRevert(documentId: String, revision: String): Result<RevertCheckModel, FuelError> {
checked += revision
return checkAnswer
}

override suspend fun revertDocumentRevision(documentId: String, revision: String): Result<HistoryEntryModel, FuelError> {
reverted += revision
return revertAnswer
Expand Down Expand Up @@ -93,10 +103,11 @@ class HistoryViewModelTest {
@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, canRevert = true)
}
private fun TestScope.viewModel(canRestore: Boolean = true, canCheckRevert: Boolean = false) =
HistoryViewModel(client).also { viewModel ->
backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { viewModel.events.collect { events += it } }
viewModel.initialize("d1", canRestore, canRevert = true, canCheckRevert = canCheckRevert)
}

@Test
fun `the history of the document is listed newest first`() = runTest {
Expand Down Expand Up @@ -264,4 +275,50 @@ class HistoryViewModelTest {
assertEquals(listOf<HistoryEvent>(HistoryEvent.SectionMissing("Setup", inRevision = false)), events)
assertEquals(1, historyRequests)
}

@Test
fun `an opened entry asks each time whether its change can be undone`() = runTest {
checkAnswer = Result.success(RevertCheckModel(possible = false, code = "nothing-to-revert"))
val viewModel = viewModel(canCheckRevert = true)

viewModel.onUiEvent(UiEvent.EntryClicked("b"))
assertEquals(UndoCheck.Gone, viewModel.uiState.value.undoChecks["b"])

checkAnswer = Result.success(
RevertCheckModel(possible = false, code = "revert-conflict", details = RevertConflictModel(listOf("Install", null)))
)
viewModel.onUiEvent(UiEvent.EntryClicked("b"))
viewModel.onUiEvent(UiEvent.EntryClicked("b"))

assertEquals(UndoCheck.Conflict(listOf("Install", null)), viewModel.uiState.value.undoChecks["b"])
assertEquals(listOf("b", "b"), checked)
}

@Test
fun `the first version and a server without the check are not asked`() = runTest {
viewModel(canCheckRevert = true).onUiEvent(UiEvent.EntryClicked("a"))
viewModel(canCheckRevert = false).onUiEvent(UiEvent.EntryClicked("b"))

assertEquals(emptyList(), checked)
}

@Test
fun `a failed check leaves the undo to tell`() = runTest {
checkAnswer = Result.error(FuelError.wrap(RuntimeException("500"), Response(URL("http://localhost/"), statusCode = 500)))
val viewModel = viewModel(canCheckRevert = true)

viewModel.onUiEvent(UiEvent.EntryClicked("b"))

assertEquals(UndoCheck.Possible, viewModel.uiState.value.undoChecks["b"])
}

@Test
fun `after an undo the open entry is asked again`() = runTest {
val viewModel = viewModel(canCheckRevert = true)
viewModel.onUiEvent(UiEvent.EntryClicked("b"))
viewModel.onUiEvent(UiEvent.UndoClicked(entry("b")))
viewModel.onUiEvent(UiEvent.Confirmed)

assertEquals(listOf("b", "b"), checked)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ 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.UndoCheck
import de.markusressel.mkdocseditor.feature.history.ui.HistoryViewModel.UiState
import de.markusressel.mkdocseditor.feature.theme.MkDocsEditorTheme
import de.markusressel.mkdocsrestclient.history.DiffHunkModel
Expand Down Expand Up @@ -180,4 +181,40 @@ class HistoryScreenContentTest {

composeRule.onNodeWithText("Restore “Install”").assertDoesNotExist()
}

@Test
fun `a change that can't be undone says why instead of offering the undo`() {
composeRule.setContent {
Shown {
HistoryScreenContent(
UiState(
loading = false, entries = entries, expanded = "b", diffs = mapOf("b" to DiffState.Loaded(listOf(hunk))),
canRevert = true, undoChecks = mapOf("b" to UndoCheck.Conflict(listOf("Install"))),
),
onUiEvent = {},
)
}
}

composeRule.onNodeWithText("Can't undo: later changes in Install are in the way.").assertExists()
composeRule.onNodeWithText("Undo this change").assertDoesNotExist()
}

@Test
fun `a change undone already says so`() {
composeRule.setContent {
Shown {
HistoryScreenContent(
UiState(
loading = false, entries = entries, expanded = "b", diffs = mapOf("b" to DiffState.Loaded(listOf(hunk))),
canRevert = true, undoChecks = mapOf("b" to UndoCheck.Gone),
),
onUiEvent = {},
)
}
}

composeRule.onNodeWithText("Can't undo: this change was undone already or edited away.").assertExists()
composeRule.onNodeWithText("Undo this change").assertDoesNotExist()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,9 @@ object ServerFeature {
/** `POST /document/{id}/history/{revision}/revert/` */
const val REVERT = "revert"

/** `GET /document/{id}/history/{revision}/revert/`: whether a revert would work */
const val REVERT_CHECK = "revert-check"

/** `GET /document/{id}/blame/` and the restore of a single section */
const val BLAME = "blame"
}
Expand Down
Loading
Loading