Yokan / rebuild
Course 1 8624561

Navigator.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/navigation/Navigator.kt

implementation205 lines
1package eu.friedcutlet.yokan.ui.navigation23import androidx.lifecycle.ViewModelStore4import androidx.lifecycle.viewModelScope5import androidx.lifecycle.ViewModelStoreOwner6import eu.friedcutlet.yokan.data.SettingsStore7import eu.friedcutlet.yokan.domain.ItemType8import kotlinx.coroutines.CoroutineScope9import kotlinx.coroutines.Job10import kotlinx.coroutines.NonCancellable11import kotlinx.coroutines.SupervisorJob12import kotlinx.coroutines.cancel13import kotlinx.coroutines.withContext14import kotlinx.coroutines.sync.Mutex15import kotlinx.coroutines.sync.withLock16import kotlinx.coroutines.flow.MutableStateFlow17import kotlinx.coroutines.flow.SharingStarted18import kotlinx.coroutines.flow.StateFlow19import kotlinx.coroutines.flow.asStateFlow20import kotlinx.coroutines.flow.combine21import kotlinx.coroutines.flow.map22import kotlinx.coroutines.flow.stateIn23import kotlinx.coroutines.launch24import eu.friedcutlet.yokan.ui.navigation.navigationOrder as visibleSections2526/** One back-stack entry; its [viewModelStore] lives until the entry leaves the stack. */27class NavEntry internal constructor(val id: Long, val route: Route) : ViewModelStoreOwner {28    override val viewModelStore = ViewModelStore()29}3031/** Asks the library for [itemType] to show [query] (all categories), or its default category when null. */32data class LibraryRequest(val id: Long, val itemType: ItemType, val query: String?)3334/**35 * App navigation: the selected root section, the per-section item-type cursor and the stack of36 * pushed [Route]s. Main-thread only.37 */38class Navigator(private val settings: SettingsStore, scope: CoroutineScope) {39    private val uiContext = scope.coroutineContext.minusKey(Job)40    private val ownerJob = SupervisorJob(scope.coroutineContext[Job])41    private val ownerScope = CoroutineScope(scope.coroutineContext + ownerJob)42    private val retirementLock = Mutex()43    private val entries = mutableSetOf<NavEntry>()44    private val pendingJobs = mutableSetOf<Job>()45    private val pendingCleanup = mutableSetOf<AwaitedViewModelCleanup>()46    private var closed = false4748    private var nextEntryId = 0L49    private var nextRequestId = 0L50    private val itemTypeBySection = mutableMapOf(51        NavSection.TrackerLibrary to ItemType.Manga,52        NavSection.Updates to ItemType.Manga,53        NavSection.History to ItemType.Manga,54        NavSection.Browse to ItemType.Manga,55    )5657    private val _backStack = MutableStateFlow<List<NavEntry>>(emptyList())58    val backStack: StateFlow<List<NavEntry>> = _backStack.asStateFlow()5960    val navigationOrder: StateFlow<List<NavSection>>61    val hiddenSections: StateFlow<Set<NavSection>>6263    private val _section: MutableStateFlow<NavSection>64    val section: StateFlow<NavSection>6566    private val _itemType: MutableStateFlow<ItemType>67    val itemType: StateFlow<ItemType>6869    private val _transitionDirection = MutableStateFlow(1)70    val transitionDirection: StateFlow<Int> = _transitionDirection.asStateFlow()7172    private val _playerMinimized = MutableStateFlow(false)73    val playerMinimized: StateFlow<Boolean> = _playerMinimized.asStateFlow()7475    private val _libraryRequest = MutableStateFlow<LibraryRequest?>(null)76    val libraryRequest: StateFlow<LibraryRequest?> = _libraryRequest.asStateFlow()7778    val rootViewModelStoreOwner: ViewModelStoreOwner = object : ViewModelStoreOwner {79        override val viewModelStore = ViewModelStore()80    }8182    init {83        if (settings.db.value.withNavigationOrderMigrated() != settings.db.value) {84            settings.updateDb { it.withNavigationOrderMigrated() }85        }86        val db = settings.db.value87        navigationOrder = settings.db.map { visibleSections(it) }88            .stateIn(ownerScope, SharingStarted.Eagerly, visibleSections(db))89        hiddenSections = settings.db.map { hiddenNavigationSections(it) }90            .stateIn(ownerScope, SharingStarted.Eagerly, hiddenNavigationSections(db))91        val initialSection = navigationOrder.value.firstOrNull() ?: NavSection.MangaLibrary92        _section = MutableStateFlow(initialSection)93        section = _section.asStateFlow()94        _itemType = MutableStateFlow(initialSection.itemType ?: itemTypeBySection[initialSection] ?: ItemType.Manga)95        itemType = _itemType.asStateFlow()96        // A section that is hidden (or was opened by a deep link while hidden) falls back to the first visible one.97        ownerScope.launch {98            combine(section, navigationOrder) { current, order -> current to order }.collect { (current, order) ->99                if (current !in order) order.firstOrNull()?.let(::select)100            }101        }102    }103104    fun navigate(route: Route) {105        if (closed) return106        if (route is Route.Reader) _playerMinimized.value = false107        val stack = _backStack.value108        val entry = NavEntry(nextEntryId++, route).also { entries += it }109        val replaceTop = stack.lastOrNull()?.route?.destination() == route.destination()110        _transitionDirection.value = 1111        _backStack.value = if (replaceTop) stack.dropLast(1) + entry else stack + entry112    }113114    fun back() = pop(direction = -1)115116    fun completeInteractiveBack() = pop(direction = 0)117118    private fun pop(direction: Int) {119        if (closed) return120        val stack = _backStack.value121        if (stack.isEmpty()) return122        _transitionDirection.value = direction123        _backStack.value = stack.dropLast(1)124    }125126    fun select(section: NavSection) {127        if (closed) return128        val popped = _backStack.value129        if (popped.isNotEmpty()) _transitionDirection.value = -1130        _backStack.value = emptyList()131        // The top is still composed (exit animation); the host releases it. Nothing below is composed.132        popped.dropLast(1).forEach(::clearEntry)133        _section.value = section134        (section.itemType ?: itemTypeBySection[section])?.let { _itemType.value = it }135        section.itemType?.let { requestLibrary(it, query = null) }136    }137138    /** Switches the root item type; Updates/History/Browse/Tracking remember it per section. */139    fun selectItemType(type: ItemType) {140        if (closed) return141        if (_itemType.value == type) return142        _itemType.value = type143        if (_section.value in itemTypeBySection) itemTypeBySection[_section.value] = type144    }145146    fun showLibrary(itemType: ItemType, query: String? = null) {147        select(itemType.librarySection())148        requestLibrary(itemType, query)149    }150151    private fun requestLibrary(itemType: ItemType, query: String?) {152        if (closed) return153        _libraryRequest.value = LibraryRequest(nextRequestId++, itemType, query)154    }155156    fun minimizePlayer() { if (!closed) _playerMinimized.value = true }157158    fun restorePlayer() { if (!closed) _playerMinimized.value = false }159160    fun dismissPlayer() {161        restorePlayer()162        back()163    }164165    /** Clears [entry]'s ViewModels once it has left the stack; true when it did. */166    internal fun release(entry: NavEntry): Boolean {167        if (entry in _backStack.value) return false168        clearEntry(entry)169        return true170    }171172    private fun clearStore(store: ViewModelStore) {173        // Capture scopes before clear removes references and cancels them. Retain jobs even for174        // entries already popped: their non-cancelable finalizers may still own profile resources.175        store.keys().mapNotNull(store::get).forEach { model ->176            model.viewModelScope.coroutineContext[Job]?.let { pendingJobs += it }177            (model as? AwaitedViewModelCleanup)?.let { pendingCleanup += it }178        }179        store.clear()180        pendingJobs.removeAll { it.isCompleted }181    }182183    private fun clearEntry(entry: NavEntry) {184        clearStore(entry.viewModelStore)185        entries.remove(entry)186    }187188    /** Synchronously close navigation admission and cancel every owned ViewModel and watcher. */189    fun close() {190        closed = true191        ownerScope.cancel()192        entries.toList().forEach(::clearEntry)193        clearStore(rootViewModelStoreOwner.viewModelStore)194    }195196    /** Call on the captured UI context, after child composition disposal and progress capture. */197    suspend fun closeAndJoin() = withContext(uiContext + NonCancellable) {198        retirementLock.withLock {199            close()200            pendingJobs.toList().forEach { it.join(); pendingJobs.remove(it) }201            pendingCleanup.toList().forEach { it.awaitCleanup(); pendingCleanup.remove(it) }202            ownerJob.join()203        }204    }205}206

Search chapters, reference and source filenames.