135 lines · 5.5 KB · KotlinRaw
package com.cottondb.androidimport com.cottondb.android.core.CottonCallingimport com.cottondb.android.navigation.Routeimport com.cottondb.android.work.memory.*import kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.CoroutineStartimport kotlinx.coroutines.Deferredimport kotlinx.coroutines.Jobimport kotlinx.coroutines.SupervisorJobimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.asStateFlowimport kotlinx.coroutines.launch/** Main-thread models survive pushed detail routes and rotation while their route remains in the stack. */class MemoryModels(core: CottonCalling, private val scope: CoroutineScope) { private val reads = MemoryRepository(core) private val writes = RepositoryMemoryMutationGateway(MemoryWriteRepository(core)) private val lists = mutableMapOf<MemoryListKey, MemoryListVisit>() private val entries = mutableMapOf<String, MemoryEntryVisit>() private val lifetimes = mutableMapOf<MemoryVisit, Job>() fun list(key: MemoryListKey) = lists.getOrPut(key) { ownedVisit { visitScope -> MemoryListVisit(MemoryListModel(reads, key, visitScope), writes, visitScope) } } fun entry(id: String) = entries.getOrPut(id) { ownedVisit { visitScope -> MemoryEntryVisit(MemoryEntryModel(reads, id, visitScope), writes, visitScope) } } private fun <T : MemoryVisit> ownedVisit(create: (CoroutineScope) -> T): T { val lifetime = SupervisorJob(scope.coroutineContext[Job]) return create(CoroutineScope(scope.coroutineContext + lifetime)).also { lifetimes[it] = lifetime } } private fun retire(visit: MemoryVisit) { visit.close() // The eager read collectors belong to this visit, too, not the whole application. lifetimes.remove(visit)?.cancel() } fun retain(routes: List<Route>) { val listKeys = routes.mapNotNull { route -> when (route) { is Route.ProjectsMemory -> MemoryListKey(project = route.slug) Route.MemoryDropped -> MemoryListKey(archived = true) else -> null } }.toSet() val ids = routes.filterIsInstance<Route.Memory>().map { it.id }.toSet() lists.keys.filterNot(listKeys::contains).forEach { lists.remove(it)?.let(::retire) } entries.keys.filterNot(ids::contains).forEach { entries.remove(it)?.let(::retire) } }}/** Keeps the undo only once its immutable successful receipt is classified. */open class MemoryVisit( gateway: MemoryMutationGateway, scope: CoroutineScope, refresh: suspend () -> Boolean,) : AutoCloseable { val writer = MemoryMutationModel(gateway, scope, refresh, ::appliedReceipt) protected val mutableUndo = MutableStateFlow<MemoryUndo?>(null) val undo = mutableUndo.asStateFlow() fun submit(action: MemoryAction, undo: MemoryUndo? = null): Deferred<MemoryMutationResult>? { if (!writer.state.value.canMutate) return null return writer.submit(action, undo) } fun undo() { mutableUndo.value?.let { submit(it.action) } } private fun appliedReceipt(receipt: MemoryMutationReceipt) { mutableUndo.value = receipt.undo applied(receipt.action) } protected open fun applied(action: MemoryAction) = Unit override fun close() { writer.close() }}class MemoryListVisit( val read: MemoryListModel, gateway: MemoryMutationGateway, scope: CoroutineScope,) : MemoryVisit(gateway, scope, { read.refresh() != null }) { fun drop(entry: MemoryListEntry) { val project = read.key.project ?: return submit(MemoryAction.Unlink(entry.id, project), MemoryUndo(MemoryAction.Link(entry.id, project), "Dropped")) }}sealed interface MemoryTitleCommit { data object Unchanged : MemoryTitleCommit data object Blocked : MemoryTitleCommit data class Started(val result: Deferred<MemoryMutationResult>) : MemoryTitleCommit}class MemoryEntryVisit( val read: MemoryEntryModel, gateway: MemoryMutationGateway, scope: CoroutineScope,) : MemoryVisit(gateway, scope, { read.refresh() != null }) { val drafts = MemoryDrafts() private val seeding = scope.launch(start = CoroutineStart.UNDISPATCHED) { read.state.collect { state -> val answer = when (state) { is MemoryEntryState.Data -> state.read is MemoryEntryState.Error -> state.last MemoryEntryState.Loading -> null } answer?.entry?.let { drafts.seed(it.title) } } } fun saveTitle(): MemoryTitleCommit { // Read admission synchronously: a Compose callback can run before busy recomposes. if (writer.state.value.busy) return MemoryTitleCommit.Blocked val draft = drafts.state.value if (draft.remoteTitle != null) return MemoryTitleCommit.Blocked if (draft.seededTitle == null || draft.title.trim() == draft.seededTitle) return MemoryTitleCommit.Unchanged // Empty edits reach validation and show its refusal; they never silently navigate away. val save = submit(MemoryAction.UpdateTitle(read.id, draft.title)) ?: return MemoryTitleCommit.Blocked return MemoryTitleCommit.Started(save) } override fun applied(action: MemoryAction) { when (action) { is MemoryAction.CreateComment -> drafts.commentSaved(action.body, action.parentId) is MemoryAction.ResolveComment -> drafts.threadResolved(action.commentId) else -> Unit } } override fun close() { seeding.cancel(); super.close() }}