package com.cottondb.android import com.cottondb.android.core.CottonCalling import com.cottondb.android.navigation.Route import com.cottondb.android.work.memory.* import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Deferred import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import 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() private val entries = mutableMapOf() private val lifetimes = mutableMapOf() 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 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) { 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().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(null) val undo = mutableUndo.asStateFlow() fun submit(action: MemoryAction, undo: MemoryUndo? = null): Deferred? { 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) : 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() } }