# 10 — navigation-and-design-system: file workbook

[Implementation chapter](../chapters/10-navigation-and-design-system.md) · [Coverage index](README.md)

Each text entry includes the complete pinned file to write at the displayed path, plus an exact-byte download. Read the chapter for implementation order and behavior, then connect callers and reproduce the tests. Platform variants preserve their platform capabilities. Binary assets are retained with applicable licenses or independently recreated, not transcribed as code.

**Pinned baseline for comparison.** Use the reviewed listings in the [implementation chapters](../README.md#reading-order) and the [reviewed source archive](reviewed-source.zip) when reconstructing the app. See the [architecture review](architecture-review.md) for changes.

## `composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/ui/SecureScreen.android.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/ui/SecureScreen.android.kt) · implementation · 15 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.

Declaration checklist (source line numbers):
```text
9: internal actual fun SecureScreenEffect(secure: Boolean) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/ui/SecureScreen.android.kt) · SHA-256 `06f313db55910284fee12336d24e36a963d8d48bc2e4697498c4c2f5ad996b2a`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui

import android.view.WindowManager
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import eu.friedcutlet.yokan.AndroidForegroundActivity

@Composable
internal actual fun SecureScreenEffect(secure: Boolean) {
    DisposableEffect(secure) {
        val window = AndroidForegroundActivity.activity?.window
        if (secure) window?.addFlags(WindowManager.LayoutParams.FLAG_SECURE) else window?.clearFlags(WindowManager.LayoutParams.FLAG_SECURE)
        onDispose { }
    }
}
```
[complete-source-end]: #

## `composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/ui/components/Scrollbar.android.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/ui/components/Scrollbar.android.kt) · implementation · 16 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
10: internal actual fun BoxScope.PlatformVerticalScrollbar(state: LazyListState) = Unit
13: internal actual fun BoxScope.PlatformVerticalScrollbar(state: LazyGridState) = Unit
16: internal actual fun BoxScope.PlatformVerticalScrollbar(state: ScrollState) = Unit
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/ui/components/Scrollbar.android.kt) · SHA-256 `187af72d36701b91b619458c0ed81e18f68048b79126d2ed1263e69e7a0ef60e`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.components

import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.grid.LazyGridState
import androidx.compose.runtime.Composable

@Composable
internal actual fun BoxScope.PlatformVerticalScrollbar(state: LazyListState) = Unit

@Composable
internal actual fun BoxScope.PlatformVerticalScrollbar(state: LazyGridState) = Unit

@Composable
internal actual fun BoxScope.PlatformVerticalScrollbar(state: ScrollState) = Unit
```
[complete-source-end]: #

## `composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/ui/image/PlatformImageDecoders.android.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/ui/image/PlatformImageDecoders.android.kt) · implementation · 5 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
5: internal actual fun addPlatformImageDecoders(components: ComponentRegistry.Builder) = Unit
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/ui/image/PlatformImageDecoders.android.kt) · SHA-256 `9e9a01f3e26ab97c7107e0253af4a7aff7dc5da5cd07e922fa65841954276820`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.image

import coil3.ComponentRegistry

internal actual fun addPlatformImageDecoders(components: ComponentRegistry.Builder) = Unit
```
[complete-source-end]: #

## `composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/ui/navigation/PlatformNavigation.android.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/ui/navigation/PlatformNavigation.android.kt) · implementation · 3 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
3: internal actual fun usesCupertinoPageTransitions(): Boolean = false
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/ui/navigation/PlatformNavigation.android.kt) · SHA-256 `3f7994820fdb314dc673eef72a7005590718ec0e4a1b10358c2f0a5ff3fde722`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.navigation

internal actual fun usesCupertinoPageTransitions(): Boolean = false
```
[complete-source-end]: #

## `composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/ui/theme/MaterialYou.android.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/ui/theme/MaterialYou.android.kt) · implementation · 17 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
11: actual fun rememberMaterialYouScheme(isDark: Boolean): ColorScheme? {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/ui/theme/MaterialYou.android.kt) · SHA-256 `b712ba06fd6188929878f9dfd600be0717bf95bed159bcf3d31e401b9011190b`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.theme

import android.os.Build
import androidx.compose.material3.ColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext

@Composable
actual fun rememberMaterialYouScheme(isDark: Boolean): ColorScheme? {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) return null
    val context = LocalContext.current
    return if (isDark) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}

actual val materialYouAvailable: Boolean = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
```
[complete-source-end]: #

## `composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/ui/theme/SystemBarTheme.android.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/ui/theme/SystemBarTheme.android.kt) · implementation · 17 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
9: actual fun applySystemBarTheme(isDark: Boolean) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/ui/theme/SystemBarTheme.android.kt) · SHA-256 `1d47ff5aee8a5613d67b7cec7cb881db78b0ec056d6892ba853b09fe6bde8ed1`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.theme

import android.graphics.Color
import androidx.activity.ComponentActivity
import androidx.activity.SystemBarStyle
import androidx.activity.enableEdgeToEdge
import eu.friedcutlet.yokan.AndroidForegroundActivity

actual fun applySystemBarTheme(isDark: Boolean) {
    val activity = AndroidForegroundActivity.activity as? ComponentActivity ?: return
    activity.runOnUiThread {
        activity.enableEdgeToEdge(
            statusBarStyle = SystemBarStyle.auto(Color.TRANSPARENT, Color.TRANSPARENT) { isDark },
            navigationBarStyle = SystemBarStyle.auto(Color.TRANSPARENT, Color.TRANSPARENT) { isDark },
        )
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/App.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/App.kt) · implementation · 438 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
104: fun YokanApp() {
154: private fun YokanReadyApp(owner: ProfileSession, initialDeepLink: String?, catalogEnrollmentEnabled: Boolean) {
175: private fun YokanAppContent(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/App.kt) · SHA-256 `a36e2c0fbfa61da590fb31f3b557483179b159d001051aead516a497e3e5717d`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui

import androidx.compose.foundation.focusGroup
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.consumeWindowInsets
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ScaffoldDefaults
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusDirection
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.input.key.type
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.unit.dp
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LifecycleEventEffect
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import coil3.compose.LocalPlatformContext
import coil3.SingletonImageLoader
import androidx.compose.material3.TextButton
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.*
import eu.friedcutlet.yokan.app.profiles.*
import eu.friedcutlet.yokan.ui.screens.settings.profiles.*
import eu.friedcutlet.yokan.app.AppBootstrapReport
import eu.friedcutlet.yokan.services.system.AppDeepLinks
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.database.secureScreenActive
import eu.friedcutlet.yokan.app.runAppStartup
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.media.player.pictureInPicturePlatform
import eu.friedcutlet.yokan.services.sync.SyncTriggerKind
import eu.friedcutlet.yokan.services.system.applyAppLanguage
import eu.friedcutlet.yokan.services.system.isTvDevice
import eu.friedcutlet.yokan.services.system.showBottomNavigation
import eu.friedcutlet.yokan.services.system.useRailNavigation
import eu.friedcutlet.yokan.ui.image.newYokanImageLoader
import eu.friedcutlet.yokan.ui.navigation.BottomNavigation
import eu.friedcutlet.yokan.ui.navigation.DeepLinkViewModel
import eu.friedcutlet.yokan.ui.navigation.NavHost
import eu.friedcutlet.yokan.ui.navigation.Navigator
import eu.friedcutlet.yokan.ui.navigation.PendingDeepLinkDialog
import eu.friedcutlet.yokan.ui.navigation.RailNavigation
import eu.friedcutlet.yokan.ui.navigation.Route
import eu.friedcutlet.yokan.ui.navigation.SettingsPage
import eu.friedcutlet.yokan.ui.navigation.navBadges
import eu.friedcutlet.yokan.ui.navigation.rootNavigationGestures
import eu.friedcutlet.yokan.ui.navigation.usesCupertinoPageTransitions
import eu.friedcutlet.yokan.ui.screens.applock.AppLockLifecycleEffect
import eu.friedcutlet.yokan.ui.screens.applock.AppLockOverlay
import eu.friedcutlet.yokan.ui.screens.browse.rememberSignedCatalogSheet
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.ui.screens.activity.resumeLatestHistory
import eu.friedcutlet.yokan.ui.screens.onboarding.OnboardingScreen
import eu.friedcutlet.yokan.ui.screens.onboarding.RequiredOnboardingVersion
import eu.friedcutlet.yokan.ui.screens.onboarding.needsOnboarding
import eu.friedcutlet.yokan.ui.screens.player.MinimizedAnimePlayerHeight
import eu.friedcutlet.yokan.ui.screens.player.MinimizedAnimePlayerMargin
import eu.friedcutlet.yokan.ui.status.GlobalStatusOverlayHost
import eu.friedcutlet.yokan.ui.status.InAppSnackbarEffect
import eu.friedcutlet.yokan.ui.status.GlobalStatusViewModel
import eu.friedcutlet.yokan.ui.status.LocalGlobalStatusOpener
import eu.friedcutlet.yokan.ui.theme.LocalYokanScaffoldColor
import eu.friedcutlet.yokan.ui.theme.YokanScaffold as Scaffold
import eu.friedcutlet.yokan.ui.theme.YokanThemeFromSettings
import eu.friedcutlet.yokan.ui.tv.handleTvDpadNavigation
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

@Composable
fun YokanApp() {
    var bootstrapReport by remember { mutableStateOf<AppBootstrapReport?>(null) }
    var bootstrapError by remember { mutableStateOf<String?>(null) }
    LaunchedEffect(Unit) {
        catchingNonCancellation {
            withContext(Dispatchers.Default) { YokanRuntime.bootstrap() }
        }.onSuccess { bootstrapReport = it }
            .onFailure { bootstrapError = it.message.orEmpty().ifBlank { "App startup failed" } }
    }
    val report = bootstrapReport
    if (report == null) {
        Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
            bootstrapError?.let { Text(it, color = MaterialTheme.colorScheme.error) }
                ?: CircularProgressIndicator()
        }
        return
    }
    val deviceStore = remember { object : ViewModelStoreOwner { override val viewModelStore = ViewModelStore() } }
    DisposableEffect(deviceStore) { onDispose { deviceStore.viewModelStore.clear() } }
    val profilesModel = viewModel(viewModelStoreOwner = deviceStore) { ProfilesViewModel(YokanRuntime.profiles, YokanRuntime.profileCoordinator) }
    val profilesState by profilesModel.state.collectAsStateWithLifecycle()
    val activation by YokanRuntime.profileCoordinator.state.collectAsStateWithLifecycle()
    LifecycleEventEffect(Lifecycle.Event.ON_START) { profilesModel.resumeLastProfile() }
    val controls = ProfileControls(profilesState, profilesModel::switchTo, profilesModel::showCreate, profilesModel::showRename,
        profilesModel::showDelete, profilesModel::retryProvisioning, profilesModel::refresh, profilesModel::changeName, profilesModel::confirm, profilesModel::dismissDialog)
    val backupModel = viewModel(viewModelStoreOwner = deviceStore, key = "profile-backups") {
        ProfileBackupsViewModel(YokanRuntime.profiles, ProfileBackupOperations(YokanRuntime.profiles, YokanRuntime.profileCoordinator))
    }
    val backupState by backupModel.state.collectAsStateWithLifecycle()
    val backupControls = ProfileBackupControls(backupState, backupModel::select, backupModel::password, backupModel::format,
        backupModel::mode, backupModel::export, backupModel::chooseFile, backupModel::unlock, backupModel::apply,
        { backupModel.refreshSnapshots() }, backupModel::rollback)
    val initialOwner = remember { YokanRuntime.activeSession }
    CompositionLocalProvider(LocalProfileControls provides controls, LocalProfileBackupControls provides backupControls) {
        when (val current = activation) {
            is ProfileActivationState.Ready -> key(current.session) {
                YokanReadyApp(current.session, if (current.session === initialOwner) report.initialDeepLink else null, report.platform.platformName != "Web")
            }
            is ProfileActivationState.Switching -> Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { CircularProgressIndicator() }
            is ProfileActivationState.RecoveryRequired -> Column(Modifier.fillMaxSize().padding(24.dp), horizontalAlignment = Alignment.CenterHorizontally) {
                Text(stringResource(Res.string.profiles_recovery))
                Text(current.message, color = MaterialTheme.colorScheme.error)
                TextButton(onClick = profilesModel::recover, enabled = !profilesState.busy) { Text(stringResource(Res.string.profiles_retry)) }
            }
        }
    }
}

@OptIn(coil3.annotation.DelicateCoilApi::class)
@Composable
private fun YokanReadyApp(owner: ProfileSession, initialDeepLink: String?, catalogEnrollmentEnabled: Boolean) {
    val platformContext = LocalPlatformContext.current
    val navScope = rememberCoroutineScope()
    val imageLoader = remember(owner, platformContext) { newYokanImageLoader(platformContext, owner).also(SingletonImageLoader::setUnsafe) }
    DisposableEffect(owner) {
        val disposed = YokanRuntime.profileUi.mount(owner)
        onDispose { disposed() }
    }
    val nav = remember(owner) {
        owner.ownResource(factory = { Navigator(owner.settings, navScope) }, close = { it.closeAndJoin() })
    }
    LaunchedEffect(owner) { owner.runBackgroundWork { runAppStartup(platformContext) } }
    YokanAppContent(
        nav = nav,
        initialDeepLink = initialDeepLink,
        catalogEnrollmentEnabled = catalogEnrollmentEnabled,
    )
}

@OptIn(ExperimentalComposeUiApi::class, ExperimentalMaterial3Api::class)
@Composable
private fun YokanAppContent(
    nav: Navigator,
    initialDeepLink: String?,
    catalogEnrollmentEnabled: Boolean,
) {
    val owner = remember(nav) { YokanRuntime.activeSession }
    val cupertinoNavigation = remember { usesCupertinoPageTransitions() }
    val globalStatusViewModel = viewModel(
        viewModelStoreOwner = nav.rootViewModelStoreOwner,
        key = "global-status",
    ) {
        GlobalStatusViewModel(
            databaseSnapshots = owner.repository.snapshots,
            activeDownloads = owner.services.downloader.activeDownloadProgress,
            syncOperations = owner.services.sync.operationState,
            libraryUpdates = owner.libraryUpdates.progress,
        )
    }
    val globalStatus by globalStatusViewModel.state.collectAsStateWithLifecycle()
    val deepLinkViewModel = viewModel(
        viewModelStoreOwner = nav.rootViewModelStoreOwner,
        key = "deep-links",
    ) {
        DeepLinkViewModel(
            repository = owner.repository,
            database = owner.services.database,
            http = owner.services.http,
            navigator = nav,
        )
    }
    val deepLinkState by deepLinkViewModel.state.collectAsStateWithLifecycle()
    val signedCatalog = rememberSignedCatalogSheet(
        viewModelStoreOwner = nav.rootViewModelStoreOwner,
        installation = owner.services.recipeCatalogInstallation,
        enabled = catalogEnrollmentEnabled,
    )
    LaunchedEffect(initialDeepLink) { deepLinkViewModel.open(initialDeepLink) }
    DisposableEffect(nav) {
        val unregister = AppDeepLinks.register(deepLinkViewModel::open)
        onDispose {
            unregister()
            nav.close()
        }
    }
    val settingsStore = owner.settings
    val db by settingsStore.db.collectAsStateWithLifecycle()
    val userSettings by settingsStore.user.collectAsStateWithLifecycle()
    val onboarding = needsOnboarding(db.completedOnboardingVersion)
    val completeOnboarding = { settingsStore.updateDb { it.copy(completedOnboardingVersion = RequiredOnboardingVersion) } }
    val onResumeLatestHistory: (ItemType, String) -> Unit = { itemType, emptyMessage ->
        resumeLatestHistory(owner.repository, nav, itemType, emptyMessage)
    }
    val backStack by nav.backStack.collectAsStateWithLifecycle()
    val playerMinimized by nav.playerMinimized.collectAsStateWithLifecycle()
    val immersive = backStack.lastOrNull()?.route is Route.Reader
    val badges by remember(nav) { navBadges(owner.repository, nav.hiddenSections) }
        .collectAsStateWithLifecycle(emptyMap())
    // App lock: a full-screen overlay covers the UI until platform authentication
    // succeeds (Mangayomi's AppLockScreen-over-router).
    val appLock = remember { YokanRuntime.appLock }
    val appUnlocked by appLock.isUnlocked.collectAsStateWithLifecycle()
    val pictureInPicture by pictureInPicturePlatform.active.collectAsStateWithLifecycle()
    // The ViewModel is the single source of host context; the overlay renders its state.
    LaunchedEffect(
        immersive,
        playerMinimized,
        onboarding,
        db.appLockEnabled,
        appUnlocked,
        pictureInPicture,
    ) {
        globalStatusViewModel.updateHostContext(
            immersive = immersive,
            playerMinimized = playerMinimized,
            onboarding = onboarding,
            appLocked = db.appLockEnabled && !appUnlocked,
            pictureInPicture = pictureInPicture,
        )
    }
    AppLockLifecycleEffect(settingsStore, appLock)
    LifecycleEventEffect(Lifecycle.Event.ON_START) {
        // A retiring owner rejects resource access; a missed resume trigger is harmless.
        runCatching { owner.syncTriggers }.getOrNull()?.onTrigger(SyncTriggerKind.AppResume)
    }
    SecureScreenEffect(db.secureScreenActive())
    val snackbarHostState = remember { SnackbarHostState() }
    InAppSnackbarEffect(snackbarHostState, owner.id)
    val languageCode = db.locale?.languageCode
    // Apply the user's chosen UI language to the platform locale. The
    // surrounding `key(languageCode)` block forces the entire content tree
    // to recompose when the language changes so Compose Resources re-resolves
    // every cached string against the new locale.
    LaunchedEffect(languageCode) { applyAppLanguage(languageCode) }
    val baseDensity = LocalDensity.current
    YokanThemeFromSettings(db, userSettings.darkTheme) {
        key(languageCode) {
        Surface(
            modifier = Modifier.fillMaxSize(),
            color = LocalYokanScaffoldColor.current,
            contentColor = MaterialTheme.colorScheme.onSurface,
        ) {
            if (onboarding) {
                OnboardingScreen(
                    onSkip = completeOnboarding,
                    onFinish = completeOnboarding,
                )
            } else BoxWithConstraints(Modifier.fillMaxSize()) {
                val compact = with(baseDensity) { constraints.maxWidth.toDp() } < 600.dp
                val tv = isTvDevice()
                val showRail = useRailNavigation(tv, compact)
                val showRootNav = backStack.isEmpty() || playerMinimized
                val bottomBar: @Composable () -> Unit = {
                    BottomNavigation(
                        nav = nav,
                        badges = badges,
                        mergeLibraries = db.mergeLibraryNavMobile,
                        onResumeLatestHistory = onResumeLatestHistory,
                    )
                }
                val rail: @Composable (Modifier) -> Unit = { modifier ->
                    RailNavigation(nav = nav, badges = badges, onResumeLatestHistory = onResumeLatestHistory, modifier = modifier)
                }
                // Keep root chrome inside the moving page: adding it after a pop resizes the
                // library at the final frame, and a rail would otherwise recreate the NavHost.
                val rootContainer: @Composable (@Composable () -> Unit) -> Unit = { content ->
                    if (!cupertinoNavigation) content() else {
                        Scaffold(
                            contentWindowInsets = WindowInsets(0, 0, 0, 0),
                            bottomBar = { if (!showRail) bottomBar() },
                        ) { padding ->
                            Row(Modifier.fillMaxSize().padding(padding).consumeWindowInsets(padding)) {
                                if (showRail) rail(Modifier)
                                Box(Modifier.weight(1f).fillMaxSize().rootNavigationGestures(nav)) { content() }
                            }
                        }
                    }
                }
                CompositionLocalProvider(LocalGlobalStatusOpener provides globalStatusViewModel::open) {
                  Column(Modifier.fillMaxSize()) {
                    Scaffold(
                        modifier = Modifier.weight(1f),
                        contentWindowInsets = ScaffoldDefaults.contentWindowInsets,
                        snackbarHost = { SnackbarHost(snackbarHostState) },
                        bottomBar = {
                            if (!cupertinoNavigation && showBottomNavigation(tv, compact, showRootNav)) bottomBar()
                        },
                    ) { innerPadding ->
                        if (cupertinoNavigation || !showRail || !showRootNav) {
                            Box(
                                modifier = Modifier
                                    .fillMaxSize()
                                    .padding(innerPadding)
                                    .consumeWindowInsets(innerPadding)
                                    .let { if (showRootNav && !cupertinoNavigation) it.rootNavigationGestures(nav) else it },
                            ) {
                                NavHost(
                                    nav = nav,
                                    compact = compact,
                                    onAddSignedCatalog = signedCatalog.onAdd,
                                    signedCatalogSheet = signedCatalog.sheet,
                                    rootContainer = rootContainer,
                                )
                            }
                        } else {
                            val focusManager = LocalFocusManager.current
                            val railFocusRequester = remember { FocusRequester() }
                            val contentFocusRequester = remember { FocusRequester() }
                            var railHasFocus by remember { mutableStateOf(false) }

                            Row(
                                modifier = Modifier
                                    .fillMaxSize()
                                    .padding(innerPadding)
                                    .consumeWindowInsets(innerPadding)
                                    .then(
                                        if (tv) {
                                            Modifier.onPreviewKeyEvent { event ->
                                                handleTvDpadNavigation(
                                                    key = event.key,
                                                    isKeyDown = event.type == KeyEventType.KeyDown,
                                                    railHasFocus = railHasFocus,
                                                    moveLeft = { focusManager.moveFocus(FocusDirection.Left) },
                                                    moveRight = { focusManager.moveFocus(FocusDirection.Right) },
                                                    requestRailFocus = { railFocusRequester.requestFocus() },
                                                    requestContentFocus = { contentFocusRequester.requestFocus() },
                                                )
                                            }
                                        } else Modifier
                                    ),
                            ) {
                                rail(
                                    Modifier
                                        .focusRequester(railFocusRequester)
                                        .onFocusChanged { railHasFocus = it.hasFocus },
                                )
                                Box(
                                    modifier = Modifier
                                        .weight(1f)
                                        .fillMaxSize()
                                        .focusRequester(contentFocusRequester)
                                        .focusGroup()
                                        .let { if (showRootNav) it.rootNavigationGestures(nav) else it },
                                ) {
                                    NavHost(
                                        nav = nav,
                                        compact = false,
                                        onAddSignedCatalog = signedCatalog.onAdd,
                                        signedCatalogSheet = signedCatalog.sheet,
                                    )
                                }
                            }
                        }
                    }
                  }
                }
                GlobalStatusOverlayHost(
                    state = globalStatus,
                    onOpen = globalStatusViewModel::open,
                    onDismiss = globalStatusViewModel::dismiss,
                    onVisibilityChange = { visibility ->
                        settingsStore.updateDb { it.copy(globalStatusVisibility = visibility) }
                    },
                    onToggleDownloadedOnly = { settingsStore.update { it.copy(downloadedOnly = !it.downloadedOnly) } },
                    onToggleIncognito = { settingsStore.update { it.copy(incognitoMode = !it.incognitoMode) } },
                    onOpenDownloads = {
                        globalStatusViewModel.dismiss()
                        nav.navigate(Route.Settings(SettingsPage.DownloadQueue))
                    },
                    onOpenSync = {
                        globalStatusViewModel.dismiss()
                        nav.navigate(Route.Settings(SettingsPage.Sync))
                    },
                    onCancelLibraryUpdate = owner.libraryUpdates::cancel,
                    modifier = Modifier
                        .align(
                            if (globalStatus.immersive && !globalStatus.playerMinimized) {
                                Alignment.CenterEnd
                            } else {
                                Alignment.BottomEnd
                            },
                        )
                        .navigationBarsPadding()
                        .padding(
                            bottom = (if (compact && showRootNav) 72.dp else 0.dp) +
                                (if (globalStatus.playerMinimized) {
                                    MinimizedAnimePlayerHeight + MinimizedAnimePlayerMargin
                                } else {
                                    0.dp
                                }),
                        ),
                )
            }
            PendingDeepLinkDialog(
                state = deepLinkState,
                onConfirm = deepLinkViewModel::confirm,
                onDismiss = deepLinkViewModel::dismiss,
            )
            if (db.appLockEnabled && !appUnlocked) {
                AppLockOverlay(unlocked = appUnlocked, supported = appLock.isSupported, onUnlock = appLock::requestUnlock)
            }
        }
        } // end key(languageCode)
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/Formatting.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/Formatting.kt) · implementation · 144 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
25: fun formatTimestamp(
48: fun formatTimestamp(settings: DbSettings, epochMillis: Long): String =
52: fun formatClockTime(epochMillis: Long): String {
66: fun formatAbsoluteDate(epochMillis: Long, pattern: String): String {
89: fun parseDateToEpochMillis(raw: String): Long? {
102: private fun normalizeEpochMillis(value: Long): Long {
107: private fun startOfDayMillis(date: LocalDate): Long =
110: fun formatDecimal(value: Double, decimals: Int): String {
125: private fun epochToLocalDate(epochMillis: Long): LocalDateTime {
130: private fun monthShort(month: Int): String = when (month) {
136: private fun monthLong(month: Int): String = when (month) {
142: private fun Int.pad2(): String = if (this < 10) "0$this" else toString()
144: private fun Int.twoDigitYear(): String = (this % 100).pad2()
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/Formatting.kt) · SHA-256 `d659ab3e1776b75112db50f5e585691a598b9988c7a8448faee4f03f7826c1f8`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui

import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.util.nowMillis
import kotlin.time.Instant
import kotlinx.datetime.LocalDate
import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.TimeZone
import kotlinx.datetime.atStartOfDayIn
import kotlinx.datetime.toLocalDateTime

/**
 * Format an epoch-millis timestamp using the user's preferences from settings.
 *
 * - [DbSettings.relativeTimesTamps]:
 *   * 0 — Off: always show the absolute date in [DbSettings.dateFormat].
 *   * 1 — Short: show Today / Yesterday.
 *   * 2 — Long: show Today / Yesterday / N days ago for entries within the
 *     last week.
 *   Both relative modes fall back to the absolute date outside their relative
 *   window so timestamps stay unambiguous.
 *
 * Returns "—" if [epochMillis] is non-positive (uninitialised/never-set).
 */
fun formatTimestamp(
    epochMillis: Long,
    dateFormat: String,
    relativeMode: Int,
    now: Long = nowMillis(),
): String {
    if (epochMillis <= 0L) return "—"
    val normalizedEpochMillis = normalizeEpochMillis(epochMillis)
    if (relativeMode != 0) {
        val date = epochToLocalDate(normalizedEpochMillis).date
        val today = epochToLocalDate(now).date
        val deltaDays = ((startOfDayMillis(today) - startOfDayMillis(date)) / 86_400_000L).toInt()
        when {
            deltaDays == 0 -> return "Today"
            deltaDays == 1 -> return "Yesterday"
            relativeMode == 2 && deltaDays in 2..6 -> return "$deltaDays days ago"
            relativeMode == 2 && deltaDays == 7 -> return "A week ago"
        }
    }
    return formatAbsoluteDate(normalizedEpochMillis, dateFormat)
}

/** Top-level convenience: format using the user's settings. */
fun formatTimestamp(settings: DbSettings, epochMillis: Long): String =
    formatTimestamp(epochMillis, settings.dateFormat, settings.relativeTimesTamps)

/** Clock-only timestamp used by Mangayomi's history rows. */
fun formatClockTime(epochMillis: Long): String {
    if (epochMillis <= 0L) return "—"
    val local = epochToLocalDate(normalizeEpochMillis(epochMillis))
    return "${local.hour.pad2()}:${local.minute.pad2()}"
}

/**
 * Format [epochMillis] as a date using the user-visible values from the
 * Appearance settings picker.
 *
 * The format string is the user-visible value from the settings picker. Any
 * unrecognised pattern falls back to ISO `yyyy-MM-dd` so we never crash on a
 * malformed value in storage.
 */
fun formatAbsoluteDate(epochMillis: Long, pattern: String): String {
    val ld = epochToLocalDate(normalizeEpochMillis(epochMillis))
    val month = ld.month.ordinal + 1
    val day = ld.day
    return when (pattern) {
        "M/d/y" -> "$month/$day/${ld.year}"
        "d/M/y" -> "$day/$month/${ld.year}"
        "y/M/d" -> "${ld.year}/$month/$day"
        "MM/dd/yy" -> "${month.pad2()}/${day.pad2()}/${ld.year.twoDigitYear()}"
        "dd/MM/yy" -> "${day.pad2()}/${month.pad2()}/${ld.year.twoDigitYear()}"
        "MM/dd/yyyy" -> "${month.pad2()}/${day.pad2()}/${ld.year}"
        "dd/MM/yyyy" -> "${day.pad2()}/${month.pad2()}/${ld.year}"
        "yyyy/MM/dd" -> "${ld.year}/${month.pad2()}/${day.pad2()}"
        "yyyy-MM-dd" -> "${ld.year}-${month.pad2()}-${day.pad2()}"
        "dd MMM yyyy" -> "${day.pad2()} ${monthShort(month)} ${ld.year}"
        "MMM d, y" -> "${monthShort(month)} $day, ${ld.year}"
        "MMM d, yyyy" -> "${monthShort(month)} $day, ${ld.year}"
        "MMM dd, yyyy" -> "${monthShort(month)} ${day.pad2()}, ${ld.year}"
        "MMMM d, yyyy" -> "${monthLong(month)} $day, ${ld.year}"
        else -> "${ld.year}-${month.pad2()}-${day.pad2()}"
    }
}

fun parseDateToEpochMillis(raw: String): Long? {
    val value = raw.trim()
    if (value.isBlank()) return null
    value.toLongOrNull()?.let { return normalizeEpochMillis(it) }
    val isoMatch = Regex("""(\d{4})-(\d{1,2})-(\d{1,2})""").find(value) ?: return null
    val (year, month, day) = isoMatch.destructured
    return runCatching {
        LocalDate(year.toInt(), month.toInt(), day.toInt())
            .atStartOfDayIn(TimeZone.currentSystemDefault())
            .toEpochMilliseconds()
    }.getOrNull()
}

private fun normalizeEpochMillis(value: Long): Long {
    val abs = kotlin.math.abs(value)
    return if (abs in 1L until 10_000_000_000L) value * 1000L else value
}

private fun startOfDayMillis(date: LocalDate): Long =
    date.atStartOfDayIn(TimeZone.currentSystemDefault()).toEpochMilliseconds()

fun formatDecimal(value: Double, decimals: Int): String {
    val places = decimals.coerceAtLeast(0)
    var factor = 1L
    repeat(places) { factor *= 10L }

    val sign = if (value < 0) "-" else ""
    val scaled = kotlin.math.round(kotlin.math.abs(value) * factor).toLong()
    val whole = scaled / factor
    if (places == 0) return "$sign$whole"

    val fraction = (scaled % factor).toString().padStart(places, '0')
    return "$sign$whole.$fraction"
}

@OptIn(kotlin.time.ExperimentalTime::class)
private fun epochToLocalDate(epochMillis: Long): LocalDateTime {
    val instant = Instant.fromEpochMilliseconds(epochMillis)
    return instant.toLocalDateTime(TimeZone.currentSystemDefault())
}

private fun monthShort(month: Int): String = when (month) {
    1 -> "Jan"; 2 -> "Feb"; 3 -> "Mar"; 4 -> "Apr"; 5 -> "May"; 6 -> "Jun"
    7 -> "Jul"; 8 -> "Aug"; 9 -> "Sep"; 10 -> "Oct"; 11 -> "Nov"; 12 -> "Dec"
    else -> month.toString()
}

private fun monthLong(month: Int): String = when (month) {
    1 -> "January"; 2 -> "February"; 3 -> "March"; 4 -> "April"; 5 -> "May"; 6 -> "June"
    7 -> "July"; 8 -> "August"; 9 -> "September"; 10 -> "October"; 11 -> "November"; 12 -> "December"
    else -> month.toString()
}

private fun Int.pad2(): String = if (this < 10) "0$this" else toString()

private fun Int.twoDigitYear(): String = (this % 100).pad2()
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/SecureScreen.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/SecureScreen.kt) · implementation · 11 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.

Declaration checklist (source line numbers):
```text
11: internal expect fun SecureScreenEffect(secure: Boolean)
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/SecureScreen.kt) · SHA-256 `982e6676373f55eb2acfb6e2d06664862bf62db76ac1037b3e576cf0122d3ec3`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui

import androidx.compose.runtime.Composable

/**
 * Keeps app content out of screenshots, screen recording and the app switcher while [secure].
 * Android: FLAG_SECURE. iOS: a privacy cover in the app switcher and while the screen is
 * captured. Desktop and web have no equivalent (docs/features/PRIVACY_AND_SECURITY.md).
 */
@Composable
internal expect fun SecureScreenEffect(secure: Boolean)
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/ChoiceDialog.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/ChoiceDialog.kt) · implementation · 123 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.

Declaration checklist (source line numbers):
```text
36: fun <T> ChoiceDialog(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/ChoiceDialog.kt) · SHA-256 `6d3c378f66967de5b63f80f9f3ee54b1455d7f6714ef22c071bc8cad9b38b60e`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.components

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_cancel

/**
 * Modal single-choice picker. Replaces the "tap to cycle" pattern from the early settings tiles
 * (where each click rotated through values) with a dialog that shows every option with a
 * RadioButton, matching how Aniyomi / Mihon expose enum settings.
 */
@Composable
fun <T> ChoiceDialog(
    title: String,
    options: List<T>,
    selected: T?,
    label: (T) -> String,
    onSelect: (T) -> Unit,
    onDismiss: () -> Unit,
) {
    AlertDialog(
        onDismissRequest = onDismiss,
        modifier = Modifier.compactDialogWidth(),
        // MUI's `<Select>` overlay reads as a single rounded card with each
        // option as its own pill-shaped row — pick state tints the row instead
        // of relying on the bare radio control.
        shape = MaterialTheme.shapes.extraLarge,
        title = {
            Text(title, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
        },
        text = {
            // Wrapping the option list in a LazyColumn + ScrollbarBox lets
            // long pickers (font family, audio language, date format, etc.)
            // scroll instead of overflowing the dialog. The trailing scrollbar
            // makes the overflow discoverable. Bounded height keeps short
            // pickers (2-3 options) from claiming the whole screen.
            val listState = rememberLazyListState()
            // Important: heightIn lives on the LazyColumn itself, not on the
            // surrounding Box. If we put the height constraint on the Box and
            // let the LazyColumn use matchParentSize(), the Box has no
            // measurable children and collapses to 0 height — the dialog
            // renders with no visible options. Letting the LazyColumn size to
            // its own content (capped at 480.dp) and the Box wrap that keeps
            // short pickers compact AND keeps long pickers scrollable.
            ScrollbarBox(
                state = listState,
                modifier = Modifier.fillMaxWidth(),
            ) {
                LazyColumn(
                    state = listState,
                    modifier = Modifier
                        .fillMaxWidth()
                        .heightIn(max = 360.dp),
                    verticalArrangement = Arrangement.spacedBy(4.dp),
                ) {
                    items(options.size, key = { options[it]?.hashCode() ?: it }) { index ->
                        val option = options[index]
                        val isSelected = selected == option
                        Surface(
                            modifier = Modifier
                                .fillMaxWidth()
                                .clip(MaterialTheme.shapes.large)
                                .clickable {
                                    onSelect(option)
                                    onDismiss()
                                },
                            shape = MaterialTheme.shapes.large,
                            color = if (isSelected) MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.55f) else Color.Transparent,
                        ) {
                            Row(
                                modifier = Modifier.padding(horizontal = 8.dp, vertical = 8.dp),
                                verticalAlignment = Alignment.CenterVertically,
                            ) {
                                RadioButton(
                                    selected = isSelected,
                                    onClick = {
                                        onSelect(option)
                                        onDismiss()
                                    },
                                )
                                Spacer(Modifier.width(8.dp))
                                Text(
                                    label(option),
                                    modifier = Modifier.weight(1f),
                                    style = MaterialTheme.typography.bodyLarge,
                                    color = if (isSelected) MaterialTheme.colorScheme.onPrimaryContainer else MaterialTheme.colorScheme.onSurface,
                                    fontWeight = if (isSelected) FontWeight.Medium else FontWeight.Normal,
                                )
                            }
                        }
                    }
                }
            }
        },
        confirmButton = {},
        dismissButton = {
            TextButton(onClick = onDismiss) { Text(stringResource(Res.string.action_cancel)) }
        },
    )
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/ConfirmDialog.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/ConfirmDialog.kt) · implementation · 69 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.

Declaration checklist (source line numbers):
```text
21: fun ConfirmDialog(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/ConfirmDialog.kt) · SHA-256 `46376386a5c7d74fcbea8deca90f528ec2e993b668c456561aa4f1029470d91e`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.components

import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_cancel
import yokan.composeapp.generated.resources.dialog_confirm

@Composable
fun ConfirmDialog(
    title: String,
    message: String,
    confirmLabel: String = stringResource(Res.string.dialog_confirm),
    dismissLabel: String = stringResource(Res.string.action_cancel),
    danger: Boolean = false,
    onConfirm: () -> Unit,
    onDismiss: () -> Unit,
) {
    AlertDialog(
        onDismissRequest = onDismiss,
        modifier = Modifier.compactDialogWidth(),
        // Extra-large rounded card with a pill confirm button — danger
        // variants use the error palette so destructive actions stand out
        // without resorting to all-caps text labels.
        shape = MaterialTheme.shapes.extraLarge,
        title = {
            Text(
                title,
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.SemiBold,
            )
        },
        text = {
            Text(message, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
        },
        confirmButton = {
            Button(
                onClick = {
                    onConfirm()
                    onDismiss()
                },
                shape = RoundedCornerShape(50),
                colors = if (danger) {
                    ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.errorContainer,
                        contentColor = MaterialTheme.colorScheme.onErrorContainer,
                    )
                } else ButtonDefaults.buttonColors(),
                contentPadding = PaddingValues(horizontal = 20.dp, vertical = 8.dp),
            ) {
                Text(confirmLabel, style = MaterialTheme.typography.labelLarge)
            }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) { Text(dismissLabel) }
        },
    )
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/ContentPadding.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/ContentPadding.kt) · implementation · 28 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
17: fun adaptiveContentPadding(): PaddingValues {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/ContentPadding.kt) · SHA-256 `68f37b5dd4fb466a842e74a6496ce9ec7d4f1ec2d78b8f7caec7447b9d9fea45`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.components

import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalWindowInfo
import androidx.compose.ui.unit.dp

val DefaultContentPadding = PaddingValues(16.dp)

/**
 * Compose-friendly content padding that grows on wide viewports so library and home views don't
 * stretch edge-to-edge on desktop. Callers can swap [DefaultContentPadding] for this when they
 * want responsive horizontal whitespace.
 */
@Composable
fun adaptiveContentPadding(): PaddingValues {
    val density = LocalDensity.current
    val widthPx = LocalWindowInfo.current.containerSize.width
    val widthDp = with(density) { widthPx.toDp() }
    val horizontal = when {
        widthDp >= 1400.dp -> 64.dp
        widthDp >= 1100.dp -> 40.dp
        widthDp >= 720.dp -> 24.dp
        else -> 16.dp
    }
    return PaddingValues(horizontal = horizontal, vertical = 16.dp)
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/CoverImage.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/CoverImage.kt) · implementation · 62 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
21: fun CoverImage(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/CoverImage.kt) · SHA-256 `82d19560bf50525fa6cd6cbef41708a6ef54822a2b643190cb5531a75c799c26`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.components

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.font.FontWeight
import coil3.compose.AsyncImage

@Composable
fun CoverImage(
    model: Any?,
    contentDescription: String?,
    modifier: Modifier = Modifier,
    shape: Shape? = null,
    contentScale: ContentScale = ContentScale.Crop,
    fallbackInitials: String? = null,
) {
    val alpha = 0.25f
    val resolvedShape = shape ?: MaterialTheme.shapes.medium
    var loadFailed by remember(model) { mutableStateOf(false) }
    Box(
        modifier = modifier
            .clip(resolvedShape)
            .background(MaterialTheme.colorScheme.surfaceVariant.copy(alpha = alpha)),
        contentAlignment = Alignment.Center,
    ) {
        Box(
            modifier = Modifier
                .matchParentSize()
                .background(MaterialTheme.colorScheme.surfaceVariant.copy(alpha = alpha)),
            contentAlignment = Alignment.Center,
        ) {
            fallbackInitials?.let { initials ->
                Text(
                    text = initials,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    fontWeight = FontWeight.SemiBold,
                )
            }
        }
        if (!loadFailed && model != null) {
            AsyncImage(
                model = model,
                contentDescription = contentDescription,
                contentScale = contentScale,
                modifier = Modifier.matchParentSize(),
                onError = { loadFailed = true },
            )
        }
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/DialogWidth.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/DialogWidth.kt) · implementation · 15 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.

Declaration checklist (source line numbers):
```text
11: fun Modifier.compactDialogWidth(): Modifier =
14: fun Modifier.compactSheetWidth(): Modifier =
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/DialogWidth.kt) · SHA-256 `75c6fb54abb5f5ec050a5157b81f0d967c2150d3610364fd2b893bc712de82d3`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.components

import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.widthIn
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp

private val CompactDialogMaxWidth = 520.dp
private val CompactSheetMaxWidth = 720.dp

fun Modifier.compactDialogWidth(): Modifier =
    widthIn(max = CompactDialogMaxWidth)

fun Modifier.compactSheetWidth(): Modifier =
    widthIn(max = CompactSheetMaxWidth).fillMaxWidth()
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/Modern.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/Modern.kt) · implementation · 283 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
59: fun Modifier.hoverHighlight(onClick: (() -> Unit)? = null): Modifier {
92: fun YokanCard(
147: fun YokanPrimaryButton(
172: fun YokanTopBar(
217: fun YokanChipTabs(
238: fun YokanDivider(modifier: Modifier = Modifier, inset: Dp = 0.dp) {
247: fun YokanListRow(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/Modern.kt) · SHA-256 `2b9d44389ebade7f99417b6026fba56236619af8eab4d101d9812c89c9e526bb`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.components

import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsHoveredAsState
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.ListItemDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.SegmentedButton
import androidx.compose.material3.SegmentedButtonDefaults
import androidx.compose.material3.SingleChoiceSegmentedButtonRow
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_back

/**
 * Adds stable hover and press feedback without moving content under the
 * pointer. Touch input keeps the same pressed-color path.
 */
@Composable
fun Modifier.hoverHighlight(onClick: (() -> Unit)? = null): Modifier {
    val interactionSource = remember { MutableInteractionSource() }
    val hovered by interactionSource.collectIsHoveredAsState()
    val pressed by interactionSource.collectIsPressedAsState()
    val tint by animateColorAsState(
        targetValue = when {
            pressed -> MaterialTheme.colorScheme.primary.copy(alpha = 0.12f)
            hovered -> MaterialTheme.colorScheme.primary.copy(alpha = 0.06f)
            else -> Color.Transparent
        },
    )
    return this
        .hoverable(interactionSource = interactionSource)
        .background(tint)
        .let { base ->
            if (onClick != null) {
                base.clickable(
                    interactionSource = interactionSource,
                    indication = null,
                    onClick = onClick,
                )
            } else {
                base
            }
        }
}

/**
 * Interactive surface with a quiet outline and elevation transition. The
 * bounds stay fixed across hover and press states so dense grids do not
 * visually jitter.
 */
@Composable
fun YokanCard(
    modifier: Modifier = Modifier,
    onClick: (() -> Unit)? = null,
    padding: PaddingValues = PaddingValues(16.dp),
    content: @Composable () -> Unit,
) {
    val interactionSource = remember { MutableInteractionSource() }
    val hovered by interactionSource.collectIsHoveredAsState()
    val pressed by interactionSource.collectIsPressedAsState()

    val borderColor by animateColorAsState(
        targetValue = when {
            pressed -> MaterialTheme.colorScheme.primary
            hovered -> MaterialTheme.colorScheme.primary.copy(alpha = 0.6f)
            else -> MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.4f)
        },
    )
    val elevation by animateDpAsState(
        targetValue = when {
            pressed -> 6.dp
            hovered -> 3.dp
            else -> 1.dp
        },
    )

    Surface(
        modifier = modifier
            .hoverable(interactionSource = interactionSource)
            .let { base ->
                if (onClick != null) {
                    base.clickable(
                        interactionSource = interactionSource,
                        indication = null,
                        onClick = onClick,
                    )
                } else {
                    base
                }
            },
        shape = MaterialTheme.shapes.large,
        color = MaterialTheme.colorScheme.surfaceContainer,
        border = androidx.compose.foundation.BorderStroke(1.dp, borderColor),
        tonalElevation = elevation,
        shadowElevation = elevation,
    ) {
        Box(Modifier.padding(padding)) { content() }
    }
}

/**
 * Pill-shaped primary button with optional leading icon. The shape is forced
 * regardless of the host theme so call sites don't have to repeat the
 * RoundedCornerShape(50) idiom MUI uses for its `Button shape="pill"`.
 */
@Composable
fun YokanPrimaryButton(
    text: String,
    modifier: Modifier = Modifier,
    icon: ImageVector? = null,
    enabled: Boolean = true,
    onClick: () -> Unit,
) {
    Button(
        onClick = onClick,
        enabled = enabled,
        modifier = modifier.height(46.dp),
        shape = RoundedCornerShape(50),
        contentPadding = PaddingValues(horizontal = 20.dp, vertical = 0.dp),
    ) {
        icon?.let {
            Icon(it, contentDescription = null, modifier = Modifier.size(18.dp))
            Spacer(Modifier.width(8.dp))
        }
        Text(text, style = MaterialTheme.typography.labelLarge, letterSpacing = 0.3.sp)
    }
}

/** Mangayomi-compatible transparent, start-aligned Material app bar. */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun YokanTopBar(
    title: String,
    subtitle: String? = null,
    onBack: (() -> Unit)? = null,
    actions: @Composable () -> Unit = {},
) {
    TopAppBar(
        title = {
            Column {
                Text(title)
                subtitle?.let {
                    Text(
                        text = it,
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                    )
                }
            }
        },
        navigationIcon = {
            onBack?.let {
                IconButton(onClick = it) {
                    Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(Res.string.action_back))
                }
            }
        },
        actions = { actions() },
        colors = TopAppBarDefaults.topAppBarColors(
            containerColor = Color.Transparent,
            scrolledContainerColor = Color.Transparent,
            titleContentColor = MaterialTheme.colorScheme.onSurface,
            navigationIconContentColor = MaterialTheme.colorScheme.onSurface,
            actionIconContentColor = MaterialTheme.colorScheme.onSurfaceVariant,
        ),
    )
}

/**
 * Compact Material 3 single-choice control for short option lists.
 *
 * Segmented buttons provide selected-state semantics and platform-standard
 * minimum touch targets without each caller rebuilding those contracts.
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun YokanChipTabs(
    options: List<String>,
    selectedIndex: Int,
    onSelect: (Int) -> Unit,
    modifier: Modifier = Modifier,
) {
    SingleChoiceSegmentedButtonRow(modifier = modifier) {
        options.forEachIndexed { index, label ->
            SegmentedButton(
                selected = index == selectedIndex,
                onClick = { onSelect(index) },
                shape = SegmentedButtonDefaults.itemShape(index, options.size),
                icon = {},
                label = { Text(label) },
            )
        }
    }
}

/** Hairline horizontal divider with consistent tint across screens. */
@Composable
fun YokanDivider(modifier: Modifier = Modifier, inset: Dp = 0.dp) {
    eu.friedcutlet.yokan.ui.theme.YokanHorizontalDivider(
        modifier = modifier.padding(horizontal = inset),
        thickness = 1.dp,
    )
}

/** Mangayomi-compatible ListTile: primary leading icon and no implicit chevron. */
@Composable
fun YokanListRow(
    title: String,
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
    subtitle: String? = null,
    icon: ImageVector? = null,
    trailingContent: (@Composable () -> Unit)? = null,
) {
    ListItem(
        modifier = modifier
            .fillMaxWidth()
            .hoverHighlight(onClick),
        headlineContent = { Text(title) },
        supportingContent = subtitle?.let {
            {
                Text(
                    text = it,
                    fontSize = 11.sp,
                    color = MaterialTheme.colorScheme.secondary,
                )
            }
        },
        leadingContent = icon?.let {
            {
                Box(modifier = Modifier.height(40.dp), contentAlignment = Alignment.Center) {
                    Icon(
                        imageVector = it,
                        contentDescription = null,
                        tint = MaterialTheme.colorScheme.primary,
                    )
                }
            }
        },
        trailingContent = trailingContent,
        colors = ListItemDefaults.colors(containerColor = Color.Transparent),
    )
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/Reorderable.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/Reorderable.kt) · implementation · 105 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
38: fun <T> ReorderableColumn(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/Reorderable.kt) · SHA-256 `6604a4db1dcb476ca408c070a6e81e33852ba9a531451f955a9fde12ffd77ecb`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.components

import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.offset
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.zIndex
import kotlin.math.roundToInt

/**
 * A vertical list whose rows can be reordered by dragging a handle. Replaces
 * the old up/down arrow buttons.
 *
 * Reordering is committed as the dragged row crosses row-height thresholds.
 * Fast drags can move several positions in one gesture update; stores that
 * reorder by offset can use `toIndex - fromIndex` directly.
 *
 * The list is intentionally a plain [Column] (not lazy): reorderable settings
 * lists are short, and a Column sidesteps the index/offset bookkeeping that
 * drag-reorder inside a LazyColumn requires. Drop this as a single `item {}`
 * inside an outer LazyColumn when needed.
 *
 * @param itemContent receives the item, a [Modifier] to attach to the drag
 *   handle, and whether this row is currently being dragged.
 */
@Composable
fun <T> ReorderableColumn(
    items: List<T>,
    key: (T) -> Any,
    onMove: (fromIndex: Int, toIndex: Int) -> Unit,
    modifier: Modifier = Modifier,
    itemContent: @Composable (item: T, dragHandle: Modifier, isDragging: Boolean) -> Unit,
) {
    var draggedKey by remember { mutableStateOf<Any?>(null) }
    var dragOffset by remember { mutableStateOf(0f) }
    val itemHeights = remember { mutableStateMapOf<Any, Int>() }
    val latestItems by rememberUpdatedState(items)
    val latestOnMove by rememberUpdatedState(onMove)

    Column(modifier = modifier) {
        items.forEach { item ->
            val itemKey = key(item)
            androidx.compose.runtime.key(itemKey) {
                val isDragging = itemKey == draggedKey
                Box(
                    modifier = Modifier
                        .onGloballyPositioned { itemHeights[itemKey] = it.size.height }
                        .zIndex(if (isDragging) 1f else 0f)
                        .then(
                            if (isDragging) {
                                Modifier.offset { IntOffset(0, dragOffset.roundToInt()) }
                            } else {
                                Modifier
                            },
                        ),
                ) {
                    val handle = Modifier.pointerInput(itemKey) {
                        detectDragGestures(
                            onDragStart = {
                                draggedKey = itemKey
                                dragOffset = 0f
                            },
                            onDragEnd = {
                                draggedKey = null
                                dragOffset = 0f
                            },
                            onDragCancel = {
                                draggedKey = null
                                dragOffset = 0f
                            },
                            onDrag = { change, amount ->
                                change.consume()
                                dragOffset += amount.y
                                val currentItems = latestItems
                                val current = currentItems.indexOfFirst { key(it) == draggedKey }
                                if (current < 0) return@detectDragGestures
                                val height = (itemHeights[draggedKey] ?: 0).coerceAtLeast(1)
                                val steps = (dragOffset / height.toFloat()).toInt()
                                if (steps != 0) {
                                    val target = (current + steps).coerceIn(0, currentItems.lastIndex)
                                    if (target != current) {
                                        latestOnMove(current, target)
                                        dragOffset -= (target - current) * height.toFloat()
                                    }
                                }
                            },
                        )
                    }
                    itemContent(item, handle, isDragging)
                }
            }
        }
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/RouteScaffold.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/RouteScaffold.kt) · implementation · 35 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.

Declaration checklist (source line numbers):
```text
14: internal fun RouteScaffold(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/RouteScaffold.kt) · SHA-256 `22837de15fc1fcbf2658b20793d61a56d689c42cf28fdaf2540cb5fe31b8803c`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.components

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.ui.theme.YokanScaffold

/** Top bar over a padded, scrollable lazy column: the shared shell of the simple route screens. */
@Composable
internal fun RouteScaffold(
    title: String,
    onBack: () -> Unit,
    actions: @Composable () -> Unit = {},
    content: LazyListScope.() -> Unit,
) {
    YokanScaffold(
        topBar = {
            YokanTopBar(
                title = title,
                onBack = onBack,
                actions = actions,
            )
        },
    ) { padding ->
        ScrollableLazyColumn(
            modifier = Modifier.fillMaxSize().padding(padding).padding(DefaultContentPadding),
            verticalArrangement = Arrangement.spacedBy(12.dp),
            content = content,
        )
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/Scrollable.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/Scrollable.kt) · implementation · 103 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
34: fun ScrollableLazyColumn(
65: fun ScrollableLazyVerticalGrid(
95: private suspend fun LazyListState.scrollBy(amount: Float) {
100: private suspend fun LazyGridState.scrollBy(amount: Float) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/Scrollable.kt) · SHA-256 `53a876779d360c9d65899e319e5fe48902e5b38ea072e6a6b288247ad8c29f67`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.components

import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.draggable
import androidx.compose.foundation.gestures.rememberDraggableState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyGridScope
import androidx.compose.foundation.lazy.grid.LazyGridState
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.launch
/**
 * `LazyColumn` wrapped in a [ScrollbarBox] so desktop users see a real
 * draggable scrollbar on the trailing edge. The list itself remains a stock
 * `LazyColumn`, so existing item/`stickyHeader` DSL keeps working.
 *
 * The whole composable also responds to mouse-drag and touch-drag, so users on
 * desktop touch screens can swipe through long lists without falling back to
 * the scrollbar handle.
 */
@Composable
fun ScrollableLazyColumn(
    modifier: Modifier = Modifier,
    state: LazyListState = rememberLazyListState(),
    contentPadding: PaddingValues = PaddingValues(0.dp),
    verticalArrangement: Arrangement.Vertical = Arrangement.Top,
    horizontalAlignment: Alignment.Horizontal = Alignment.Start,
    userScrollEnabled: Boolean = true,
    content: LazyListScope.() -> Unit,
) {
    val scope = rememberCoroutineScope()
    // `draggable` is what gives touchscreens on desktop the same finger-pan
    // behaviour as mobile. LazyColumn already exposes the wheel/keyboard path.
    val dragHandle = rememberDraggableState { delta ->
        scope.launch { state.scrollBy(-delta) }
    }
    ScrollbarBox(state = state, modifier = modifier) {
        LazyColumn(
            state = state,
            modifier = Modifier
                .fillMaxWidth()
                .draggable(state = dragHandle, orientation = Orientation.Vertical),
            contentPadding = contentPadding,
            verticalArrangement = verticalArrangement,
            horizontalAlignment = horizontalAlignment,
            userScrollEnabled = userScrollEnabled,
            content = content,
        )
    }
}

@Composable
fun ScrollableLazyVerticalGrid(
    columns: GridCells,
    modifier: Modifier = Modifier,
    state: LazyGridState = rememberLazyGridState(),
    contentPadding: PaddingValues = PaddingValues(0.dp),
    verticalArrangement: Arrangement.Vertical = Arrangement.Top,
    horizontalArrangement: Arrangement.Horizontal = Arrangement.Start,
    userScrollEnabled: Boolean = true,
    content: LazyGridScope.() -> Unit,
) {
    val scope = rememberCoroutineScope()
    val dragHandle = rememberDraggableState { delta ->
        scope.launch { state.scrollBy(-delta) }
    }
    ScrollbarBox(state = state, modifier = modifier) {
        LazyVerticalGrid(
            columns = columns,
            state = state,
            modifier = Modifier
                .fillMaxWidth()
                .draggable(state = dragHandle, orientation = Orientation.Vertical),
            contentPadding = contentPadding,
            verticalArrangement = verticalArrangement,
            horizontalArrangement = horizontalArrangement,
            userScrollEnabled = userScrollEnabled,
            content = content,
        )
    }
}

private suspend fun LazyListState.scrollBy(amount: Float) {
    if (amount == 0f) return
    scroll { scrollBy(amount) }
}

private suspend fun LazyGridState.scrollBy(amount: Float) {
    if (amount == 0f) return
    scroll { scrollBy(amount) }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/Scrollbar.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/Scrollbar.kt) · implementation · 73 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
21: fun ScrollbarBox(
39: fun ScrollbarBox(
53: fun ScrollbarBox(
67: internal expect fun BoxScope.PlatformVerticalScrollbar(state: LazyListState)
70: internal expect fun BoxScope.PlatformVerticalScrollbar(state: LazyGridState)
73: internal expect fun BoxScope.PlatformVerticalScrollbar(state: ScrollState)
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/Scrollbar.kt) · SHA-256 `e107feafc3c355108d3642a7975cfa83fb232cf597522fa4df63b516d9c53351`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.components

import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.grid.LazyGridState
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier

/**
 * Wraps content in a Box and overlays a vertical scrollbar on the trailing
 * edge on platforms that expose one. Desktop gets a real draggable scrollbar;
 * Android and iOS keep their native scroll feedback.
 *
 * Three overloads cover the three scroll state types we actually use in the
 * app: LazyListState (LazyColumn/LazyRow), LazyGridState (LazyVerticalGrid),
 * and ScrollState (vertical/horizontal Modifier.verticalScroll).
 */
@Composable
fun ScrollbarBox(
    state: LazyListState,
    modifier: Modifier = Modifier,
    content: @Composable BoxScope.() -> Unit,
) {
    Box(modifier, propagateMinConstraints = true) {
        content()
        // Keep the overlay out of the outer Box's wrap-content measurement.
        // Desktop's scrollbar fills its available height; measuring it as a
        // normal child would therefore expand compact dialogs to their maximum
        // height instead of letting their scrollable content determine it.
        Box(Modifier.matchParentSize()) {
            PlatformVerticalScrollbar(state)
        }
    }
}

@Composable
fun ScrollbarBox(
    state: LazyGridState,
    modifier: Modifier = Modifier,
    content: @Composable BoxScope.() -> Unit,
) {
    Box(modifier, propagateMinConstraints = true) {
        content()
        Box(Modifier.matchParentSize()) {
            PlatformVerticalScrollbar(state)
        }
    }
}

@Composable
fun ScrollbarBox(
    state: ScrollState,
    modifier: Modifier = Modifier,
    content: @Composable BoxScope.() -> Unit,
) {
    Box(modifier, propagateMinConstraints = true) {
        content()
        Box(Modifier.matchParentSize()) {
            PlatformVerticalScrollbar(state)
        }
    }
}

@Composable
internal expect fun BoxScope.PlatformVerticalScrollbar(state: LazyListState)

@Composable
internal expect fun BoxScope.PlatformVerticalScrollbar(state: LazyGridState)

@Composable
internal expect fun BoxScope.PlatformVerticalScrollbar(state: ScrollState)
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/SearchField.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/SearchField.kt) · implementation · 115 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
41: fun AppBarSearchField(
84: fun Modifier.closeSearchOnEscape(onClose: () -> Unit): Modifier =
94: fun Modifier.searchOnEnter(onSearch: () -> Unit): Modifier =
105: fun Modifier.autoFocusOnMount(): Modifier {
114: fun Modifier.compactSearchField(): Modifier =
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/SearchField.kt) · SHA-256 `7570c1d213a351cee852555017ec6c43925853e5545955ab0676b3105f5b0705`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.components

import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Clear
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.input.key.type
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.services.system.isTvDevice
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_clear_search
import yokan.composeapp.generated.resources.action_close_search

/**
 * The inline search field that replaces an app-bar title: a back arrow that calls [onClose]
 * (also bound to Escape), a clear button, and transparent chrome. [onSearch] adds an IME
 * search action and Enter-to-submit; [onClear] defaults to emptying the query.
 */
@Composable
fun AppBarSearchField(
    query: String,
    placeholder: String,
    onQueryChange: (String) -> Unit,
    onClose: () -> Unit,
    modifier: Modifier = Modifier,
    onSearch: (() -> Unit)? = null,
    onClear: () -> Unit = { onQueryChange("") },
) {
    OutlinedTextField(
        value = query,
        onValueChange = onQueryChange,
        modifier = modifier
            .fillMaxWidth()
            .autoFocusOnMount()
            .compactSearchField()
            .then(if (onSearch != null) Modifier.searchOnEnter(onSearch) else Modifier)
            .closeSearchOnEscape(onClose),
        singleLine = true,
        placeholder = { Text(placeholder) },
        leadingIcon = {
            IconButton(onClick = onClose) {
                Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(Res.string.action_close_search))
            }
        },
        trailingIcon = {
            if (query.isNotEmpty()) {
                IconButton(onClick = onClear) {
                    Icon(Icons.Filled.Clear, contentDescription = stringResource(Res.string.action_clear_search))
                }
            }
        },
        keyboardOptions = if (onSearch != null) KeyboardOptions(imeAction = ImeAction.Search) else KeyboardOptions.Default,
        keyboardActions = if (onSearch != null) KeyboardActions(onSearch = { onSearch() }) else KeyboardActions.Default,
        colors = OutlinedTextFieldDefaults.colors(
            focusedBorderColor = Color.Transparent,
            unfocusedBorderColor = Color.Transparent,
            focusedContainerColor = Color.Transparent,
            unfocusedContainerColor = Color.Transparent,
        ),
    )
}

fun Modifier.closeSearchOnEscape(onClose: () -> Unit): Modifier =
    onPreviewKeyEvent { event ->
        if (event.type == KeyEventType.KeyDown && event.key == Key.Escape) {
            onClose()
            true
        } else {
            false
        }
    }

fun Modifier.searchOnEnter(onSearch: () -> Unit): Modifier =
    onPreviewKeyEvent { event ->
        if (event.type == KeyEventType.KeyUp && event.key == Key.Enter) {
            onSearch()
            true
        } else {
            false
        }
    }

@Composable
fun Modifier.autoFocusOnMount(): Modifier {
    if (isTvDevice()) return this
    val focusRequester = remember { FocusRequester() }
    LaunchedEffect(focusRequester) {
        runCatching { focusRequester.requestFocus() }
    }
    return focusRequester(focusRequester)
}

fun Modifier.compactSearchField(): Modifier =
    heightIn(min = 52.dp, max = 56.dp)
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/StateViews.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/StateViews.kt) · implementation · 148 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
37: fun EmptyState(
84: fun LoadingState(
110: fun ErrorState(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/StateViews.kt) · SHA-256 `186759e863ea8f27bfa32bedc2b5d5c93c1ed957aeeec23abea04f56666ceaea`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.components

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ErrorOutline
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.semantics.LiveRegionMode
import androidx.compose.ui.semantics.liveRegion
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.services.system.openSystemBrowser
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.open_in_browser
import yokan.composeapp.generated.resources.retry

@Composable
fun EmptyState(
    icon: ImageVector,
    title: String,
    modifier: Modifier = Modifier,
    subtitle: String? = null,
    action: (@Composable () -> Unit)? = null,
) {
    Box(modifier = modifier, contentAlignment = Alignment.Center) {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.spacedBy(14.dp),
        ) {
            // Tonal-container disc so the empty state feels intentional rather than missing.
            Box(
                modifier = Modifier
                    .size(88.dp)
                    .clip(CircleShape)
                    .background(MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.55f)),
                contentAlignment = Alignment.Center,
            ) {
                Icon(
                    imageVector = icon,
                    contentDescription = null,
                    modifier = Modifier.size(40.dp),
                    tint = MaterialTheme.colorScheme.onPrimaryContainer,
                )
            }
            Text(
                text = title,
                color = MaterialTheme.colorScheme.onSurface,
                style = MaterialTheme.typography.titleSmall,
                fontWeight = FontWeight.Medium,
            )
            subtitle?.let {
                Text(
                    text = it,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    style = MaterialTheme.typography.bodyMedium,
                    textAlign = TextAlign.Center,
                )
            }
            action?.invoke()
        }
    }
}

@Composable
fun LoadingState(
    label: String = "Loading…",
    modifier: Modifier = Modifier,
) {
    Column(
        modifier = modifier.fillMaxWidth().padding(vertical = 28.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.spacedBy(12.dp),
    ) {
        Box(contentAlignment = Alignment.Center, modifier = Modifier.size(58.dp)) {
            CircularProgressIndicator(
                strokeWidth = 3.dp,
                color = MaterialTheme.colorScheme.primary,
                trackColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.12f),
            )
        }
        Text(
            label,
            modifier = Modifier.semantics { liveRegion = LiveRegionMode.Polite },
            color = MaterialTheme.colorScheme.onSurfaceVariant,
            style = MaterialTheme.typography.bodyMedium,
        )
    }
}

@Composable
fun ErrorState(
    message: String,
    modifier: Modifier = Modifier,
    onRetry: (() -> Unit)? = null,
    openInBrowserUrl: String? = null,
) {
    val looksLikeCloudflare = message.contains("Cloudflare", ignoreCase = true) ||
        message.contains("HTTP 403") ||
        message.contains("HTTP 503") ||
        message.contains("challenge", ignoreCase = true)
    Column(
        modifier = modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 24.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.spacedBy(10.dp),
    ) {
        Icon(
            imageVector = Icons.Filled.ErrorOutline,
            contentDescription = null,
            tint = MaterialTheme.colorScheme.error,
            modifier = Modifier
                .background(MaterialTheme.colorScheme.error.copy(alpha = 0.10f), CircleShape)
                .padding(10.dp),
        )
        Text(
            text = message,
            color = MaterialTheme.colorScheme.error,
            style = MaterialTheme.typography.bodyMedium,
            textAlign = TextAlign.Center,
        )
        Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
            if (onRetry != null) {
                OutlinedButton(onClick = onRetry) { Text(stringResource(Res.string.retry)) }
            }
            if (looksLikeCloudflare && !openInBrowserUrl.isNullOrBlank()) {
                OutlinedButton(onClick = { openSystemBrowser(openInBrowserUrl) }) { Text(stringResource(Res.string.open_in_browser)) }
            }
        }
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/Tooltips.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/Tooltips.kt) · implementation · 63 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
24: fun TooltipIconButton(
45: fun TooltipIconButton(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/Tooltips.kt) · SHA-256 `8b261171292f47a3e6f603cb08a4106ca4789709e72a39aece55b79fb97ae5bd`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.components

import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.PlainTooltip
import androidx.compose.material3.Text
import androidx.compose.material3.TooltipBox
import androidx.compose.material3.TooltipAnchorPosition
import androidx.compose.material3.TooltipDefaults
import androidx.compose.material3.rememberTooltipState
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector

/**
 * An [IconButton] wrapped in a Material 3 [TooltipBox]. The tooltip appears on
 * long-press (touch) and on pointer hover (desktop), giving every icon a short
 * description of what tapping it does.
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TooltipIconButton(
    tooltip: String,
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
    buttonModifier: Modifier = Modifier,
    enabled: Boolean = true,
    content: @Composable () -> Unit,
) {
    TooltipBox(
        positionProvider = TooltipDefaults.rememberTooltipPositionProvider(TooltipAnchorPosition.Above),
        tooltip = { PlainTooltip { Text(tooltip) } },
        state = rememberTooltipState(),
        modifier = modifier,
    ) {
        IconButton(onClick = onClick, enabled = enabled, modifier = buttonModifier, content = content)
    }
}

/** Convenience overload that draws [icon] with [tooltip] used as its description. */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TooltipIconButton(
    tooltip: String,
    icon: ImageVector,
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
    buttonModifier: Modifier = Modifier,
    enabled: Boolean = true,
    tint: androidx.compose.ui.graphics.Color = MaterialTheme.colorScheme.onSurfaceVariant,
) {
    TooltipIconButton(
        tooltip = tooltip,
        onClick = onClick,
        modifier = modifier,
        buttonModifier = buttonModifier,
        enabled = enabled,
    ) {
        Icon(icon, contentDescription = tooltip, tint = tint)
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/TypeDot.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/TypeDot.kt) · implementation · 25 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
14: fun TypeDot(itemType: ItemType, modifier: Modifier = Modifier) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/TypeDot.kt) · SHA-256 `27bf2ec8da7d7fe27ae3a512ca367756857c6e721aa90235b00ed3d96b42264e`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.components

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.domain.ItemType

@Composable
fun TypeDot(itemType: ItemType, modifier: Modifier = Modifier) {
    val color = when (itemType) {
        ItemType.Manga -> MaterialTheme.colorScheme.primary
        ItemType.Anime -> MaterialTheme.colorScheme.secondary
        ItemType.Novel -> MaterialTheme.colorScheme.tertiary
    }
    Box(
        modifier = modifier
            .size(9.dp)
            .background(color, CircleShape),
    )
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/image/ImageDataSaverInterceptor.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/image/ImageDataSaverInterceptor.kt) · implementation · 65 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
19: internal class ImageDataSaverInterceptor(private val saver: ImageDataSaver, private val database: YokanDatabase) : Interceptor {
24: override suspend fun intercept(chain: Interceptor.Chain): ImageResult {
52: private fun coverSource(url: String): Long? = lock.withLock {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/image/ImageDataSaverInterceptor.kt) · SHA-256 `69902448adaa8d176b0316b6e8a06f327b9896762bcebcade2942d6537ca88d0`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.image

import coil3.Extras
import coil3.getExtra
import coil3.intercept.Interceptor
import coil3.network.NetworkHeaders
import coil3.network.httpHeaders
import coil3.request.ErrorResult
import coil3.request.ImageResult
import coil3.request.transformations
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.services.download.ImageDataSaver
import eu.friedcutlet.yokan.util.PlatformLock

internal val ImageChapterIdExtra = Extras.Key<Long?>(null)
internal const val OriginalImageProgressHeader = "X-Yokan-Original-Image"

internal class ImageDataSaverInterceptor(private val saver: ImageDataSaver, private val database: YokanDatabase) : Interceptor {
    private val lock = PlatformLock()
    private var indexedTitles: List<DbManga>? = null
    private var coverSources: Map<String, Long?> = emptyMap()

    override suspend fun intercept(chain: Interceptor.Chain): ImageResult {
        val request = chain.request
        val original = request.data as? String ?: return chain.proceed()
        val settings = database.settings().features.imageDataSaver
        if (settings.provider == eu.friedcutlet.yokan.database.ImageSaverProvider.Off || !settings.forReader) return chain.proceed()
        val chapterId = request.getExtra(ImageChapterIdExtra)
        val sourceId = if (chapterId != null) database.chapter(chapterId)?.mangaId?.let(database::manga)?.sourceId
            else if (settings.excludedSourceIds.isNotEmpty()) coverSource(original) else null
        val headers = request.httpHeaders.asMap().mapValues { it.value.joinToString(", ") }
        val optimized = saver.resolve(original, headers, sourceId, settings, download = false) ?: return chain.proceed()
        val proxyRequest = request.newBuilder()
            .data(optimized.url)
            .memoryCacheKey("${request.memoryCacheKey ?: original}#${optimized.cacheVariant}")
            .memoryCacheKeyExtra("imageSaverTransformations", request.transformations.joinToString { it.cacheKey })
            .diskCacheKey("${request.diskCacheKey ?: original}#${optimized.cacheVariant}")
            .httpHeaders(NetworkHeaders.Builder().apply {
                optimized.headers.forEach { (name, value) -> set(name, value) }
                set(OriginalImageProgressHeader, original)
            }.build())
            .build()
        val result = chain.withRequest(proxyRequest).proceed()
        if (result !is ErrorResult) return result
        if (result.throwable is kotlinx.coroutines.CancellationException) throw result.throwable
        saver.failed(optimized)
        return chain.proceed()
    }

    /** Rebuild once per library change, only when per-source exclusions need cover identity. */
    private fun coverSource(url: String): Long? = lock.withLock {
        val titles = database.snapshots().value.mangas
        if (titles !== indexedTitles) {
            val index = mutableMapOf<String, Long?>()
            titles.forEach { title ->
                val cover = title.imageUrl.orEmpty()
                if (cover.isNotBlank()) index[cover] = if (cover in index && index[cover] != title.sourceId) null else title.sourceId
            }
            coverSources = index
            indexedTitles = titles
        }
        coverSources[url]
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/image/ImageDecoder.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/image/ImageDecoder.kt) · implementation · 17 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
16: internal fun decodeImageBitmap(path: String): ImageBitmap? =
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/image/ImageDecoder.kt) · SHA-256 `88662fe380b485d2fc64c29270799b623f607ec872daf8dc711d4d122b254a2f`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.image

import androidx.compose.ui.graphics.ImageBitmap
import eu.friedcutlet.yokan.services.files.createPlatformLocalFileService
import org.jetbrains.compose.resources.decodeToImageBitmap

/**
 * Decode the image at [path] into an [ImageBitmap]. Used by the theme system to
 * derive a Material seed color from a user-chosen image via MaterialKolor's
 * `themeColor(image: ImageBitmap, …)` extension.
 *
 * Bytes come from the platform [eu.friedcutlet.yokan.services.files.LocalFileService], so
 * picker results that are not plain paths (Android `content://`, iOS security-scoped URLs,
 * browser-selected files) decode too. Returns null when the file is missing or undecodable.
 */
internal fun decodeImageBitmap(path: String): ImageBitmap? =
    runCatching { createPlatformLocalFileService().readBytes(path).decodeToImageBitmap() }.getOrNull()
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/image/ImageLoaderSetup.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/image/ImageLoaderSetup.kt) · implementation · 95 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
29: internal fun newYokanImageLoader(context: PlatformContext, owner: eu.friedcutlet.yokan.app.profiles.ProfileSession = YokanRuntime.activeSession): ImageLoader {
56: private class OwnedImageLoader(val loader: ImageLoader, val transport: ProfileImageHttpClient)
59: private object ImageLoadDiagnostics : EventListener() {
60: override fun onSuccess(request: ImageRequest, result: SuccessResult) = when (result.dataSource) {
66: override fun onError(request: ImageRequest, result: ErrorResult) {
76: internal data class ImageCacheUsage(val memoryBytes: Long, val memoryMaxBytes: Long, val diskBytes: Long?, val diskMaxBytes: Long?)
79: internal fun imageCacheUsage(): ImageCacheUsage? = activeImageLoaderLock.withLock { activeImageLoader }?.let { loader ->
89: internal expect fun imageDiskCache(cacheRoot: String): DiskCache?
92: internal fun ImageLoader.clearCaches() {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/image/ImageLoaderSetup.kt) · SHA-256 `34182c1dd6d195a6bbbb1b1ca029dbd0694ab8aa762a1d2a5b1109f92b3810d3`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.image

import coil3.EventListener
import coil3.ImageLoader
import coil3.PlatformContext
import coil3.decode.DataSource
import coil3.disk.DiskCache
import coil3.network.ktor3.KtorNetworkFetcherFactory
import coil3.request.ErrorResult
import coil3.request.ImageRequest
import coil3.request.SuccessResult
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.services.logging.Diagnostics
import eu.friedcutlet.yokan.services.logging.redactUrlForLog
import eu.friedcutlet.yokan.ui.screens.reader.ReaderPageRequestLimiter
import eu.friedcutlet.yokan.ui.screens.reader.ReaderPageDownloadProgress
import eu.friedcutlet.yokan.util.PlatformLock

/**
 * Coil 3 needs a `NetworkFetcher` registered explicitly on KMP targets. Without this, remote
 * covers/thumbnails silently fail because the default loader cannot resolve HTTP/HTTPS sources on
 * desktop or iOS. The dedicated client also reports byte-level download progress so reader page
 * placeholders can show a determinate ring.
 *
 * The disk cache lives under `LocalFileService.cacheRoot`, so storage usage and "Clear chapter and
 * episode cache" cover page images on every platform.
 */
internal fun newYokanImageLoader(context: PlatformContext, owner: eu.friedcutlet.yokan.app.profiles.ProfileSession = YokanRuntime.activeSession): ImageLoader {
    return owner.ownResource(factory = {
        val transport = ProfileImageHttpClient(owner.services.cookieJar, owner.database, owner.scope, owner.dohResolver::resolve)
        val loader = ImageLoader.Builder(context)
            .components {
                addPlatformImageDecoders(this)
                add(ReaderPageRequestLimiter)
                add(ImageDataSaverInterceptor(owner.services.imageDataSaver, owner.database))
                add(KtorNetworkFetcherFactory(httpClient = { transport.client }))
            }
            .diskCache { imageDiskCache(owner.localFiles.cacheRoot) }
            .eventListener(ImageLoadDiagnostics)
            .build()
        activeImageLoaderLock.withLock { activeImageLoader = loader }
        OwnedImageLoader(loader, transport)
    }, close = { owned ->
        try { owned.loader.shutdown() } finally { owned.transport.closeAndJoin() }
        // Serialized with replacement publication: an old loader cannot clear a newer target.
        activeImageLoaderLock.withLock {
            if (activeImageLoader === owned.loader) {
                activeImageLoader = null
                ReaderPageDownloadProgress.clearAll()
            }
        }
    }).loader
}

private class OwnedImageLoader(val loader: ImageLoader, val transport: ProfileImageHttpClient)

/** Where each finished image came from, for Settings → Developer; failures are logged once each. */
private object ImageLoadDiagnostics : EventListener() {
    override fun onSuccess(request: ImageRequest, result: SuccessResult) = when (result.dataSource) {
        DataSource.MEMORY_CACHE -> Diagnostics.recordImageMemoryHit()
        DataSource.DISK -> Diagnostics.recordImageDiskHit()
        DataSource.MEMORY, DataSource.NETWORK -> Diagnostics.recordImageNetworkLoad()
    }

    override fun onError(request: ImageRequest, result: ErrorResult) {
        Diagnostics.recordImageError()
        val cause = result.throwable.message?.lineSequence()?.firstOrNull()?.takeIf { it.isNotBlank() } ?: result.throwable::class.simpleName
        AppLogger.warn("[image] ${redactUrlForLog(request.data.toString())} failed: $cause")
    }
}

private val activeImageLoaderLock = PlatformLock()
private var activeImageLoader: ImageLoader? = null

internal data class ImageCacheUsage(val memoryBytes: Long, val memoryMaxBytes: Long, val diskBytes: Long?, val diskMaxBytes: Long?)

/** Current fill of the app's image caches; null before the first image loader exists. */
internal fun imageCacheUsage(): ImageCacheUsage? = activeImageLoaderLock.withLock { activeImageLoader }?.let { loader ->
    ImageCacheUsage(
        memoryBytes = loader.memoryCache?.size ?: 0L,
        memoryMaxBytes = loader.memoryCache?.maxSize ?: 0L,
        diskBytes = loader.diskCache?.size,
        diskMaxBytes = loader.diskCache?.maxSize,
    )
}

/** Coil's disk cache in [cacheRoot]; null where Coil has no disk cache (the browser). */
internal expect fun imageDiskCache(cacheRoot: String): DiskCache?

/** Empties the image caches through Coil, which owns (and keeps open) its cache directory. */
internal fun ImageLoader.clearCaches() {
    memoryCache?.clear()
    diskCache?.clear()
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/image/PlatformImageDecoders.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/image/PlatformImageDecoders.kt) · implementation · 6 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
6: internal expect fun addPlatformImageDecoders(components: ComponentRegistry.Builder)
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/image/PlatformImageDecoders.kt) · SHA-256 `1876d553db48e9642f8e9d7658973d9f59dd192853a0b2d352b1a57eba404c60`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.image

import coil3.ComponentRegistry

/** Adds codecs missing from the platform's default Coil decoder. */
internal expect fun addPlatformImageDecoders(components: ComponentRegistry.Builder)
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/image/ProfileImageHttpClient.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/image/ProfileImageHttpClient.kt) · implementation · 88 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
27: internal class ProfileImageHttpClient(
72: suspend fun closeAndJoin() = withContext(NonCancellable) {
77: private suspend fun release() = withContext(NonCancellable) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/image/ProfileImageHttpClient.kt) · SHA-256 `c9a5cb81cfa3351b8fbe5be7007b9f9a961cf927b761e328fab374aff1a2f12e`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.image

import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.services.http.cookies.CookieJar
import eu.friedcutlet.yokan.services.http.createPlatformHttpClientEngine
import eu.friedcutlet.yokan.services.http.HostResolver
import eu.friedcutlet.yokan.ui.screens.reader.ReaderPageDownloadProgress
import io.ktor.client.HttpClient
import io.ktor.client.engine.HttpClientEngine
import io.ktor.client.plugins.BodyProgress
import io.ktor.client.plugins.onDownload
import io.ktor.client.request.HttpRequestPipeline
import io.ktor.http.HttpHeaders
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext

/** One Coil transport captures one jar/database and retires with its owner, before database close. */
internal class ProfileImageHttpClient(
    private val jar: CookieJar,
    private val database: YokanDatabase,
    ownerScope: CoroutineScope,
    resolveHost: HostResolver? = null,
    engineFactory: () -> HttpClientEngine = { createPlatformHttpClientEngine(jar.profileId, resolveHost) },
) {
    private val ownerJob = requireNotNull(ownerScope.coroutineContext[Job]) { "Image HTTP requires an owner job" }
        .also { it.ensureActive() }
    private val engine = eu.friedcutlet.yokan.services.http.ProfileHttpEngine(engineFactory(), ownerJob)
    private val retirementLock = Mutex()
    private var released = false
    val client: HttpClient = HttpClient(engine) {
        followRedirects = true
        install(BodyProgress)
    }.apply {
        requestPipeline.intercept(HttpRequestPipeline.State) {
            ownerJob.ensureActive()
            currentCoroutineContext().ensureActive()
            this@ProfileImageHttpClient.client.coroutineContext[Job]?.ensureActive()
            if (!jar.isAvailable) throw kotlinx.coroutines.CancellationException("Image profile session has ended")
            val url = context.url.buildString()
            val progressUrl = context.headers[OriginalImageProgressHeader] ?: url
            context.headers.remove(OriginalImageProgressHeader)
            if (context.headers[HttpHeaders.Cookie] == null) {
                jar.cookieHeader(url)?.let { context.headers.append(HttpHeaders.Cookie, it) }
            }
            val sessionUserAgent = jar.userAgent(url)
            if (sessionUserAgent != null) {
                // A solved clearance is tied to this exact UA, including when a source supplies one.
                context.headers.remove(HttpHeaders.UserAgent)
                context.headers.append(HttpHeaders.UserAgent, sessionUserAgent)
            } else if (context.headers[HttpHeaders.UserAgent] == null) {
                context.headers.append(HttpHeaders.UserAgent, database.settings().userAgent)
            }
            context.onDownload { received, total ->
                if (ownerJob.isActive && jar.isAvailable) ReaderPageDownloadProgress.report(progressUrl, received, total)
            }
        }
    }
    private val cleanup = ownerScope.async(start = CoroutineStart.UNDISPATCHED) {
        try { awaitCancellation() }
        finally { release() }
    }

    suspend fun closeAndJoin() = withContext(NonCancellable) {
        cleanup.cancel(); cleanup.join()
        release() // Retry a failed release; joining a canceled deferred does not rethrow its failure.
    }

    private suspend fun release() = withContext(NonCancellable) {
        retirementLock.withLock {
            if (released) return@withLock
            val clientJob = client.coroutineContext[Job]
            clientJob?.cancel()
            engine.closeAndJoin()
            clientJob?.join()
            client.close()
            released = true
        }
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/navigation/AwaitedViewModelCleanup.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/navigation/AwaitedViewModelCleanup.kt) · implementation · 6 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.

Declaration checklist (source line numbers):
```text
4: internal interface AwaitedViewModelCleanup {
5: suspend fun awaitCleanup()
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/navigation/AwaitedViewModelCleanup.kt) · SHA-256 `1ca0b7db1e89bf92b02502f7963d735485609df8afeaaedd0b45e1dd00bf7b3f`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.navigation

/** Native/file finalizers that continue after ViewModel.onCleared must expose completion. */
internal interface AwaitedViewModelCleanup {
    suspend fun awaitCleanup()
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/navigation/DeepLinkDialog.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/navigation/DeepLinkDialog.kt) · implementation · 69 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.

Declaration checklist (source line numbers):
```text
17: internal fun PendingDeepLinkDialog(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/navigation/DeepLinkDialog.kt) · SHA-256 `7d7d7374a002979edf2b13f5fd8edf29d0fd6848b3a76b9a555bd65e09666600`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.navigation

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.unit.dp
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_add
import yokan.composeapp.generated.resources.action_cancel

@Composable
internal fun PendingDeepLinkDialog(
    state: DeepLinkState,
    onConfirm: () -> Unit,
    onDismiss: () -> Unit,
) {
    val action = state.action ?: return
    val title = when (action) {
        is PendingDeepLinkAction.AddRepositories -> "Add repository"
        is PendingDeepLinkAction.AddCustomButtons -> "Add custom button"
    }
    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text(title) },
        text = {
            Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
                when (action) {
                    is PendingDeepLinkAction.AddRepositories -> {
                        Text("Name: ${action.name ?: "Unknown"}")
                        Text("URL: ${action.website ?: "Unknown"}")
                        if (action.repositories.size > 1) {
                            Text("${action.repositories.size} repository lists")
                        }
                    }
                    is PendingDeepLinkAction.AddCustomButtons -> {
                        Text("Name: ${action.buttons.firstOrNull()?.title ?: "Unknown"}")
                        if (action.buttons.size > 1) {
                            Text("${action.buttons.size} buttons remaining")
                        }
                    }
                }
                state.error?.let { error ->
                    Text(error, color = MaterialTheme.colorScheme.error)
                }
            }
        },
        confirmButton = {
            TextButton(
                onClick = onConfirm,
                enabled = !state.busy,
            ) {
                Text(if (state.busy) "Checking…" else stringResource(Res.string.action_add))
            }
        },
        dismissButton = {
            TextButton(
                onClick = onDismiss,
                enabled = !state.busy,
            ) {
                Text(stringResource(Res.string.action_cancel))
            }
        },
    )
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/navigation/DeepLinks.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/navigation/DeepLinks.kt) · implementation · 290 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
37: internal data class DeepLinkState(
44: internal class DeepLinkViewModel(
56: fun open(link: String?) {
102: fun dismiss() {
107: fun confirm() {
158: private fun PendingDeepLinkAction.AddCustomButtons.remaining(): PendingDeepLinkAction.AddCustomButtons? =
162: internal fun legacyRoute(name: String, itemType: ItemType): Route? = when (name) {
178: internal sealed interface PendingDeepLinkAction {
179: data class AddRepositories(
185: data class AddCustomButtons(
190: internal data class RepositoryPayload(
195: internal data class CustomButtonPayload(
203: internal fun searchDeepLink(query: String, type: ItemType? = null): String =
207: internal fun isBackupFileLink(link: String): Boolean = link.startsWith("content://") || link.startsWith("file:")
210: internal object PendingBackupFile {
213: fun offer(path: String) { pending.value = path }
214: fun take(): String? = pending.getAndUpdate { null }
218: private fun foreignRepositoryType(scheme: String): ItemType? = when (scheme) {
225: internal fun parseDeepLinkAction(link: String): PendingDeepLinkAction? {
259: internal fun repositoryPayloadIsValid(body: String): Boolean = runCatching {
268: internal fun parseQueryParameters(link: String): Map<String, List<String>> {
279: private fun decodeCustomButton(encoded: String): CustomButtonPayload? = runCatching {
290: private fun JsonObject.string(key: String): String? = get(key)?.jsonPrimitive?.contentOrNull
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/navigation/DeepLinks.kt) · SHA-256 `05a80484491eb36f6659f0f368ac1681cb4829a697e49dffac6aae8fbc28642a`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.navigation

import kotlinx.coroutines.CoroutineDispatcher
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.database.DbCustomButton
import eu.friedcutlet.yokan.database.DbRepo
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.notifications.InAppNotifications
import eu.friedcutlet.yokan.ui.screens.together.TogetherSession
import eu.friedcutlet.yokan.util.nowMillis
import kotlin.io.encoding.Base64
import kotlin.io.encoding.ExperimentalEncodingApi
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.getAndUpdate
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.jsonPrimitive
import io.ktor.http.URLDecodeException
import io.ktor.http.encodeURLParameter
import io.ktor.http.parseQueryString
import io.ktor.util.toMap

internal data class DeepLinkState(
    val action: PendingDeepLinkAction? = null,
    val busy: Boolean = false,
    val error: String? = null,
)

/** Handles app links: action links become a confirmation dialog, backup files open the restore preview, route links navigate. */
internal class DeepLinkViewModel(
    private val repository: YokanRepository,
    private val database: YokanDatabase,
    private val http: HttpService,
    private val navigator: Navigator,
    private val injectedScope: CoroutineScope? = null,
    private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,
) : ViewModel() {
    private val scope: CoroutineScope get() = injectedScope ?: viewModelScope
    private val _state = MutableStateFlow(DeepLinkState())
    val state: StateFlow<DeepLinkState> = _state.asStateFlow()

    fun open(link: String?) {
        if (link.isNullOrBlank()) return
        parseDeepLinkAction(link)?.let { action ->
            _state.update { it.copy(action = action, error = null) }
            return
        }
        if (isBackupFileLink(link)) {
            PendingBackupFile.offer(link)
            navigator.navigate(Route.Settings(SettingsPage.DataAndStorage))
            return
        }
        val path = link.substringBefore("?").substringBefore("#")
        val name = path
            .let { raw ->
                when {
                    raw.startsWith("yokan://") -> raw.removePrefix("yokan://")
                    raw.startsWith("/") -> raw
                    else -> raw.substringAfterLast("/")
                }
            }
            .trim('/')
            .substringBefore("/")
        if (name == "room") {
            val code = path.removePrefix("yokan://").trim('/').split('/').getOrNull(1)
            if (!code.isNullOrBlank()) TogetherSession.offerCode(code.uppercase())
        }
        when (name) {
            "search" -> {
                val parameters = parseQueryParameters(link)
                val query = parameters["q"]?.firstOrNull()?.trim().orEmpty()
                val type = parameters["type"]?.firstOrNull()?.let { raw -> ItemType.entries.firstOrNull { it.name.equals(raw, ignoreCase = true) } }
                if (query.isNotEmpty()) navigator.navigate(Route.GlobalSearch(type ?: navigator.itemType.value, query))
            }
            "Home", "home" -> navigator.select(NavSection.Home)
            "MangaLibrary", "manga", "" -> navigator.select(NavSection.MangaLibrary)
            "AnimeLibrary", "anime" -> navigator.select(NavSection.AnimeLibrary)
            "NovelLibrary", "novel" -> navigator.select(NavSection.NovelLibrary)
            "updates" -> navigator.select(NavSection.Updates)
            "history" -> navigator.select(NavSection.History)
            "browse" -> navigator.select(NavSection.Browse)
            "trackerLibrary", "tracking" -> navigator.select(NavSection.TrackerLibrary)
            "more" -> navigator.select(NavSection.More)
            else -> legacyRoute(name, navigator.itemType.value)?.let(navigator::navigate)
        }
    }

    fun dismiss() {
        if (_state.value.busy) return
        _state.update { it.copy(action = (it.action as? PendingDeepLinkAction.AddCustomButtons)?.remaining(), error = null) }
    }

    fun confirm() {
        val current = _state.value
        if (current.busy) return
        when (val action = current.action) {
            is PendingDeepLinkAction.AddCustomButtons -> {
                val button = action.buttons.firstOrNull() ?: return
                database.upsertCustomButton(
                    DbCustomButton(
                        title = button.title,
                        codePress = button.codePress,
                        codeLongPress = button.codeLongPress,
                        codeStartup = button.codeStartup,
                        isFavourite = false,
                        position = database.customButtons().size,
                        updatedAt = nowMillis(),
                    ),
                )
                _state.update { it.copy(action = action.remaining(), error = null) }
                InAppNotifications.post("Custom button added")
            }
            is PendingDeepLinkAction.AddRepositories -> {
                _state.update { it.copy(busy = true, error = null) }
                scope.launch {
                    val valid = action.repositories.all { payload ->
                        catchingNonCancellation {
                            val response = http.request(HttpRequest(payload.url))
                            response.statusCode in 200..299 &&
                                withContext(workDispatcher) { repositoryPayloadIsValid(response.body) }
                        }.getOrDefault(false)
                    }
                    when {
                        _state.value.action != action -> _state.update { it.copy(busy = false) }
                        !valid -> _state.update { it.copy(busy = false, error = "Unsupported repository") }
                        else -> {
                            action.repositories.forEach { payload ->
                                repository.upsertRepository(
                                    payload.itemType,
                                    DbRepo(name = action.name, website = action.website, jsonUrl = payload.url),
                                )
                            }
                            _state.update { it.copy(action = null, busy = false) }
                            InAppNotifications.post("Repository added")
                        }
                    }
                }
            }
            null -> Unit
        }
    }
}

private fun PendingDeepLinkAction.AddCustomButtons.remaining(): PendingDeepLinkAction.AddCustomButtons? =
    buttons.drop(1).takeIf(List<CustomButtonPayload>::isNotEmpty)?.let { PendingDeepLinkAction.AddCustomButtons(it) }

/** Maps a legacy `yokan://<name>` route; routes that need arguments (a title, a source) resolve to null. */
internal fun legacyRoute(name: String, itemType: ItemType): Route? = when (name) {
    "updateErrors" -> Route.UpdateErrors
    "localLibraryOverview" -> Route.LocalLibraryOverview
    "globalSearch" -> Route.GlobalSearch(itemType)
    "ExtensionLang" -> Route.ExtensionLanguages(itemType)
    "sourceFilter" -> Route.SourceFilters(itemType)
    "createExtension" -> Route.CreateExtension(itemType)
    "massMigration" -> Route.MassMigration(itemType)
    "localLibraryBrowse" -> Route.LocalLibraryBrowse(itemType)
    "add-repo" -> Route.Settings(SettingsPage.Repositories)
    "add-button" -> Route.Settings(SettingsPage.CustomButtons)
    "success" -> Route.Settings(SettingsPage.TrackingDetail)
    "room" -> Route.Settings(SettingsPage.Together)
    else -> SettingsPage.entries.firstOrNull { it.legacyRoute == name }?.let { Route.Settings(it) }
}

internal sealed interface PendingDeepLinkAction {
    data class AddRepositories(
        val name: String?,
        val website: String?,
        val repositories: List<RepositoryPayload>,
    ) : PendingDeepLinkAction

    data class AddCustomButtons(
        val buttons: List<CustomButtonPayload>,
    ) : PendingDeepLinkAction
}

internal data class RepositoryPayload(
    val itemType: ItemType,
    val url: String,
)

internal data class CustomButtonPayload(
    val title: String?,
    val codePress: String?,
    val codeLongPress: String,
    val codeStartup: String,
)

/** Global-search link built by OS intake (shared text, system search, launch arguments, `?search=`). */
internal fun searchDeepLink(query: String, type: ItemType? = null): String =
    "yokan://search?q=${query.encodeURLParameter()}" + type?.let { "&type=${it.name.lowercase()}" }.orEmpty()

/** Links that reach the app as a document: Android VIEW (`content://`, `file://`), iOS open-in, desktop file arguments. */
internal fun isBackupFileLink(link: String): Boolean = link.startsWith("content://") || link.startsWith("file:")

/** Backup file handed in by the OS, consumed once by the Data and storage page. */
internal object PendingBackupFile {
    private val pending = MutableStateFlow<String?>(null)
    val value: StateFlow<String?> = pending.asStateFlow()
    fun offer(path: String) { pending.value = path }
    fun take(): String? = pending.getAndUpdate { null }
}

/** Mihon/Tachiyomi publish manga repositories; Aniyomi/Animetail publish anime repositories. */
private fun foreignRepositoryType(scheme: String): ItemType? = when (scheme) {
    "tachiyomi", "mihon" -> ItemType.Manga
    "aniyomi", "animetail" -> ItemType.Anime
    else -> null
}

@OptIn(ExperimentalEncodingApi::class)
internal fun parseDeepLinkAction(link: String): PendingDeepLinkAction? {
    val parameters = parseQueryParameters(link)
    foreignRepositoryType(link.substringBefore("://", "").lowercase())?.let { itemType ->
        val host = link.substringAfter("://").substringBefore('?').substringBefore('#').trim('/').substringBefore('/')
        if (host != "add-repo" && host != "extension-store") return null
        val urls = parameters["url"].orEmpty().filter(String::isNotBlank)
        if (urls.isEmpty()) return null
        return PendingDeepLinkAction.AddRepositories(null, null, urls.map { RepositoryPayload(itemType, it) })
    }
    val route = link
        .substringBefore('?')
        .substringBefore('#')
        .removePrefix("yokan://")
        .trim('/')
        .substringBefore('/')
    return when (route) {
        "add-repo" -> PendingDeepLinkAction.AddRepositories(
            name = parameters["repo_name"]?.firstOrNull(),
            website = parameters["repo_url"]?.firstOrNull(),
            repositories = buildList {
                parameters["manga_url"].orEmpty().forEach { add(RepositoryPayload(ItemType.Manga, it)) }
                parameters["anime_url"].orEmpty().forEach { add(RepositoryPayload(ItemType.Anime, it)) }
                parameters["novel_url"].orEmpty().forEach { add(RepositoryPayload(ItemType.Novel, it)) }
            },
        )
        "add-button" -> parameters["button"]
            .orEmpty()
            .mapNotNull(::decodeCustomButton)
            .takeIf(List<CustomButtonPayload>::isNotEmpty)
            ?.let { PendingDeepLinkAction.AddCustomButtons(it) }
        else -> null
    }
}

internal fun repositoryPayloadIsValid(body: String): Boolean = runCatching {
    val first = Json.parseToJsonElement(body)
        .let { it as? kotlinx.serialization.json.JsonArray }
        ?.firstOrNull() as? JsonObject
    val name = first?.get("name")?.jsonPrimitive?.contentOrNull
    !name.isNullOrBlank()
}.getOrDefault(false)

/** Query parameters of [link]; a malformed `%` escape rejects the whole query instead of half-decoding it. */
internal fun parseQueryParameters(link: String): Map<String, List<String>> {
    val query = link.substringAfter('?', missingDelimiterValue = "").substringBefore('#')
    if (query.isBlank()) return emptyMap()
    return try {
        parseQueryString(query).toMap()
    } catch (_: URLDecodeException) {
        emptyMap()
    }
}

@OptIn(ExperimentalEncodingApi::class)
private fun decodeCustomButton(encoded: String): CustomButtonPayload? = runCatching {
    val value = Json.parseToJsonElement(Base64.decode(encoded).decodeToString()) as? JsonObject
        ?: return@runCatching null
    CustomButtonPayload(
        title = value.string("title"),
        codePress = value.string("codePress"),
        codeLongPress = value.string("codeLongPress").orEmpty(),
        codeStartup = value.string("codeStartup").orEmpty(),
    )
}.getOrNull()

private fun JsonObject.string(key: String): String? = get(key)?.jsonPrimitive?.contentOrNull
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/navigation/InteractiveBackGesture.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/navigation/InteractiveBackGesture.kt) · implementation · 109 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
22: internal class InteractiveBackGesture(private val scope: CoroutineScope) {
30: fun begin(): Boolean {
36: fun drag(pixels: Float, width: Float) {
40: fun finish(velocity: Float, cancelled: Boolean, onComplete: () -> Unit) {
59: fun dispose() { disposed = true; settling?.cancel() }
63: internal fun shouldCompleteBack(progress: Float, velocity: Float): Boolean =
66: internal fun Modifier.interactiveBackGesture(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/navigation/InteractiveBackGesture.kt) · SHA-256 `13635783b8bf8f63e8b1373b9d18a974c20780ec7695f18a41d9862d1645ad93`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.navigation

import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animate
import androidx.compose.animation.core.spring
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.input.pointer.util.VelocityTracker
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlin.math.abs

/** Gesture state belongs to one entry. Its offset survives until that entry finishes leaving. */
internal class InteractiveBackGesture(private val scope: CoroutineScope) {
    var active by mutableStateOf(false)
        private set
    var progress by mutableFloatStateOf(0f)
        private set
    private var settling: Job? = null
    private var disposed = false

    fun begin(): Boolean {
        if (disposed || active || settling?.isActive == true) return false
        active = true
        return true
    }

    fun drag(pixels: Float, width: Float) {
        progress = (progress + pixels / width).coerceIn(0f, 1f)
    }

    fun finish(velocity: Float, cancelled: Boolean, onComplete: () -> Unit) {
        if (disposed || !active || settling?.isActive == true) return
        val complete = !cancelled && shouldCompleteBack(progress, velocity)
        settling = scope.launch {
            animate(
                initialValue = progress,
                targetValue = if (complete) 1f else 0f,
                initialVelocity = if (cancelled) 0f else velocity,
                animationSpec = spring(dampingRatio = Spring.DampingRatioNoBouncy, stiffness = 700f, visibilityThreshold = 0.001f),
            ) { value, _ -> progress = value.coerceIn(0f, 1f) }
            if (complete) {
                // Do not reset to zero here: the outgoing entry is still composed for this frame.
                onComplete()
            } else {
                active = false
            }
        }
    }

    fun dispose() { disposed = true; settling?.cancel() }
}

/** Velocity is in screen widths/second, so the same gesture works on phones and tablets. */
internal fun shouldCompleteBack(progress: Float, velocity: Float): Boolean =
    if (abs(velocity) >= 1f) velocity > 0f else progress >= 0.5f

internal fun Modifier.interactiveBackGesture(
    gesture: InteractiveBackGesture,
    edgeWidth: Float,
    canStart: () -> Boolean,
    onComplete: () -> Unit,
): Modifier = pointerInput(gesture, edgeWidth) {
    awaitEachGesture {
        val down = awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial)
        // Check the original DOWN, not the position after touch slop. Leave other swipes alone.
        if (down.position.x > edgeWidth || !canStart() || !gesture.begin()) return@awaitEachGesture
        val width = size.width.toFloat().coerceAtLeast(1f)
        val tracker = VelocityTracker().apply { addPosition(down.uptimeMillis, down.position) }
        var dragging = false
        var cancelled = true
        var totalX = 0f
        var totalY = 0f
        try {
            while (true) {
                val event = awaitPointerEvent(PointerEventPass.Initial)
                val change = event.changes.firstOrNull { it.id == down.id } ?: break
                tracker.addPosition(change.uptimeMillis, change.position)
                if (change.isConsumed || event.changes.count { it.pressed } > 1) break
                if (!change.pressed) {
                    cancelled = !dragging
                    break
                }
                val delta = change.position - change.previousPosition
                totalX += delta.x
                totalY += delta.y
                if (!dragging) {
                    if (abs(totalY) > viewConfiguration.touchSlop || totalX < -viewConfiguration.touchSlop) break
                    if (totalX <= viewConfiguration.touchSlop) continue
                    dragging = true
                    gesture.drag(totalX - viewConfiguration.touchSlop, width)
                } else {
                    gesture.drag(delta.x, width)
                }
                change.consume()
            }
        } finally {
            gesture.finish(tracker.calculateVelocity().x / width, cancelled, onComplete)
        }
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/navigation/NavHost.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/navigation/NavHost.kt) · implementation · 187 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
64: internal fun NavHost(
111: private fun RootSection(
133: private fun EntryContent(entry: NavEntry, nav: Navigator, stateHolder: SaveableStateHolder) {
147: private fun RouteContent(route: Route, nav: Navigator) {
178: internal fun MissingRoute(title: String, onBack: () -> Unit) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/navigation/NavHost.kt) · SHA-256 `9d3dcd2325a90518855beb56f9b6f381e1d0757c32d91c7a02a9f78a14350c8d`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.navigation

import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Info
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.SaveableStateHolder
import androidx.compose.runtime.saveable.rememberSaveableStateHolder
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.navigationevent.NavigationEventInfo
import androidx.navigationevent.compose.NavigationBackHandler
import androidx.navigationevent.compose.rememberNavigationEventState
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.LocalViewModelStoreOwner
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.ui.components.EmptyState
import eu.friedcutlet.yokan.ui.components.YokanTopBar
import eu.friedcutlet.yokan.ui.screens.activity.HistoryRoute
import eu.friedcutlet.yokan.ui.screens.activity.TrackerLibraryRoute
import eu.friedcutlet.yokan.ui.screens.activity.UpdateErrorsRoute
import eu.friedcutlet.yokan.ui.screens.activity.UpdatesRoute
import eu.friedcutlet.yokan.ui.screens.browse.BrowseRoute
import eu.friedcutlet.yokan.ui.screens.browse.GlobalSearchRoute
import eu.friedcutlet.yokan.ui.screens.browse.SourceHomeRoute
import eu.friedcutlet.yokan.ui.screens.detail.DetailRoute
import eu.friedcutlet.yokan.ui.screens.discovery.RecommendationsRoute
import eu.friedcutlet.yokan.ui.screens.discovery.SourceRelatedRoute
import eu.friedcutlet.yokan.ui.screens.discovery.SequelsRoute
import eu.friedcutlet.yokan.ui.screens.discovery.WatchOrderRoute
import eu.friedcutlet.yokan.ui.screens.extensions.CodeEditorRoute
import eu.friedcutlet.yokan.ui.screens.extensions.CreateExtensionRoute
import eu.friedcutlet.yokan.ui.screens.extensions.ExtensionDetailRoute
import eu.friedcutlet.yokan.ui.screens.extensions.ExtensionLanguagesRoute
import eu.friedcutlet.yokan.ui.screens.extensions.SourceFiltersRoute
import eu.friedcutlet.yokan.ui.screens.library.LibraryRoute
import eu.friedcutlet.yokan.ui.screens.home.HomeRoute
import eu.friedcutlet.yokan.ui.screens.local.LocalLibraryBrowseRoute
import eu.friedcutlet.yokan.ui.screens.local.LocalLibraryOverviewRoute
import eu.friedcutlet.yokan.ui.screens.migration.MassMigrationDestinationRoute
import eu.friedcutlet.yokan.ui.screens.migration.MassMigrationPreviewRoute
import eu.friedcutlet.yokan.ui.screens.migration.MassMigrationRoute
import eu.friedcutlet.yokan.ui.screens.migration.MassMigrationRunnerRoute
import eu.friedcutlet.yokan.ui.screens.migration.MigrateRoute
import eu.friedcutlet.yokan.ui.screens.more.MoreRoute
import eu.friedcutlet.yokan.ui.screens.reader.ReaderEntryRoute
import eu.friedcutlet.yokan.ui.screens.settings.SettingsRoute
import eu.friedcutlet.yokan.ui.screens.webview.InAppWebViewRoute
import eu.friedcutlet.yokan.ui.theme.YokanScaffold as Scaffold

/**
 * Root section content plus the animated stack of pushed routes (with iOS-style interactive back).
 * Each rendered entry gets its own ViewModelStore and saveable state; root sections share
 * [Navigator.rootViewModelStoreOwner].
 */
@OptIn(ExperimentalComposeUiApi::class)
@Composable
internal fun NavHost(
    nav: Navigator,
    compact: Boolean,
    onAddSignedCatalog: (() -> Unit)?,
    signedCatalogSheet: @Composable () -> Unit,
    modifier: Modifier = Modifier,
    rootContainer: @Composable (@Composable () -> Unit) -> Unit = { it() },
) {
    val backStack by nav.backStack.collectAsStateWithLifecycle()
    val section by nav.section.collectAsStateWithLifecycle()
    val navigationOrder by nav.navigationOrder.collectAsStateWithLifecycle()
    val playerMinimized by nav.playerMinimized.collectAsStateWithLifecycle()
    val stateHolder = rememberSaveableStateHolder()
    // Entries popped without being composed (select() clearing a deep stack) drop their saved state too.
    val savedEntryIds = remember { mutableSetOf<Long>() }
    LaunchedEffect(backStack) {
        val live = backStack.mapTo(HashSet()) { it.id }
        savedEntryIds.filterNot(live::contains).forEach(stateHolder::removeState)
        savedEntryIds.retainAll(live)
        savedEntryIds += live
    }

    NavigationBackHandler(rememberNavigationEventState(NavigationEventInfo.None), isBackEnabled = backStack.isNotEmpty()) { nav.back() }

    val visibleSection = section.takeIf { it in navigationOrder } ?: navigationOrder.firstOrNull()
    NavigationStack(
        backStack = backStack,
        direction = nav.transitionDirection.value,
        cupertino = remember { usesCupertinoPageTransitions() },
        playerMinimized = playerMinimized,
        animationsEnabled = !eu.friedcutlet.yokan.ui.theme.LocalEinkMode.current,
        onCompleteBack = { entry -> if (nav.backStack.value.lastOrNull() === entry) nav.completeInteractiveBack() },
        modifier = modifier,
        rootContent = {
            if (visibleSection != null) {
                CompositionLocalProvider(LocalViewModelStoreOwner provides nav.rootViewModelStoreOwner) {
                    stateHolder.SaveableStateProvider(visibleSection.name) {
                        rootContainer { RootSection(visibleSection, compact, nav, onAddSignedCatalog, signedCatalogSheet) }
                    }
                }
            }
        },
        entryContent = { EntryContent(it, nav, stateHolder) },
    )
}

@Composable
private fun RootSection(
    section: NavSection,
    compact: Boolean,
    nav: Navigator,
    onAddSignedCatalog: (() -> Unit)?,
    signedCatalogSheet: @Composable () -> Unit,
) {
    when (section) {
        NavSection.Home -> HomeRoute(nav)
        NavSection.MangaLibrary -> LibraryRoute(ItemType.Manga, compact, nav)
        NavSection.AnimeLibrary -> LibraryRoute(ItemType.Anime, compact, nav)
        NavSection.NovelLibrary -> LibraryRoute(ItemType.Novel, compact, nav)
        NavSection.LocalLibrary -> LocalLibraryOverviewRoute(nav)
        NavSection.TrackerLibrary -> TrackerLibraryRoute(nav)
        NavSection.Updates -> UpdatesRoute(nav)
        NavSection.History -> HistoryRoute(nav, nested = false)
        NavSection.Browse -> BrowseRoute(nav, onAddSignedCatalog, signedCatalogSheet)
        NavSection.More -> MoreRoute(nav)
    }
}

@Composable
private fun EntryContent(entry: NavEntry, nav: Navigator, stateHolder: SaveableStateHolder) {
    // Declared before the content so it is disposed after it: the entry's screen finishes with its
    // ViewModels before the store is cleared (only once the entry has left the stack).
    DisposableEffect(entry) {
        onDispose { if (nav.release(entry)) stateHolder.removeState(entry.id) }
    }
    CompositionLocalProvider(LocalViewModelStoreOwner provides entry) {
        stateHolder.SaveableStateProvider(entry.id) {
            RouteContent(entry.route, nav)
        }
    }
}

@Composable
private fun RouteContent(route: Route, nav: Navigator) {
    when (route) {
        is Route.Detail -> DetailRoute(route, nav)
        is Route.Reader -> ReaderEntryRoute(route, nav)
        is Route.SourceHome -> SourceHomeRoute(route, nav)
        is Route.GlobalSearch -> GlobalSearchRoute(route, nav)
        is Route.InAppWebView -> InAppWebViewRoute(route, nav)
        Route.History -> HistoryRoute(nav, nested = true)
        Route.UpdateErrors -> UpdateErrorsRoute(nav)
        is Route.ExtensionLanguages -> ExtensionLanguagesRoute(route, nav)
        is Route.SourceFilters -> SourceFiltersRoute(route, nav)
        is Route.ExtensionDetail -> ExtensionDetailRoute(route, nav)
        is Route.CodeEditor -> CodeEditorRoute(route, nav)
        is Route.CreateExtension -> CreateExtensionRoute(route, nav)
        is Route.Recommendations -> RecommendationsRoute(route, nav)
        is Route.SourceRelated -> SourceRelatedRoute(route, nav)
        is Route.WatchOrder -> WatchOrderRoute(route, nav)
        is Route.Sequels -> SequelsRoute(route, nav)
        is Route.Migrate -> MigrateRoute(route, nav)
        is Route.MassMigration -> MassMigrationRoute(route, nav)
        is Route.MassMigrationPreview -> MassMigrationPreviewRoute(route, nav)
        is Route.MassMigrationDestination -> MassMigrationDestinationRoute(route, nav)
        is Route.MassMigrationRunner -> MassMigrationRunnerRoute(route, nav)
        is Route.LocalLibraryBrowse -> LocalLibraryBrowseRoute(route, nav)
        Route.LocalLibraryOverview -> LocalLibraryOverviewRoute(nav)
        is Route.Settings -> SettingsRoute(route, nav)
    }
}

/** Shown when a route's title/source no longer exists (deleted, or a stale deep link). */
@Composable
internal fun MissingRoute(title: String, onBack: () -> Unit) {
    Scaffold(topBar = { YokanTopBar(title = title, onBack = onBack) }) { padding ->
        EmptyState(
            icon = Icons.Filled.Info,
            title = "Unavailable",
            modifier = Modifier.fillMaxSize().padding(padding),
            subtitle = "This item no longer exists.",
        )
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/navigation/NavSection.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/navigation/NavSection.kt) · implementation · 176 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
40: enum class NavSection(val title: String, val itemType: ItemType? = null) {
53: fun ItemType.librarySection(): NavSection = when (this) {
84: fun navigationSectionForStoredName(name: String): NavSection? = when (name.trim().removePrefix("/")) {
98: fun hiddenNavigationSections(db: DbSettings): Set<NavSection> {
104: fun completeNavigationOrder(db: DbSettings): List<NavSection> =
108: fun navigationOrder(db: DbSettings): List<NavSection> {
114: fun DbSettings.withNavSectionMoved(section: NavSection, direction: Int): DbSettings {
124: fun DbSettings.withNavSectionHiddenToggled(section: NavSection): DbSettings {
131: internal fun DbSettings.withNavigationOrderMigrated(): DbSettings {
141: data class NavIcon(
147: fun localizedTitle(section: NavSection): String = when (section) {
165: fun iconFor(section: NavSection): NavIcon = when (section) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/navigation/NavSection.kt) · SHA-256 `54842941aca67493e077e6ac61c44ae41c35a946d8593e951bdeacad827df61b`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.navigation

import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AccountTree
import androidx.compose.material.icons.filled.CollectionsBookmark
import androidx.compose.material.icons.filled.Explore
import androidx.compose.material.icons.filled.History
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.LocalLibrary
import androidx.compose.material.icons.filled.MoreHoriz
import androidx.compose.material.icons.filled.NewReleases
import androidx.compose.material.icons.filled.VideoLibrary
import androidx.compose.material.icons.outlined.AccountTree
import androidx.compose.material.icons.outlined.CollectionsBookmark
import androidx.compose.material.icons.outlined.Explore
import androidx.compose.material.icons.outlined.History
import androidx.compose.material.icons.outlined.Home
import androidx.compose.material.icons.outlined.LocalLibrary
import androidx.compose.material.icons.outlined.MoreHoriz
import androidx.compose.material.icons.outlined.NewReleases
import androidx.compose.material.icons.outlined.VideoLibrary
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.vector.ImageVector
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.services.system.isLocalLibraryManagerSupported
import eu.friedcutlet.yokan.services.system.isTvDevice
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.nav_anime_library
import yokan.composeapp.generated.resources.nav_browse
import yokan.composeapp.generated.resources.nav_history
import yokan.composeapp.generated.resources.nav_home
import yokan.composeapp.generated.resources.nav_manga_library
import yokan.composeapp.generated.resources.nav_more
import yokan.composeapp.generated.resources.nav_novel_library
import yokan.composeapp.generated.resources.nav_tracker_library
import yokan.composeapp.generated.resources.nav_updates

enum class NavSection(val title: String, val itemType: ItemType? = null) {
    Home("Home"),
    MangaLibrary("Manga", ItemType.Manga),
    AnimeLibrary("Anime", ItemType.Anime),
    NovelLibrary("Novel", ItemType.Novel),
    LocalLibrary("Local media"),
    TrackerLibrary("Tracking"),
    Updates("Updates"),
    History("History"),
    Browse("Browse"),
    More("More"),
}

fun ItemType.librarySection(): NavSection = when (this) {
    ItemType.Manga -> NavSection.MangaLibrary
    ItemType.Anime -> NavSection.AnimeLibrary
    ItemType.Novel -> NavSection.NovelLibrary
}

private val defaultNavigationOrder = listOf(
    NavSection.Home,
    NavSection.MangaLibrary,
    NavSection.AnimeLibrary,
    NavSection.NovelLibrary,
    NavSection.LocalLibrary,
    NavSection.Updates,
    NavSection.History,
    NavSection.Browse,
    NavSection.More,
    NavSection.TrackerLibrary,
)

private val previousYokanDefaultNavigationOrder = listOf(
    NavSection.Updates,
    NavSection.MangaLibrary,
    NavSection.AnimeLibrary,
    NavSection.NovelLibrary,
    NavSection.LocalLibrary,
    NavSection.History,
    NavSection.Browse,
    NavSection.More,
    NavSection.TrackerLibrary,
)

fun navigationSectionForStoredName(name: String): NavSection? = when (name.trim().removePrefix("/")) {
    "Home", "home" -> NavSection.Home
    "MangaLibrary" -> NavSection.MangaLibrary
    "AnimeLibrary" -> NavSection.AnimeLibrary
    "NovelLibrary" -> NavSection.NovelLibrary
    "LocalLibrary", "localLibrary" -> NavSection.LocalLibrary
    "updates", "Updates" -> NavSection.Updates
    "history", "History" -> NavSection.History
    "browse", "Browse" -> NavSection.Browse
    "more", "More" -> NavSection.More
    "trackerLibrary", "TrackerLibrary" -> NavSection.TrackerLibrary
    else -> null
}

fun hiddenNavigationSections(db: DbSettings): Set<NavSection> {
    val stored = db.hideItems.orEmpty().mapNotNull(::navigationSectionForStoredName).toSet()
    val tvAnimeOnly = isTvDevice() && (db.animeOnlyTvMode ?: true)
    return if (tvAnimeOnly) stored + setOf(NavSection.MangaLibrary, NavSection.NovelLibrary) else stored
}

fun completeNavigationOrder(db: DbSettings): List<NavSection> =
    (db.navigationOrder.orEmpty().mapNotNull(::navigationSectionForStoredName) + defaultNavigationOrder).distinct()

/** The visible root sections, in order. */
fun navigationOrder(db: DbSettings): List<NavSection> {
    val hidden = hiddenNavigationSections(db)
    val localHidden = !db.showLocalLibraryNavigation || !isLocalLibraryManagerSupported()
    return completeNavigationOrder(db).filterNot { it in hidden || (it == NavSection.LocalLibrary && localHidden) }
}

fun DbSettings.withNavSectionMoved(section: NavSection, direction: Int): DbSettings {
    val current = completeNavigationOrder(this).toMutableList()
    val index = current.indexOf(section).takeIf { it >= 0 } ?: return this
    val target = (index + direction).coerceIn(0, current.size - 1)
    if (target == index) return this
    current.removeAt(index)
    current.add(target, section)
    return copy(navigationOrder = current.map(NavSection::name))
}

fun DbSettings.withNavSectionHiddenToggled(section: NavSection): DbSettings {
    val hidden = hiddenNavigationSections(this).toMutableSet()
    if (!hidden.remove(section)) hidden.add(section)
    return copy(hideItems = hidden.map(NavSection::name))
}

/** One-time migration from the previous Yokan default order (Updates first) to the Mangayomi one. */
internal fun DbSettings.withNavigationOrderMigrated(): DbSettings {
    val parsed = navigationOrder.orEmpty().mapNotNull(::navigationSectionForStoredName)
    val previousWithoutLocal = previousYokanDefaultNavigationOrder.filterNot { it == NavSection.LocalLibrary }
    return if (parsed == previousYokanDefaultNavigationOrder || parsed == previousWithoutLocal) {
        copy(navigationOrder = defaultNavigationOrder.map(NavSection::name))
    } else {
        this
    }
}

data class NavIcon(
    val selected: ImageVector,
    val unselected: ImageVector,
)

@Composable
fun localizedTitle(section: NavSection): String = when (section) {
    NavSection.LocalLibrary -> "Local media"
    else -> stringResource(
        when (section) {
            NavSection.Home -> Res.string.nav_home
            NavSection.MangaLibrary -> Res.string.nav_manga_library
            NavSection.AnimeLibrary -> Res.string.nav_anime_library
            NavSection.NovelLibrary -> Res.string.nav_novel_library
            NavSection.TrackerLibrary -> Res.string.nav_tracker_library
            NavSection.Updates -> Res.string.nav_updates
            NavSection.History -> Res.string.nav_history
            NavSection.Browse -> Res.string.nav_browse
            NavSection.More -> Res.string.nav_more
            NavSection.LocalLibrary -> Res.string.nav_more
        },
    )
}

fun iconFor(section: NavSection): NavIcon = when (section) {
    NavSection.Home -> NavIcon(Icons.Filled.Home, Icons.Outlined.Home)
    NavSection.MangaLibrary -> NavIcon(Icons.Filled.CollectionsBookmark, Icons.Outlined.CollectionsBookmark)
    NavSection.AnimeLibrary -> NavIcon(Icons.Filled.VideoLibrary, Icons.Outlined.VideoLibrary)
    NavSection.NovelLibrary -> NavIcon(Icons.Filled.LocalLibrary, Icons.Outlined.LocalLibrary)
    NavSection.LocalLibrary -> NavIcon(Icons.Filled.LocalLibrary, Icons.Outlined.LocalLibrary)
    NavSection.TrackerLibrary -> NavIcon(Icons.Filled.AccountTree, Icons.Outlined.AccountTree)
    NavSection.Updates -> NavIcon(Icons.Filled.NewReleases, Icons.Outlined.NewReleases)
    NavSection.History -> NavIcon(Icons.Filled.History, Icons.Outlined.History)
    NavSection.Browse -> NavIcon(Icons.Filled.Explore, Icons.Outlined.Explore)
    NavSection.More -> NavIcon(Icons.Filled.MoreHoriz, Icons.Outlined.MoreHoriz)
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/navigation/NavigationStack.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/navigation/NavigationStack.kt) · implementation · 139 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
40: internal fun NavigationStack(
73: fun contentFor(entry: NavEntry?): @Composable () -> Unit = if (entry == null) movableRoot else {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/navigation/NavigationStack.kt) · SHA-256 `224acc77ea962dbf9aa5fff114793d27dfba0e9234361e5fa2ad3486c9fcb8af`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.navigation

import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.EnterTransition
import androidx.compose.animation.ExitTransition
import androidx.compose.animation.core.CubicBezierEasing
import androidx.compose.animation.core.tween
import androidx.compose.animation.core.updateTransition
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.scaleIn
import androidx.compose.animation.scaleOut
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.movableContentOf
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.ui.theme.LocalYokanScaffoldColor

/** Page motion is confined to graphics layers; content changes only at gesture/navigation boundaries. */
@Composable
internal fun NavigationStack(
    backStack: List<NavEntry>,
    direction: Int,
    cupertino: Boolean,
    playerMinimized: Boolean,
    animationsEnabled: Boolean,
    onCompleteBack: (NavEntry) -> Unit,
    modifier: Modifier = Modifier,
    rootContent: @Composable () -> Unit,
    entryContent: @Composable (NavEntry) -> Unit,
) {
    val completeBack by rememberUpdatedState(onCompleteBack)
    val edgeWidthPx = with(LocalDensity.current) { 24.dp.toPx() }
    val settleScope = rememberCoroutineScope()
    var routeWidthPx by remember { mutableFloatStateOf(1f) }
    val top = backStack.lastOrNull()
    val previous = backStack.getOrNull(backStack.size - 2)
    val transition = updateTransition(top, label = "Navigation")
    val gesture = remember(top) { InteractiveBackGesture(settleScope) }
    DisposableEffect(gesture) { onDispose { gesture.dispose() } }
    val interactiveBackModifier = if (cupertino && animationsEnabled && top != null && !playerMinimized) {
        Modifier.interactiveBackGesture(
            gesture = gesture,
            edgeWidth = edgeWidthPx,
            canStart = { !transition.isRunning && transition.currentState === transition.targetState },
            onComplete = { completeBack(top) },
        )
    } else Modifier
    val currentRoot by rememberUpdatedState(rootContent)
    val currentEntry by rememberUpdatedState(entryContent)
    val movableRoot = remember { movableContentOf { currentRoot() } }
    // Move a preview into its final slot on pop; never mount the same saveable entry twice.
    val entryContents = remember { mutableMapOf<NavEntry, @Composable () -> Unit>() }
    fun contentFor(entry: NavEntry?): @Composable () -> Unit = if (entry == null) movableRoot else {
        entryContents.getOrPut(entry) { movableContentOf { currentEntry(entry) } }
    }
    LaunchedEffect(backStack, transition.currentState, transition.targetState) {
        entryContents.keys.retainAll(backStack.toSet() + listOfNotNull(transition.currentState, transition.targetState))
    }
    val pageColor = LocalYokanScaffoldColor.current
    Box(
        modifier = modifier
            .fillMaxSize()
            .clipToBounds()
            .onSizeChanged { routeWidthPx = it.width.toFloat().coerceAtLeast(1f) }
            .then(interactiveBackModifier),
    ) {
        if ((!cupertino && (top == null || playerMinimized)) ||
            (cupertino && playerMinimized && top != null)
        ) movableRoot()

        if (gesture.active) {
            Box(
                Modifier.fillMaxSize().graphicsLayer {
                    translationX = -routeWidthPx / 3f * (1f - gesture.progress)
                }.background(pageColor),
            ) { contentFor(previous)() }
        }

        transition.AnimatedContent(
            contentKey = { if (cupertino) it?.id ?: "root" else it?.route?.destination() ?: "root" },
            transitionSpec = {
                // Chapter changes and same-page argument replacements must not run two readers
                // through a push animation. They still get distinct entry/saveable identities.
                val replacing = direction > 0 && initialState != null && targetState != null &&
                    initialState?.route?.destination() == targetState?.route?.destination()
                if (direction == 0 || !animationsEnabled || replacing) {
                    EnterTransition.None togetherWith ExitTransition.None
                } else if (cupertino) {
                    val motion = tween<IntOffset>(320, easing = CubicBezierEasing(0.25f, 0.1f, 0.25f, 1f))
                    if (direction > 0) {
                        (slideInHorizontally(motion) { it } togetherWith
                            slideOutHorizontally(motion) { -it / 3 }).apply { targetContentZIndex = 1f }
                    } else {
                        (slideInHorizontally(motion) { -it / 3 } togetherWith
                            slideOutHorizontally(motion) { it }).apply { targetContentZIndex = -1f }
                    }
                } else if (direction > 0) {
                    (
                        fadeIn(tween(220)) + scaleIn(tween(220), initialScale = 0.94f)
                        ) togetherWith fadeOut(tween(140))
                } else {
                    fadeIn(tween(180)) togetherWith (
                        fadeOut(tween(180)) + scaleOut(tween(220), targetScale = 0.94f)
                        )
                }
            },
            modifier = Modifier.fillMaxSize(),
        ) { entry ->
            val entryGesture = remember(entry) { gesture }
            Box(
                Modifier.fillMaxSize().graphicsLayer {
                    translationX = routeWidthPx * entryGesture.progress
                }.then(if (cupertino && !playerMinimized) Modifier.background(pageColor) else Modifier),
            ) {
                if (entry != null || (cupertino && !playerMinimized)) contentFor(entry)()
            }
        }
    }
}
```
[complete-source-end]: #

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

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/navigation/Navigator.kt) · implementation · 205 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
27: class NavEntry internal constructor(val id: Long, val route: Route) : ViewModelStoreOwner {
32: data class LibraryRequest(val id: Long, val itemType: ItemType, val query: String?)
38: class Navigator(private val settings: SettingsStore, scope: CoroutineScope) {
104: fun navigate(route: Route) {
114: fun back() = pop(direction = -1)
116: fun completeInteractiveBack() = pop(direction = 0)
118: private fun pop(direction: Int) {
126: fun select(section: NavSection) {
139: fun selectItemType(type: ItemType) {
146: fun showLibrary(itemType: ItemType, query: String? = null) {
151: private fun requestLibrary(itemType: ItemType, query: String?) {
156: fun minimizePlayer() { if (!closed) _playerMinimized.value = true }
158: fun restorePlayer() { if (!closed) _playerMinimized.value = false }
160: fun dismissPlayer() {
166: internal fun release(entry: NavEntry): Boolean {
172: private fun clearStore(store: ViewModelStore) {
183: private fun clearEntry(entry: NavEntry) {
189: fun close() {
197: suspend fun closeAndJoin() = withContext(uiContext + NonCancellable) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/navigation/Navigator.kt) · SHA-256 `c29209cf7a4214cfdc627ae33304a001edd96249c9812f2e87d6424e12d70c7b`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.navigation

import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.ViewModelStoreOwner
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.domain.ItemType
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.withContext
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import eu.friedcutlet.yokan.ui.navigation.navigationOrder as visibleSections

/** One back-stack entry; its [viewModelStore] lives until the entry leaves the stack. */
class NavEntry internal constructor(val id: Long, val route: Route) : ViewModelStoreOwner {
    override val viewModelStore = ViewModelStore()
}

/** Asks the library for [itemType] to show [query] (all categories), or its default category when null. */
data class LibraryRequest(val id: Long, val itemType: ItemType, val query: String?)

/**
 * App navigation: the selected root section, the per-section item-type cursor and the stack of
 * pushed [Route]s. Main-thread only.
 */
class Navigator(private val settings: SettingsStore, scope: CoroutineScope) {
    private val uiContext = scope.coroutineContext.minusKey(Job)
    private val ownerJob = SupervisorJob(scope.coroutineContext[Job])
    private val ownerScope = CoroutineScope(scope.coroutineContext + ownerJob)
    private val retirementLock = Mutex()
    private val entries = mutableSetOf<NavEntry>()
    private val pendingJobs = mutableSetOf<Job>()
    private val pendingCleanup = mutableSetOf<AwaitedViewModelCleanup>()
    private var closed = false

    private var nextEntryId = 0L
    private var nextRequestId = 0L
    private val itemTypeBySection = mutableMapOf(
        NavSection.TrackerLibrary to ItemType.Manga,
        NavSection.Updates to ItemType.Manga,
        NavSection.History to ItemType.Manga,
        NavSection.Browse to ItemType.Manga,
    )

    private val _backStack = MutableStateFlow<List<NavEntry>>(emptyList())
    val backStack: StateFlow<List<NavEntry>> = _backStack.asStateFlow()

    val navigationOrder: StateFlow<List<NavSection>>
    val hiddenSections: StateFlow<Set<NavSection>>

    private val _section: MutableStateFlow<NavSection>
    val section: StateFlow<NavSection>

    private val _itemType: MutableStateFlow<ItemType>
    val itemType: StateFlow<ItemType>

    private val _transitionDirection = MutableStateFlow(1)
    val transitionDirection: StateFlow<Int> = _transitionDirection.asStateFlow()

    private val _playerMinimized = MutableStateFlow(false)
    val playerMinimized: StateFlow<Boolean> = _playerMinimized.asStateFlow()

    private val _libraryRequest = MutableStateFlow<LibraryRequest?>(null)
    val libraryRequest: StateFlow<LibraryRequest?> = _libraryRequest.asStateFlow()

    val rootViewModelStoreOwner: ViewModelStoreOwner = object : ViewModelStoreOwner {
        override val viewModelStore = ViewModelStore()
    }

    init {
        if (settings.db.value.withNavigationOrderMigrated() != settings.db.value) {
            settings.updateDb { it.withNavigationOrderMigrated() }
        }
        val db = settings.db.value
        navigationOrder = settings.db.map { visibleSections(it) }
            .stateIn(ownerScope, SharingStarted.Eagerly, visibleSections(db))
        hiddenSections = settings.db.map { hiddenNavigationSections(it) }
            .stateIn(ownerScope, SharingStarted.Eagerly, hiddenNavigationSections(db))
        val initialSection = navigationOrder.value.firstOrNull() ?: NavSection.MangaLibrary
        _section = MutableStateFlow(initialSection)
        section = _section.asStateFlow()
        _itemType = MutableStateFlow(initialSection.itemType ?: itemTypeBySection[initialSection] ?: ItemType.Manga)
        itemType = _itemType.asStateFlow()
        // A section that is hidden (or was opened by a deep link while hidden) falls back to the first visible one.
        ownerScope.launch {
            combine(section, navigationOrder) { current, order -> current to order }.collect { (current, order) ->
                if (current !in order) order.firstOrNull()?.let(::select)
            }
        }
    }

    fun navigate(route: Route) {
        if (closed) return
        if (route is Route.Reader) _playerMinimized.value = false
        val stack = _backStack.value
        val entry = NavEntry(nextEntryId++, route).also { entries += it }
        val replaceTop = stack.lastOrNull()?.route?.destination() == route.destination()
        _transitionDirection.value = 1
        _backStack.value = if (replaceTop) stack.dropLast(1) + entry else stack + entry
    }

    fun back() = pop(direction = -1)

    fun completeInteractiveBack() = pop(direction = 0)

    private fun pop(direction: Int) {
        if (closed) return
        val stack = _backStack.value
        if (stack.isEmpty()) return
        _transitionDirection.value = direction
        _backStack.value = stack.dropLast(1)
    }

    fun select(section: NavSection) {
        if (closed) return
        val popped = _backStack.value
        if (popped.isNotEmpty()) _transitionDirection.value = -1
        _backStack.value = emptyList()
        // The top is still composed (exit animation); the host releases it. Nothing below is composed.
        popped.dropLast(1).forEach(::clearEntry)
        _section.value = section
        (section.itemType ?: itemTypeBySection[section])?.let { _itemType.value = it }
        section.itemType?.let { requestLibrary(it, query = null) }
    }

    /** Switches the root item type; Updates/History/Browse/Tracking remember it per section. */
    fun selectItemType(type: ItemType) {
        if (closed) return
        if (_itemType.value == type) return
        _itemType.value = type
        if (_section.value in itemTypeBySection) itemTypeBySection[_section.value] = type
    }

    fun showLibrary(itemType: ItemType, query: String? = null) {
        select(itemType.librarySection())
        requestLibrary(itemType, query)
    }

    private fun requestLibrary(itemType: ItemType, query: String?) {
        if (closed) return
        _libraryRequest.value = LibraryRequest(nextRequestId++, itemType, query)
    }

    fun minimizePlayer() { if (!closed) _playerMinimized.value = true }

    fun restorePlayer() { if (!closed) _playerMinimized.value = false }

    fun dismissPlayer() {
        restorePlayer()
        back()
    }

    /** Clears [entry]'s ViewModels once it has left the stack; true when it did. */
    internal fun release(entry: NavEntry): Boolean {
        if (entry in _backStack.value) return false
        clearEntry(entry)
        return true
    }

    private fun clearStore(store: ViewModelStore) {
        // Capture scopes before clear removes references and cancels them. Retain jobs even for
        // entries already popped: their non-cancelable finalizers may still own profile resources.
        store.keys().mapNotNull(store::get).forEach { model ->
            model.viewModelScope.coroutineContext[Job]?.let { pendingJobs += it }
            (model as? AwaitedViewModelCleanup)?.let { pendingCleanup += it }
        }
        store.clear()
        pendingJobs.removeAll { it.isCompleted }
    }

    private fun clearEntry(entry: NavEntry) {
        clearStore(entry.viewModelStore)
        entries.remove(entry)
    }

    /** Synchronously close navigation admission and cancel every owned ViewModel and watcher. */
    fun close() {
        closed = true
        ownerScope.cancel()
        entries.toList().forEach(::clearEntry)
        clearStore(rootViewModelStoreOwner.viewModelStore)
    }

    /** Call on the captured UI context, after child composition disposal and progress capture. */
    suspend fun closeAndJoin() = withContext(uiContext + NonCancellable) {
        retirementLock.withLock {
            close()
            pendingJobs.toList().forEach { it.join(); pendingJobs.remove(it) }
            pendingCleanup.toList().forEach { it.awaitCleanup(); pendingCleanup.remove(it) }
            ownerJob.join()
        }
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/navigation/PlatformNavigation.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/navigation/PlatformNavigation.kt) · implementation · 3 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
3: internal expect fun usesCupertinoPageTransitions(): Boolean
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/navigation/PlatformNavigation.kt) · SHA-256 `6842a30a60e164480c691d6aed040a5537cfa07ea436300940885bf4b905284f`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.navigation

internal expect fun usesCupertinoPageTransitions(): Boolean
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/navigation/RootNavigationBars.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/navigation/RootNavigationBars.kt) · implementation · 358 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
66: internal fun navBadges(repository: YokanRepository, hidden: Flow<Set<NavSection>>): Flow<Map<NavSection, Int>> =
84: private fun NavigationIcon(
100: internal fun RailNavigation(
185: internal fun BottomNavigation(
305: internal fun compactPrimarySections(sections: List<NavSection>): List<NavSection> =
309: private fun NavLabel(text: String) {
323: private fun LibraryPickerBar(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/navigation/RootNavigationBars.kt) · SHA-256 `c3a2b88f2a082d93cdd7af5d5982e6e1d06220d8640b197af4aa5531b3fff3c4`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.navigation

import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.focusGroup
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Badge
import androidx.compose.material3.BadgedBox
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.NavigationRail
import androidx.compose.material3.NavigationRailItem
import androidx.compose.material3.NavigationRailItemDefaults
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.navigationevent.NavigationEventInfo
import androidx.navigationevent.compose.NavigationBackHandler
import androidx.navigationevent.compose.rememberNavigationEventState
import androidx.compose.ui.graphics.lerp
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.services.extensions.VersionComparison
import eu.friedcutlet.yokan.services.system.isTvDevice
import eu.friedcutlet.yokan.ui.screens.activity.HistoryNavigationActivation
import eu.friedcutlet.yokan.util.nowMillis
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flowOn
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_back
import yokan.composeapp.generated.resources.nothing_read_recently
import yokan.composeapp.generated.resources.nav_sections

/**
 * Badge counts for the root navigation: unread updates and outdated active extensions of the visible
 * media types. Recomputed off the main thread only when the snapshot parts it reads change.
 */
internal fun navBadges(repository: YokanRepository, hidden: Flow<Set<NavSection>>): Flow<Map<NavSection, Int>> =
    combine(
        repository.snapshots.distinctUntilChanged { old, new ->
            old.updates === new.updates && old.chapters === new.chapters &&
                old.mangas === new.mangas && old.sources === new.sources
        },
        hidden,
    ) { _, hiddenSections ->
        val visibleTypes = ItemType.entries.filter { it.librarySection() !in hiddenSections }
        mapOf(
            NavSection.Updates to repository.updates().count { !it.isRead && it.itemType in visibleTypes },
            NavSection.Browse to visibleTypes.sumOf { type ->
                repository.sources(type).count { it.isActive && VersionComparison.isOutdated(it.version, it.versionLast) }
            },
        )
    }.flowOn(Dispatchers.Default)

@Composable
private fun NavigationIcon(
    count: Int,
    imageVector: ImageVector,
    label: String,
) {
    if (count > 0) {
        BadgedBox(badge = { Badge { Text(count.toString()) } }) {
            Icon(imageVector = imageVector, contentDescription = label)
        }
    } else {
        Icon(imageVector = imageVector, contentDescription = label)
    }
}

@Composable
@OptIn(ExperimentalFoundationApi::class)
internal fun RailNavigation(
    nav: Navigator,
    badges: Map<NavSection, Int>,
    onResumeLatestHistory: (ItemType, String) -> Unit,
    modifier: Modifier = Modifier,
) {
    val navigationOrder by nav.navigationOrder.collectAsStateWithLifecycle()
    val selectedSection by nav.section.collectAsStateWithLifecycle()
    val historyActivation = remember { HistoryNavigationActivation() }
    val emptyHistoryMessage = stringResource(Res.string.nothing_read_recently)
    val isTv = isTvDevice()
    NavigationRail(
        modifier = modifier
            .width(100.dp)
            .focusGroup(),
        header = if (isTv) {
            {
                Surface(
                    shape = RoundedCornerShape(6.dp),
                    color = MaterialTheme.colorScheme.primary,
                    modifier = Modifier.padding(vertical = 8.dp),
                ) {
                    Text(
                        text = "BETA",
                        color = MaterialTheme.colorScheme.onPrimary,
                        style = MaterialTheme.typography.labelSmall.copy(
                            fontSize = 10.sp,
                            fontWeight = FontWeight.Bold,
                            letterSpacing = 1.5.sp,
                        ),
                        modifier = Modifier.padding(horizontal = 8.dp, vertical = 3.dp),
                    )
                }
            }
        } else null,
    ) {
        navigationOrder.forEach { section ->
            val selected = selectedSection == section
            val navIcon = iconFor(section)
            val label = localizedTitle(section)
            val baseIndicatorColor = lerp(
                MaterialTheme.colorScheme.secondaryContainer,
                MaterialTheme.colorScheme.onSecondaryContainer,
                0.03f,
            )
            val indicatorColor = baseIndicatorColor.copy(
                red = (baseIndicatorColor.red + 2.5f / 255f).coerceAtMost(1f),
                blue = (baseIndicatorColor.blue - 2.5f / 255f).coerceAtLeast(0f),
            )
            NavigationRailItem(
                modifier = Modifier.height(65.dp).offset(y = 0.5.dp),
                selected = selected,
                onClick = {
                    if (section == NavSection.History) {
                        historyActivation.activate(
                            nowMillis(),
                            onSingle = { nav.select(section) },
                            onDouble = { nav.select(section); onResumeLatestHistory(nav.itemType.value, emptyHistoryMessage) },
                        )
                    } else nav.select(section)
                },
                colors = NavigationRailItemDefaults.colors(
                    indicatorColor = indicatorColor,
                ),
                icon = {
                    Box(Modifier.offset(y = (-0.5).dp)) {
                        NavigationIcon(
                            count = badges[section] ?: 0,
                            imageVector = if (selected) navIcon.selected else navIcon.unselected,
                            label = label,
                        )
                    }
                },
                label = {
                    Box(Modifier.offset(y = 5.5.dp)) {
                        NavLabel(label)
                    }
                },
            )
        }
    }
}

@OptIn(ExperimentalComposeUiApi::class)
@Composable
internal fun BottomNavigation(
    nav: Navigator,
    badges: Map<NavSection, Int>,
    mergeLibraries: Boolean,
    onResumeLatestHistory: (ItemType, String) -> Unit,
) {
    val navigationOrder by nav.navigationOrder.collectAsStateWithLifecycle()
    val selectedSection by nav.section.collectAsStateWithLifecycle()
    val hidden by nav.hiddenSections.collectAsStateWithLifecycle()
    val historyActivation = remember { HistoryNavigationActivation() }
    val emptyHistoryMessage = stringResource(Res.string.nothing_read_recently)
    // Mirror the Flutter app's mobile nav:
    //  1. Pull from `navigationOrder`, which already drops anything in
    //     `dbSettings.hideItems`, so every enabled section is reachable.
    //  2. When `mergeLibraryNavMobile` is on, replace the first library entry
    //     in the order with a synthetic "Library" entry and remove the other
    //     two. Tapping the merged entry swaps the bar into a sub-navigation
    //     showing [Back] [Manga] [Anime] [Novel] limited to the visible
    //     library types; selecting one activates it and collapses back.
    val librarySections = setOf(NavSection.MangaLibrary, NavSection.AnimeLibrary, NavSection.NovelLibrary)
    val merge = mergeLibraries
    val visibleLibraries = remember(hidden) {
        listOf(NavSection.MangaLibrary, NavSection.AnimeLibrary, NavSection.NovelLibrary)
            .filterNot { it in hidden }
    }
    var libraryPickerOpen by remember(merge) { mutableStateOf(false) }
    // Picking is meaningful for any non-empty visible library list. Mangayomi
    // still shows Back + the one available type when only one remains visible.
    if (!merge || visibleLibraries.isEmpty()) libraryPickerOpen = false

    if (libraryPickerOpen) {
        // Predictive back collapses the picker instead of falling through to
        // the root back handler (which would close the app from a root section).
        NavigationBackHandler(rememberNavigationEventState(NavigationEventInfo.None)) { libraryPickerOpen = false }
        LibraryPickerBar(
            selectedSection = selectedSection,
            options = visibleLibraries,
            onClose = { libraryPickerOpen = false },
            onSelect = nav::select,
        )
        return
    }

    val collapsed = remember(navigationOrder, merge) {
        if (!merge) return@remember navigationOrder
        val result = mutableListOf<NavSection>()
        var placed = false
        navigationOrder.forEach { section ->
            if (section in librarySections) {
                if (!placed) {
                    result += section
                    placed = true
                }
            } else {
                result += section
            }
        }
        result
    }

    var sectionsOpen by remember { mutableStateOf(false) }
    val primary = compactPrimarySections(collapsed)
    val overflow = collapsed.drop(primary.size)
    NavigationBar(modifier = Modifier.focusGroup()) {
        primary.forEach { section ->
            val isMergedLibrary = merge && section in librarySections
            val selected = if (isMergedLibrary) selectedSection in librarySections else selectedSection == section
            val navIcon = iconFor(if (isMergedLibrary) NavSection.MangaLibrary else section)
            val label = if (isMergedLibrary) "Library" else localizedTitle(section)
            NavigationBarItem(
                selected = selected,
                onClick = {
                    if (isMergedLibrary) {
                        if (visibleLibraries.isEmpty()) return@NavigationBarItem
                        libraryPickerOpen = true
                    } else if (section == NavSection.History) {
                        historyActivation.activate(
                            nowMillis(),
                            onSingle = { nav.select(section) },
                            onDouble = { nav.select(section); onResumeLatestHistory(nav.itemType.value, emptyHistoryMessage) },
                        )
                    } else {
                        nav.select(section)
                    }
                },
                icon = {
                    NavigationIcon(
                        count = badges[section] ?: 0,
                        imageVector = if (selected) navIcon.selected else navIcon.unselected,
                        label = label,
                    )
                },
                label = { NavLabel(label) },
            )
        }
        if (overflow.isNotEmpty()) {
            NavigationBarItem(
                selected = selectedSection in overflow,
                onClick = { sectionsOpen = true },
                icon = { Box {
                    NavigationIcon(overflow.sumOf { badges[it] ?: 0 }, Icons.Filled.Menu, stringResource(Res.string.nav_sections))
                    DropdownMenu(expanded = sectionsOpen, onDismissRequest = { sectionsOpen = false }) {
                        overflow.forEach { section ->
                            val merged = merge && section in librarySections
                            DropdownMenuItem(text = { Text(if (merged) "Library" else localizedTitle(section)) },
                                leadingIcon = { Icon(iconFor(section).unselected, null) },
                                onClick = {
                                    sectionsOpen = false
                                    if (merged) libraryPickerOpen = true else nav.select(section)
                                })
                        }
                    }
                } },
                label = { NavLabel(stringResource(Res.string.nav_sections)) },
            )
        }
    }
}

/** Keep compact navigation usable as new destinations are added; every other section remains reachable. */
internal fun compactPrimarySections(sections: List<NavSection>): List<NavSection> =
    if (sections.size <= 5) sections else sections.take(4)

@Composable
private fun NavLabel(text: String) {
    // Without an explicit center alignment, NavigationBarItem labels default
    // to TextAlign.Start, so labels of differing lengths drift left within
    // their slot and the icon/label column reads as off-center. Single line
    // with ellipsis keeps the slot height stable even on narrow screens.
    Text(
        text = text,
        textAlign = TextAlign.Center,
        maxLines = 1,
        overflow = TextOverflow.Ellipsis,
    )
}

@Composable
private fun LibraryPickerBar(
    selectedSection: NavSection,
    options: List<NavSection>,
    onClose: () -> Unit,
    onSelect: (NavSection) -> Unit,
) {
    NavigationBar(modifier = Modifier.focusGroup()) {
        NavigationBarItem(
            selected = false,
            onClick = onClose,
            icon = {
                Icon(
                    imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                    contentDescription = stringResource(Res.string.action_back),
                )
            },
            label = { NavLabel(stringResource(Res.string.action_back)) },
        )
        options.forEach { section ->
            val selected = selectedSection == section
            val navIcon = iconFor(section)
            val label = localizedTitle(section)
            NavigationBarItem(
                selected = selected,
                onClick = { onSelect(section) },
                icon = {
                    Icon(
                        imageVector = if (selected) navIcon.selected else navIcon.unselected,
                        contentDescription = label,
                    )
                },
                label = { NavLabel(label) },
            )
        }
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/navigation/RootNavigationGestures.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/navigation/RootNavigationGestures.kt) · implementation · 82 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
35: internal fun Modifier.rootNavigationGestures(nav: Navigator): Modifier {
42: fun isLibrarySection() = nav.section.value.itemType != null
44: fun shiftItemType(delta: Int) {
66: fun shift(delta: Int) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/navigation/RootNavigationGestures.kt) · SHA-256 `05575fe9addbccf6bd78951fe2c6958f1696b0d55db7e04537ea5382d36e6f08`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.navigation

import androidx.compose.foundation.focusable
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onKeyEvent
import androidx.compose.ui.input.key.type
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.ui.screens.library.rememberLibraryViewModel

/**
 * Attaches keyboard movement between item-type tabs (Manga / Anime / Novel)
 * within the active section, outside the bottom-nav:
 *
 *  - **Keyboard A / D** — left / right shifts `selectedItemType` through the
 *    visible item-type list, wrapping at the ends. Wired via `onKeyEvent`
 *    so child handlers (TextFields, etc.) get first dibs on the keystroke;
 *    typing "a" in a focused search field never triggers tab switching.
 *
 * When the active section is one of the per-library variants (`MangaLibrary`,
 * `AnimeLibrary`, `NovelLibrary`), the gesture also re-routes the active
 * section to match the new item type so the user lands on the matching
 * library page rather than the Manga library showing Anime data.
 */
@Composable
internal fun Modifier.rootNavigationGestures(nav: Navigator): Modifier {
    val focusRequester = remember { FocusRequester() }
    LaunchedEffect(Unit) { runCatching { focusRequester.requestFocus() } }
    val section by nav.section.collectAsStateWithLifecycle()
    // The visible library screen's ViewModel: same root store, same key.
    val library = section.itemType?.let { rememberLibraryViewModel(it, nav) }

    fun isLibrarySection() = nav.section.value.itemType != null

    fun shiftItemType(delta: Int) {
        val hidden = nav.hiddenSections.value
        val types = ItemType.entries.filter { it.librarySection() !in hidden }
        if (types.size < 2) return
        val currentIdx = types.indexOf(nav.itemType.value).takeIf { it >= 0 } ?: 0
        val nextIdx = ((currentIdx + delta) % types.size + types.size) % types.size
        val nextType = types[nextIdx]
        nav.selectItemType(nextType)
        if (isLibrarySection()) nav.select(nextType.librarySection())
    }

    /**
     * Pick the right horizontal-swipe action for the active section.
     *
     *  - Library sections: cycle categories within the current item type.
     *    Falls back to item-type cycling when the user only has one (or
     *    zero) category for the active type, so a single-category library
     *    can still be navigated.
     *  - Everywhere else (Updates / History / Browse / Tracker / More):
     *    cycle item types so each section's tab strip flips through Manga /
     *    Anime / Novel without changing the active section itself.
     */
    fun shift(delta: Int) {
        if (library?.shiftCategory(delta) == true) return
        shiftItemType(delta)
    }

    return this
        .focusRequester(focusRequester)
        .focusable()
        .onKeyEvent { event ->
            if (event.type != KeyEventType.KeyDown) return@onKeyEvent false
            when (event.key) {
                Key.A -> { shift(-1); true }
                Key.D -> { shift(+1); true }
                else -> false
            }
        }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/navigation/Route.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/navigation/Route.kt) · implementation · 107 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.

Declaration checklist (source line numbers):
```text
25: sealed interface Route {
60: enum class SettingsPage(val title: StringResource, val legacyRoute: String, val icon: ImageVector? = null) {
107: internal fun Route.destination(): Any = if (this is Route.Settings) page else this::class
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/navigation/Route.kt) · SHA-256 `dcb6382725ac853530724135ef75ba5f6ee41ac65d820bf04a1fb7fa5daff84c`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.navigation

import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ChromeReaderMode
import androidx.compose.material.icons.filled.Code
import androidx.compose.material.icons.filled.CloudSync
import androidx.compose.material.icons.filled.ColorLens
import androidx.compose.material.icons.filled.Download
import androidx.compose.material.icons.filled.Explore
import androidx.compose.material.icons.filled.Forum
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.LocalLibrary
import androidx.compose.material.icons.filled.PlayCircle
import androidx.compose.material.icons.filled.Security
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.filled.Sync
import androidx.compose.ui.graphics.vector.ImageVector
import eu.friedcutlet.yokan.domain.ItemType
import kotlinx.serialization.Serializable
import org.jetbrains.compose.resources.StringResource
import yokan.composeapp.generated.resources.*

/** A pushed destination. Arguments are IDs/primitives; screens observe fresh data for them. */
@Serializable
sealed interface Route {
    @Serializable data class Detail(val mangaId: Long) : Route
    /** `chapterId == null` opens the first unread chapter, else the first chapter. */
    @Serializable data class Reader(val mangaId: Long, val chapterId: Long? = null) : Route
    @Serializable data class SourceHome(val sourceId: Long, val genre: String? = null) : Route
    @Serializable data class GlobalSearch(val itemType: ItemType, val query: String = "") : Route
    @Serializable data class InAppWebView(val url: String, val title: String = "", val userAgent: String? = null) : Route
    @Serializable data object History : Route
    @Serializable data object UpdateErrors : Route
    @Serializable data class ExtensionLanguages(val itemType: ItemType) : Route
    @Serializable data class SourceFilters(val itemType: ItemType) : Route
    @Serializable data class ExtensionDetail(val sourceId: Long) : Route
    @Serializable data class CodeEditor(val sourceId: Long) : Route
    @Serializable data class CreateExtension(val itemType: ItemType) : Route
    @Serializable data class Recommendations(val mangaId: Long) : Route
    @Serializable data class SourceRelated(val mangaId: Long) : Route
    @Serializable data class WatchOrder(val mangaId: Long) : Route
    @Serializable data class Sequels(val mangaId: Long) : Route
    @Serializable data class Migrate(val mangaId: Long) : Route
    @Serializable data class MassMigration(val itemType: ItemType) : Route
    @Serializable data class MassMigrationPreview(val sourceId: Long) : Route
    @Serializable data class MassMigrationDestination(val sourceId: Long, val mangaIds: List<Long>) : Route
    @Serializable data class MassMigrationRunner(
        val sourceId: Long,
        val destinationId: Long? = null,
        val mangaIds: List<Long>,
        val destinationIds: List<Long> = emptyList(),
    ) : Route
    @Serializable data class LocalLibraryBrowse(val itemType: ItemType) : Route
    @Serializable data object LocalLibraryOverview : Route
    @Serializable data class Settings(val page: SettingsPage = SettingsPage.Index, val highlight: String? = null) : Route
}

/** `legacyRoute` is used ONLY by deep-link parsing (`yokan://<name>`). `icon` is set for pages listed on the settings index. */
@Serializable
enum class SettingsPage(val title: StringResource, val legacyRoute: String, val icon: ImageVector? = null) {
    Index(Res.string.settings, "settings"),
    General(Res.string.settings_page_general, "general", Icons.Filled.Settings),
    Appearance(Res.string.appearance, "appearance", Icons.Filled.ColorLens),
    Reader(Res.string.settings_page_reader, "readerMode", Icons.AutoMirrored.Filled.ChromeReaderMode),
    NovelReader(Res.string.settings_page_novel_reader, "novelReaderSettings", Icons.AutoMirrored.Filled.ChromeReaderMode),
    PlayerOverview(Res.string.settings_page_player_overview, "playerOverview", Icons.Filled.PlayCircle),
    Player(Res.string.settings_page_player, "playerMode"),
    PlayerDecoder(Res.string.settings_page_player_decoder, "playerDecoderScreen"),
    PlayerAudio(Res.string.settings_page_player_audio, "playerAudioScreen"),
    CustomButtons(Res.string.settings_page_custom_buttons, "customButtonScreen"),
    PlayerAdvanced(Res.string.settings_page_player_advanced, "playerAdvancedScreen"),
    Downloads(Res.string.settings_page_downloads, "downloads", Icons.Filled.Download),
    Tracking(Res.string.settings_page_tracking, "track", Icons.Filled.Sync),
    ManageTrackers(Res.string.settings_page_manage_trackers, "manageTrackers"),
    TrackingDetail(Res.string.settings_page_tracking_detail, "trackingDetail"),
    Sync(Res.string.settings_page_sync, "sync", Icons.Filled.CloudSync),
    Browse(Res.string.settings_page_browse, "browseS", Icons.Filled.Explore),
    Cookies(Res.string.settings_page_cookies, "cookies"),
    ExtensionServer(Res.string.android_proxy_server_mihon, "extensionServer"),
    MetadataServer(Res.string.settings_page_metadata_server, "metadataServer"),
    Repositories(Res.string.settings_page_repositories, "SourceRepositories"),
    MangaRepositories(Res.string.settings_page_manga_repositories, "mangaRepositories"),
    AnimeRepositories(Res.string.settings_page_anime_repositories, "animeRepositories"),
    NovelRepositories(Res.string.settings_page_novel_repositories, "novelRepositories"),
    Security(Res.string.security, "security", Icons.Filled.Security),
    About(Res.string.about, "about", Icons.Filled.Info),
    DataAndStorage(Res.string.settings_page_data_and_storage, "dataAndStorage"),
    CreateBackup(Res.string.settings_page_create_backup, "createBackup"),
    Library(Res.string.settings_page_library, "library", Icons.Filled.LocalLibrary),
    Categories(Res.string.categories, "categories"),
    Statistics(Res.string.statistics, "statistics"),
    Calendar(Res.string.calendar, "calendarScreen"),
    DownloadQueue(Res.string.download_queue, "downloadQueue"),
    CustomNavigation(Res.string.settings_page_custom_navigation, "customNavigationSettings"),
    Together(Res.string.settings_page_together, "together"),
    RestoreBackup(Res.string.settings_page_restore_backup, "restoreBackup"),
    Profiles(Res.string.profiles_title, "profiles", Icons.Filled.Settings),
    Developer(Res.string.settings_page_developer, "developer", Icons.Filled.Code),
    Discord(Res.string.settings_page_discord, "discord", Icons.Filled.Forum),
    Torrent(Res.string.settings_page_torrent, "torrentServer"),
}

/**
 * Navigating to a route whose destination equals the top's replaces the top instead of pushing
 * (the reader switching chapters, a settings page re-opened with a search highlight).
 */
internal fun Route.destination(): Any = if (this is Route.Settings) page else this::class
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/navigation/ViewModelFinalizer.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/navigation/ViewModelFinalizer.kt) · implementation · 38 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.

Declaration checklist (source line numbers):
```text
8: internal class ViewModelFinalizer(
22: fun retire() { work.cancel(); requested.complete(Unit) }
23: suspend fun closeAndJoin() = withContext(NonCancellable) {
29: private suspend fun releaseOnce() = withContext(dispatcher + NonCancellable) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/navigation/ViewModelFinalizer.kt) · SHA-256 `50ab52aa7d5dc425d2b146226c6f2e25e5de76e1dbc25543cadf971b3987e947`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.navigation

import kotlinx.coroutines.*
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock

/** Native/file cleanup follows all ViewModel work, including blocking cancellation finalizers. */
internal class ViewModelFinalizer(
    private val work: Job,
    private val dispatcher: CoroutineDispatcher = Dispatchers.Default,
    private val release: suspend () -> Unit,
) {
    private val owner = SupervisorJob()
    private val requested = CompletableDeferred<Unit>()
    private val mutex = Mutex()
    private var released = false
    private val cleanup = CoroutineScope(owner + dispatcher).async(start = CoroutineStart.UNDISPATCHED) {
        requested.await()
        work.join()
        releaseOnce()
    }
    fun retire() { work.cancel(); requested.complete(Unit) }
    suspend fun closeAndJoin() = withContext(NonCancellable) {
        retire()
        cleanup.join()
        releaseOnce()
        owner.join()
    }
    private suspend fun releaseOnce() = withContext(dispatcher + NonCancellable) {
        mutex.withLock {
            if (!released) {
                release()
                released = true
                owner.complete()
            }
        }
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/ReadingSessionClock.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/ReadingSessionClock.kt) · implementation · 45 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
12: internal class ReadingSessionClock(private val timeSource: TimeSource = TimeSource.Monotonic) {
18: fun pause(): Boolean {
26: fun resume() {
31: fun takeSeconds(): Int {
40: fun finishSeconds(): Int {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/ReadingSessionClock.kt) · SHA-256 `fc2b086fd3df2a89fc1ae6432bf13fafd64175bab6350dd831033d6e06f6a9b9`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens

import kotlin.time.Duration
import kotlin.time.TimeMark
import kotlin.time.TimeSource

/**
 * Foreground reading time of one reader session. It starts running; [pause] and [resume] exclude
 * background intervals, [takeSeconds] hands out the time counted so far, and [finishSeconds] closes
 * the session so later calls neither count nor resume.
 */
internal class ReadingSessionClock(private val timeSource: TimeSource = TimeSource.Monotonic) {
    private var startedAt: TimeMark? = timeSource.markNow()
    private var accumulated: Duration = Duration.ZERO
    private var closed = false

    /** Stops counting; returns false when the clock was already paused or closed. */
    fun pause(): Boolean {
        val started = startedAt ?: return false
        accumulated += started.elapsedNow()
        startedAt = null
        return true
    }

    /** Starts counting again unless the clock is running or closed. */
    fun resume() {
        if (!closed && startedAt == null) startedAt = timeSource.markNow()
    }

    /** Whole seconds counted since the last take; a running clock keeps running. */
    fun takeSeconds(): Int {
        val running = pause()
        val seconds = accumulated.inWholeSeconds.coerceAtMost(Int.MAX_VALUE.toLong()).toInt()
        accumulated = Duration.ZERO
        if (running) resume()
        return seconds
    }

    /** Takes the remaining seconds and closes the session; later calls return 0. */
    fun finishSeconds(): Int {
        pause()
        closed = true
        return takeSeconds()
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/onboarding/Onboarding.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/onboarding/Onboarding.kt) · implementation · 127 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
39: internal fun needsOnboarding(
45: fun OnboardingScreen(
108: private data class OnboardingStep(val icon: ImageVector, val title: String, val body: String)
111: private fun OnboardingStepCard(step: OnboardingStep, modifier: Modifier = Modifier) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/onboarding/Onboarding.kt) · SHA-256 `ae21f07124a6bee66a796ea68bcb7e804fc3ec903ddb48f25438b368641dd774`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.onboarding

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CloudDownload
import androidx.compose.material.icons.filled.CollectionsBookmark
import androidx.compose.material.icons.filled.Explore
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.unit.dp

/** Increase this when a future release needs to show onboarding again. */
const val RequiredOnboardingVersion = 1

internal fun needsOnboarding(
    completedVersion: Int,
    requiredVersion: Int = RequiredOnboardingVersion,
): Boolean = completedVersion < requiredVersion

@Composable
fun OnboardingScreen(
    onSkip: () -> Unit,
    onFinish: () -> Unit,
    modifier: Modifier = Modifier,
) {
    Surface(modifier = modifier.fillMaxSize(), color = MaterialTheme.colorScheme.surface) {
        BoxWithConstraints(Modifier.fillMaxSize()) {
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .verticalScroll(rememberScrollState())
                    .padding(horizontal = 24.dp, vertical = 32.dp)
                    .widthIn(max = 720.dp)
                    .align(Alignment.Center),
                verticalArrangement = Arrangement.Center,
            ) {
            Text(
                text = "Make Yokan yours",
                style = MaterialTheme.typography.headlineLarge,
                color = MaterialTheme.colorScheme.primary,
            )
            Spacer(Modifier.height(8.dp))
            Text(
                text = "A few optional pointers to get your media shelf ready.",
                style = MaterialTheme.typography.bodyLarge,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
            )
            Spacer(Modifier.height(24.dp))

            val steps = listOf(
                OnboardingStep(Icons.Default.CollectionsBookmark, "Set up your library", "Keep manga, anime, and novels together in one calm shelf."),
                OnboardingStep(Icons.Default.Explore, "Add your repositories", "Yokan includes no extensions or catalogs. Add your own repositories or restore them from a backup."),
                OnboardingStep(Icons.Default.CloudDownload, "Restore a backup", "Bring your library and settings back from a backup whenever you need to."),
            )
                if (this@BoxWithConstraints.maxWidth >= 600.dp) {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.spacedBy(12.dp),
                    ) {
                        steps.forEach { step ->
                            OnboardingStepCard(step, Modifier.weight(1f))
                        }
                    }
                } else {
                    Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
                        steps.forEach { step -> OnboardingStepCard(step, Modifier.fillMaxWidth()) }
                    }
                }
                Spacer(Modifier.height(32.dp))
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.End,
                    verticalAlignment = Alignment.CenterVertically,
                ) {
                    OutlinedButton(onClick = onSkip) { Text("Skip") }
                    Spacer(Modifier.width(12.dp))
                    Button(onClick = onFinish) { Text("Finish") }
                }
            }
        }
    }
}

private data class OnboardingStep(val icon: ImageVector, val title: String, val body: String)

@Composable
private fun OnboardingStepCard(step: OnboardingStep, modifier: Modifier = Modifier) {
    Card(
        modifier = modifier,
        shape = RoundedCornerShape(16.dp),
        colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer),
        elevation = CardDefaults.cardElevation(defaultElevation = 1.dp),
    ) {
        Column(
            modifier = Modifier.padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(10.dp),
        ) {
            Icon(step.icon, contentDescription = null, tint = MaterialTheme.colorScheme.primary)
            Text(step.title, style = MaterialTheme.typography.titleMedium)
            Text(step.body, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
        }
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/theme/FlexColorMath.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/theme/FlexColorMath.kt) · implementation · 321 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
12: internal fun Long.asColor(): Color = Color(this.toULong().toLong())
14: private fun isFlexLight(color: Color): Boolean {
19: private fun onColorFor(color: Color): Color =
22: private fun blendTowards(base: Color, accent: Color, level: Float): Color {
24: fun channel(baseValue: Float, accentValue: Float): Int {
36: private fun blendPercent(base: Color, accent: Color, amount: Double): Color {
39: fun channel(baseValue: Float, accentValue: Float): Int {
54: private fun shiftHslLightness(color: Color, delta: Double): Color {
55: fun normalizedChannel(value: Float): Double =
91: fun channel(value: Double): Int =
101: private fun brightenChannels(color: Color, amount: Int): Color {
103: fun channel(value: Float): Float =
108: private fun onContainerColor(color: Color): Color {
115: private fun inversePrimary(brightnessIsDark: Boolean, primary: Color, surface: Color): Color =
122: private fun fixedColor(color: Color): Color =
129: private fun fixedDimColor(color: Color): Color =
136: private fun onFixedColor(color: Color): Color =
143: private fun onFixedVariantColor(color: Color): Color =
152: private fun flexBlendFactor(blendLevel: Float, multiplier: Int = 1): Float {
156: internal fun buildLightScaffoldColor(palette: FlexPalette, blendLevel: Float): Color =
163: internal fun buildDarkScaffoldColor(
174: internal fun buildLightScheme(palette: FlexPalette, blendLevel: Float): ColorScheme {
247: internal fun buildDarkScheme(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/theme/FlexColorMath.kt) · SHA-256 `f1f25ac9f41993a77d9a552f93b7c2a48e35b0e86f2ac4c8fe1531a228d6e02f`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.theme

import androidx.compose.material3.ColorScheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.luminance
import kotlin.math.abs

// Port of FlexColorScheme's color math and light/dark scheme builders.

internal fun Long.asColor(): Color = Color(this.toULong().toLong())

private fun isFlexLight(color: Color): Boolean {
    val relativeLuminance = color.luminance()
    return (relativeLuminance + 0.05f) * (relativeLuminance + 0.05f) > 0.15f
}

private fun onColorFor(color: Color): Color =
    if (isFlexLight(color)) Color.Black else Color.White

private fun blendTowards(base: Color, accent: Color, level: Float): Color {
    val alpha = (level.coerceIn(0f, 1f) * 255f + 0.5f).toInt()
    fun channel(baseValue: Float, accentValue: Float): Int {
        val base8 = (baseValue * 255f + 0.5f).toInt()
        val accent8 = (accentValue * 255f + 0.5f).toInt()
        return ((accent8 * alpha + base8 * (255 - alpha) + 127) / 255).coerceIn(0, 255)
    }
    return Color(
        red = channel(base.red, accent.red),
        green = channel(base.green, accent.green),
        blue = channel(base.blue, accent.blue),
        alpha = channel(base.alpha, accent.alpha),
    )
}
private fun blendPercent(base: Color, accent: Color, amount: Double): Color {
    val fraction = amount.coerceIn(0.0, 1.0)
    val inverse = 1.0 - fraction
    fun channel(baseValue: Float, accentValue: Float): Int {
        val base8 = (baseValue * 255f + 0.5f).toInt()
        val accent8 = (accentValue * 255f + 0.5f).toInt()
        val blended = (accent8 / 255.0) * fraction + (base8 / 255.0) * inverse
        return (blended * 255.0 + 0.5).toInt().coerceIn(0, 255)
    }
    return Color(
        red = channel(base.red, accent.red),
        green = channel(base.green, accent.green),
        blue = channel(base.blue, accent.blue),
        alpha = channel(base.alpha, accent.alpha),
    )
}


private fun shiftHslLightness(color: Color, delta: Double): Color {
    fun normalizedChannel(value: Float): Double =
        (value * 255f + 0.5f).toInt() / 255.0

    val red = normalizedChannel(color.red)
    val green = normalizedChannel(color.green)
    val blue = normalizedChannel(color.blue)
    val maximum = maxOf(red, green, blue)
    val minimum = minOf(red, green, blue)
    val difference = maximum - minimum
    val hue = when {
        maximum == 0.0 || difference == 0.0 -> 0.0
        maximum == red -> {
            val sector = ((green - blue) / difference) % 6.0
            60.0 * if (sector < 0.0) sector + 6.0 else sector
        }
        maximum == green -> 60.0 * (((blue - red) / difference) + 2.0)
        else -> 60.0 * (((red - green) / difference) + 4.0)
    }
    val lightness = (maximum + minimum) / 2.0
    val saturation = if (minimum == maximum) {
        0.0
    } else {
        (difference / (1.0 - abs(2.0 * lightness - 1.0))).coerceIn(0.0, 1.0)
    }
    val shiftedLightness = (lightness + delta).coerceIn(0.0, 1.0)
    val chroma = (1.0 - abs(2.0 * shiftedLightness - 1.0)) * saturation
    val secondary = chroma * (1.0 - abs((hue / 60.0) % 2.0 - 1.0))
    val match = shiftedLightness - chroma / 2.0
    val (shiftedRed, shiftedGreen, shiftedBlue) = when {
        hue < 60.0 -> Triple(chroma, secondary, 0.0)
        hue < 120.0 -> Triple(secondary, chroma, 0.0)
        hue < 180.0 -> Triple(0.0, chroma, secondary)
        hue < 240.0 -> Triple(0.0, secondary, chroma)
        hue < 300.0 -> Triple(secondary, 0.0, chroma)
        else -> Triple(chroma, 0.0, secondary)
    }
    fun channel(value: Double): Int =
        ((value + match) * 255.0 + 0.5).toInt().coerceIn(0, 255)

    return Color(
        red = channel(shiftedRed),
        green = channel(shiftedGreen),
        blue = channel(shiftedBlue),
        alpha = (color.alpha * 255f + 0.5f).toInt(),
    )
}
private fun brightenChannels(color: Color, amount: Int): Color {
    val delta = (255f * amount.coerceIn(0, 100) / 100f + 0.5f).toInt()
    fun channel(value: Float): Float =
        ((value * 255f + 0.5f).toInt() + delta).coerceAtMost(255) / 255f
    return Color(channel(color.red), channel(color.green), channel(color.blue), color.alpha)
}

private fun onContainerColor(color: Color): Color {
    val light = isFlexLight(color)
    val contrast = if (light) Color.Black else Color.White
    val tinted = brightenChannels(color, if (light) 8 else 22)
    return blendTowards(contrast, tinted, flexBlendFactor(FlexOnBlendLevel, multiplier = 2))
}

private fun inversePrimary(brightnessIsDark: Boolean, primary: Color, surface: Color): Color =
    if (brightnessIsDark) {
        blendTowards(brightenChannels(primary, 5), surface, 153f / 255f)
    } else {
        shiftHslLightness(brightenChannels(primary, 40), 0.10)
    }

private fun fixedColor(color: Color): Color =
    if (isFlexLight(color)) {
        blendPercent(shiftHslLightness(blendPercent(color, Color.Black, 0.12), 0.12), Color.White, 0.45)
    } else {
        blendPercent(shiftHslLightness(blendPercent(color, Color.Black, 0.18), 0.15), Color.White, 0.75)
    }

private fun fixedDimColor(color: Color): Color =
    if (isFlexLight(color)) {
        blendPercent(shiftHslLightness(blendPercent(color, Color.Black, 0.12), 0.08), Color.White, 0.25)
    } else {
        blendPercent(shiftHslLightness(blendPercent(color, Color.Black, 0.30), 0.16), Color.White, 0.55)
    }

private fun onFixedColor(color: Color): Color =
    if (isFlexLight(color)) {
        blendPercent(shiftHslLightness(color, -0.60), Color.Black, 0.20)
    } else {
        blendPercent(shiftHslLightness(color, -0.19), Color.Black, 0.30)
    }

private fun onFixedVariantColor(color: Color): Color =
    if (isFlexLight(color)) {
        blendPercent(shiftHslLightness(color, -0.50), Color.Black, 0.10)
    } else {
        blendPercent(shiftHslLightness(color, -0.14), Color.Black, 0.30)
    }

private const val FlexOnBlendLevel = 0.10f

private fun flexBlendFactor(blendLevel: Float, multiplier: Int = 1): Float {
    val level = (blendLevel * 100f).toInt().coerceIn(0, 40)
    return (level * multiplier).coerceIn(0, 255) / 255f
}
internal fun buildLightScaffoldColor(palette: FlexPalette, blendLevel: Float): Color =
    blendTowards(
        Color.White,
        palette.primary.asColor(),
        flexBlendFactor(blendLevel, multiplier = 3),
    )

internal fun buildDarkScaffoldColor(
    palette: FlexPalette,
    blendLevel: Float,
    pureBlack: Boolean,
): Color = if (pureBlack) {
    Color.Black
} else {
    blendTowards(Color(0xFF010101), palette.primary.asColor(), flexBlendFactor(blendLevel))
}


internal fun buildLightScheme(palette: FlexPalette, blendLevel: Float): ColorScheme {
    val primary = palette.primary.asColor()
    val primaryContainer = palette.primaryContainer.asColor()
    val secondary = palette.secondary.asColor()
    val secondaryContainer = palette.secondaryContainer.asColor()
    val tertiary = palette.tertiary.asColor()
    val tertiaryContainer = palette.tertiaryContainer.asColor()
    val surfaceBlend = flexBlendFactor(blendLevel)
    val onBlend = flexBlendFactor(FlexOnBlendLevel)
    val surface = blendTowards(Color(0xFFFCFCFC), primary, surfaceBlend)
    val surfaceDim = blendTowards(Color(0xFFE0E0E0), primary, surfaceBlend)
    val surfaceBright = blendTowards(Color(0xFFFDFDFD), primary, surfaceBlend)
    val surfaceContainerLowest = blendTowards(Color.White, primary, surfaceBlend)
    val surfaceContainerLow = blendTowards(Color(0xFFF8F8F8), primary, surfaceBlend)
    val surfaceContainer = blendTowards(Color(0xFFF3F3F3), primary, surfaceBlend)
    val surfaceContainerHigh = blendTowards(Color(0xFFEDEDED), primary, surfaceBlend)
    val surfaceContainerHighest = blendTowards(Color(0xFFE7E7E7), primary, surfaceBlend)
    val inverseSurface = blendTowards(Color(0xFF2A2A2A), primary, surfaceBlend)
    val onSurfaceTint = shiftHslLightness(primary, 0.24)
    val onSurface = blendTowards(Color(0xFF111111), onSurfaceTint, onBlend)
    val onSurfaceVariant = blendTowards(Color(0xFF393939), onSurfaceTint, onBlend)
    return lightColorScheme(
        primary = primary,
        onPrimary = onColorFor(primary),
        primaryContainer = primaryContainer,
        onPrimaryContainer = onContainerColor(primaryContainer),
        secondary = secondary,
        onSecondary = onColorFor(secondary),
        secondaryContainer = secondaryContainer,
        onSecondaryContainer = onContainerColor(secondaryContainer),
        tertiary = tertiary,
        onTertiary = onColorFor(tertiary),
        tertiaryContainer = tertiaryContainer,
        onTertiaryContainer = onContainerColor(tertiaryContainer),
        background = surface,
        onBackground = onSurface,
        surface = surface,
        onSurface = onSurface,
        surfaceVariant = surfaceContainerHighest,
        onSurfaceVariant = onSurfaceVariant,
        surfaceTint = primary,
        inverseSurface = inverseSurface,
        inverseOnSurface = blendTowards(
            Color(0xFFF1F1F1),
            shiftHslLightness(primary, 0.24),
            onBlend,
        ),
        inversePrimary = inversePrimary(brightnessIsDark = false, primary = primary, surface = surface),
        outline = blendTowards(Color(0xFF919191), primary, onBlend),
        outlineVariant = blendTowards(Color(0xFFD1D1D1), primary, onBlend),
        surfaceBright = surfaceBright,
        surfaceDim = surfaceDim,
        surfaceContainerLowest = surfaceContainerLowest,
        surfaceContainerLow = surfaceContainerLow,
        surfaceContainer = surfaceContainer,
        surfaceContainerHigh = surfaceContainerHigh,
        surfaceContainerHighest = surfaceContainerHighest,
        primaryFixed = fixedColor(primary),
        primaryFixedDim = fixedDimColor(primary),
        onPrimaryFixed = onFixedColor(primary),
        onPrimaryFixedVariant = onFixedVariantColor(primary),
        secondaryFixed = fixedColor(secondary),
        secondaryFixedDim = fixedDimColor(secondary),
        onSecondaryFixed = onFixedColor(secondary),
        onSecondaryFixedVariant = onFixedVariantColor(secondary),
        tertiaryFixed = fixedColor(tertiary),
        tertiaryFixedDim = fixedDimColor(tertiary),
        onTertiaryFixed = onFixedColor(tertiary),
        onTertiaryFixedVariant = onFixedVariantColor(tertiary),
    )
}


internal fun buildDarkScheme(
    palette: FlexPalette,
    lightReference: FlexPalette,
    blendLevel: Float,
): ColorScheme {
    val primary = palette.primary.asColor()
    val primaryContainer = palette.primaryContainer.asColor()
    val secondary = palette.secondary.asColor()
    val secondaryContainer = palette.secondaryContainer.asColor()
    val tertiary = palette.tertiary.asColor()
    val tertiaryContainer = palette.tertiaryContainer.asColor()
    val surfaceBlend = flexBlendFactor(blendLevel)
    val onBlend = flexBlendFactor(FlexOnBlendLevel)
    val surface = blendTowards(Color(0xFF080808), primary, surfaceBlend)
    val surfaceDim = blendTowards(Color(0xFF060606), primary, surfaceBlend)
    val surfaceBright = blendTowards(Color(0xFF2C2C2C), primary, surfaceBlend)
    val surfaceContainerLowest = blendTowards(Color(0xFF010101), primary, surfaceBlend)
    val surfaceContainerLow = blendTowards(Color(0xFF0E0E0E), primary, surfaceBlend)
    val surfaceContainer = blendTowards(Color(0xFF151515), primary, surfaceBlend)
    val surfaceContainerHigh = blendTowards(Color(0xFF1D1D1D), primary, surfaceBlend)
    val surfaceContainerHighest = blendTowards(Color(0xFF282828), primary, surfaceBlend)
    val inverseSurface = blendTowards(Color(0xFFE8E8E8), primary, surfaceBlend)
    val onSurfaceTint = shiftHslLightness(primary, -0.10)
    val onSurface = blendTowards(Color(0xFFF1F1F1), onSurfaceTint, onBlend)
    val onSurfaceVariant = blendTowards(Color(0xFFCACACA), onSurfaceTint, onBlend)
    return darkColorScheme(
        primary = primary,
        onPrimary = onColorFor(primary),
        primaryContainer = primaryContainer,
        onPrimaryContainer = onContainerColor(primaryContainer),
        secondary = secondary,
        onSecondary = onColorFor(secondary),
        secondaryContainer = secondaryContainer,
        onSecondaryContainer = onContainerColor(secondaryContainer),
        tertiary = tertiary,
        onTertiary = onColorFor(tertiary),
        tertiaryContainer = tertiaryContainer,
        onTertiaryContainer = onContainerColor(tertiaryContainer),
        background = surface,
        onBackground = onSurface,
        surface = surface,
        onSurface = onSurface,
        surfaceVariant = surfaceContainerHighest,
        onSurfaceVariant = onSurfaceVariant,
        surfaceTint = primary,
        inverseSurface = inverseSurface,
        inverseOnSurface = blendTowards(
            Color(0xFF2A2A2A),
            shiftHslLightness(primary, -0.10),
            onBlend,
        ),
        inversePrimary = inversePrimary(brightnessIsDark = true, primary = primary, surface = surface),
        outline = blendTowards(Color(0xFF777777), primary, onBlend),
        outlineVariant = blendTowards(Color(0xFF414141), primary, onBlend),
        surfaceBright = surfaceBright,
        surfaceDim = surfaceDim,
        surfaceContainerLowest = surfaceContainerLowest,
        surfaceContainerLow = surfaceContainerLow,
        surfaceContainer = surfaceContainer,
        surfaceContainerHigh = surfaceContainerHigh,
        surfaceContainerHighest = surfaceContainerHighest,
        primaryFixed = fixedColor(lightReference.primary.asColor()),
        primaryFixedDim = fixedDimColor(lightReference.primary.asColor()),
        onPrimaryFixed = onFixedColor(lightReference.primary.asColor()),
        onPrimaryFixedVariant = onFixedVariantColor(lightReference.primary.asColor()),
        secondaryFixed = fixedColor(lightReference.secondary.asColor()),
        secondaryFixedDim = fixedDimColor(lightReference.secondary.asColor()),
        onSecondaryFixed = onFixedColor(lightReference.secondary.asColor()),
        onSecondaryFixedVariant = onFixedVariantColor(lightReference.secondary.asColor()),
        tertiaryFixed = fixedColor(lightReference.tertiary.asColor()),
        tertiaryFixedDim = fixedDimColor(lightReference.tertiary.asColor()),
        onTertiaryFixed = onFixedColor(lightReference.tertiary.asColor()),
        onTertiaryFixedVariant = onFixedVariantColor(lightReference.tertiary.asColor()),
    )
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/theme/FlexSchemes.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/theme/FlexSchemes.kt) · implementation · 349 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
3: data class FlexPalette(
12: data class FlexScheme(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/theme/FlexSchemes.kt) · SHA-256 `4222c25469d833029200adf77acc298b05d54baff519491674bb79377514a5a2`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.theme

data class FlexPalette(
    val primary: Long,
    val primaryContainer: Long,
    val secondary: Long,
    val secondaryContainer: Long,
    val tertiary: Long,
    val tertiaryContainer: Long,
)

data class FlexScheme(
    val displayName: String,
    val light: FlexPalette,
    val dark: FlexPalette,
)

val FlexSchemes: List<FlexScheme> = listOf(
    FlexScheme(  // 0: material
        displayName = "Material 2 default",
        light = FlexPalette(0xFF6200EE, 0xFFBB86FC, 0xFF03DAC6, 0xFFCEFAF8, 0xFF018786, 0xFFA4F1EF),
        dark = FlexPalette(0xFFBB86FC, 0xFF6200EE, 0xFF03DAC6, 0xFF005047, 0xFF03DAC6, 0xFF003E3E),
    ),
    FlexScheme(  // 1: materialHc
        displayName = "Material high contrast",
        light = FlexPalette(0xFF0000BA, 0xFFB6B6FF, 0xFF66FFF9, 0xFFC8F9F7, 0xFF018786, 0xFFB3F1F0),
        dark = FlexPalette(0xFFEFB7FF, 0xFF8A61DB, 0xFF66FFF9, 0xFF00504D, 0xFF66FFF9, 0xFF043232),
    ),
    FlexScheme(  // 2: blue
        displayName = "Blue delight",
        light = FlexPalette(0xFF1565C0, 0xFF90CAF9, 0xFF039BE5, 0xFFCBE6FF, 0xFF0277BD, 0xFFBEDCFF),
        dark = FlexPalette(0xFF90CAF9, 0xFF0D47A1, 0xFF81D4FA, 0xFF004B73, 0xFFE1F5FE, 0xFF1A567D),
    ),
    FlexScheme(  // 3: indigo
        displayName = "Indigo nights",
        light = FlexPalette(0xFF303F9F, 0xFFAEB9F4, 0xFF512DA8, 0xFFE9DDFF, 0xFF311B92, 0xFFD1C5FF),
        dark = FlexPalette(0xFF7986CB, 0xFF283593, 0xFF9575CD, 0xFF502CA7, 0xFF7E57C2, 0xFF4433A4),
    ),
    FlexScheme(  // 4: hippieBlue
        displayName = "Hippie blue",
        light = FlexPalette(0xFF4C9BBA, 0xFF9CEBEB, 0xFFFF4F58, 0xFFFFDAD7, 0xFFBF4A50, 0xFFFCBDBD),
        dark = FlexPalette(0xFF669DB3, 0xFF078282, 0xFFFC6E75, 0xFF92001A, 0xFFF75F67, 0xFF580810),
    ),
    FlexScheme(  // 5: aquaBlue
        displayName = "Aqua blue",
        light = FlexPalette(0xFF35A0CB, 0xFF71D3ED, 0xFF89D1C8, 0xFF91F4E8, 0xFF61D4D4, 0xFF8FF3F2),
        dark = FlexPalette(0xFF5DB3D5, 0xFF297EA0, 0xFFA1E9DF, 0xFF005049, 0xFFA0E5E5, 0xFF004F50),
    ),
    FlexScheme(  // 6: brandBlue
        displayName = "Brand blues",
        light = FlexPalette(0xFF3B5998, 0xFFA8CAE6, 0xFF55ACEE, 0xFFCBE5FF, 0xFF4285F4, 0xFFD6E2FF),
        dark = FlexPalette(0xFF8B9DC3, 0xFF3B5998, 0xFFA0D1F5, 0xFF004B75, 0xFF88B2F8, 0xFF004397),
    ),
    FlexScheme(  // 7: deepBlue
        displayName = "Deep blue sea",
        light = FlexPalette(0xFF223A5E, 0xFF97BAEA, 0xFF144955, 0xFFA9EDFF, 0xFF208399, 0xFFCCF3FF),
        dark = FlexPalette(0xFF748BAC, 0xFF1B2E4B, 0xFF539EAF, 0xFF004E5D, 0xFF219AB5, 0xFF0F5B6A),
    ),
    FlexScheme(  // 8: sakura
        displayName = "Pink sakura",
        light = FlexPalette(0xFFCE5B78, 0xFFE8B5CE, 0xFFFBAE9D, 0xFFFFDAD1, 0xFFF39682, 0xFFFFCFC3),
        dark = FlexPalette(0xFFEEC4D8, 0xFFCE5B78, 0xFFF5D6C6, 0xFFEBA689, 0xFFF7E0D4, 0xFFEEBDA8),
    ),
    FlexScheme(  // 9: mandyRed
        displayName = "Oh Mandy red",
        light = FlexPalette(0xFFCD5758, 0xFFE49797, 0xFF57C8D3, 0xFF90F2FC, 0xFF69B9CD, 0xFFA6EDFF),
        dark = FlexPalette(0xFFDA8585, 0xFFC05253, 0xFF68CDD7, 0xFF037481, 0xFF85C6D6, 0xFF21859E),
    ),
    FlexScheme(  // 10: red
        displayName = "Red tornado",
        light = FlexPalette(0xFFC62828, 0xFFFFCDD2, 0xFFAD1457, 0xFFF8BBD0, 0xFFC2185B, 0xFFFCE4EC),
        dark = FlexPalette(0xFFEF9A9A, 0xFFB71C1C, 0xFFF8BBD0, 0xFFAD1457, 0xFFFCE4EC, 0xFFC2185B),
    ),
    FlexScheme(  // 11: redWine
        displayName = "Red red wine",
        light = FlexPalette(0xFF9B1B30, 0xFFEDBAC2, 0xFFA70043, 0xFFFFD9DF, 0xFFA4121C, 0xFFFFDAD5),
        dark = FlexPalette(0xFFE4677C, 0xFF9B1B30, 0xFFC87A98, 0xFF910037, 0xFFBD545B, 0xFF930012),
    ),
    FlexScheme(  // 12: purpleBrown
        displayName = "Purple brown",
        light = FlexPalette(0xFF450A0F, 0xFFB9A6A8, 0xFF60234F, 0xFFE9CEDD, 0xFF4A0635, 0xFFE3B0C5),
        dark = FlexPalette(0xFFA98085, 0xFF682A2C, 0xFF975384, 0xFF6A2357, 0xFF5F4C5A, 0xFF501A3C),
    ),
    FlexScheme(  // 13: green
        displayName = "Green forest",
        light = FlexPalette(0xFF2E7D32, 0xFFA5D6A7, 0xFF00695C, 0xFF7DCEC4, 0xFF004D40, 0xFF59B1A1),
        dark = FlexPalette(0xFFA5D6A7, 0xFF1B5E20, 0xFF80CBC4, 0xFF00695C, 0xFF4DB6AC, 0xFF05514A),
    ),
    FlexScheme(  // 14: money
        displayName = "Green money",
        light = FlexPalette(0xFF264E36, 0xFF94BDA5, 0xFF797B3A, 0xFFBFC0A0, 0xFF555729, 0xFF9EA089),
        dark = FlexPalette(0xFF7AB893, 0xFF224430, 0xFFD5D6A8, 0xFF515402, 0xFFBBBE74, 0xFF404204),
    ),
    FlexScheme(  // 15: jungle
        displayName = "Green jungle",
        light = FlexPalette(0xFF004E15, 0xFF8FB99B, 0xFF007256, 0xFF83BCAD, 0xFF295300, 0xFF8FAA78),
        dark = FlexPalette(0xFF519E67, 0xFF27683A, 0xFF479985, 0xFF00513B, 0xFF73A497, 0xFF275000),
    ),
    FlexScheme(  // 16: greyLaw
        displayName = "Grey law",
        light = FlexPalette(0xFF37474F, 0xFFB0BEC5, 0xFF521D82, 0xFFF1DAFF, 0xFF2C314F, 0xFFDDE0FF),
        dark = FlexPalette(0xFF90A4AE, 0xFF37474F, 0xFF815AA3, 0xFF421F62, 0xFF373D5C, 0xFF1D2449),
    ),
    FlexScheme(  // 17: wasabi
        displayName = "Willow and wasabi",
        light = FlexPalette(0xFF738625, 0xFFD7DFB2, 0xFF893789, 0xFFFFD6F9, 0xFF5E3974, 0xFFF6D8FF),
        dark = FlexPalette(0xFFC3CB77, 0xFF586621, 0xFFDF9ADF, 0xFF742375, 0xFFA664CD, 0xFF61317E),
    ),
    FlexScheme(  // 18: gold
        displayName = "Gold sunset",
        light = FlexPalette(0xFFB86914, 0xFFF2C18C, 0xFFEF6C00, 0xFFFFBE93, 0xFFB36832, 0xFFCA9D7C),
        dark = FlexPalette(0xFFEDA85E, 0xFFB86914, 0xFFD28F60, 0xFFB5642C, 0xFFDDAB88, 0xFFBF7D4E),
    ),
    FlexScheme(  // 19: mango
        displayName = "Mango mojito",
        light = FlexPalette(0xFFC78D20, 0xFFDEB059, 0xFF8D9440, 0xFFBFC39B, 0xFF616247, 0xFFBCBCA8),
        dark = FlexPalette(0xFFDEB059, 0xFFC78D20, 0xFFAFB479, 0xFF82883D, 0xFF81816C, 0xFF5A5A35),
    ),
    FlexScheme(  // 20: amber
        displayName = "Amber blue",
        light = FlexPalette(0xFFE65100, 0xFFFFCC80, 0xFF2979FF, 0xFFE4EAFF, 0xFF2962FF, 0xFFCBD6FF),
        dark = FlexPalette(0xFFFFB300, 0xFFC87200, 0xFF82B1FF, 0xFF3770CF, 0xFF448AFF, 0xFF0B429C),
    ),
    FlexScheme(  // 21: vesuviusBurn
        displayName = "Vesuvius burned",
        light = FlexPalette(0xFFA6400F, 0xFFD1AA99, 0xFF185358, 0xFFA3C4C7, 0xFF144447, 0xFF7FC0C4),
        dark = FlexPalette(0xFFD17D53, 0xFF874E32, 0xFF5B8A8E, 0xFF0D494D, 0xFF3A7175, 0xFF023639),
    ),
    FlexScheme(  // 22: deepPurple
        displayName = "Deep purple",
        light = FlexPalette(0xFF4527A0, 0xFFD1C4E9, 0xFF0091EA, 0xFFCFE4FF, 0xFF00B0FF, 0xFF9FCBF1),
        dark = FlexPalette(0xFFB39DDB, 0xFF7E57C2, 0xFF80D8FF, 0xFF00497B, 0xFF40C4FF, 0xFF0179B6),
    ),
    FlexScheme(  // 23: ebonyClay
        displayName = "Ebony clay",
        light = FlexPalette(0xFF202541, 0xFF9BA7CF, 0xFF006B54, 0xFF8FC3AD, 0xFF004B3B, 0xFF82BCB5),
        dark = FlexPalette(0xFF4E597D, 0xFF202541, 0xFF4BA390, 0xFF0B5341, 0xFF3D8475, 0xFF063F36),
    ),
    FlexScheme(  // 24: barossa
        displayName = "Barossa",
        light = FlexPalette(0xFF4E0029, 0xFFBDA5B1, 0xFF00341A, 0xFF8DC1A8, 0xFF124C2F, 0xFFA4D9BF),
        dark = FlexPalette(0xFF94667E, 0xFF4E0029, 0xFF6B9882, 0xFF21614C, 0xFF599B7B, 0xFF1D5330),
    ),
    FlexScheme(  // 25: shark
        displayName = "Shark and orange",
        light = FlexPalette(0xFF1D2228, 0xFFB0B2C0, 0xFFFB8122, 0xFFFFB680, 0xFFEA9654, 0xFFE9CBAB),
        dark = FlexPalette(0xFF777A7E, 0xFF313C42, 0xFFFCB075, 0xFFD97B18, 0xFFEFB383, 0xFFA75F27),
    ),
    FlexScheme(  // 26: bigStone
        displayName = "Big stone tulip",
        light = FlexPalette(0xFF1A2C42, 0xFFB1C0DD, 0xFFE59A18, 0xFFE0BD80, 0xFFF0B03F, 0xFFE9CFA1),
        dark = FlexPalette(0xFF60748A, 0xFF1A2C42, 0xFFEBB251, 0xFFD48608, 0xFFF4CA7E, 0xFFC68E2D),
    ),
    FlexScheme(  // 27: damask
        displayName = "Damask and lunar",
        light = FlexPalette(0xFFC96646, 0xFFECC9BD, 0xFF373A36, 0xFF9EAB9F, 0xFF343E32, 0xFF94B291),
        dark = FlexPalette(0xFFDA9882, 0xFFC96646, 0xFF767D75, 0xFF3A5444, 0xFF839081, 0xFF34553E),
    ),
    FlexScheme(  // 28: bahamaBlue
        displayName = "Bahama and trinidad",
        light = FlexPalette(0xFF095D9E, 0xFFA6CCED, 0xFFDD520F, 0xFFFFDBCD, 0xFF7CC8F8, 0xFFC5E7FF),
        dark = FlexPalette(0xFF4585B5, 0xFF095D9E, 0xFFE57C4A, 0xFFDD520F, 0xFF9CD5F9, 0xFF3A7292),
    ),
    FlexScheme(  // 29: mallardGreen
        displayName = "Mallard and valencia",
        light = FlexPalette(0xFF2D4421, 0xFFA3B58A, 0xFFD34B4B, 0xFFFFDAD6, 0xFF959D33, 0xFFE2E989),
        dark = FlexPalette(0xFF808E79, 0xFF2D4421, 0xFFE18686, 0xFF501116, 0xFFC3C87A, 0xFF454B00),
    ),
    FlexScheme(  // 30: espresso
        displayName = "Espresso and crema",
        light = FlexPalette(0xFF452F2B, 0xFFC7BCAC, 0xFFE3B964, 0xFFFFDE9C, 0xFFF5E9C9, 0xFFFEE7AD),
        dark = FlexPalette(0xFF8D7F7D, 0xFF452F2B, 0xFFEED6A6, 0xFF8E774F, 0xFFF8ECD4, 0xFF705D49),
    ),
    FlexScheme(  // 31: outerSpace
        displayName = "Outer space stage",
        light = FlexPalette(0xFF1F3339, 0xFF9EC4D4, 0xFFD2600A, 0xFFFFDBC8, 0xFF93A0A9, 0xFFB5CDDB),
        dark = FlexPalette(0xFF486A71, 0xFF1F3339, 0xFFDB823F, 0xFFC05402, 0xFFAAB4BB, 0xFF285C71),
    ),
    FlexScheme(  // 32: blueWhale
        displayName = "Blue whale",
        light = FlexPalette(0xFF023047, 0xFF8EDBCE, 0xFFF86541, 0xFFFFAD91, 0xFFF07E24, 0xFFFFBF93),
        dark = FlexPalette(0xFF57859D, 0xFF2A9D8F, 0xFFFF6E48, 0xFFA3290F, 0xFFED7F29, 0xFF994600),
    ),
    FlexScheme(  // 33: sanJuanBlue
        displayName = "San Juan blue",
        light = FlexPalette(0xFF375778, 0xFFA4C4ED, 0xFFF98D94, 0xFFFFC4C6, 0xFFF2C4C7, 0xFFFFE3E5),
        dark = FlexPalette(0xFF5E7691, 0xFF375778, 0xFFEBA1A6, 0xFFAE424F, 0xFFF4CFD1, 0xFF96434F),
    ),
    FlexScheme(  // 34: rosewood
        displayName = "Rosewood",
        light = FlexPalette(0xFF5C000E, 0xFFF4CACE, 0xFF74540E, 0xFFFFDEA3, 0xFFAD8845, 0xFFFFE8C0),
        dark = FlexPalette(0xFF9C5A69, 0xFF5F111E, 0xFFEDCE9B, 0xFF805E23, 0xFFF5DFB9, 0xFF8E6E3C),
    ),
    FlexScheme(  // 35: blumineBlue
        displayName = "Blumine",
        light = FlexPalette(0xFF19647E, 0xFFA1CBCF, 0xFFFEB716, 0xFFFFDEA5, 0xFF0093C7, 0xFFC3E7FF),
        dark = FlexPalette(0xFF82BACE, 0xFF04666F, 0xFFFFD682, 0xFF9E7910, 0xFF243E4D, 0xFF426173),
    ),
    FlexScheme(  // 36: flutterDash
        displayName = "Flutter Dash",
        light = FlexPalette(0xFF4496E0, 0xFFB4E6FF, 0xFF202B6D, 0xFF99CCF9, 0xFF514239, 0xFFBAA99D),
        dark = FlexPalette(0xFFB4E6FF, 0xFF1E8FDB, 0xFF99CCF9, 0xFF202B6D, 0xFFBAA99D, 0xFF514239),
    ),
    FlexScheme(  // 37: materialBaseline
        displayName = "Material 3 purple",
        light = FlexPalette(0xFF6750A4, 0xFFEADDFF, 0xFF625B71, 0xFFE8DEF8, 0xFF7D5260, 0xFFFFD8E4),
        dark = FlexPalette(0xFFD0BCFF, 0xFF4F378B, 0xFFCCC2DC, 0xFF4A4458, 0xFFEFB8C8, 0xFF633B48),
    ),
    FlexScheme(  // 38: verdunHemlock
        displayName = "Verdun green",
        light = FlexPalette(0xFF616200, 0xFFE7E885, 0xFF606042, 0xFFE6E4C0, 0xFF3D6657, 0xFFBFECD9),
        dark = FlexPalette(0xFFCBCC58, 0xFF494A00, 0xFFC9C8A4, 0xFF48482D, 0xFFA4D0BE, 0xFF254E40),
    ),
    FlexScheme(  // 39: dellGenoa
        displayName = "Dell genoa green",
        light = FlexPalette(0xFF386A20, 0xFFB7F397, 0xFF55624C, 0xFFD9E7CB, 0xFF19686A, 0xFFA8EFF0),
        dark = FlexPalette(0xFF9CD67D, 0xFF205107, 0xFFBDCBB0, 0xFF3E4A36, 0xFFA0CFD0, 0xFF1E4E4F),
    ),
    FlexScheme(  // 40: redM3
        displayName = "Thunderbird red",
        light = FlexPalette(0xFFBB1614, 0xFFFFDAD5, 0xFF96482B, 0xFFFFDBCF, 0xFF286294, 0xFFD0E4FF),
        dark = FlexPalette(0xFFFFB4AA, 0xFF930006, 0xFFFFB59C, 0xFF783116, 0xFF9BCBFF, 0xFF004A79),
    ),
    FlexScheme(  // 41: pinkM3
        displayName = "Lipstick pink",
        light = FlexPalette(0xFFBC004B, 0xFFFFD9DE, 0xFF9B4050, 0xFFF8C7CB, 0xFF874978, 0xFFFFD7F0),
        dark = FlexPalette(0xFFFFB2BE, 0xFF900038, 0xFFFFD9DC, 0xFF5F1224, 0xFFFAAFE4, 0xFF6B325F),
    ),
    FlexScheme(  // 42: purpleM3
        displayName = "Eggplant purple",
        light = FlexPalette(0xFF9A25AE, 0xFFFFD6FE, 0xFF8728CF, 0xFFF2DAFF, 0xFF934932, 0xFFFFDBD0),
        dark = FlexPalette(0xFFF9ABFF, 0xFF7B008F, 0xFFE0B6FF, 0xFF6B00AF, 0xFFFFB59F, 0xFF76331D),
    ),
    FlexScheme(  // 43: indigoM3
        displayName = "Indigo San Marino",
        light = FlexPalette(0xFF4355B9, 0xFFDEE0FF, 0xFF3C64AE, 0xFFD8E2FF, 0xFF537577, 0xFFA9D4D6),
        dark = FlexPalette(0xFFBAC3FF, 0xFF293CA0, 0xFFAEC6FF, 0xFF14448D, 0xFFA9CDCF, 0xFF2A4C4E),
    ),
    FlexScheme(  // 44: blueM3
        displayName = "Endeavour blue",
        light = FlexPalette(0xFF0061A4, 0xFFD1E4FF, 0xFF006781, 0xFFB9EAFF, 0xFFA73A00, 0xFFFFDBCE),
        dark = FlexPalette(0xFF9ECAFF, 0xFF00497D, 0xFF86D1EE, 0xFF004D62, 0xFFFFB599, 0xFF802A00),
    ),
    FlexScheme(  // 45: cyanM3
        displayName = "Mosque cyan",
        light = FlexPalette(0xFF006876, 0xFFA1EFFF, 0xFF476365, 0xFFCAE8EA, 0xFF585C82, 0xFFDFE0FF),
        dark = FlexPalette(0xFF44D8F1, 0xFF004E59, 0xFFAECCCE, 0xFF304B4D, 0xFFC0C3EF, 0xFF404468),
    ),
    FlexScheme(  // 46: tealM3
        displayName = "Blue stone teal",
        light = FlexPalette(0xFF006A60, 0xFFBBEDE6, 0xFF4A635F, 0xFFCCE8E2, 0xFF48617A, 0xFFCFE5FF),
        dark = FlexPalette(0xFF53DBCA, 0xFF005048, 0xFFAECCCE, 0xFF304B4D, 0xFFC0C3EF, 0xFF404468),
    ),
    FlexScheme(  // 47: greenM3
        displayName = "Camarone green",
        light = FlexPalette(0xFF006E1C, 0xFFB6F2AF, 0xFF36855E, 0xFFC0FFD8, 0xFF00658C, 0xFFC5E7FF),
        dark = FlexPalette(0xFF7EDB7B, 0xFF005313, 0xFFA3F4C5, 0xFF003822, 0xFF87CFFB, 0xFF004C6A),
    ),
    FlexScheme(  // 48: limeM3
        displayName = "Verdun lime",
        light = FlexPalette(0xFF556500, 0xFFDAEB8F, 0xFF8C7519, 0xFFFFF0C7, 0xFF00687B, 0xFFAEECFF),
        dark = FlexPalette(0xFFBCD063, 0xFF3F4C00, 0xFFFFE17B, 0xFF3B2F00, 0xFF78D3EC, 0xFF224E43),
    ),
    FlexScheme(  // 49: yellowM3
        displayName = "Yukon gold yellow",
        light = FlexPalette(0xFF695F00, 0xFFF3E47F, 0xFF7C7B16, 0xFFF8F591, 0xFF375F97, 0xFFD5E3FF),
        dark = FlexPalette(0xFFD8C84F, 0xFF4F4700, 0xFFE9E784, 0xFF333200, 0xFFA7C8FF, 0xFF1B477E),
    ),
    FlexScheme(  // 50: orangeM3
        displayName = "Brown orange",
        light = FlexPalette(0xFF8B5000, 0xFFFFDCBE, 0xFFB6602F, 0xFFFFEDE6, 0xFF466827, 0xFFC6EF9F),
        dark = FlexPalette(0xFFFFB871, 0xFF6A3C00, 0xFFFFDBCB, 0xFF552000, 0xFFABD285, 0xFF2F4F11),
    ),
    FlexScheme(  // 51: deepOrangeM3
        displayName = "Rust deep orange",
        light = FlexPalette(0xFFBF360C, 0xFFFFDBD1, 0xFFBE593B, 0xFFFFEDE8, 0xFF466827, 0xFFC6EF9F),
        dark = FlexPalette(0xFFFFB5A0, 0xFF862200, 0xFFFFDBD1, 0xFF5F1600, 0xFFABD285, 0xFF2F4F11),
    ),
    FlexScheme(  // 52: blackWhite
        displayName = "Black and white",
        light = FlexPalette(0xFF000000, 0xFFE0E0E0, 0xFF000000, 0xFFE4E4E4, 0xFF000000, 0xFFC9C9C9),
        dark = FlexPalette(0xFFFFFFFF, 0xFF404040, 0xFFFFFFFF, 0xFF474747, 0xFFFFFFFF, 0xFF5E5E5E),
    ),
    FlexScheme(  // 53: greys
        displayName = "Grey",
        light = FlexPalette(0xFF202020, 0xFFD1D1D1, 0xFF777777, 0xFFC6C6C6, 0xFF454545, 0xFFB9B9B9),
        dark = FlexPalette(0xFFF0F0F0, 0xFF474747, 0xFFC6C6C6, 0xFF505050, 0xFFE2E2E2, 0xFF616161),
    ),
    FlexScheme(  // 54: sepia
        displayName = "Sepia",
        light = FlexPalette(0xFF413D32, 0xFFE3E2DE, 0xFF8F8880, 0xFFDEDCD6, 0xFF585147, 0xFFE3E2DE),
        dark = FlexPalette(0xFFF1E8D9, 0xFF363024, 0xFFE5E1D6, 0xFF958D82, 0xFFD5D3C4, 0xFF4C463C),
    ),
    FlexScheme(  // 55: shadBlue
        displayName = "Shadcn Blue",
        light = FlexPalette(0xFF2563EB, 0xFF2563EB, 0xFFF1F5F9, 0xFF2563EB, 0xFFF1F5F9, 0xFF2563EB),
        dark = FlexPalette(0xFF3B82F6, 0xFF3B82F6, 0xFF1E293B, 0xFF3B82F6, 0xFF1E293B, 0xFF3B82F6),
    ),
    FlexScheme(  // 56: shadGray
        displayName = "Shadcn Gray",
        light = FlexPalette(0xFF111827, 0xFF111827, 0xFFF3F4F6, 0xFF111827, 0xFFF3F4F6, 0xFF111827),
        dark = FlexPalette(0xFFF9FAFB, 0xFFF9FAFB, 0xFF1F2937, 0xFFF9FAFB, 0xFF1F2937, 0xFFF9FAFB),
    ),
    FlexScheme(  // 57: shadGreen
        displayName = "Shadcn Green",
        light = FlexPalette(0xFF16A34A, 0xFF16A34A, 0xFFF4F4F5, 0xFF16A34A, 0xFFF4F4F5, 0xFF16A34A),
        dark = FlexPalette(0xFF22C55E, 0xFF22C55E, 0xFF27272A, 0xFF22C55E, 0xFF292524, 0xFF22C55E),
    ),
    FlexScheme(  // 58: shadNeutral
        displayName = "Shadcn Neutral",
        light = FlexPalette(0xFF171717, 0xFF171717, 0xFFF5F5F5, 0xFF171717, 0xFFF5F5F5, 0xFF171717),
        dark = FlexPalette(0xFFFAFAFA, 0xFFFAFAFA, 0xFF262626, 0xFFFAFAFA, 0xFF262626, 0xFFFAFAFA),
    ),
    FlexScheme(  // 59: shadOrange
        displayName = "Shadcn Orange",
        light = FlexPalette(0xFFF97316, 0xFFF97316, 0xFFF5F5F4, 0xFFF97316, 0xFFF5F5F4, 0xFFF97316),
        dark = FlexPalette(0xFFEA580C, 0xFFEA580C, 0xFF292524, 0xFFEA580C, 0xFF292524, 0xFFEA580C),
    ),
    FlexScheme(  // 60: shadRed
        displayName = "Shadcn Red",
        light = FlexPalette(0xFFDC2626, 0xFFDC2626, 0xFFF5F5F5, 0xFFDC2626, 0xFFF5F5F5, 0xFFDC2626),
        dark = FlexPalette(0xFFDC2626, 0xFFDC2626, 0xFF262626, 0xFFDC2626, 0xFF262626, 0xFFDC2626),
    ),
    FlexScheme(  // 61: shadRose
        displayName = "Shadcn Rose",
        light = FlexPalette(0xFFE11D48, 0xFFE11D48, 0xFFF4F4F5, 0xFFE11D48, 0xFFF4F4F5, 0xFFE11D48),
        dark = FlexPalette(0xFFE11D48, 0xFFE11D48, 0xFF27272A, 0xFFE11D48, 0xFF292524, 0xFFE11D48),
    ),
    FlexScheme(  // 62: shadSlate
        displayName = "Shadcn Slate",
        light = FlexPalette(0xFF0F172A, 0xFF0F172A, 0xFFF1F5F9, 0xFF0F172A, 0xFFF1F5F9, 0xFF0F172A),
        dark = FlexPalette(0xFFF8FAFC, 0xFFF8FAFC, 0xFF1E293B, 0xFFF8FAFC, 0xFF1E293B, 0xFFF8FAFC),
    ),
    FlexScheme(  // 63: shadStone
        displayName = "Shadcn Stone",
        light = FlexPalette(0xFF1C1917, 0xFF1C1917, 0xFFF5F5F4, 0xFF1C1917, 0xFFF5F5F4, 0xFF1C1917),
        dark = FlexPalette(0xFFFAFAF9, 0xFFFAFAF9, 0xFF292524, 0xFFFAFAF9, 0xFF292524, 0xFFFAFAF9),
    ),
    FlexScheme(  // 64: shadViolet
        displayName = "Shadcn Violet",
        light = FlexPalette(0xFF7C3AED, 0xFF7C3AED, 0xFFF3F4F6, 0xFF7C3AED, 0xFFF3F4F6, 0xFF7C3AED),
        dark = FlexPalette(0xFF6D28D9, 0xFF6D28D9, 0xFF1F2937, 0xFF6D28D9, 0xFF1F2937, 0xFF6D28D9),
    ),
    FlexScheme(  // 65: shadYellow
        displayName = "Shadcn Yellow",
        light = FlexPalette(0xFFFACC15, 0xFFFACC15, 0xFFF5F5F4, 0xFFFACC15, 0xFFF5F5F4, 0xFFFACC15),
        dark = FlexPalette(0xFFFACC15, 0xFFFACC15, 0xFF292524, 0xFFFACC15, 0xFF292524, 0xFFFACC15),
    ),
)
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/theme/MaterialYou.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/theme/MaterialYou.kt) · implementation · 16 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
13: expect fun rememberMaterialYouScheme(isDark: Boolean): ColorScheme?
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/theme/MaterialYou.kt) · SHA-256 `13b83927e613f9202498c4516fd97904e402affe9d297343cd3d0953fe203834`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.theme

import androidx.compose.material3.ColorScheme
import androidx.compose.runtime.Composable

/**
 * Returns the OS-provided "Material You" color scheme when the platform exposes one
 * (Android 12+ via `dynamicLightColorScheme`/`dynamicDarkColorScheme`), otherwise null.
 *
 * Callers fall back to a MaterialKolor scheme derived from the user's seed or image.
 */
@Composable
expect fun rememberMaterialYouScheme(isDark: Boolean): ColorScheme?

/** True on platforms where [rememberMaterialYouScheme] can actually return a scheme. */
expect val materialYouAvailable: Boolean
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/theme/SystemBarTheme.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/theme/SystemBarTheme.kt) · implementation · 9 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
9: expect fun applySystemBarTheme(isDark: Boolean)
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/theme/SystemBarTheme.kt) · SHA-256 `34659137c48d8613e7e6a80fcd1bf7f5d90c802ad77a1552f395f7241353784d`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.theme

/**
 * Sync system bar icon contrast with the app's resolved dark mode. The app
 * theme can diverge from the system one (followSystemTheme = false), so the
 * default edge-to-edge contrast heuristic is not enough on Android. No-op on
 * platforms without status-bar icon appearance control.
 */
expect fun applySystemBarTheme(isDark: Boolean)
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/theme/Theme.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/theme/Theme.kt) · implementation · 363 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
49: private fun buildYokanTypography(family: FontFamily): Typography {
87: fun resolveAppFontFamily(name: String?): FontFamily {
106: fun resolveNovelFontFamily(name: String?, appFontFamily: String?): FontFamily = when (name?.lowercase()) {
117: private fun rememberNovelFontFamily(
160: fun YokanScaffold(
187: private fun yokanDividerColor(): Color =
195: fun YokanHorizontalDivider(
208: private data class ResolvedThemeColors(
214: private fun rememberGoogleFontFamily(
221: private fun TextStyle.withFamily(family: FontFamily): TextStyle =
224: fun resolveDarkMode(followSystem: Boolean, themeIsDark: Boolean, systemDark: Boolean): Boolean =
228: fun YokanTheme(
286: private fun resolveThemeColors(
351: private fun resolvePaletteStyle(name: String, materialExpressive: Boolean): PaletteStyle {
363: fun rememberSystemDark(): Boolean = isSystemInDarkTheme()
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/theme/Theme.kt) · SHA-256 `3eddc2c0ebefc2af19e0960bb85eb2bffface3acf6442b788bba343498954c66`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.theme

import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.ColorScheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Shapes
import androidx.compose.material3.Typography
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.luminance
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.materialkolor.PaletteStyle
import com.materialkolor.dynamiccolor.ColorSpec
import com.materialkolor.ktx.themeColor
import com.materialkolor.rememberDynamicColorScheme
import eu.friedcutlet.yokan.ui.image.decodeImageBitmap
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.atkinson_hyperlegible_regular
import yokan.composeapp.generated.resources.inter_regular
import yokan.composeapp.generated.resources.jetbrains_mono_regular
import yokan.composeapp.generated.resources.lexend_variable
import yokan.composeapp.generated.resources.nunito_regular
import yokan.composeapp.generated.resources.open_sans_regular
import yokan.composeapp.generated.resources.opendyslexic_bold
import yokan.composeapp.generated.resources.opendyslexic_regular
import yokan.composeapp.generated.resources.poppins_regular
import yokan.composeapp.generated.resources.roboto_regular
import yokan.composeapp.generated.resources.roboto_slab_regular

// Material 3 defaults. FlexColorScheme only overrides component subthemes
// (24dp inputs/chips); it does not globally tighten card and dialog shapes.
private val YokanShapes = Shapes(
    extraSmall = RoundedCornerShape(4.dp),
    small = RoundedCornerShape(8.dp),
    medium = RoundedCornerShape(12.dp),
    large = RoundedCornerShape(16.dp),
    extraLarge = RoundedCornerShape(28.dp),
)

private fun buildYokanTypography(family: FontFamily): Typography {
    val base = Typography()
    return base.copy(
        displayLarge = base.displayLarge.withFamily(family),
        displayMedium = base.displayMedium.withFamily(family),
        displaySmall = base.displaySmall.withFamily(family),
        headlineLarge = base.headlineLarge.withFamily(family),
        headlineMedium = base.headlineMedium.withFamily(family),
        headlineSmall = base.headlineSmall.withFamily(family),
        titleLarge = base.titleLarge.withFamily(family),
        titleMedium = base.titleMedium.withFamily(family),
        titleSmall = base.titleSmall.withFamily(family),
        bodyLarge = base.bodyLarge.withFamily(family),
        bodyMedium = base.bodyMedium.withFamily(family),
        bodySmall = base.bodySmall.withFamily(family),
        labelLarge = base.labelLarge.withFamily(family),
        labelMedium = base.labelMedium.withFamily(family),
        labelSmall = base.labelSmall.withFamily(family),
    )
}

/** Named font choices exposed in the Appearance picker, ordered for the dropdown. */
val AppFontFamilyChoices: List<String> = listOf(
    "Default", "Sans", "Serif", "Monospace",
    "Inter", "Roboto", "Roboto Slab", "Open Sans", "Nunito", "Poppins", "JetBrains Mono",
)

/**
 * Resolve the persisted `appFontFamily` setting to a [FontFamily].
 *
 * - The four system names ("Default", "Sans", "Serif", "Monospace") use the
 *   platform's stock families so they cost nothing to render.
 * - The named Google Fonts load from bundled regular-weight TTFs in
 *   `composeResources/font/`. Compose Multiplatform synthesises the bold and
 *   italic variants from the actual glyph metrics, which is fine for an app-
 *   wide UI font (we don't need a paragraph-level type system).
 */
@Composable
fun resolveAppFontFamily(name: String?): FontFamily {
    val n = name?.lowercase().orEmpty()
    return when (n) {
        "serif" -> FontFamily.Serif
        "sans" -> FontFamily.SansSerif
        "monospace" -> FontFamily.Monospace
        "inter" -> rememberGoogleFontFamily(Res.font.inter_regular)
        "roboto" -> rememberGoogleFontFamily(Res.font.roboto_regular)
        "roboto slab" -> rememberGoogleFontFamily(Res.font.roboto_slab_regular)
        "open sans" -> rememberGoogleFontFamily(Res.font.open_sans_regular)
        "nunito" -> rememberGoogleFontFamily(Res.font.nunito_regular)
        "poppins" -> rememberGoogleFontFamily(Res.font.poppins_regular)
        "jetbrains mono" -> rememberGoogleFontFamily(Res.font.jetbrains_mono_regular)
        else -> FontFamily.Default
    }
}

/** Resolve fonts offered specifically by the novel reader; Default follows the app choice. */
@Composable
fun resolveNovelFontFamily(name: String?, appFontFamily: String?): FontFamily = when (name?.lowercase()) {
    "opendyslexic" -> rememberNovelFontFamily(
        Res.font.opendyslexic_regular,
        Res.font.opendyslexic_bold,
    )
    "lexend" -> rememberNovelFontFamily(Res.font.lexend_variable)
    "atkinson" -> rememberNovelFontFamily(Res.font.atkinson_hyperlegible_regular)
    else -> resolveAppFontFamily(appFontFamily)
}

@Composable
private fun rememberNovelFontFamily(
    regular: org.jetbrains.compose.resources.FontResource,
    bold: org.jetbrains.compose.resources.FontResource? = null,
): FontFamily {
    val regularFont = org.jetbrains.compose.resources.Font(regular, FontWeight.Normal)
    val boldFont = bold?.let { org.jetbrains.compose.resources.Font(it, FontWeight.Bold) }
    return remember(regular, bold) {
        if (boldFont == null) FontFamily(regularFont) else FontFamily(regularFont, boldFont)
    }
}
val LocalYokanScaffoldColor = androidx.compose.runtime.staticCompositionLocalOf {
    Color.Unspecified
}

/** True in e-ink display mode: screens drop motion that would ghost on an e-paper panel. */
val LocalEinkMode = androidx.compose.runtime.staticCompositionLocalOf { false }

private val EinkGray = Color(0xFFE0E0E0)

/** Pure black on white with gray containers: tonal tints and subtle contrasts vanish on e-paper. */
private val EinkColorScheme = androidx.compose.material3.lightColorScheme(
    primary = Color.Black, onPrimary = Color.White,
    primaryContainer = EinkGray, onPrimaryContainer = Color.Black,
    inversePrimary = Color.White,
    secondary = Color.Black, onSecondary = Color.White,
    secondaryContainer = EinkGray, onSecondaryContainer = Color.Black,
    tertiary = Color.Black, onTertiary = Color.White,
    tertiaryContainer = EinkGray, onTertiaryContainer = Color.Black,
    background = Color.White, onBackground = Color.Black,
    surface = Color.White, onSurface = Color.Black,
    surfaceVariant = EinkGray, onSurfaceVariant = Color.Black,
    surfaceTint = Color.White,
    inverseSurface = Color.Black, inverseOnSurface = Color.White,
    error = Color.Black, onError = Color.White,
    errorContainer = EinkGray, onErrorContainer = Color.Black,
    outline = Color.Black, outlineVariant = Color(0xFF808080),
    scrim = Color.Black,
    surfaceBright = Color.White, surfaceDim = EinkGray,
    surfaceContainerLowest = Color.White, surfaceContainerLow = Color.White,
    surfaceContainer = Color(0xFFF0F0F0), surfaceContainerHigh = EinkGray, surfaceContainerHighest = EinkGray,
)

@Composable
fun YokanScaffold(
    modifier: androidx.compose.ui.Modifier = androidx.compose.ui.Modifier,
    topBar: @Composable () -> Unit = {},
    bottomBar: @Composable () -> Unit = {},
    snackbarHost: @Composable () -> Unit = {},
    floatingActionButton: @Composable () -> Unit = {},
    floatingActionButtonPosition: androidx.compose.material3.FabPosition =
        androidx.compose.material3.FabPosition.End,
    contentColor: Color = MaterialTheme.colorScheme.onSurface,
    contentWindowInsets: androidx.compose.foundation.layout.WindowInsets =
        androidx.compose.material3.ScaffoldDefaults.contentWindowInsets,
    content: @Composable (androidx.compose.foundation.layout.PaddingValues) -> Unit,
) {
    androidx.compose.material3.Scaffold(
        modifier = modifier,
        topBar = topBar,
        bottomBar = bottomBar,
        snackbarHost = snackbarHost,
        floatingActionButton = floatingActionButton,
        floatingActionButtonPosition = floatingActionButtonPosition,
        containerColor = LocalYokanScaffoldColor.current,
        contentColor = contentColor,
        contentWindowInsets = contentWindowInsets,
        content = content,
    )
}
@Composable
private fun yokanDividerColor(): Color =
    if (MaterialTheme.colorScheme.surface.luminance() < 0.5f) {
        Color.White.copy(alpha = 31f / 255f)
    } else {
        Color.Black.copy(alpha = 31f / 255f)
    }

@Composable
fun YokanHorizontalDivider(
    modifier: androidx.compose.ui.Modifier = androidx.compose.ui.Modifier,
    thickness: androidx.compose.ui.unit.Dp = 1.dp,
    color: Color = yokanDividerColor(),
) {
    androidx.compose.material3.HorizontalDivider(
        modifier = modifier,
        thickness = thickness,
        color = color,
    )
}


private data class ResolvedThemeColors(
    val scheme: ColorScheme,
    val scaffold: Color,
)

@Composable
private fun rememberGoogleFontFamily(
    resource: org.jetbrains.compose.resources.FontResource,
): FontFamily {
    val font = org.jetbrains.compose.resources.Font(resource, FontWeight.Normal)
    return remember(resource) { FontFamily(font) }
}

private fun TextStyle.withFamily(family: FontFamily): TextStyle =
    copy(fontFamily = family)

fun resolveDarkMode(followSystem: Boolean, themeIsDark: Boolean, systemDark: Boolean): Boolean =
    if (followSystem) systemDark else themeIsDark

@Composable
fun YokanTheme(
    darkTheme: Boolean,
    schemeIndex: Int = 2,
    pureBlackDark: Boolean = false,
    blendLevel: Float = 0.1f,
    uiScale: Float = 1.0f,
    seedColorArgb: Int? = null,
    seedImagePath: String? = null,
    materialYou: Boolean = false,
    materialExpressive: Boolean = false,
    paletteStyleName: String = "TonalSpot",
    fontFamily: FontFamily = FontFamily.Default,
    eink: Boolean = false,
    content: @Composable () -> Unit,
) {
    val themed = resolveThemeColors(
        darkTheme = darkTheme,
        schemeIndex = schemeIndex,
        pureBlackDark = pureBlackDark,
        blendLevel = blendLevel,
        seedColorArgb = seedColorArgb,
        seedImagePath = seedImagePath,
        materialYou = materialYou,
        materialExpressive = materialExpressive,
        paletteStyleName = paletteStyleName,
    )
    val resolvedColors = if (eink) ResolvedThemeColors(EinkColorScheme, Color.White) else themed
    val clampedScale = uiScale.coerceIn(0.75f, 2.0f)
    val baseDensity = androidx.compose.ui.platform.LocalDensity.current
    val scaledDensity = androidx.compose.ui.unit.Density(
        density = baseDensity.density * clampedScale,
        fontScale = baseDensity.fontScale,
    )
    androidx.compose.runtime.CompositionLocalProvider(
        androidx.compose.ui.platform.LocalDensity provides scaledDensity,
        LocalYokanScaffoldColor provides resolvedColors.scaffold,
        LocalEinkMode provides eink,
        // Ripples animate for hundreds of milliseconds and ghost on e-paper.
        androidx.compose.material3.LocalRippleConfiguration provides
            if (eink) null else androidx.compose.material3.LocalRippleConfiguration.current,
    ) {
        // `MaterialExpressiveTheme` is not yet stable in Compose Multiplatform's
        // material3 surface (1.4 marks it `internal`). To still honour the
        // user's Expressive toggle we feed `PaletteStyle.Expressive` +
        // `ColorSpec.SPEC_2025` into the color scheme (see `resolvePaletteStyle`),
        // which is the runtime-visible half of the spec. Motion/typography
        // upgrades land once material3 exposes the expressive APIs publicly.
        val typography = remember(fontFamily) { buildYokanTypography(fontFamily) }
        MaterialTheme(
            colorScheme = resolvedColors.scheme,
            typography = typography,
            shapes = YokanShapes,
            content = content,
        )
    }
}

@Composable
private fun resolveThemeColors(
    darkTheme: Boolean,
    schemeIndex: Int,
    pureBlackDark: Boolean,
    blendLevel: Float,
    seedColorArgb: Int?,
    seedImagePath: String?,
    materialYou: Boolean,
    materialExpressive: Boolean,
    paletteStyleName: String,
): ResolvedThemeColors {
    // Material You: defer to the OS palette when the user opted in and the
    // platform actually exposes one (Android 12+).
    if (materialYou) {
        rememberMaterialYouScheme(darkTheme)?.let {
            return ResolvedThemeColors(scheme = it, scaffold = it.background)
        }
    }

    val legacyFallback = remember(schemeIndex, darkTheme, pureBlackDark, blendLevel) {
        val scheme = FlexSchemes.getOrElse(schemeIndex) { FlexSchemes[2] }
        if (darkTheme) {
            ResolvedThemeColors(
                scheme = buildDarkScheme(scheme.dark, scheme.light, blendLevel),
                scaffold = buildDarkScaffoldColor(scheme.dark, blendLevel, pureBlackDark),
            )
        } else {
            ResolvedThemeColors(
                scheme = buildLightScheme(scheme.light, blendLevel),
                scaffold = buildLightScaffoldColor(scheme.light, blendLevel),
            )
        }
    }

    // Decoding and quantizing the seed image is file I/O + CPU work: keep it off composition.
    val fallbackPrimary = legacyFallback.scheme.primary
    val imageSeed: Color? by produceState<Color?>(null, seedImagePath, fallbackPrimary) {
        value = seedImagePath?.takeIf { it.isNotBlank() }?.let { path ->
            withContext(Dispatchers.Default) { decodeImageBitmap(path)?.themeColor(fallback = fallbackPrimary) }
        }
    }
    // Mangayomi's normal path is FlexThemeData built from the selected
    // FlexSchemeColor. Do not reinterpret that palette as a Material You seed:
    // doing so changes every container, badge, tab, and navigation color.
    if (seedColorArgb == null && imageSeed == null && !materialExpressive) {
        return legacyFallback
    }

    // Precedence: image > explicit seed > legacy palette primary.
    val seed = imageSeed
        ?: seedColorArgb?.let { Color(it.toLong() and 0xFFFFFFFFL) }
        ?: legacyFallback.scheme.primary
    val style = resolvePaletteStyle(paletteStyleName, materialExpressive)
    val dynamicScheme = rememberDynamicColorScheme(
        seedColor = seed,
        isDark = darkTheme,
        isAmoled = pureBlackDark && darkTheme,
        style = style,
        // SPEC_2025 is required for Material Expressive — when the toggle is off
        // we still opt into it so users get the latest tonal mapping.
        specVersion = ColorSpec.SpecVersion.SPEC_2025,
    )
    return ResolvedThemeColors(scheme = dynamicScheme, scaffold = dynamicScheme.background)
}

private fun resolvePaletteStyle(name: String, materialExpressive: Boolean): PaletteStyle {
    // Material Expressive overrides whatever the user picked because the spec
    // pairs Expressive motion with the Expressive palette.
    if (materialExpressive) return PaletteStyle.Expressive
    return PaletteStyle.entries.firstOrNull { it.name.equals(name, ignoreCase = true) } ?: PaletteStyle.TonalSpot
}

/** Names of MaterialKolor palette styles exposed in the settings dropdown. */
val PaletteStyleChoices: List<String>
    get() = PaletteStyle.entries.map { it.name }

@Composable
fun rememberSystemDark(): Boolean = isSystemInDarkTheme()
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/theme/YokanThemeFromSettings.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/theme/YokanThemeFromSettings.kt) · implementation · 37 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
11: fun YokanThemeFromSettings(db: DbSettings, themeIsDark: Boolean, content: @Composable () -> Unit) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/theme/YokanThemeFromSettings.kt) · SHA-256 `70acb6d7c9f0455ce3c68086259ceeaf058b373cffe32ea79d2766f244cc831f`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.theme

import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.services.system.isTvDevice
import eu.friedcutlet.yokan.ui.tv.resolveTvUiScale

/** [YokanTheme] as configured in [db]; [themeIsDark] is the user's dark-mode choice when not following the system. */
@Composable
fun YokanThemeFromSettings(db: DbSettings, themeIsDark: Boolean, content: @Composable () -> Unit) {
    val systemDark = rememberSystemDark()
    // E-ink display mode is always black on white.
    val appDark = !db.einkMode && resolveDarkMode(
        followSystem = db.followSystemTheme,
        themeIsDark = themeIsDark,
        systemDark = systemDark,
    )
    // Android: system bar icon contrast must follow the in-app theme, which
    // can diverge from the system dark mode (followSystemTheme = false).
    LaunchedEffect(appDark) { applySystemBarTheme(appDark) }
    YokanTheme(
        darkTheme = appDark,
        schemeIndex = db.flexSchemeColorIndex,
        pureBlackDark = db.pureBlackDarkMode,
        blendLevel = (db.flexColorSchemeBlendLevel / 100.0).toFloat().coerceIn(0f, 1f),
        uiScale = resolveTvUiScale(isTvDevice(), db),
        seedColorArgb = db.themeSeedColor,
        seedImagePath = db.themeSeedImagePath,
        materialYou = db.materialYou,
        materialExpressive = db.materialExpressive,
        paletteStyleName = db.themePaletteStyle,
        fontFamily = resolveAppFontFamily(db.appFontFamily),
        eink = db.einkMode,
        content = content,
    )
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/tv/TvFocusEngine.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/tv/TvFocusEngine.kt) · implementation · 85 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
14: fun resolveTvUiScale(
31: fun resolveTvAnimeOnly(
39: fun shouldHideNavSectionForTv(
58: fun handleTvDpadNavigation(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/tv/TvFocusEngine.kt) · SHA-256 `527d849581e76c4bef5b1592957ae2077c83e98f4e5ed8e2c69254be22392e41`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.tv

import androidx.compose.ui.input.key.Key
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.ui.navigation.NavSection

/**
 * Resolves the effective UI scale for rendering.
 *
 * On Android TV devices, [DbSettings.tvUiScale] is used (defaulting to 1.0) and clamped
 * to 0.85f..1.25f (5% increments in settings).
 * On non-TV devices, [DbSettings.autoUiScale] uses 1.0f or falls back to [DbSettings.uiScale].
 */
fun resolveTvUiScale(
    isTv: Boolean,
    settings: DbSettings,
): Float = if (isTv) {
    (settings.tvUiScale ?: 1.0).toFloat().coerceIn(0.85f, 1.25f)
} else if (settings.autoUiScale) {
    1f
} else {
    settings.uiScale.toFloat()
}

/**
 * Whether the anime-only layout gate is active.
 *
 * Defaults to true on TV devices unless explicitly overridden by [animeOnlyTvMode].
 * Off everywhere else.
 */
fun resolveTvAnimeOnly(
    isTv: Boolean,
    animeOnlyTvMode: Boolean?,
): Boolean = isTv && (animeOnlyTvMode ?: true)

/**
 * Checks if a [NavSection] should be hidden in TV anime-only mode.
 */
fun shouldHideNavSectionForTv(
    section: NavSection,
    isTv: Boolean,
    animeOnlyTvMode: Boolean?,
): Boolean {
    if (!resolveTvAnimeOnly(isTv, animeOnlyTvMode)) return false
    return section == NavSection.MangaLibrary || section == NavSection.NovelLibrary
}

/**
 * Handles D-pad crossing between the navigation rail and main content container on TV.
 *
 * When focus is in content and DirectionLeft is pressed at the leftmost boundary
 * (where moveLeft returns false), rail focus is requested and the event is consumed.
 * When focus is in the rail and DirectionRight is pressed, content focus is requested
 * and the event is consumed.
 *
 * Returns true if the key event was consumed.
 */
fun handleTvDpadNavigation(
    key: Key,
    isKeyDown: Boolean,
    railHasFocus: Boolean,
    moveLeft: () -> Boolean,
    moveRight: () -> Boolean,
    requestRailFocus: () -> Unit,
    requestContentFocus: () -> Unit,
): Boolean {
    if (!isKeyDown) return false
    return when {
        key == Key.DirectionLeft && !railHasFocus -> {
            val moved = moveLeft()
            if (!moved) {
                requestRailFocus()
            }
            true
        }
        key == Key.DirectionRight && railHasFocus -> {
            val moved = moveRight()
            if (!moved) {
                requestContentFocus()
            }
            true
        }
        else -> false
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/util/Digests.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/util/Digests.kt) · implementation · 4 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
3: expect fun sha256(data: ByteArray): ByteArray
4: expect fun sha1(data: ByteArray): ByteArray
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/util/Digests.kt) · SHA-256 `b1e2439b224c116e23337210e77e3dda4efcc6c865caf89de01bf8f868a98d0a`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.util

expect fun sha256(data: ByteArray): ByteArray
expect fun sha1(data: ByteArray): ByteArray
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/util/HtmlEntities.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/util/HtmlEntities.kt) · implementation · 43 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
28: internal fun decodeHtmlEntities(value: String): String {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/util/HtmlEntities.kt) · SHA-256 `307aaf7e9b650b21fc72125c5e1e42f8f8867a89e62175dc341b90186dabb3a6`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.util

private val htmlEntityRegex = Regex("&(#[xX]?[0-9a-fA-F]+|[a-zA-Z][a-zA-Z0-9]*);")

private val namedHtmlEntities = mapOf(
    "nbsp" to " ",
    "amp" to "&",
    "lt" to "<",
    "gt" to ">",
    "quot" to "\"",
    "apos" to "'",
    "copy" to "©",
    "reg" to "®",
    "mdash" to "—",
    "ndash" to "–",
    "hellip" to "…",
    "rsquo" to "’",
    "lsquo" to "‘",
    "ldquo" to "“",
    "rdquo" to "”",
    "trade" to "™",
)

/**
 * Decodes numeric (`&#39;`, `&#x27;`) and common named HTML entities in one pass, so `&amp;quot;`
 * stays `&quot;`. Unknown or out-of-range entities are kept verbatim; `&nbsp;` becomes a plain space.
 */
internal fun decodeHtmlEntities(value: String): String {
    if ('&' !in value) return value
    return value.replace(htmlEntityRegex) { match ->
        val entity = match.groupValues[1]
        if (!entity.startsWith('#')) return@replace namedHtmlEntities[entity.lowercase()] ?: match.value
        val code = if (entity.startsWith("#x", ignoreCase = true)) entity.drop(2).toIntOrNull(16) else entity.drop(1).toIntOrNull()
        when {
            code == null || code !in 0..0x10FFFF -> match.value
            code <= Char.MAX_VALUE.code -> code.toChar().toString()
            else -> {
                val shifted = code - 0x10000
                "${(0xD800 + (shifted shr 10)).toChar()}${(0xDC00 + (shifted and 0x3FF)).toChar()}"
            }
        }
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/util/PlatformLock.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/util/PlatformLock.kt) · implementation · 6 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
4: internal expect class PlatformLock() {
5: fun <T> withLock(block: () -> T): T
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/util/PlatformLock.kt) · SHA-256 `fa10dc07355461bef09303e04d58dd2f99f4caffb2a479656d4a651dc456d91c`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.util

/** Small re-entrant lock for synchronous state shared by coroutine and platform callbacks. */
internal expect class PlatformLock() {
    fun <T> withLock(block: () -> T): T
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/util/Time.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/util/Time.kt) · implementation · 4 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
4: internal fun nowMillis(): Long = kotlin.time.Clock.System.now().toEpochMilliseconds()
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/util/Time.kt) · SHA-256 `8919aac81dba5177f5a121978bb659435003e46be502d9294a3ac13ae4d495ab`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.util

@OptIn(kotlin.time.ExperimentalTime::class)
internal fun nowMillis(): Long = kotlin.time.Clock.System.now().toEpochMilliseconds()
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/ParityStateContractTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/ParityStateContractTest.kt) · test / fixture · 177 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
21: class ParityStateContractTest {
23: fun markSourceUsedSelectsOneSourceWithoutChangingOtherMediaTypes() {
44: fun sourceStateMappingPreservesObsoleteAndLastUsedFlags() {
61: fun downloadTaskIdentityPrefersChapterAndHasStableFallback() {
67: fun seededNavigationMatchesMangayomiAndIncludesTracking() {
73: fun previousYokanDefaultNavigationOrderMigratesAndPersists() = runTest {
103: fun validStoredNavigationOrderIsPreserved() = runTest {
129: fun showPagesNumberSettingCanBeToggledGlobally() {
163: private fun source(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/ParityStateContractTest.kt) · SHA-256 `f6c078cf891628dff95650ded0d656a73701d0d0cecc0447083cfd573f268fb8`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui

import kotlinx.coroutines.test.runTest
import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import eu.friedcutlet.yokan.domain.History
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Source
import eu.friedcutlet.yokan.services.download.downloadTaskId
import eu.friedcutlet.yokan.ui.navigation.NavSection
import eu.friedcutlet.yokan.ui.navigation.navigationOrder
import eu.friedcutlet.yokan.ui.navigation.testNavigator
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue

class ParityStateContractTest {
    @Test
    fun markSourceUsedSelectsOneSourceWithoutChangingOtherMediaTypes() {
        val database = InMemoryYokanDatabase(
            seedDatabaseSnapshot().copy(
                sources = listOf(
                    source(id = 1L, itemType = DbItemType.Manga, lastUsed = true),
                    source(id = 2L, itemType = DbItemType.Manga),
                    source(id = 3L, itemType = DbItemType.Anime, lastUsed = true),
                ),
            ),
        )
        val repository = DefaultYokanRepository(database)

        repository.markSourceUsed(2L)

        val sources = database.sources().associateBy(DbSource::id)
        assertFalse(sources.getValue(1L).lastUsed)
        assertTrue(sources.getValue(2L).lastUsed)
        assertTrue(sources.getValue(3L).lastUsed)
    }

    @Test
    fun sourceStateMappingPreservesObsoleteAndLastUsedFlags() {
        val database = InMemoryYokanDatabase(
            seedDatabaseSnapshot().copy(
                sources = listOf(
                    source(id = 7L, itemType = DbItemType.Manga, lastUsed = true, isObsolete = true),
                ),
            ),
        )
        val repository = DefaultYokanRepository(database)

        val source = repository.sources(ItemType.Manga).single()

        assertTrue(source.lastUsed)
        assertTrue(source.isObsolete)
    }

    @Test
    fun downloadTaskIdentityPrefersChapterAndHasStableFallback() {
        assertEquals("chapter-42", downloadTaskId(chapterId = 42L, downloadId = 9L))
        assertEquals("download-9", downloadTaskId(chapterId = null, downloadId = 9L))
    }

    @Test
    fun seededNavigationMatchesMangayomiAndIncludesTracking() {
        // A stored order is an existing install: Home is appended rather than made the start screen.
        assertEquals(mangayomiNavigationOrder + NavSection.Home, navigationOrder(seedDatabaseSnapshot().settings))
    }

    @Test
    fun previousYokanDefaultNavigationOrderMigratesAndPersists() = runTest {
        val seed = seedDatabaseSnapshot()
        val database = InMemoryYokanDatabase(
            seed.copy(
                settings = seed.settings.copy(
                    navigationOrder = listOf(
                        "Updates",
                        "MangaLibrary",
                        "AnimeLibrary",
                        "NovelLibrary",
                        "History",
                        "Browse",
                        "More",
                        "TrackerLibrary",
                    ),
                ),
            ),
        )

        val nav = testNavigator(DefaultYokanRepository(database))

        // An untouched previous default migrates to the current default, which starts at Home.
        assertEquals(listOf(NavSection.Home) + mangayomiNavigationOrder, nav.navigationOrder.value)
        // The persisted default includes LocalLibrary; the visible order hides it until enabled.
        val persistedDefault = listOf(NavSection.Home) + mangayomiNavigationOrder.take(3) + NavSection.LocalLibrary + mangayomiNavigationOrder.drop(3)
        assertEquals(persistedDefault.map(NavSection::name), database.settings().navigationOrder)
    }


    @Test
    fun validStoredNavigationOrderIsPreserved() = runTest {
        val seed = seedDatabaseSnapshot()
        val database = InMemoryYokanDatabase(
            seed.copy(
                settings = seed.settings.copy(
                    navigationOrder = listOf(
                        "More",
                        "Browse",
                        "History",
                        "Updates",
                        "MangaLibrary",
                        "AnimeLibrary",
                        "NovelLibrary",
                        "TrackerLibrary",
                    ),
                    hideItems = null,
                ),
            ),
        )
        val nav = testNavigator(DefaultYokanRepository(database))

        assertEquals(customNavigationOrder + NavSection.Home, nav.navigationOrder.value)
        assertTrue(nav.hiddenSections.value.isEmpty())
    }

    @Test
    fun showPagesNumberSettingCanBeToggledGlobally() {
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot())
        val repository = DefaultYokanRepository(database)
        assertTrue(repository.settings().showPagesNumber)

        repository.updateSettings { it.copy(showPagesNumber = false) }
        assertFalse(repository.settings().showPagesNumber)

        repository.updateSettings { it.copy(showPagesNumber = true) }
        assertTrue(repository.settings().showPagesNumber)
    }

    private val mangayomiNavigationOrder = listOf(
        NavSection.MangaLibrary,
        NavSection.AnimeLibrary,
        NavSection.NovelLibrary,
        NavSection.Updates,
        NavSection.History,
        NavSection.Browse,
        NavSection.More,
        NavSection.TrackerLibrary,
    )

    private val customNavigationOrder = listOf(
        NavSection.More,
        NavSection.Browse,
        NavSection.History,
        NavSection.Updates,
        NavSection.MangaLibrary,
        NavSection.AnimeLibrary,
        NavSection.NovelLibrary,
        NavSection.TrackerLibrary,
    )

    private fun source(
        id: Long,
        itemType: DbItemType,
        lastUsed: Boolean = false,
        isObsolete: Boolean = false,
    ) = DbSource(
        id = id,
        name = "Source $id",
        baseUrl = "https://source$id.example",
        lang = "en",
        itemType = itemType,
        lastUsed = lastUsed,
        isObsolete = isObsolete,
    )
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/ViewModelTestHost.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/ViewModelTestHost.kt) · test / fixture · 26 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
13: internal class ViewModelTestHost {
20: fun <T : ViewModel> create(init: () -> T): T = init().also { store.put("vm${count++}", it) }
22: fun close() {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/ViewModelTestHost.kt) · SHA-256 `58d3ad130ffde39e4ffe8c38c916389529605c9586189d9af7a1656faa725f00`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui

import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelStore
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.setMain

/** Installs an unconfined Main dispatcher and owns created view models; [close] clears them and restores Main. */
@OptIn(ExperimentalCoroutinesApi::class)
internal class ViewModelTestHost {
    val dispatcher = UnconfinedTestDispatcher()
    private val store = ViewModelStore()
    private var count = 0

    init { Dispatchers.setMain(dispatcher) }

    fun <T : ViewModel> create(init: () -> T): T = init().also { store.put("vm${count++}", it) }

    fun close() {
        store.clear()
        Dispatchers.resetMain()
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/image/ProfileImageHttpClientTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/image/ProfileImageHttpClientTest.kt) · test / fixture · 122 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
38: class ProfileImageHttpClientTest {
120: private suspend fun response() = HttpResponseData(HttpStatusCode.OK, GMTDate(), Headers.Empty,
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/image/ProfileImageHttpClientTest.kt) · SHA-256 `75e46729c6ce40b7f58ee0117c783cfc4c23e8d644339fbb7ab06a6d50c3c9a1`.

### Complete file

```kotlin
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class, io.ktor.utils.io.InternalAPI::class)

package eu.friedcutlet.yokan.ui.image

import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.emptySnapshot
import eu.friedcutlet.yokan.services.http.ProfileTestEngine
import eu.friedcutlet.yokan.services.http.cookies.CookieJar
import io.ktor.client.engine.callContext
import io.ktor.client.request.HttpResponseData
import io.ktor.client.request.get
import io.ktor.client.request.header
import io.ktor.client.statement.bodyAsText
import io.ktor.http.Headers
import io.ktor.http.HttpProtocolVersion
import io.ktor.http.HttpStatusCode
import io.ktor.util.date.GMTDate
import io.ktor.utils.io.ByteReadChannel
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withContext
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertTrue

class ProfileImageHttpClientTest {
    @Test fun proxyProgressHeaderNeverLeavesTheApp() = runTest {
        val parent = SupervisorJob(); val db = InMemoryYokanDatabase(emptySnapshot())
        val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { response() }
        val transport = ProfileImageHttpClient(CookieJar(db), db, CoroutineScope(parent + StandardTestDispatcher(testScheduler))) { engine }
        transport.client.get("https://wsrv.nl/image") { header(OriginalImageProgressHeader, "https://source.example.org/page.png") }
        assertEquals(null, engine.requests.receive().headers[OriginalImageProgressHeader])
        transport.closeAndJoin(); parent.cancelAndJoin()
    }
    @Test fun capturesJarAndSettingsWhileRetainingSourceHeadersAndSolvedUserAgent() = runTest {
        val parent = SupervisorJob(); val db = InMemoryYokanDatabase(emptySnapshot())
        db.updateSettings(db.settings().copy(userAgent = "profile-agent"))
        val jar = CookieJar(db, ProfileId.Default) { parent.isActive }
        jar.put("source.test", "session=profile")
        val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { response() }
        val transport = ProfileImageHttpClient(jar, db, CoroutineScope(parent + StandardTestDispatcher(testScheduler))) { engine }
        assertEquals("image", transport.client.get("https://source.test/page").bodyAsText())
        val first = engine.requests.receive()
        assertEquals("session=profile", first.headers["Cookie"]); assertEquals("profile-agent", first.headers["User-Agent"])
        transport.client.get("https://source.test/page") { header("Cookie", "source=explicit"); header("User-Agent", "source-agent") }
        val second = engine.requests.receive()
        assertEquals("source=explicit", second.headers["Cookie"]); assertEquals("source-agent", second.headers["User-Agent"])
        jar.rememberUserAgent("https://source.test/page", "solved-agent")
        transport.client.get("https://source.test/page") { header("User-Agent", "source-agent") }
        assertEquals("solved-agent", engine.requests.receive().headers["User-Agent"])
        transport.closeAndJoin(); parent.cancelAndJoin(); assertEquals(1, engine.closeCalls)
    }

    @Test fun retirementCancelsAndJoinsEngineFinalizersBeforeDatabaseRelease() = runTest {
        val parent = SupervisorJob(); val db = InMemoryYokanDatabase(emptySnapshot())
        val release = CompletableDeferred<Unit>(); var finalized = false
        val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) {
            try { awaitCancellation() } finally { withContext(NonCancellable) { release.await(); finalized = true } }
        }
        val transport = ProfileImageHttpClient(CookieJar(db, ProfileId.Default) { parent.isActive }, db, CoroutineScope(parent + StandardTestDispatcher(testScheduler))) { engine }
        val caller = launch { transport.client.get("https://source.test/page").bodyAsText() }
        engine.requests.receive()
        val retiring = launch { parent.cancelAndJoin() }
        testScheduler.runCurrent(); assertFalse(retiring.isCompleted)
        release.complete(Unit); retiring.join(); caller.join()
        assertTrue(finalized); assertTrue(engine.coroutineContext[Job]?.isCompleted == true)
        transport.closeAndJoin(); assertEquals(1, engine.closeCalls)
        assertFailsWith<CancellationException> { transport.client.get("https://source.test/page") }
        assertTrue(engine.requests.tryReceive().isFailure)
    }

    @Test fun explicitTransportClosePreservesOwnerAndRejectsFurtherRequests() = runTest {
        val parent = SupervisorJob(); val db = InMemoryYokanDatabase(emptySnapshot())
        val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { response() }
        val transport = ProfileImageHttpClient(CookieJar(db), db, CoroutineScope(parent + StandardTestDispatcher(testScheduler))) { engine }
        transport.closeAndJoin(); transport.closeAndJoin()
        assertTrue(parent.isActive); assertEquals(1, engine.closeCalls)
        assertFailsWith<CancellationException> { transport.client.get("https://source.test/page") }
        assertTrue(engine.requests.tryReceive().isFailure); parent.cancelAndJoin()
    }

    @Test fun expiredOwnerCannotAllocateImageTransport() = runTest {
        val parent = SupervisorJob(); val db = InMemoryYokanDatabase(emptySnapshot())
        parent.cancelAndJoin()
        assertFailsWith<CancellationException> {
            ProfileImageHttpClient(CookieJar(db), db, CoroutineScope(parent + StandardTestDispatcher(testScheduler))) { error("Expired allocation") }
        }
    }

    @Test fun replacementClientsWithSameUrlUseTheirOwnCredentialsAndCleanup() = runTest {
        val a = SupervisorJob(); val b = SupervisorJob()
        val dbA = InMemoryYokanDatabase(emptySnapshot()); val dbB = InMemoryYokanDatabase(emptySnapshot())
        val jarA = CookieJar(dbA, ProfileId.Default) { a.isActive }; val jarB = CookieJar(dbB, ProfileId.Default) { b.isActive }
        jarA.put("source.test", "session=A"); jarB.put("source.test", "session=B")
        val engineA = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { response() }
        val engineB = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { response() }
        val first = ProfileImageHttpClient(jarA, dbA, CoroutineScope(a + StandardTestDispatcher(testScheduler))) { engineA }
        val second = ProfileImageHttpClient(jarB, dbB, CoroutineScope(b + StandardTestDispatcher(testScheduler))) { engineB }
        first.client.get("https://source.test/page"); second.client.get("https://source.test/page")
        assertEquals("session=A", engineA.requests.receive().headers["Cookie"])
        assertEquals("session=B", engineB.requests.receive().headers["Cookie"])
        a.cancelAndJoin(); first.closeAndJoin()
        second.client.get("https://source.test/page")
        assertEquals("session=B", engineB.requests.receive().headers["Cookie"])
        assertEquals(0, engineB.closeCalls); b.cancelAndJoin(); second.closeAndJoin()
    }

    private suspend fun response() = HttpResponseData(HttpStatusCode.OK, GMTDate(), Headers.Empty,
        HttpProtocolVersion.HTTP_1_1, ByteReadChannel("image"), callContext())
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/navigation/DeepLinksTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/navigation/DeepLinksTest.kt) · test / fixture · 230 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
23: class DeepLinksTest {
25: fun parsesRepeatedRepositoryPayloadsWithoutDroppingQueryData() {
49: fun malformedPercentEscapeRejectsTheQueryInsteadOfThrowing() {
59: fun decodesFlutterCustomButtonPayload() {
82: fun confirmsCustomButtonsOneAtATimeAndResetsImportedIdentity() = runTest {
109: fun validatesAndPersistsEveryRepositoryPayloadAfterConfirmation() = runTest {
148: fun routeLinksSelectSectionsOpenSettingsAndIgnoreRoutesThatNeedArguments() = runTest {
167: fun validatesRepositoryCatalogShape() {
174: fun foreignRepositorySchemesBecomeConfirmedRepositoryAdditions() {
192: fun searchLinksOpenGlobalSearchWithTheQuery() = runTest {
209: fun backupFileLinksOpenDataAndStorageWithThePendingFile() = runTest {
222: private object NoHttp : HttpService {
223: override suspend fun request(request: HttpRequest): HttpResponse = error("No network in this test")
226: private fun String.urlQueryEncoded(): String = this
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/navigation/DeepLinksTest.kt) · SHA-256 `185719994fbaf6e3994007ddc1a8c4e05d193a2c3dfa5296442962e7eaf6faa8`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.navigation

import kotlinx.coroutines.test.UnconfinedTestDispatcher
import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.http.RecordingHttpService
import kotlin.io.encoding.Base64
import kotlin.io.encoding.ExperimentalEncodingApi
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertIs
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.runTest

@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
class DeepLinksTest {
    @Test
    fun parsesRepeatedRepositoryPayloadsWithoutDroppingQueryData() {
        val action = assertIs<PendingDeepLinkAction.AddRepositories>(
            parseDeepLinkAction(
                "yokan://add-repo?repo_name=Community+Repo" +
                    "&repo_url=https%3A%2F%2Fexample.com" +
                    "&manga_url=https%3A%2F%2Fexample.com%2Fmanga.json" +
                    "&anime_url=https%3A%2F%2Fexample.com%2Fanime-one.json" +
                    "&anime_url=https%3A%2F%2Fexample.com%2Fanime-two.json",
            ),
        )

        assertEquals("Community Repo", action.name)
        assertEquals("https://example.com", action.website)
        assertEquals(
            listOf(
                RepositoryPayload(ItemType.Manga, "https://example.com/manga.json"),
                RepositoryPayload(ItemType.Anime, "https://example.com/anime-one.json"),
                RepositoryPayload(ItemType.Anime, "https://example.com/anime-two.json"),
            ),
            action.repositories,
        )
    }

    @Test
    fun malformedPercentEscapeRejectsTheQueryInsteadOfThrowing() {
        assertEquals(emptyMap(), parseQueryParameters("yokan://add-repo?manga_url=%zz&repo_name=x"))
        assertEquals(emptyMap(), parseQueryParameters("yokan://add-repo?repo_name=trailing%2"))

        val action = assertIs<PendingDeepLinkAction.AddRepositories>(parseDeepLinkAction("yokan://add-repo?manga_url=%zz"))
        assertTrue(action.repositories.isEmpty())
    }

    @OptIn(ExperimentalEncodingApi::class)
    @Test
    fun decodesFlutterCustomButtonPayload() {
        val encoded = Base64.encode(
            """{"id":42,"title":"Skip intro","codePress":"seek(90)","codeLongPress":"","codeStartup":"setup()","isFavourite":true,"pos":7,"updatedAt":1}"""
                .encodeToByteArray(),
        ).urlQueryEncoded()

        val action = assertIs<PendingDeepLinkAction.AddCustomButtons>(
            parseDeepLinkAction("yokan://add-button?button=$encoded"),
        )

        assertEquals(
            CustomButtonPayload(
                title = "Skip intro",
                codePress = "seek(90)",
                codeLongPress = "",
                codeStartup = "setup()",
            ),
            action.buttons.single(),
        )
    }

    @OptIn(ExperimentalEncodingApi::class)
    @Test
    fun confirmsCustomButtonsOneAtATimeAndResetsImportedIdentity() = runTest {
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot())
        val repository = DefaultYokanRepository(database)
        val nav = testNavigator(repository)
        val deepLinks = DeepLinkViewModel(repository, database, NoHttp, nav)
        val originalButtons = database.customButtons()
        val importedTitle = "Imported ${originalButtons.size}"
        val encoded = Base64.encode(
            """{"id":42,"title":"$importedTitle","codePress":"play()","isFavourite":true,"pos":7}"""
                .encodeToByteArray(),
        ).urlQueryEncoded()

        deepLinks.open("yokan://add-button?button=$encoded")
        assertIs<PendingDeepLinkAction.AddCustomButtons>(deepLinks.state.value.action)
        assertTrue(nav.backStack.value.isEmpty())

        deepLinks.confirm()

        val imported = database.customButtons().single { it.title == importedTitle }
        assertEquals(importedTitle, imported.title)
        assertEquals("play()", imported.codePress)
        assertEquals(originalButtons.size, imported.position)
        assertTrue(!imported.isFavourite)
        assertNull(deepLinks.state.value.action)
    }

    @Test
    fun validatesAndPersistsEveryRepositoryPayloadAfterConfirmation() = runTest {
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot())
        val repository = DefaultYokanRepository(database)
        val http = RecordingHttpService { HttpResponse(200, """[{"name":"Example"}]""") }
        val deepLinks = DeepLinkViewModel(
            repository,
            database,
            http,
            testNavigator(repository),
            injectedScope = this,
            workDispatcher = UnconfinedTestDispatcher(testScheduler),
        )
        deepLinks.open(
            "yokan://add-repo?repo_name=Community+Repo" +
                "&repo_url=https%3A%2F%2Fexample.com" +
                "&manga_url=https%3A%2F%2Fexample.com%2Fmanga.json" +
                "&novel_url=https%3A%2F%2Fexample.com%2Fnovel.json",
        )

        deepLinks.confirm()
        deepLinks.state.first { !it.busy }

        assertEquals(
            listOf(
                "https://example.com/manga.json",
                "https://example.com/novel.json",
            ),
            http.requests.map { it.url },
        )
        val mangaRepo = repository.repositories(ItemType.Manga)
            .single { it.jsonUrl == "https://example.com/manga.json" }
        val novelRepo = repository.repositories(ItemType.Novel)
            .single { it.jsonUrl == "https://example.com/novel.json" }
        assertEquals("Community Repo", mangaRepo.name)
        assertEquals("https://example.com", novelRepo.website)
        assertNull(deepLinks.state.value.action)
    }

    @Test
    fun routeLinksSelectSectionsOpenSettingsAndIgnoreRoutesThatNeedArguments() = runTest {
        val nav = testNavigator()
        val deepLinks = DeepLinkViewModel(DefaultYokanRepository(), InMemoryYokanDatabase(seedDatabaseSnapshot()), NoHttp, nav)

        deepLinks.open("yokan://anime")
        assertEquals(NavSection.AnimeLibrary, nav.section.value)

        deepLinks.open("yokan://general")
        deepLinks.open("yokan://extension_detail")
        assertEquals(listOf<Route>(Route.Settings(SettingsPage.General)), nav.backStack.value.map(NavEntry::route))

        deepLinks.open("yokan://sourceFilter")
        assertEquals(Route.SourceFilters(ItemType.Anime), nav.backStack.value.last().route)

        deepLinks.open("https://example.com/oauth/success?code=1")
        assertEquals(Route.Settings(SettingsPage.TrackingDetail), nav.backStack.value.last().route)
    }

    @Test
    fun validatesRepositoryCatalogShape() {
        assertTrue(repositoryPayloadIsValid("""[{"name":"Example","sources":[]}]"""))
        assertTrue(!repositoryPayloadIsValid("""[{"sources":[]}]"""))
        assertTrue(!repositoryPayloadIsValid("{}"))
    }

    @Test
    fun foreignRepositorySchemesBecomeConfirmedRepositoryAdditions() {
        val url = "https://example.com/repo/index.min.json"
        val encoded = "https%3A%2F%2Fexample.com%2Frepo%2Findex.min.json"
        listOf(
            "tachiyomi://add-repo?url=$encoded" to ItemType.Manga,
            "mihon://extension-store?url=$encoded" to ItemType.Manga,
            "aniyomi://add-repo?url=$encoded" to ItemType.Anime,
            "animetail://add-repo?url=$encoded" to ItemType.Anime,
        ).forEach { (link, type) ->
            val action = assertIs<PendingDeepLinkAction.AddRepositories>(parseDeepLinkAction(link), link)
            assertEquals(listOf(RepositoryPayload(type, url)), action.repositories, link)
        }
        assertNull(parseDeepLinkAction("tachiyomi://add-repo"))
        assertNull(parseDeepLinkAction("mihon://other?url=$encoded"))
        assertNull(parseDeepLinkAction("https://add-repo?url=$encoded"))
    }

    @Test
    fun searchLinksOpenGlobalSearchWithTheQuery() = runTest {
        val nav = testNavigator()
        val deepLinks = DeepLinkViewModel(DefaultYokanRepository(), InMemoryYokanDatabase(seedDatabaseSnapshot()), NoHttp, nav)
        val query = "Frieren: Beyond & Journey's End +1 ✓"

        deepLinks.open(searchDeepLink(query, ItemType.Anime))
        assertEquals(Route.GlobalSearch(ItemType.Anime, query), nav.backStack.value.last().route)

        deepLinks.open(searchDeepLink("  Berserk  "))
        assertEquals(Route.GlobalSearch(nav.itemType.value, "Berserk"), nav.backStack.value.last().route)

        val depth = nav.backStack.value.size
        deepLinks.open("yokan://search?q=%20")
        assertEquals(depth, nav.backStack.value.size)
    }

    @Test
    fun backupFileLinksOpenDataAndStorageWithThePendingFile() = runTest {
        val nav = testNavigator()
        val deepLinks = DeepLinkViewModel(DefaultYokanRepository(), InMemoryYokanDatabase(seedDatabaseSnapshot()), NoHttp, nav)

        listOf("content://com.android.providers.downloads.documents/document/42", "file:///tmp/library.tachibk").forEach { link ->
            deepLinks.open(link)
            assertEquals(Route.Settings(SettingsPage.DataAndStorage), nav.backStack.value.last().route)
            assertEquals(link, PendingBackupFile.take())
            assertNull(PendingBackupFile.take())
        }
        assertNull(deepLinks.state.value.action)
    }

    private object NoHttp : HttpService {
        override suspend fun request(request: HttpRequest): HttpResponse = error("No network in this test")
    }

    private fun String.urlQueryEncoded(): String = this
        .replace("+", "%2B")
        .replace("/", "%2F")
        .replace("=", "%3D")
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/navigation/HomeNavigationTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/navigation/HomeNavigationTest.kt) · test / fixture · 24 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
6: class HomeNavigationTest {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/navigation/HomeNavigationTest.kt) · SHA-256 `6a1317b850f5cdaba39dad169a7c7fc1a5882f4297c5f3d6731aa41368d7e76d`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.navigation

import eu.friedcutlet.yokan.database.DbSettings
import kotlin.test.*

class HomeNavigationTest {
    @Test fun freshInstallStartsAtHomeAndExistingCustomOrdersStayIntact() {
        assertEquals(NavSection.Home, completeNavigationOrder(DbSettings()).first())
        val custom = DbSettings(navigationOrder = listOf("Browse", "AnimeLibrary", "More"))
        assertEquals(listOf(NavSection.Browse, NavSection.AnimeLibrary, NavSection.More), completeNavigationOrder(custom).take(3))
        assertEquals(1, completeNavigationOrder(custom).count { it == NavSection.Home })
        assertEquals(custom, custom.withNavigationOrderMigrated())
    }
    @Test fun compactBarLeavesAnOverflowSlotAndKeepsConfiguredOrder() {
        val order = completeNavigationOrder(DbSettings())
        assertEquals(order.take(4), compactPrimarySections(order))
        assertEquals(order.take(5), compactPrimarySections(order.take(5)))
        assertEquals(order, compactPrimarySections(order) + order.drop(compactPrimarySections(order).size))
    }
    @Test fun homeCanBeHiddenAndDeepLinkNamesAreRecognized() {
        assertEquals(NavSection.Home, navigationSectionForStoredName("/home"))
        assertTrue(NavSection.Home !in navigationOrder(DbSettings(hideItems = listOf("Home"))))
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/navigation/InteractiveBackGestureTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/navigation/InteractiveBackGestureTest.kt) · test / fixture · 61 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
13: class InteractiveBackGestureTest {
15: fun releaseUsesVelocityDirectionAndFallsBackToDistance() {
23: fun completionKeepsOutgoingPageOffscreenAndOnlyPopsOnce() = runTest {
41: fun cancellationReturnsToRestAndDisposedGestureCannotPop() = runTest {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/navigation/InteractiveBackGestureTest.kt) · SHA-256 `fec2a74570b3ef7f3665b562d6b6b101feb9f232dae51ad3e08119790f9de9f4`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.navigation

import androidx.compose.runtime.BroadcastFrameClock
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue

@OptIn(ExperimentalCoroutinesApi::class)
class InteractiveBackGestureTest {
    @Test
    fun releaseUsesVelocityDirectionAndFallsBackToDistance() {
        assertTrue(shouldCompleteBack(0.15f, 2f))
        assertFalse(shouldCompleteBack(0.8f, -2f))
        assertFalse(shouldCompleteBack(0.49f, 0.1f))
        assertTrue(shouldCompleteBack(0.51f, -0.1f))
    }

    @Test
    fun completionKeepsOutgoingPageOffscreenAndOnlyPopsOnce() = runTest {
        val clock = BroadcastFrameClock()
        val gesture = InteractiveBackGesture(CoroutineScope(backgroundScope.coroutineContext + clock))
        var pops = 0
        assertTrue(gesture.begin())
        gesture.drag(240f, 400f)
        gesture.finish(2f, false) { pops++ }
        gesture.finish(2f, false) { pops++ }
        assertFalse(gesture.begin())
        repeat(120) { testScheduler.runCurrent(); clock.sendFrame(it * 16_000_000L) }
        testScheduler.runCurrent()
        assertEquals(1, pops)
        assertEquals(1f, gesture.progress)
        assertTrue(gesture.active)
        gesture.dispose()
    }

    @Test
    fun cancellationReturnsToRestAndDisposedGestureCannotPop() = runTest {
        val clock = BroadcastFrameClock()
        val gesture = InteractiveBackGesture(CoroutineScope(backgroundScope.coroutineContext + clock))
        var pops = 0
        gesture.begin()
        gesture.drag(300f, 400f)
        gesture.finish(3f, true) { pops++ }
        repeat(120) { testScheduler.runCurrent(); clock.sendFrame(it * 16_000_000L) }
        testScheduler.runCurrent()
        assertEquals(0, pops)
        assertEquals(0f, gesture.progress)
        assertFalse(gesture.active)
        assertTrue(gesture.begin())
        gesture.drag(300f, 400f)
        gesture.finish(3f, false) { pops++ }
        gesture.dispose()
        repeat(120) { testScheduler.runCurrent(); clock.sendFrame((it + 120) * 16_000_000L) }
        assertEquals(0, pops)
        assertFalse(gesture.begin())
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/navigation/NavigatorRetirementTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/navigation/NavigatorRetirementTest.kt) · test / fixture · 108 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
15: class NavigatorRetirementTest {
67: override suspend fun awaitCleanup() {
90: private class Probe(finish: CompletableDeferred<Unit>, entered: CompletableDeferred<Unit>) : ViewModel() {
96: override fun onCleared() { cleared = true }
98: private class Fixture(test: TestScope) {
105: suspend fun close() { nav.closeAndJoin(); parent.cancelAndJoin(); Dispatchers.resetMain() }
107: private fun <T : ViewModel> ViewModelStoreOwner.attach(model: T): T = model.also { viewModelStore.put("probe", it) }
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/navigation/NavigatorRetirementTest.kt) · SHA-256 `1aa0cc3903def8cc169dd0c9400718b04ee18228ff265c7ea4da8ad7e6780a34`.

### Complete file

```kotlin
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)

package eu.friedcutlet.yokan.ui.navigation

import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelStoreOwner
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.domain.ItemType
import kotlinx.coroutines.*
import kotlinx.coroutines.test.*
import kotlin.test.*

class NavigatorRetirementTest {
    @Test fun retirementJoinsRootAndEntryFinalizersAndPreservesParentWork() = runTest {
        val f = Fixture(this); val finish = CompletableDeferred<Unit>(); val entered = CompletableDeferred<Unit>()
        try {
            f.nav.navigate(Route.Detail(1))
            f.nav.backStack.value.single().attach(Probe(finish, entered))
            val root = f.nav.rootViewModelStoreOwner.attach(Probe(finish, entered)); runCurrent()
            val close = async { f.nav.closeAndJoin() }; entered.await(); runCurrent()
            assertFalse(close.isCompleted); assertTrue(root.cleared); assertTrue(f.parent.isActive)
            finish.complete(Unit); close.await(); assertTrue(f.parent.isActive)
        } finally { finish.complete(Unit); f.close() }
    }

    @Test fun poppedEntryFinalizerIsStillJoinedAfterItsStoreHasGone() = runTest {
        val f = Fixture(this); val finish = CompletableDeferred<Unit>(); val entered = CompletableDeferred<Unit>()
        try {
            f.nav.navigate(Route.Detail(1)); val entry = f.nav.backStack.value.single()
            entry.attach(Probe(finish, entered)); runCurrent(); f.nav.back(); f.nav.release(entry)
            entered.await(); val close = async { f.nav.closeAndJoin() }; runCurrent(); assertFalse(close.isCompleted)
            finish.complete(Unit); close.await()
        } finally { finish.complete(Unit); f.close() }
    }

    @Test fun replacementBeforeHostDisposalCannotLeaveAnUntrackedStore() = runTest {
        val f = Fixture(this); val finish = CompletableDeferred<Unit>(); val entered = CompletableDeferred<Unit>()
        try {
            f.nav.navigate(Route.Reader(1, 10)); val old = f.nav.backStack.value.single().attach(Probe(finish, entered))
            runCurrent(); f.nav.navigate(Route.Reader(1, 11))
            val close = async { f.nav.closeAndJoin() }; entered.await(); runCurrent()
            assertTrue(old.cleared); assertFalse(close.isCompleted)
            finish.complete(Unit); close.await()
        } finally { finish.complete(Unit); f.close() }
    }

    @Test fun closedNavigatorRejectsRetainedNavigationAndPlayerCallbacks() = runTest {
        val f = Fixture(this)
        try {
            f.nav.navigate(Route.Detail(1)); val stack = f.nav.backStack.value
            val section = f.nav.section.value; val item = f.nav.itemType.value; val request = f.nav.libraryRequest.value
            f.nav.close()
            f.nav.navigate(Route.Settings()); f.nav.back(); f.nav.completeInteractiveBack()
            f.nav.select(NavSection.More); f.nav.showLibrary(ItemType.Anime, "late")
            f.nav.selectItemType(ItemType.Novel); f.nav.minimizePlayer(); f.nav.dismissPlayer()
            assertEquals(stack, f.nav.backStack.value); assertEquals(section, f.nav.section.value)
            assertEquals(item, f.nav.itemType.value); assertEquals(request, f.nav.libraryRequest.value)
            assertFalse(f.nav.playerMinimized.value)
        } finally { f.close() }
    }

    @Test fun failedNativeCleanupRetriesOnTheCapturedUiContext() = runTest {
        val f = Fixture(this); val names = mutableListOf<String?>(); var fail = true
        val model = object : ViewModel(), AwaitedViewModelCleanup {
            override suspend fun awaitCleanup() {
                names += currentCoroutineContext()[CoroutineName]?.name
                if (fail) error("native cleanup failed")
            }
        }
        try {
            f.nav.rootViewModelStoreOwner.attach(model)
            assertFailsWith<IllegalStateException> { withContext(CoroutineName("controller")) { f.nav.closeAndJoin() } }
            fail = false; withContext(CoroutineName("retry")) { f.nav.closeAndJoin() }
            assertEquals<List<String?>>(listOf("navigation-ui", "navigation-ui"), names)
            f.nav.closeAndJoin(); assertEquals(2, names.size)
        } finally { fail = false; f.close() }
    }

    @Test fun cancelledAwaiterStillJoinsOwnedFinalizers() = runTest {
        val f = Fixture(this); val finish = CompletableDeferred<Unit>(); val entered = CompletableDeferred<Unit>()
        try {
            f.nav.rootViewModelStoreOwner.attach(Probe(finish, entered)); runCurrent()
            val close = launch { f.nav.closeAndJoin() }; entered.await(); close.cancel(); runCurrent()
            assertFalse(close.isCompleted); finish.complete(Unit); close.join()
        } finally { finish.complete(Unit); f.close() }
    }

    private class Probe(finish: CompletableDeferred<Unit>, entered: CompletableDeferred<Unit>) : ViewModel() {
        var cleared = false
        init { viewModelScope.launch {
            try { awaitCancellation() }
            finally { withContext(NonCancellable) { entered.complete(Unit); finish.await() } }
        } }
        override fun onCleared() { cleared = true }
    }
    private class Fixture(test: TestScope) {
        val dispatcher = StandardTestDispatcher(test.testScheduler)
        val parent = SupervisorJob()
        val scope = CoroutineScope(parent + dispatcher + CoroutineName("navigation-ui"))
        val settings = SettingsStore(DefaultYokanRepository(), scope) {}
        val nav: Navigator
        init { Dispatchers.setMain(dispatcher); nav = Navigator(settings, scope) }
        suspend fun close() { nav.closeAndJoin(); parent.cancelAndJoin(); Dispatchers.resetMain() }
    }
    private fun <T : ViewModel> ViewModelStoreOwner.attach(model: T): T = model.also { viewModelStore.put("probe", it) }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/navigation/NavigatorTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/navigation/NavigatorTest.kt) · test / fixture · 221 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
23: class NavigatorTest {
25: fun popRestoresThePreviousRoutesArguments() = runTest {
46: fun sameDestinationReplacesTheTopAndReleasesOnlyTheReplacedEntry() = runTest {
74: fun selectClearsTheStackAndReleasesEntriesBelowTheTop() = runTest {
96: fun rootSectionsRememberTheirOwnItemType() = runTest {
113: fun libraryRequestsResetToTheDefaultCategoryOrSearchAllCategories() = runTest {
132: fun hiddenOrUnavailableSectionFallsBackToTheFirstVisibleOne() {
153: fun localMediaNavigationIsOptionalAndNeedsPlatformSupport() {
165: fun miniPlayerIsRestoredByOpeningAReaderAndDismissalPopsIt() = runTest {
185: fun interactiveBackPopsWithoutATransition() = runTest {
198: fun closeClearsEveryStoreIncludingTheRootOwner() = runTest {
210: private fun Navigator.top(): Route? = backStack.value.lastOrNull()?.route
212: private class Probe : ViewModel() {
214: override fun onCleared() {
219: private fun ViewModelStoreOwner.probe(): Probe =
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/navigation/NavigatorTest.kt) · SHA-256 `9fa15a65664ff884246d4e008cd6ffe0a4015b404778ccce42feb25d7287305f`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.navigation

import kotlinx.coroutines.test.runTest
import eu.friedcutlet.yokan.domain.testManga
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStoreOwner
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.services.system.isLocalLibraryManagerSupported
import eu.friedcutlet.yokan.ui.LibrarySearchQuery
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertTrue

class NavigatorTest {
    @Test
    fun popRestoresThePreviousRoutesArguments() = runTest {
        val nav = testNavigator()

        nav.navigate(Route.SourceHome(123, genre = "Action"))
        nav.navigate(Route.Detail(1))
        nav.navigate(Route.SourceHome(123, genre = "Drama"))
        assertEquals(Route.SourceHome(123, genre = "Drama"), nav.top())
        assertEquals(1, nav.transitionDirection.value)

        nav.back()
        assertEquals(Route.Detail(1), nav.top())
        assertEquals(-1, nav.transitionDirection.value)
        nav.back()
        assertEquals(Route.SourceHome(123, genre = "Action"), nav.top())
        nav.back()
        assertTrue(nav.backStack.value.isEmpty())
        nav.back()
        assertTrue(nav.backStack.value.isEmpty())
    }

    @Test
    fun sameDestinationReplacesTheTopAndReleasesOnlyTheReplacedEntry() = runTest {
        val nav = testNavigator()
        nav.navigate(Route.Detail(1))
        nav.navigate(Route.Reader(1, chapterId = 10))
        val first = nav.backStack.value.last()
        val firstProbe = first.probe()

        nav.navigate(Route.Reader(1, chapterId = 11))
        assertEquals(listOf(Route.Detail(1), Route.Reader(1, 11)), nav.backStack.value.map(NavEntry::route))

        val current = nav.backStack.value.last()
        val currentProbe = current.probe()
        assertTrue(nav.release(first))
        assertTrue(firstProbe.cleared)
        assertFalse(nav.release(current))
        assertFalse(currentProbe.cleared)

        // Settings pages are distinct destinations: Index → General pushes, a highlight re-open replaces.
        nav.navigate(Route.Settings())
        nav.navigate(Route.Settings(SettingsPage.General))
        nav.navigate(Route.Settings(SettingsPage.General, highlight = "doh"))
        assertEquals(
            listOf(Route.Settings(), Route.Settings(SettingsPage.General, highlight = "doh")),
            nav.backStack.value.takeLast(2).map(NavEntry::route),
        )
    }

    @Test
    fun selectClearsTheStackAndReleasesEntriesBelowTheTop() = runTest {
        val nav = testNavigator()
        nav.select(NavSection.More)
        nav.navigate(Route.Settings())
        val below = nav.backStack.value.last().probe()
        nav.navigate(Route.Settings(SettingsPage.General))
        val top = nav.backStack.value.last()
        val topProbe = top.probe()

        nav.select(NavSection.Updates)

        assertTrue(nav.backStack.value.isEmpty())
        assertEquals(NavSection.Updates, nav.section.value)
        assertEquals(-1, nav.transitionDirection.value)
        assertTrue(below.cleared)
        // The top may still be animating out; the host releases it once disposed.
        assertFalse(topProbe.cleared)
        assertTrue(nav.release(top))
        assertTrue(topProbe.cleared)
    }

    @Test
    fun rootSectionsRememberTheirOwnItemType() = runTest {
        val nav = testNavigator()

        nav.select(NavSection.History)
        nav.selectItemType(ItemType.Anime)
        nav.select(NavSection.Browse)
        nav.selectItemType(ItemType.Novel)
        nav.select(NavSection.AnimeLibrary)
        assertEquals(ItemType.Anime, nav.itemType.value)

        nav.select(NavSection.History)
        assertEquals(ItemType.Anime, nav.itemType.value)
        nav.select(NavSection.Browse)
        assertEquals(ItemType.Novel, nav.itemType.value)
    }

    @Test
    fun libraryRequestsResetToTheDefaultCategoryOrSearchAllCategories() = runTest {
        val nav = testNavigator()

        nav.select(NavSection.NovelLibrary)
        assertEquals(ItemType.Novel to null, nav.libraryRequest.value?.let { it.itemType to it.query })

        nav.navigate(Route.Detail(1))
        nav.showLibrary(ItemType.Anime, "genre:Sci-Fi")
        assertEquals(NavSection.AnimeLibrary, nav.section.value)
        assertEquals(ItemType.Anime, nav.itemType.value)
        assertTrue(nav.backStack.value.isEmpty())
        val query = checkNotNull(nav.libraryRequest.value?.query)
        assertEquals("genre:Sci-Fi", query)
        val title = testManga(1, "Sci-Fi in the title").copy(genres = listOf("Drama"))
        assertFalse(LibrarySearchQuery(query).matches(title))
        assertTrue(LibrarySearchQuery(query).matches(title.copy(genres = listOf("SCI-FI"))))
    }

    @Test
    fun hiddenOrUnavailableSectionFallsBackToTheFirstVisibleOne() {
        val repository = DefaultYokanRepository()
        repository.updateDbSettings {
            it.copy(navigationOrder = listOf("Updates", "More", "MangaLibrary"), hideItems = listOf("Updates"))
        }
        val scope = CoroutineScope(Dispatchers.Unconfined)
        val settings = SettingsStore(repository, scope) {}
        val nav = Navigator(settings, scope)
        assertEquals(NavSection.More, nav.section.value)

        nav.navigate(Route.Settings())
        settings.updateDb { it.copy(hideItems = listOf("Updates", "More")) }
        assertEquals(NavSection.MangaLibrary, nav.section.value)
        assertTrue(nav.backStack.value.isEmpty())

        // A deep link can select a hidden section; it immediately falls back as well.
        nav.select(NavSection.Updates)
        assertEquals(NavSection.MangaLibrary, nav.section.value)
    }

    @Test
    fun localMediaNavigationIsOptionalAndNeedsPlatformSupport() {
        val db = DefaultYokanRepository().dbSettings()
        assertFalse(NavSection.LocalLibrary in navigationOrder(db))
        // Web has no local media manager (DeviceCapabilities.wasm.kt), so enabling the setting must
        // not surface a nav entry that cannot work there.
        assertEquals(
            isLocalLibraryManagerSupported(),
            NavSection.LocalLibrary in navigationOrder(db.copy(showLocalLibraryNavigation = true)),
        )
    }

    @Test
    fun miniPlayerIsRestoredByOpeningAReaderAndDismissalPopsIt() = runTest {
        val nav = testNavigator()
        nav.navigate(Route.Detail(1))
        nav.navigate(Route.Reader(1))
        nav.minimizePlayer()
        assertTrue(nav.playerMinimized.value)
        nav.restorePlayer()
        assertFalse(nav.playerMinimized.value)

        nav.minimizePlayer()
        nav.navigate(Route.Reader(1, chapterId = 2))
        assertFalse(nav.playerMinimized.value)

        nav.minimizePlayer()
        nav.dismissPlayer()
        assertFalse(nav.playerMinimized.value)
        assertEquals(Route.Detail(1), nav.top())
    }

    @Test
    fun interactiveBackPopsWithoutATransition() = runTest {
        val nav = testNavigator()
        nav.select(NavSection.More)
        nav.navigate(Route.History)

        nav.completeInteractiveBack()

        assertNull(nav.backStack.value.lastOrNull())
        assertEquals(NavSection.More, nav.section.value)
        assertEquals(0, nav.transitionDirection.value)
    }

    @Test
    fun closeClearsEveryStoreIncludingTheRootOwner() = runTest {
        val nav = testNavigator()
        nav.navigate(Route.Detail(1))
        val entry = nav.backStack.value.single().probe()
        val root = nav.rootViewModelStoreOwner.probe()

        nav.close()

        assertTrue(entry.cleared)
        assertTrue(root.cleared)
    }

    private fun Navigator.top(): Route? = backStack.value.lastOrNull()?.route

    private class Probe : ViewModel() {
        var cleared = false
        override fun onCleared() {
            cleared = true
        }
    }

    private fun ViewModelStoreOwner.probe(): Probe =
        ViewModelProvider.create(this, viewModelFactory { initializer { Probe() } })[Probe::class]
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/navigation/TestNavigator.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/navigation/TestNavigator.kt) · test / fixture · 16 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
13: fun TestScope.testNavigator(repository: YokanRepository = DefaultYokanRepository()): Navigator {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/navigation/TestNavigator.kt) · SHA-256 `71cfd139c6c4c3592e12d82737c763c635f3ebc528365b53c73ba26bde61b246`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.navigation

import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.data.YokanRepository
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.plus
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.UnconfinedTestDispatcher

/** A [Navigator] on the test's unconfined background scope: settings changes and the hidden-section fallback apply synchronously; cancelled when the test ends. */
@OptIn(ExperimentalCoroutinesApi::class)
fun TestScope.testNavigator(repository: YokanRepository = DefaultYokanRepository()): Navigator {
    val scope = backgroundScope + UnconfinedTestDispatcher(testScheduler)
    return Navigator(SettingsStore(repository, scope) {}, scope)
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/navigation/ViewModelFinalizerTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/navigation/ViewModelFinalizerTest.kt) · test / fixture · 38 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
8: class ViewModelFinalizerTest {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/navigation/ViewModelFinalizerTest.kt) · SHA-256 `5b81bbd2d0ab054a617a3bd29ed0edfa2395c2b75a5af1bd970e5fc8e445ea33`.

### Complete file

```kotlin
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
package eu.friedcutlet.yokan.ui.navigation

import kotlinx.coroutines.*
import kotlinx.coroutines.test.*
import kotlin.test.*

class ViewModelFinalizerTest {
    @Test fun fileCleanupFollowsBlockingWriteFinalizers() = runTest {
        val dispatcher = StandardTestDispatcher(testScheduler)
        val job = SupervisorJob(); val scope = CoroutineScope(job + dispatcher)
        val entered = CompletableDeferred<Unit>(); val finish = CompletableDeferred<Unit>(); val order = mutableListOf<String>()
        scope.launch { try { awaitCancellation() } finally { withContext(NonCancellable) { entered.complete(Unit); finish.await(); order += "write" } } }
        runCurrent()
        val finalizer = ViewModelFinalizer(job, dispatcher) { order += "delete" }
        val close = async { finalizer.closeAndJoin() }; entered.await(); runCurrent()
        assertFalse(close.isCompleted); assertTrue(order.isEmpty())
        finish.complete(Unit); close.await(); assertEquals(listOf("write", "delete"), order)
    }
    @Test fun failedReleaseRetriesWithoutRevivingReaderWork() = runTest {
        val job = SupervisorJob(); var fail = true; var attempts = 0
        val finalizer = ViewModelFinalizer(job, StandardTestDispatcher(testScheduler)) { attempts++; if (fail) error("file release failed") }
        assertFailsWith<IllegalStateException> { finalizer.closeAndJoin() }; assertFalse(job.isActive)
        fail = false; finalizer.closeAndJoin(); finalizer.closeAndJoin(); assertEquals(3, attempts)
    }
    @Test fun cancelledAwaiterCannotAbandonFileCleanup() = runTest {
        val entered = CompletableDeferred<Unit>(); val finish = CompletableDeferred<Unit>()
        val finalizer = ViewModelFinalizer(SupervisorJob(), StandardTestDispatcher(testScheduler)) { entered.complete(Unit); finish.await() }
        val close = launch { finalizer.closeAndJoin() }; entered.await(); close.cancel(); runCurrent()
        assertFalse(close.isCompleted); finish.complete(Unit); close.join(); finalizer.closeAndJoin()
    }
    @Test fun oldCleanupPreservesOtherReaderAndParentJobs() = runTest {
        val parent = SupervisorJob(); val old = SupervisorJob(parent); val fresh = SupervisorJob(parent)
        val finalizer = ViewModelFinalizer(old, StandardTestDispatcher(testScheduler)) {}
        finalizer.closeAndJoin(); assertTrue(parent.isActive); assertTrue(fresh.isActive)
        parent.cancelAndJoin()
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/ReadingSessionClockTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/ReadingSessionClockTest.kt) · test / fixture · 38 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
10: class ReadingSessionClockTest {
12: fun countsOnlyForegroundIntervalsAndTakesThemOnce() {
28: fun finishedClockNeitherCountsNorResumes() {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/ReadingSessionClockTest.kt) · SHA-256 `075806eb106865b7762ececcdbaf585684b853349f68454bc9e75763b11186d1`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens

import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.TestTimeSource

class ReadingSessionClockTest {
    @Test
    fun countsOnlyForegroundIntervalsAndTakesThemOnce() {
        val time = TestTimeSource()
        val clock = ReadingSessionClock(time)
        time += 3_500.milliseconds
        assertTrue(clock.pause())
        assertFalse(clock.pause())
        time += 5_500.milliseconds
        clock.resume()
        time += 2_500.milliseconds

        assertEquals(6, clock.takeSeconds())
        time += 2_000.milliseconds
        assertEquals(2, clock.takeSeconds())
    }

    @Test
    fun finishedClockNeitherCountsNorResumes() {
        val time = TestTimeSource()
        val clock = ReadingSessionClock(time)
        time += 4_000.milliseconds

        assertEquals(4, clock.finishSeconds())
        clock.resume()
        time += 4_000.milliseconds
        assertEquals(0, clock.finishSeconds())
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/theme/ThemeParityTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/theme/ThemeParityTest.kt) · test / fixture · 232 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
9: class ThemeParityTest {
11: fun darkModeFollowsSystemOnlyWhenEnabled() {
18: fun userSurfaceBlendDoesNotChangeFixedOnBlendRoles() {
41: fun brownOrangeLightMatchesMangayomiFlexThemeData() {
99: fun brownOrangeDarkMatchesMangayomiFlexThemeData() {
161: fun pureBlackOnlyChangesMangayomiScaffold() {
177: private fun assertRoleSnapshot(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/theme/ThemeParityTest.kt) · SHA-256 `fdccdafba336e34ca1ba5d829757812da3b9d0f1fef27c8919245b2dbf9f0553`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.theme

import androidx.compose.material3.ColorScheme
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import kotlin.test.Test
import kotlin.test.assertEquals

class ThemeParityTest {
    @Test
    fun darkModeFollowsSystemOnlyWhenEnabled() {
        assertEquals(true, resolveDarkMode(followSystem = true, themeIsDark = false, systemDark = true))
        assertEquals(false, resolveDarkMode(followSystem = true, themeIsDark = true, systemDark = false))
        assertEquals(true, resolveDarkMode(followSystem = false, themeIsDark = true, systemDark = false))
        assertEquals(false, resolveDarkMode(followSystem = false, themeIsDark = false, systemDark = true))
    }
    @Test
    fun userSurfaceBlendDoesNotChangeFixedOnBlendRoles() {
        val palette = FlexSchemes[50].light
        val blendTen = buildLightScheme(palette, blendLevel = 0.10f)
        val blendTwenty = buildLightScheme(palette, blendLevel = 0.20f)

        assertEquals(0xFFF3EFE8.toInt(), blendTwenty.surface.toArgb(), "blend 20 surface")
        assertEquals(
            0xFFE4D6C3.toInt(),
            buildLightScaffoldColor(palette, blendLevel = 0.20f).toArgb(),
            "blend 20 scaffold",
        )
        assertEquals(blendTen.onPrimaryContainer, blendTwenty.onPrimaryContainer)
        assertEquals(blendTen.onSecondaryContainer, blendTwenty.onSecondaryContainer)
        assertEquals(blendTen.onTertiaryContainer, blendTwenty.onTertiaryContainer)
        assertEquals(blendTen.onSurface, blendTwenty.onSurface)
        assertEquals(blendTen.onSurfaceVariant, blendTwenty.onSurfaceVariant)
        assertEquals(blendTen.inverseOnSurface, blendTwenty.inverseOnSurface)
        assertEquals(blendTen.outline, blendTwenty.outline)
        assertEquals(blendTen.outlineVariant, blendTwenty.outlineVariant)
    }


    @Test
    fun brownOrangeLightMatchesMangayomiFlexThemeData() {
        val scheme = buildLightScheme(FlexSchemes[50].light, blendLevel = 0.10f)

        assertRoleSnapshot(
            mode = "light",
            scheme = scheme,
            expected = mapOf(
                "primary" to 0xFF8B5000,
                "onPrimary" to 0xFFFFFFFF,
                "primaryContainer" to 0xFFFFDCBE,
                "onPrimaryContainer" to 0xFF141310,
                "secondary" to 0xFFB6602F,
                "onSecondary" to 0xFFFFFFFF,
                "secondaryContainer" to 0xFFFFEDE6,
                "onSecondaryContainer" to 0xFF141414,
                "tertiary" to 0xFF466827,
                "onTertiary" to 0xFFFFFFFF,
                "tertiaryContainer" to 0xFFC6EF9F,
                "onTertiaryContainer" to 0xFF11140E,
                "surface" to 0xFFF8F5F2,
                "background" to 0xFFF8F5F2,
                "onBackground" to 0xFF1A1611,
                "onSurface" to 0xFF1A1611,
                "onSurfaceVariant" to 0xFF413D37,
                "surfaceDim" to 0xFFDDDAD7,
                "surfaceBright" to 0xFFF9F6F3,
                "surfaceContainerLowest" to 0xFFFAF8F5,
                "surfaceContainerLow" to 0xFFF4F1EE,
                "surfaceContainer" to 0xFFEFEDE9,
                "surfaceContainerHigh" to 0xFFE9E7E4,
                "surfaceContainerHighest" to 0xFFE3E1DE,
                "inverseSurface" to 0xFF2E2B28,
                "inverseOnSurface" to 0xFFF2EDE8,
                "inversePrimary" to 0xFFF5CC95,
                "outline" to 0xFF918E8B,
                "outlineVariant" to 0xFFCECCC9,
                "primaryFixed" to 0xFFEFDBBF,
                "primaryFixedDim" to 0xFFDDBB8C,
                "onPrimaryFixed" to 0xFF1D1100,
                "onPrimaryFixedVariant" to 0xFF301B00,
                "secondaryFixed" to 0xFFF2DCCE,
                "secondaryFixedDim" to 0xFFE3BAA3,
                "onSecondaryFixed" to 0xFF4A2713,
                "onSecondaryFixedVariant" to 0xFF572E16,
                "tertiaryFixed" to 0xFFD7E3CD,
                "tertiaryFixedDim" to 0xFFB4C8A2,
                "onTertiaryFixed" to 0xFF101809,
                "onTertiaryFixedVariant" to 0xFF19240E,
            ),
        )
        assertEquals(
            0xFFF1EAE1.toInt(),
            buildLightScaffoldColor(FlexSchemes[50].light, blendLevel = 0.10f).toArgb(),
            "light scaffold",
        )
    }

    @Test
    fun brownOrangeDarkMatchesMangayomiFlexThemeData() {
        val flex = FlexSchemes[50]
        val scheme = buildDarkScheme(
            palette = flex.dark,
            lightReference = flex.light,
            blendLevel = 0.10f,
        )

        assertRoleSnapshot(
            mode = "dark",
            scheme = scheme,
            expected = mapOf(
                "primary" to 0xFFFFB871,
                "onPrimary" to 0xFF000000,
                "primaryContainer" to 0xFF6A3C00,
                "onPrimaryContainer" to 0xFFF8F4EF,
                "secondary" to 0xFFFFDBCB,
                "onSecondary" to 0xFF000000,
                "secondaryContainer" to 0xFF552000,
                "onSecondaryContainer" to 0xFFF6F2EF,
                "tertiary" to 0xFFABD285,
                "onTertiary" to 0xFF000000,
                "tertiaryContainer" to 0xFF2F4F11,
                "onTertiaryContainer" to 0xFFF3F6F1,
                "surface" to 0xFF120F0C,
                "background" to 0xFF120F0C,
                "onBackground" to 0xFFF2EEEA,
                "onSurface" to 0xFFF2EEEA,
                "onSurfaceVariant" to 0xFFCCC8C5,
                "surfaceDim" to 0xFF100D0A,
                "surfaceBright" to 0xFF34312F,
                "surfaceContainerLowest" to 0xFF0B0805,
                "surfaceContainerLow" to 0xFF171512,
                "surfaceContainer" to 0xFF1E1B19,
                "surfaceContainerHigh" to 0xFF262320,
                "surfaceContainerHighest" to 0xFF302E2B,
                "inverseSurface" to 0xFFE9E6E3,
                "inverseOnSurface" to 0xFF322F2B,
                "inversePrimary" to 0xFF71583A,
                "outline" to 0xFF7C7A77,
                "outlineVariant" to 0xFF484643,
                "primaryFixed" to 0xFFEFDBBF,
                "primaryFixedDim" to 0xFFDDBB8C,
                "onPrimaryFixed" to 0xFF1D1100,
                "onPrimaryFixedVariant" to 0xFF301B00,
                "secondaryFixed" to 0xFFF2DCCE,
                "secondaryFixedDim" to 0xFFE3BAA3,
                "onSecondaryFixed" to 0xFF4A2713,
                "onSecondaryFixedVariant" to 0xFF572E16,
                "tertiaryFixed" to 0xFFD7E3CD,
                "tertiaryFixedDim" to 0xFFB4C8A2,
                "onTertiaryFixed" to 0xFF101809,
                "onTertiaryFixedVariant" to 0xFF19240E,
            ),
        )
        assertEquals(
            0xFF0B0805.toInt(),
            buildDarkScaffoldColor(FlexSchemes[50].dark, blendLevel = 0.10f, pureBlack = false).toArgb(),
            "dark scaffold",
        )
    }
    @Test
    fun pureBlackOnlyChangesMangayomiScaffold() {
        val palette = FlexSchemes[50].dark

        assertEquals(
            0xFF0B0805.toInt(),
            buildDarkScaffoldColor(palette, blendLevel = 0.10f, pureBlack = false).toArgb(),
            "normal scaffold",
        )
        assertEquals(
            Color.Black.toArgb(),
            buildDarkScaffoldColor(palette, blendLevel = 0.10f, pureBlack = true).toArgb(),
            "pure black scaffold",
        )
    }


    private fun assertRoleSnapshot(
        mode: String,
        scheme: ColorScheme,
        expected: Map<String, Long>,
    ) {
        val actual = mapOf(
            "primary" to scheme.primary,
            "onPrimary" to scheme.onPrimary,
            "primaryContainer" to scheme.primaryContainer,
            "onPrimaryContainer" to scheme.onPrimaryContainer,
            "secondary" to scheme.secondary,
            "onSecondary" to scheme.onSecondary,
            "secondaryContainer" to scheme.secondaryContainer,
            "onSecondaryContainer" to scheme.onSecondaryContainer,
            "tertiary" to scheme.tertiary,
            "onTertiary" to scheme.onTertiary,
            "tertiaryContainer" to scheme.tertiaryContainer,
            "onTertiaryContainer" to scheme.onTertiaryContainer,
            "surface" to scheme.surface,
            "background" to scheme.background,
            "onBackground" to scheme.onBackground,
            "onSurface" to scheme.onSurface,
            "onSurfaceVariant" to scheme.onSurfaceVariant,
            "surfaceDim" to scheme.surfaceDim,
            "surfaceBright" to scheme.surfaceBright,
            "surfaceContainerLowest" to scheme.surfaceContainerLowest,
            "surfaceContainerLow" to scheme.surfaceContainerLow,
            "surfaceContainer" to scheme.surfaceContainer,
            "surfaceContainerHigh" to scheme.surfaceContainerHigh,
            "surfaceContainerHighest" to scheme.surfaceContainerHighest,
            "inverseSurface" to scheme.inverseSurface,
            "inverseOnSurface" to scheme.inverseOnSurface,
            "inversePrimary" to scheme.inversePrimary,
            "outline" to scheme.outline,
            "outlineVariant" to scheme.outlineVariant,
            "primaryFixed" to scheme.primaryFixed,
            "primaryFixedDim" to scheme.primaryFixedDim,
            "onPrimaryFixed" to scheme.onPrimaryFixed,
            "onPrimaryFixedVariant" to scheme.onPrimaryFixedVariant,
            "secondaryFixed" to scheme.secondaryFixed,
            "secondaryFixedDim" to scheme.secondaryFixedDim,
            "onSecondaryFixed" to scheme.onSecondaryFixed,
            "onSecondaryFixedVariant" to scheme.onSecondaryFixedVariant,
            "tertiaryFixed" to scheme.tertiaryFixed,
            "tertiaryFixedDim" to scheme.tertiaryFixedDim,
            "onTertiaryFixed" to scheme.onTertiaryFixed,
            "onTertiaryFixedVariant" to scheme.onTertiaryFixedVariant,
        )

        assertEquals(expected.keys, actual.keys, "$mode role names")
        expected.forEach { (role, expectedArgb) ->
            val actualColor: Color = actual.getValue(role)
            assertEquals(expectedArgb.toInt(), actualColor.toArgb(), "$mode $role")
        }
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/tv/TvFocusEngineTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/tv/TvFocusEngineTest.kt) · test / fixture · 142 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
11: class TvFocusEngineTest {
14: fun resolveTvUiScaleOnTvUsesTvScaleWithClamping() {
33: fun resolveTvUiScaleOffTvUsesUiScaleOrAutoUiScale() {
42: fun resolveTvAnimeOnlyDefaultsToTrueOnTvAndFalseOffTv() {
53: fun shouldHideNavSectionForTvHidesMangaAndNovelOnlyWhenTvAnimeOnlyIsActive() {
73: fun handleTvDpadNavigationMovesBetweenContentAndRail() {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/tv/TvFocusEngineTest.kt) · SHA-256 `245237dfb8b96a4dd4bd8e745f03b3487d06d0563fe8d1c3066f24b8d142e1d6`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.tv

import androidx.compose.ui.input.key.Key
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.ui.navigation.NavSection
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue

class TvFocusEngineTest {

    @Test
    fun resolveTvUiScaleOnTvUsesTvScaleWithClamping() {
        // Default null tvUiScale -> 1.0
        val defaultSettings = DbSettings(tvUiScale = null, uiScale = 1.4)
        assertEquals(1.0f, resolveTvUiScale(isTv = true, defaultSettings))

        // Explicit valid tvUiScale
        val customSettings = DbSettings(tvUiScale = 1.15, uiScale = 1.0)
        assertEquals(1.15f, resolveTvUiScale(isTv = true, customSettings))

        // Lower bound clamp (0.85)
        val lowSettings = DbSettings(tvUiScale = 0.50)
        assertEquals(0.85f, resolveTvUiScale(isTv = true, lowSettings))

        // Upper bound clamp (1.25)
        val highSettings = DbSettings(tvUiScale = 1.50)
        assertEquals(1.25f, resolveTvUiScale(isTv = true, highSettings))
    }

    @Test
    fun resolveTvUiScaleOffTvUsesUiScaleOrAutoUiScale() {
        val normalSettings = DbSettings(tvUiScale = 1.20, uiScale = 1.35, autoUiScale = false)
        assertEquals(1.35f, resolveTvUiScale(isTv = false, normalSettings))

        val autoSettings = DbSettings(tvUiScale = 1.20, uiScale = 1.35, autoUiScale = true)
        assertEquals(1.0f, resolveTvUiScale(isTv = false, autoSettings))
    }

    @Test
    fun resolveTvAnimeOnlyDefaultsToTrueOnTvAndFalseOffTv() {
        assertTrue(resolveTvAnimeOnly(isTv = true, animeOnlyTvMode = null))
        assertTrue(resolveTvAnimeOnly(isTv = true, animeOnlyTvMode = true))
        assertFalse(resolveTvAnimeOnly(isTv = true, animeOnlyTvMode = false))

        assertFalse(resolveTvAnimeOnly(isTv = false, animeOnlyTvMode = null))
        assertFalse(resolveTvAnimeOnly(isTv = false, animeOnlyTvMode = true))
        assertFalse(resolveTvAnimeOnly(isTv = false, animeOnlyTvMode = false))
    }

    @Test
    fun shouldHideNavSectionForTvHidesMangaAndNovelOnlyWhenTvAnimeOnlyIsActive() {
        // On TV with anime-only mode
        assertTrue(shouldHideNavSectionForTv(NavSection.MangaLibrary, isTv = true, animeOnlyTvMode = true))
        assertTrue(shouldHideNavSectionForTv(NavSection.NovelLibrary, isTv = true, animeOnlyTvMode = true))
        assertFalse(shouldHideNavSectionForTv(NavSection.AnimeLibrary, isTv = true, animeOnlyTvMode = true))
        assertFalse(shouldHideNavSectionForTv(NavSection.Browse, isTv = true, animeOnlyTvMode = true))
        assertFalse(shouldHideNavSectionForTv(NavSection.Updates, isTv = true, animeOnlyTvMode = true))
        assertFalse(shouldHideNavSectionForTv(NavSection.History, isTv = true, animeOnlyTvMode = true))
        assertFalse(shouldHideNavSectionForTv(NavSection.More, isTv = true, animeOnlyTvMode = true))

        // On TV with anime-only mode explicitly disabled
        assertFalse(shouldHideNavSectionForTv(NavSection.MangaLibrary, isTv = true, animeOnlyTvMode = false))
        assertFalse(shouldHideNavSectionForTv(NavSection.NovelLibrary, isTv = true, animeOnlyTvMode = false))

        // Off TV
        assertFalse(shouldHideNavSectionForTv(NavSection.MangaLibrary, isTv = false, animeOnlyTvMode = true))
        assertFalse(shouldHideNavSectionForTv(NavSection.NovelLibrary, isTv = false, animeOnlyTvMode = true))
    }

    @Test
    fun handleTvDpadNavigationMovesBetweenContentAndRail() {
        var railRequested = false
        var contentRequested = false

        // Ignored when not KeyDown
        val upIgnored = handleTvDpadNavigation(
            key = Key.DirectionLeft,
            isKeyDown = false,
            railHasFocus = false,
            moveLeft = { false },
            moveRight = { false },
            requestRailFocus = { railRequested = true },
            requestContentFocus = { contentRequested = true },
        )
        assertFalse(upIgnored)
        assertFalse(railRequested)

        // In content: Left at leftmost boundary (moveLeft -> false) requests rail focus
        val leftConsumed = handleTvDpadNavigation(
            key = Key.DirectionLeft,
            isKeyDown = true,
            railHasFocus = false,
            moveLeft = { false },
            moveRight = { false },
            requestRailFocus = { railRequested = true },
            requestContentFocus = { contentRequested = true },
        )
        assertTrue(leftConsumed)
        assertTrue(railRequested)

        // In content: Left when not at leftmost boundary (moveLeft -> true) does not request rail focus
        railRequested = false
        val leftNormalConsumed = handleTvDpadNavigation(
            key = Key.DirectionLeft,
            isKeyDown = true,
            railHasFocus = false,
            moveLeft = { true },
            moveRight = { false },
            requestRailFocus = { railRequested = true },
            requestContentFocus = { contentRequested = true },
        )
        assertTrue(leftNormalConsumed)
        assertFalse(railRequested)

        // In rail: Right requests content focus
        val rightConsumed = handleTvDpadNavigation(
            key = Key.DirectionRight,
            isKeyDown = true,
            railHasFocus = true,
            moveLeft = { false },
            moveRight = { false },
            requestRailFocus = { railRequested = true },
            requestContentFocus = { contentRequested = true },
        )
        assertTrue(rightConsumed)
        assertTrue(contentRequested)

        // Other keys (e.g. DirectionUp, DirectionDown) are not handled by this crossing handler
        val upResult = handleTvDpadNavigation(
            key = Key.DirectionUp,
            isKeyDown = true,
            railHasFocus = false,
            moveLeft = { false },
            moveRight = { false },
            requestRailFocus = { railRequested = true },
            requestContentFocus = { contentRequested = true },
        )
        assertFalse(upResult)
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/util/HtmlEntitiesTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/util/HtmlEntitiesTest.kt) · test / fixture · 24 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
6: class HtmlEntitiesTest {
8: fun decodesNamedEntitiesCaseInsensitively() {
14: fun decodesDecimalHexAndSupplementaryCodePoints() {
20: fun decodesInOnePassAndKeepsUnknownOrInvalidEntities() {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/util/HtmlEntitiesTest.kt) · SHA-256 `5056796cda9a56d30e2553bbf82b7ab0a7fd17ca91d49d5fca32ccb7f11c6ae6`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.util

import kotlin.test.Test
import kotlin.test.assertEquals

class HtmlEntitiesTest {
    @Test
    fun decodesNamedEntitiesCaseInsensitively() {
        assertEquals("Tom & Jerry \"<b>\" it's © — …", decodeHtmlEntities("Tom &amp; Jerry &quot;&lt;b&gt;&quot; it&apos;s &COPY; &mdash; &hellip;"))
        assertEquals("a b", decodeHtmlEntities("a&nbsp;b"))
    }

    @Test
    fun decodesDecimalHexAndSupplementaryCodePoints() {
        assertEquals("it's it's", decodeHtmlEntities("it&#039;s it&#x27;s"))
        assertEquals("A😀", decodeHtmlEntities("&#X41;&#128512;"))
    }

    @Test
    fun decodesInOnePassAndKeepsUnknownOrInvalidEntities() {
        assertEquals("&quot;", decodeHtmlEntities("&amp;quot;"))
        assertEquals("&unknown; &#1114112; & alone", decodeHtmlEntities("&unknown; &#1114112; & alone"))
    }
}
```
[complete-source-end]: #

## `composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/ui/SecureScreen.desktop.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/ui/SecureScreen.desktop.kt) · implementation · 8 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.

Declaration checklist (source line numbers):
```text
8: internal actual fun SecureScreenEffect(secure: Boolean) = Unit
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/ui/SecureScreen.desktop.kt) · SHA-256 `b8f2ed00d84136ab8657d31164473fa2d21734a7cb163c5ae0af2e2871b7fae9`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui

import androidx.compose.runtime.Composable

// Excluding a window from capture needs NSWindow.sharingType / SetWindowDisplayAffinity, which AWT
// does not expose and Yokan ships no native bridge (JNA) for.
@Composable
internal actual fun SecureScreenEffect(secure: Boolean) = Unit
```
[complete-source-end]: #

## `composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/ui/components/Scrollbar.desktop.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/ui/components/Scrollbar.desktop.kt) · implementation · 79 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
28: private fun yokanScrollbarStyle(): ScrollbarStyle {
43: internal actual fun BoxScope.PlatformVerticalScrollbar(state: LazyListState) {
56: internal actual fun BoxScope.PlatformVerticalScrollbar(state: LazyGridState) {
69: internal actual fun BoxScope.PlatformVerticalScrollbar(state: ScrollState) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/ui/components/Scrollbar.desktop.kt) · SHA-256 `5efdb6754e8faf15d72a1f7d700b245cab56c81fe84e48c6e0a01e05926411d6`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.components

import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.ScrollbarStyle
import androidx.compose.foundation.VerticalScrollbar
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.grid.LazyGridState
import androidx.compose.foundation.rememberScrollbarAdapter
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp

/**
 * An always-visible, draggable scrollbar style. The Compose Desktop default
 * fades the thumb out when idle, which made it hard to tell a list was
 * scrollable or to grab the thumb. We keep the thumb visible at a steady
 * alpha and darken it on hover so it always reads as a draggable control.
 */
@Composable
private fun yokanScrollbarStyle(): ScrollbarStyle {
    val base = MaterialTheme.colorScheme.onSurface
    return remember(base) {
        ScrollbarStyle(
            minimalHeight = 32.dp,
            thickness = 10.dp,
            shape = RoundedCornerShape(5.dp),
            hoverDurationMillis = 200,
            unhoverColor = base.copy(alpha = 0.32f),
            hoverColor = base.copy(alpha = 0.60f),
        )
    }
}

@Composable
internal actual fun BoxScope.PlatformVerticalScrollbar(state: LazyListState) {
    VerticalScrollbar(
        adapter = rememberScrollbarAdapter(state),
        style = yokanScrollbarStyle(),
        modifier = Modifier
            .align(Alignment.CenterEnd)
            .fillMaxHeight()
            .padding(vertical = 2.dp)
            .width(10.dp),
    )
}

@Composable
internal actual fun BoxScope.PlatformVerticalScrollbar(state: LazyGridState) {
    VerticalScrollbar(
        adapter = rememberScrollbarAdapter(state),
        style = yokanScrollbarStyle(),
        modifier = Modifier
            .align(Alignment.CenterEnd)
            .fillMaxHeight()
            .padding(vertical = 2.dp)
            .width(10.dp),
    )
}

@Composable
internal actual fun BoxScope.PlatformVerticalScrollbar(state: ScrollState) {
    VerticalScrollbar(
        adapter = rememberScrollbarAdapter(state),
        style = yokanScrollbarStyle(),
        modifier = Modifier
            .align(Alignment.CenterEnd)
            .fillMaxHeight()
            .padding(vertical = 2.dp)
            .width(10.dp),
    )
}
```
[complete-source-end]: #

## `composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/ui/image/AvifImageDecoder.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/ui/image/AvifImageDecoder.kt) · implementation · 131 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
35: internal class AvifImageDecoder(
39: override suspend fun decode(): DecodeResult = decodePermit.withPermit {
99: class Factory : Decoder.Factory {
100: override fun create(result: SourceFetchResult, options: Options, imageLoader: ImageLoader): Decoder? =
118: internal fun isAvifSource(source: BufferedSource): Boolean {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/ui/image/AvifImageDecoder.kt) · SHA-256 `e1bee64d229cd41a855827bd87e31301b9b94ee07e6c6298e5d7b669d7864b02`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.image

import coil3.ImageLoader
import coil3.asImage
import coil3.decode.DecodeResult
import coil3.decode.DecodeUtils
import coil3.decode.Decoder
import coil3.decode.ImageSource
import coil3.fetch.SourceFetchResult
import coil3.request.Options
import coil3.request.maxBitmapSize
import coil3.size.Scale
import coil3.size.isOriginal
import coil3.size.pxOrElse
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withPermit
import kotlinx.coroutines.withContext
import okio.BufferedSource
import org.glavo.avif.AvifImageReaderFactory
import org.glavo.avif.AvifPixelFormat
import org.glavo.avif.av1.Av1DecoderConfig
import org.jetbrains.skia.Bitmap
import org.jetbrains.skia.Canvas
import org.jetbrains.skia.ColorAlphaType
import org.jetbrains.skia.ColorType
import org.jetbrains.skia.Image
import org.jetbrains.skia.ImageInfo
import org.jetbrains.skia.Rect
import java.io.IOException
import kotlin.coroutines.coroutineContext

/** First-frame AVIF decoding for reader pages, covers, local files and cached responses. */
internal class AvifImageDecoder(
    private val source: ImageSource,
    private val options: Options,
) : Decoder {
    override suspend fun decode(): DecodeResult = decodePermit.withPermit {
        withContext(Dispatchers.Default) {
            coroutineContext.ensureActive()
            val bytes = source.source().use {
                if (it.request(MAX_INPUT_BYTES + 1)) throw IOException("AVIF exceeds encoded image size limit")
                it.readByteArray()
            }
            val frame = readerFactory.open(bytes).use { reader ->
                val info = reader.info()
                if (info.width().toLong() * info.height() > MAX_PIXELS) {
                    throw IOException("AVIF exceeds decoded image size limit")
                }
                requireNotNull(reader.readFrame()) { "AVIF contains no image frame" }
            }
            coroutineContext.ensureActive()
            val width = frame.width()
            val height = frame.height()
            val pixels = frame.intPixelBuffer()
            val rgba = ByteArray(width * height * 4)
            repeat(width * height) { index ->
                val argb = pixels.get(index)
                val offset = index * 4
                rgba[offset] = (argb ushr 16).toByte()
                rgba[offset + 1] = (argb ushr 8).toByte()
                rgba[offset + 2] = argb.toByte()
                rgba[offset + 3] = (argb ushr 24).toByte()
            }
            val undefinedDimension = if (options.scale == Scale.FIT) Int.MAX_VALUE else 0
            val targetWidth = if (options.size.isOriginal) width else options.size.width.pxOrElse { undefinedDimension }
            val targetHeight = if (options.size.isOriginal) height else options.size.height.pxOrElse { undefinedDimension }
            val multiplier = DecodeUtils.computeSizeMultiplier(
                width, height, targetWidth, targetHeight, options.scale, options.maxBitmapSize,
            ).coerceAtMost(1.0)
            val outWidth = (width * multiplier).toInt().coerceAtLeast(1)
            val outHeight = (height * multiplier).toInt().coerceAtLeast(1)
            val output = Bitmap()
            try {
                Bitmap().use { original ->
                    check(original.installPixels(
                        ImageInfo(width, height, ColorType.RGBA_8888, ColorAlphaType.UNPREMUL),
                        rgba, width * 4,
                    )) { "Unable to allocate AVIF pixels" }
                    check(output.allocN32Pixels(outWidth, outHeight)) { "Unable to allocate AVIF bitmap" }
                    output.erase(0) // Source-over must preserve alpha over a transparent destination.
                    Image.makeFromBitmap(original).use { image ->
                        Canvas(output).use { canvas ->
                            canvas.drawImageRect(image, Rect.makeWH(outWidth.toFloat(), outHeight.toFloat()))
                        }
                    }
                }
                coroutineContext.ensureActive()
                output.setImmutable()
                DecodeResult(output.asImage(), outWidth < width || outHeight < height)
            } catch (failure: Throwable) {
                output.close()
                throw failure
            }
        }
    }

    class Factory : Decoder.Factory {
        override fun create(result: SourceFetchResult, options: Options, imageLoader: ImageLoader): Decoder? =
            if (isAvifSource(result.source.source())) AvifImageDecoder(result.source, options) else null
    }

    private companion object {
        // Serialize expensive AV1 reconstruction even when several pages are prefetched.
        val decodePermit = Semaphore(1)
        const val MAX_INPUT_BYTES = 64L * 1024 * 1024
        const val MAX_PIXELS = 32L * 1024 * 1024
        val readerFactory = AvifImageReaderFactory.DEFAULT
            .withOutputPixelFormat(AvifPixelFormat.ARGB_8888)
            .withInputSizeLimit(MAX_INPUT_BYTES)
            .withMetadataSizeLimit(4L * 1024 * 1024)
            .withAv1DecoderConfig(Av1DecoderConfig.DEFAULT.withFrameSizeLimit(MAX_PIXELS))
    }
}

/** Sniff bytes, not extensions/MIME: sources and offline caches often omit both. */
internal fun isAvifSource(source: BufferedSource): Boolean {
    val peek = source.peek()
    if (!peek.request(16)) return false
    val boxSize = peek.readInt().toLong() and 0xffffffffL
    if (peek.readUtf8(4) != "ftyp" || boxSize < 16 || boxSize > 4096) return false
    val majorBrand = peek.readUtf8(4)
    peek.skip(4) // minor version is not a compatible brand
    if (majorBrand == "avif" || majorBrand == "avis") return true
    repeat(((boxSize - 16) / 4).toInt()) {
        if (!peek.request(4)) return false
        if (peek.readUtf8(4) in setOf("avif", "avis")) return true
    }
    return false
}
```
[complete-source-end]: #

## `composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/ui/image/PlatformImageDecoders.desktop.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/ui/image/PlatformImageDecoders.desktop.kt) · implementation · 7 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
5: internal actual fun addPlatformImageDecoders(components: ComponentRegistry.Builder) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/ui/image/PlatformImageDecoders.desktop.kt) · SHA-256 `522f221cd5a8e27b266caf58714b14684c1835d222a06b327cc1f84fba8a8f4a`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.image

import coil3.ComponentRegistry

internal actual fun addPlatformImageDecoders(components: ComponentRegistry.Builder) {
    components.add(AvifImageDecoder.Factory())
}
```
[complete-source-end]: #

## `composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/ui/navigation/PlatformNavigation.desktop.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/ui/navigation/PlatformNavigation.desktop.kt) · implementation · 4 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
3: internal actual fun usesCupertinoPageTransitions(): Boolean =
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/ui/navigation/PlatformNavigation.desktop.kt) · SHA-256 `4fb03353b5524d0f140a7ac960040517ccbc8db53dcf271b02b486ed9ce468cc`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.navigation

internal actual fun usesCupertinoPageTransitions(): Boolean =
    System.getProperty("os.name").startsWith("Mac", ignoreCase = true)
```
[complete-source-end]: #

## `composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/ui/theme/MaterialYou.desktop.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/ui/theme/MaterialYou.desktop.kt) · implementation · 9 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
7: actual fun rememberMaterialYouScheme(isDark: Boolean): ColorScheme? = null
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/ui/theme/MaterialYou.desktop.kt) · SHA-256 `18fc2a987430b73c874cae9917bbbe37f9ee7b735b107faf773c88df1ba30aa6`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.theme

import androidx.compose.material3.ColorScheme
import androidx.compose.runtime.Composable

@Composable
actual fun rememberMaterialYouScheme(isDark: Boolean): ColorScheme? = null

actual val materialYouAvailable: Boolean = false
```
[complete-source-end]: #

## `composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/ui/theme/SystemBarTheme.desktop.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/ui/theme/SystemBarTheme.desktop.kt) · implementation · 3 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
3: actual fun applySystemBarTheme(isDark: Boolean) = Unit
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/ui/theme/SystemBarTheme.desktop.kt) · SHA-256 `17941a7e2d5fad634ba283190f7e1ac657b8549b70d61f5dbd45223ccec86b56`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.theme

actual fun applySystemBarTheme(isDark: Boolean) = Unit
```
[complete-source-end]: #

## `composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/HardcodedUiStringsTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/HardcodedUiStringsTest.kt) · test / fixture · 31 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
12: class HardcodedUiStringsTest {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/HardcodedUiStringsTest.kt) · SHA-256 `dbbd20542c8833c58c5335c0357d775eb1a3cf5af25e455209315df054a9c8a1`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui

import java.io.File
import kotlin.test.Test
import kotlin.test.assertTrue

/**
 * Ratchet for hardcoded user-visible text: per-file counts under `ui/` may only go down.
 * New text belongs in `composeResources` (`stringResource(Res.string.…)`); after moving text,
 * lower the file's count in `src/desktopTest/resources/hardcoded-ui-strings.txt`.
 */
class HardcodedUiStringsTest {
    private val uiRoot = File("src/commonMain/kotlin/eu/friedcutlet/yokan/ui")
    private val baselineFile = File("src/desktopTest/resources/hardcoded-ui-strings.txt")
    private val literal = Regex("""\bText\(\s*"[A-Za-z]|\b(?:title|label|text|subtitle|message|contentDescription|placeholder)\s*=\s*"[A-Za-z]""")

    @Test fun hardcodedUiStringsOnlyDecrease() {
        val baseline = baselineFile.readLines()
            .filter { it.isNotBlank() && !it.startsWith("#") }
            .associate { line -> line.substringBeforeLast(' ') to line.substringAfterLast(' ').toInt() }
        val actual = uiRoot.walkTopDown()
            .filter { it.extension == "kt" }
            .associate { file -> file.relativeTo(uiRoot).invariantSeparatorsPath to file.readLines().sumOf { literal.findAll(it).count() } }
            .filterValues { it > 0 }

        val grown = actual.filter { (path, count) -> count > (baseline[path] ?: 0) }
        assertTrue(grown.isEmpty(), "New hardcoded UI strings (move them to composeResources): $grown")
        val shrunk = baseline.filter { (path, count) -> (actual[path] ?: 0) < count }
        assertTrue(shrunk.isEmpty(), "Hardcoded UI strings went down; lower these counts in ${baselineFile.path}: $shrunk")
    }
}
```
[complete-source-end]: #

## `composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/image/AvifImageDecoderTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/image/AvifImageDecoderTest.kt) · test / fixture · 130 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
20: class AvifImageDecoderTest {
22: fun decodesAvifPageBytes() = runBlocking<Unit> {
38: fun decodesExtensionlessLocalReaderPageAndHonorsRequestedSize() = runBlocking<Unit> {
59: fun decodesFirstFrameOfAvifSequence() = runBlocking<Unit> {
73: fun preservesAvifTransparency() = runBlocking<Unit> {
86: fun corruptAvifReturnsImageErrorAndDoesNotBlockNextDecode() = runBlocking<Unit> {
100: fun sniffsCompatibleBrandsWithoutConsumingSource() {
109: fun leavesPngDecodingToStandardDecoder() = runBlocking<Unit> {
124: private fun imageLoader() = ImageLoader.Builder(PlatformContext.INSTANCE)
128: private fun fixture(name: String): ByteArray =
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/image/AvifImageDecoderTest.kt) · SHA-256 `fe007a20adf0ac144a19586da08deb9a8bff4a97c88863e5a3415d4133aea3cb`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.image

import coil3.ImageLoader
import coil3.PlatformContext
import coil3.BitmapImage
import coil3.request.ErrorResult
import coil3.request.ImageRequest
import coil3.request.SuccessResult
import eu.friedcutlet.yokan.database.DbPageUrl
import eu.friedcutlet.yokan.ui.screens.reader.readerPageData
import kotlinx.coroutines.runBlocking
import okio.Buffer
import java.nio.file.Files
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertIs
import kotlin.test.assertTrue

class AvifImageDecoderTest {
    @Test
    fun decodesAvifPageBytes() = runBlocking<Unit> {
        val loader = imageLoader()
        try {
            val bytes = requireNotNull(javaClass.getResourceAsStream("/images/white_1x1.avif")).use { it.readBytes() }
            val result = loader.execute(ImageRequest.Builder(PlatformContext.INSTANCE).data(bytes).build())
            val success = assertIs<SuccessResult>(result)
            assertEquals(1, success.image.width)
            assertEquals(1, success.image.height)
            val color = assertIs<BitmapImage>(success.image).bitmap.getColor(0, 0)
            assertTrue((color ushr 24) == 255 && (color and 0xff) >= 250)
        } finally {
            loader.shutdown()
        }
    }

    @Test
    fun decodesExtensionlessLocalReaderPageAndHonorsRequestedSize() = runBlocking<Unit> {
        val file = Files.createTempFile("reader-avif-", ".page")
        val loader = imageLoader()
        try {
            Files.write(file, fixture("draw_points_idat.avif"))
            val result = loader.execute(ImageRequest.Builder(PlatformContext.INSTANCE)
                .readerPageData(DbPageUrl(url = file.toUri().toString()), chapterId = 1)
                .size(11, 11)
                .scale(coil3.size.Scale.FIT)
                .build())
            val success = assertIs<SuccessResult>(result)
            assertEquals(11, success.image.width)
            assertEquals(3, success.image.height)
            assertTrue(success.isSampled)
        } finally {
            loader.shutdown()
            Files.deleteIfExists(file)
        }
    }

    @Test
    fun decodesFirstFrameOfAvifSequence() = runBlocking<Unit> {
        val loader = imageLoader()
        try {
            val result = loader.execute(ImageRequest.Builder(PlatformContext.INSTANCE)
                .data(fixture("colors-animated-8bpc.avif")).build())
            val success = assertIs<SuccessResult>(result)
            assertEquals(150, success.image.width)
            assertEquals(150, success.image.height)
        } finally {
            loader.shutdown()
        }
    }

    @Test
    fun preservesAvifTransparency() = runBlocking<Unit> {
        val loader = imageLoader()
        try {
            val success = assertIs<SuccessResult>(loader.execute(ImageRequest.Builder(PlatformContext.INSTANCE)
                .data(fixture("colors-animated-8bpc-alpha-exif-xmp.avif")).build()))
            val bitmap = assertIs<BitmapImage>(success.image).bitmap
            assertEquals(0x80000000.toInt(), bitmap.getColor(0, 0))
        } finally {
            loader.shutdown()
        }
    }

    @Test
    fun corruptAvifReturnsImageErrorAndDoesNotBlockNextDecode() = runBlocking<Unit> {
        val loader = imageLoader()
        try {
            val bytes = fixture("white_1x1.avif")
            assertIs<ErrorResult>(loader.execute(ImageRequest.Builder(PlatformContext.INSTANCE)
                .data(bytes.copyOf(32)).build()))
            assertIs<SuccessResult>(loader.execute(ImageRequest.Builder(PlatformContext.INSTANCE)
                .data(bytes).build()))
        } finally {
            loader.shutdown()
        }
    }

    @Test
    fun sniffsCompatibleBrandsWithoutConsumingSource() {
        val source = Buffer().writeInt(24).writeUtf8("ftypmif1").writeInt(0).writeUtf8("miafavif")
        assertTrue(isAvifSource(source))
        assertEquals(24, source.readInt())
        assertFalse(isAvifSource(Buffer().writeInt(16).writeUtf8("ftypheicavif")))
        assertFalse(isAvifSource(Buffer().writeUtf8("not an image")))
    }

    @Test
    fun leavesPngDecodingToStandardDecoder() = runBlocking<Unit> {
        val bytes = java.io.ByteArrayOutputStream().use { output ->
            javax.imageio.ImageIO.write(java.awt.image.BufferedImage(7, 5, java.awt.image.BufferedImage.TYPE_INT_RGB), "png", output)
            output.toByteArray()
        }
        val loader = imageLoader()
        try {
            val success = assertIs<SuccessResult>(loader.execute(ImageRequest.Builder(PlatformContext.INSTANCE).data(bytes).build()))
            assertEquals(7, success.image.width)
            assertEquals(5, success.image.height)
        } finally {
            loader.shutdown()
        }
    }

    private fun imageLoader() = ImageLoader.Builder(PlatformContext.INSTANCE)
        .components { addPlatformImageDecoders(this) }
        .build()

    private fun fixture(name: String): ByteArray =
        requireNotNull(javaClass.getResourceAsStream("/images/$name")).use { it.readBytes() }
}
```
[complete-source-end]: #

## `composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/image/ImageDataSaverInterceptorTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/image/ImageDataSaverInterceptorTest.kt) · test / fixture · 101 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
19: class ImageDataSaverInterceptorTest {
71: suspend fun sent(request: ImageRequest): String {
84: private fun request() = ImageRequest.Builder(PlatformContext.INSTANCE).data(original).build()
85: private fun database() = InMemoryYokanDatabase(emptySnapshot()).also { db ->
88: private fun interceptor(db: YokanDatabase): ImageDataSaverInterceptor {
92: private class Chain(
97: override fun withRequest(request: ImageRequest) = Chain(request, size, action)
98: override fun withSize(size: Size) = Chain(request, size, action)
99: override suspend fun proceed() = action(request)
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/image/ImageDataSaverInterceptorTest.kt) · SHA-256 `4bdcfb9a6dce0b19dd604e90911340e33abc2e08238bca82fa9209f76b50454f`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.image

import coil3.ColorImage
import coil3.PlatformContext
import coil3.decode.DataSource
import coil3.intercept.Interceptor
import coil3.network.NetworkHeaders
import coil3.network.httpHeaders
import coil3.request.*
import coil3.size.Size
import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.services.download.ImageDataSaver
import eu.friedcutlet.yokan.services.http.*
import eu.friedcutlet.yokan.services.http.cookies.CookieJar
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.test.runTest
import kotlin.test.*

class ImageDataSaverInterceptorTest {
    @Test fun rewritesTransportButKeepsReaderCacheIdentityAndOriginalProgressUrl() = runTest {
        val db = database()
        val calls = mutableListOf<ImageRequest>()
        val request = request().newBuilder().memoryCacheKey("chapter-1").diskCacheKey("chapter-1").memoryCacheKeyExtra("borderCrop", "true").build()
        val result = interceptor(db).intercept(Chain(request) { sent ->
            calls += sent
            SuccessResult(ColorImage(), sent, DataSource.NETWORK)
        })
        assertIs<SuccessResult>(result)
        val sent = calls.single()
        assertTrue(sent.data.toString().startsWith("https://wsrv.nl/"))
        assertEquals(request.data.toString(), sent.httpHeaders[OriginalImageProgressHeader])
        assertTrue(sent.memoryCacheKey.orEmpty().startsWith("chapter-1#saver-v1"))
        assertEquals("true", sent.memoryCacheKeyExtras["borderCrop"])
        assertNotEquals(request.diskCacheKey, sent.diskCacheKey)
    }

    @Test fun providerFailureRetriesOriginalWithItsOwnHeadersAndCacheKeys() = runTest {
        val db = database()
        val calls = mutableListOf<ImageRequest>()
        val request = request().newBuilder().httpHeaders(NetworkHeaders.Builder().set("Referer", "https://source.example.org").build()).build()
        val interceptor = interceptor(db)
        val chain = Chain(request) { sent ->
            calls += sent
            if (sent.data != request.data) ErrorResult(null, sent, IllegalStateException("offline")) else SuccessResult(ColorImage(), sent, DataSource.NETWORK)
        }
        assertIs<SuccessResult>(interceptor.intercept(chain))
        assertEquals(2, calls.size)
        assertEquals(request, calls.last())
        calls.clear()
        assertIs<SuccessResult>(interceptor.intercept(chain))
        assertEquals(listOf(request), calls)
    }

    @Test fun cancellationDoesNotIssueAnOriginalRetry() = runTest {
        var calls = 0
        assertFailsWith<CancellationException> {
            interceptor(database()).intercept(Chain(request()) { sent ->
                calls++
                ErrorResult(null, sent, CancellationException("retired"))
            })
        }
        assertEquals(1, calls)
    }

    @Test fun chapterAndCoverSourcesHonorExclusionsWithoutLeakingUnknownImages() = runTest {
        val db = database()
        db.upsertManga(DbManga(id = 1, sourceId = 7, imageUrl = original))
        db.upsertChapter(DbChapter(id = 1, mangaId = 1))
        db.updateSettings(db.settings().let { it.copy(features = it.features.copy(imageDataSaver = it.features.imageDataSaver.copy(excludedSourceIds = setOf(7)))) })
        val interceptor = interceptor(db)
        suspend fun sent(request: ImageRequest): String {
            var url = ""
            interceptor.intercept(Chain(request) { image -> url = image.data.toString(); SuccessResult(ColorImage(), image, DataSource.NETWORK) })
            return url
        }
        assertEquals(original, sent(request()))
        assertEquals(original, sent(request().newBuilder().apply { extras[ImageChapterIdExtra] = 1L }.build()))
        assertEquals("https://unknown.example.org/a.png", sent(request().newBuilder().data("https://unknown.example.org/a.png").build()))
        db.upsertManga(requireNotNull(db.manga(1)).copy(sourceId = 8))
        assertTrue(sent(request()).startsWith("https://wsrv.nl/"))
    }

    private val original = "https://images.example.org/page.png"
    private fun request() = ImageRequest.Builder(PlatformContext.INSTANCE).data(original).build()
    private fun database() = InMemoryYokanDatabase(emptySnapshot()).also { db ->
        db.updateSettings(db.settings().let { it.copy(features = it.features.copy(imageDataSaver = DbImageDataSaver(provider = ImageSaverProvider.Wsrv))) })
    }
    private fun interceptor(db: YokanDatabase): ImageDataSaverInterceptor {
        val http = HttpService { error("Unexpected resolver HTTP") }
        return ImageDataSaverInterceptor(ImageDataSaver(http, CookieJar(db)), db)
    }
    private class Chain(
        override val request: ImageRequest,
        override val size: Size = Size.ORIGINAL,
        private val action: suspend (ImageRequest) -> ImageResult,
    ) : Interceptor.Chain {
        override fun withRequest(request: ImageRequest) = Chain(request, size, action)
        override fun withSize(size: Size) = Chain(request, size, action)
        override suspend fun proceed() = action(request)
    }
}
```
[complete-source-end]: #

## `composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/navigation/NavigationStackTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/navigation/NavigationStackTest.kt) · test / fixture · 206 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
27: class NavigationStackTest {
29: fun ordinaryBackAndSameDestinationReplacementDisposeOutgoingPages() = runTest {
49: fun navigationDuringSettleCannotPopTheReplacementPage() = runTest {
64: fun verticalEdgeScrollDoesNotTurnIntoBackNavigation() = runTest {
79: fun dragDoesNotRecomposePagesAndPreviewSurvivesCompletedPop() = runTest {
99: fun rootPreviewSurvivesPopAndInteriorSwipeDoesNotNavigate() = runTest {
121: fun shortSlowSwipeCancelsAndNextSwipeCanComplete() = runTest {
140: private class Fixture(private val test: TestScope, nested: Boolean) {
167: private fun Page(id: Long) {
176: fun frame() = ui {
183: fun pointer(type: PointerEventType, x: Float, y: Float = 200f) = ui {
189: fun settle() { repeat(90) { frame() } }
190: fun replaceTop() = ui {
194: fun back() = ui { direction.value = -1; stack.value = stack.value.dropLast(1) }
195: fun close() = ui { scene.close() }
199: private fun <T> ui(block: () -> T): T {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/navigation/NavigationStackTest.kt) · SHA-256 `3f8395a1647e76fce2ca96fbf9719a14b9b51de77ee55d71a81eaa73b7734cbc`.

### Complete file

```kotlin
@file:OptIn(androidx.compose.ui.ExperimentalComposeUiApi::class, kotlinx.coroutines.ExperimentalCoroutinesApi::class)

package eu.friedcutlet.yokan.ui.navigation

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveableStateHolder
import androidx.compose.ui.ImageComposeScene
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.PointerEventType
import androidx.compose.ui.input.pointer.PointerType
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runTest
import java.util.concurrent.FutureTask
import javax.swing.SwingUtilities
import kotlin.test.Test
import kotlin.test.assertEquals

class NavigationStackTest {
    @Test
    fun ordinaryBackAndSameDestinationReplacementDisposeOutgoingPages() = runTest {
        val f = Fixture(this, nested = true)
        try {
            f.frame()
            f.replaceTop()
            repeat(4) { f.frame() }
            assertEquals(1, f.mounts[3L])
            assertEquals(1, f.disposals[2L], "Same-destination replacement must not retain the old page for an animation")
            f.back()
            f.settle()
            assertEquals(1, f.mounts[1L])
            assertEquals(1, f.disposals[3L])
            f.back()
            f.settle()
            assertEquals(1, f.mounts[0L])
            assertEquals(1, f.disposals[1L])
        } finally { f.close() }
    }

    @Test
    fun navigationDuringSettleCannotPopTheReplacementPage() = runTest {
        val f = Fixture(this, nested = true)
        try {
            f.frame()
            f.pointer(PointerEventType.Press, 4f)
            f.pointer(PointerEventType.Move, 260f)
            f.pointer(PointerEventType.Release, 260f)
            f.replaceTop()
            f.settle()
            assertEquals(0, f.pops)
            assertEquals(3L, f.stack.value.last().id)
        } finally { f.close() }
    }

    @Test
    fun verticalEdgeScrollDoesNotTurnIntoBackNavigation() = runTest {
        val f = Fixture(this, nested = false)
        try {
            f.frame()
            f.pointer(PointerEventType.Press, 4f)
            f.pointer(PointerEventType.Move, 8f, 250f)
            f.pointer(PointerEventType.Move, 260f, 260f)
            f.pointer(PointerEventType.Release, 260f, 260f)
            f.settle()
            assertEquals(0, f.pops)
            assertEquals(1, f.stack.value.size)
        } finally { f.close() }
    }

    @Test
    fun dragDoesNotRecomposePagesAndPreviewSurvivesCompletedPop() = runTest {
        val f = Fixture(this, nested = true)
        try {
            f.frame()
            f.pointer(PointerEventType.Press, 4f)
            f.pointer(PointerEventType.Move, 60f)
            val compositions = f.compositions.toMap()
            for (x in 80..280 step 20) f.pointer(PointerEventType.Move, x.toFloat())
            assertEquals(compositions, f.compositions, "Drag frames must only update layer translation")
            f.pointer(PointerEventType.Release, 280f)
            f.settle()
            assertEquals(listOf(1L), f.stack.value.map { it.id })
            assertEquals(1, f.mounts[1L], "The preview must become the page without remounting")
            assertEquals(null, f.disposals[1L])
            assertEquals(1, f.disposals[2L])
            assertEquals(1, f.pops)
        } finally { f.close() }
    }

    @Test
    fun rootPreviewSurvivesPopAndInteriorSwipeDoesNotNavigate() = runTest {
        val f = Fixture(this, nested = false)
        try {
            f.frame()
            f.pointer(PointerEventType.Press, 140f)
            f.pointer(PointerEventType.Move, 330f)
            f.pointer(PointerEventType.Release, 330f)
            f.settle()
            assertEquals(0, f.pops)
            assertEquals(null, f.mounts[0L])
            f.pointer(PointerEventType.Press, 4f)
            for (x in 30..310 step 20) f.pointer(PointerEventType.Move, x.toFloat())
            f.pointer(PointerEventType.Release, 310f)
            f.settle()
            assertEquals(emptyList(), f.stack.value)
            assertEquals(1, f.mounts[0L])
            assertEquals(null, f.disposals[0L])
            assertEquals(1, f.pops)
        } finally { f.close() }
    }

    @Test
    fun shortSlowSwipeCancelsAndNextSwipeCanComplete() = runTest {
        val f = Fixture(this, nested = true)
        try {
            f.frame()
            f.pointer(PointerEventType.Press, 4f)
            f.pointer(PointerEventType.Move, 40f)
            f.pointer(PointerEventType.Move, 45f)
            f.pointer(PointerEventType.Release, 45f)
            f.settle()
            assertEquals(0, f.pops)
            assertEquals(2, f.stack.value.size)
            f.pointer(PointerEventType.Press, 4f)
            for (x in 30..310 step 20) f.pointer(PointerEventType.Move, x.toFloat())
            f.pointer(PointerEventType.Release, 310f)
            f.settle()
            assertEquals(1, f.pops)
        } finally { f.close() }
    }

    private class Fixture(private val test: TestScope, nested: Boolean) {
        val stack = mutableStateOf(if (nested) listOf(NavEntry(1, Route.Detail(1)), NavEntry(2, Route.Settings())) else listOf(NavEntry(1, Route.Detail(1))))
        val direction = mutableStateOf(1)
        val mounts = mutableMapOf<Long, Int>()
        val disposals = mutableMapOf<Long, Int>()
        val compositions = mutableMapOf<Long, Int>()
        var pops = 0
        private val scene = ui {
            ImageComposeScene(400, 600, coroutineContext = UnconfinedTestDispatcher(test.testScheduler)) {
                val holder = rememberSaveableStateHolder()
                NavigationStack(
                    backStack = stack.value, direction = direction.value, cupertino = true,
                    playerMinimized = false, animationsEnabled = true,
                    onCompleteBack = { entry ->
                        if (stack.value.lastOrNull() === entry) {
                            pops++
                            direction.value = 0
                            stack.value = stack.value.dropLast(1)
                        }
                    },
                    rootContent = { holder.SaveableStateProvider(0L) { Page(0) } },
                    entryContent = { entry -> holder.SaveableStateProvider(entry.id) { Page(entry.id) } },
                )
            }
        }

        @Composable
        private fun Page(id: Long) {
            SideEffect { compositions[id] = (compositions[id] ?: 0) + 1 }
            DisposableEffect(id) {
                mounts[id] = (mounts[id] ?: 0) + 1
                onDispose { disposals[id] = (disposals[id] ?: 0) + 1 }
            }
            Box(Modifier.fillMaxSize().background(if (id == 2L) Color.Red else Color.Blue))
        }

        fun frame() = ui {
            test.testScheduler.advanceTimeBy(16)
            test.testScheduler.runCurrent()
            scene.render(test.testScheduler.currentTime * 1_000_000).close()
            test.testScheduler.runCurrent()
        }

        fun pointer(type: PointerEventType, x: Float, y: Float = 200f) = ui {
            test.testScheduler.advanceTimeBy(30)
            scene.sendPointerEvent(type, Offset(x, y), type = PointerType.Touch, timeMillis = test.testScheduler.currentTime)
            frame()
        }

        fun settle() { repeat(90) { frame() } }
        fun replaceTop() = ui {
            direction.value = 1
            stack.value = stack.value.dropLast(1) + NavEntry(3, stack.value.last().route)
        }
        fun back() = ui { direction.value = -1; stack.value = stack.value.dropLast(1) }
        fun close() = ui { scene.close() }
    }

    companion object {
        private fun <T> ui(block: () -> T): T {
            if (SwingUtilities.isEventDispatchThread()) return block()
            val task = FutureTask(block)
            SwingUtilities.invokeAndWait(task)
            return task.get()
        }
    }
}
```
[complete-source-end]: #

## `composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/ui/SecureScreen.ios.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/ui/SecureScreen.ios.kt) · implementation · 75 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.

Declaration checklist (source line numbers):
```text
22: internal actual fun SecureScreenEffect(secure: Boolean) {
33: private object IosPrivacyShield {
45: private fun observe() {
55: private fun refresh() {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/ui/SecureScreen.ios.kt) · SHA-256 `d06a7fdba2218031f511d4d2f9e7bb670111f9595d63cd12cd373a5332a2e5ec`.

### Complete file

```kotlin
@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)

package eu.friedcutlet.yokan.ui

import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import platform.Foundation.NSNotificationCenter
import platform.Foundation.NSOperationQueue
import platform.UIKit.UIApplication
import platform.UIKit.UIApplicationDidBecomeActiveNotification
import platform.UIKit.UIApplicationWillResignActiveNotification
import platform.UIKit.UIColor
import platform.UIKit.UIScreen
import platform.UIKit.UIScreenCapturedDidChangeNotification
import platform.UIKit.UIView
import platform.UIKit.UIViewAutoresizingFlexibleHeight
import platform.UIKit.UIViewAutoresizingFlexibleWidth
import platform.UIKit.UIWindow
import platform.UIKit.UIWindowScene

@Composable
internal actual fun SecureScreenEffect(secure: Boolean) {
    DisposableEffect(secure) {
        IosPrivacyShield.enabled = secure
        onDispose { }
    }
}

/**
 * iOS cannot block screenshots with public API. While enabled, a cover hides the UI in the app
 * switcher snapshot (taken after resign-active) and while the screen is recorded or mirrored.
 */
private object IosPrivacyShield {
    private var cover: UIView? = null
    private var inactive = false
    private var observing = false

    var enabled = false
        set(value) {
            field = value
            if (value) observe()
            refresh()
        }

    private fun observe() {
        if (observing) return
        observing = true
        val center = NSNotificationCenter.defaultCenter
        val queue = NSOperationQueue.mainQueue
        center.addObserverForName(UIApplicationWillResignActiveNotification, null, queue) { _ -> inactive = true; refresh() }
        center.addObserverForName(UIApplicationDidBecomeActiveNotification, null, queue) { _ -> inactive = false; refresh() }
        center.addObserverForName(UIScreenCapturedDidChangeNotification, null, queue) { _ -> refresh() }
    }

    private fun refresh() {
        val hide = enabled && (inactive || UIScreen.mainScreen.isCaptured())
        if (!hide) {
            cover?.removeFromSuperview()
            cover = null
            return
        }
        if (cover != null) return
        val window = UIApplication.sharedApplication.connectedScenes
            .filterIsInstance<UIWindowScene>()
            .flatMap { it.windows }
            .filterIsInstance<UIWindow>()
            .let { windows -> windows.firstOrNull { it.isKeyWindow() } ?: windows.firstOrNull() }
            ?: return
        cover = UIView(frame = window.bounds).apply {
            backgroundColor = UIColor.blackColor
            autoresizingMask = UIViewAutoresizingFlexibleWidth or UIViewAutoresizingFlexibleHeight
            window.addSubview(this)
        }
    }
}
```
[complete-source-end]: #

## `composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/ui/components/Scrollbar.ios.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/ui/components/Scrollbar.ios.kt) · implementation · 16 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
10: internal actual fun BoxScope.PlatformVerticalScrollbar(state: LazyListState) = Unit
13: internal actual fun BoxScope.PlatformVerticalScrollbar(state: LazyGridState) = Unit
16: internal actual fun BoxScope.PlatformVerticalScrollbar(state: ScrollState) = Unit
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/ui/components/Scrollbar.ios.kt) · SHA-256 `187af72d36701b91b619458c0ed81e18f68048b79126d2ed1263e69e7a0ef60e`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.components

import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.grid.LazyGridState
import androidx.compose.runtime.Composable

@Composable
internal actual fun BoxScope.PlatformVerticalScrollbar(state: LazyListState) = Unit

@Composable
internal actual fun BoxScope.PlatformVerticalScrollbar(state: LazyGridState) = Unit

@Composable
internal actual fun BoxScope.PlatformVerticalScrollbar(state: ScrollState) = Unit
```
[complete-source-end]: #

## `composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/ui/image/PlatformImageDecoders.ios.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/ui/image/PlatformImageDecoders.ios.kt) · implementation · 5 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
5: internal actual fun addPlatformImageDecoders(components: ComponentRegistry.Builder) = Unit
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/ui/image/PlatformImageDecoders.ios.kt) · SHA-256 `9e9a01f3e26ab97c7107e0253af4a7aff7dc5da5cd07e922fa65841954276820`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.image

import coil3.ComponentRegistry

internal actual fun addPlatformImageDecoders(components: ComponentRegistry.Builder) = Unit
```
[complete-source-end]: #

## `composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/ui/navigation/PlatformNavigation.ios.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/ui/navigation/PlatformNavigation.ios.kt) · implementation · 3 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
3: internal actual fun usesCupertinoPageTransitions(): Boolean = true
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/ui/navigation/PlatformNavigation.ios.kt) · SHA-256 `ab2c013fcdbc7c9dc23a8f95068c4457826dec60c63c28fd2d26bc88b537a7b8`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.navigation

internal actual fun usesCupertinoPageTransitions(): Boolean = true
```
[complete-source-end]: #

## `composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/ui/theme/MaterialYou.ios.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/ui/theme/MaterialYou.ios.kt) · implementation · 9 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
7: actual fun rememberMaterialYouScheme(isDark: Boolean): ColorScheme? = null
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/ui/theme/MaterialYou.ios.kt) · SHA-256 `18fc2a987430b73c874cae9917bbbe37f9ee7b735b107faf773c88df1ba30aa6`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.theme

import androidx.compose.material3.ColorScheme
import androidx.compose.runtime.Composable

@Composable
actual fun rememberMaterialYouScheme(isDark: Boolean): ColorScheme? = null

actual val materialYouAvailable: Boolean = false
```
[complete-source-end]: #

## `composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/ui/theme/SystemBarTheme.ios.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/ui/theme/SystemBarTheme.ios.kt) · implementation · 25 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
4: object IosSystemBarThemeBridge {
8: fun register(handler: (Boolean) -> Unit) {
13: fun unregister() {
17: internal fun setTheme(isDark: Boolean) {
23: actual fun applySystemBarTheme(isDark: Boolean) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/ui/theme/SystemBarTheme.ios.kt) · SHA-256 `e8215e74fb3012949d8b9a1750ba8a865b05c94802c0254bf062bd4007c41d29`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.theme

/** Bridges the resolved Compose palette to the UIKit controller that owns the status bar. */
object IosSystemBarThemeBridge {
    private var isDark = false
    private var handler: ((Boolean) -> Unit)? = null

    fun register(handler: (Boolean) -> Unit) {
        this.handler = handler
        handler(isDark)
    }

    fun unregister() {
        handler = null
    }

    internal fun setTheme(isDark: Boolean) {
        this.isDark = isDark
        handler?.invoke(isDark)
    }
}

actual fun applySystemBarTheme(isDark: Boolean) {
    IosSystemBarThemeBridge.setTheme(isDark)
}
```
[complete-source-end]: #

## `composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/util/PlatformLock.ios.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/util/PlatformLock.ios.kt) · implementation · 16 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
5: internal actual class PlatformLock actual constructor() {
8: actual fun <T> withLock(block: () -> T): T {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/util/PlatformLock.ios.kt) · SHA-256 `d1738c416db1aa0745416d82844f39058d70dc69d736cb9b708e17ada0ece8e3`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.util

import platform.Foundation.NSRecursiveLock

internal actual class PlatformLock actual constructor() {
    private val delegate = NSRecursiveLock()

    actual fun <T> withLock(block: () -> T): T {
        delegate.lock()
        return try {
            block()
        } finally {
            delegate.unlock()
        }
    }
}
```
[complete-source-end]: #

## `composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/util/PlatformLock.jvm.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/util/PlatformLock.jvm.kt) · implementation · 10 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
6: internal actual class PlatformLock actual constructor() {
9: actual fun <T> withLock(block: () -> T): T = delegate.withLock(block)
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/util/PlatformLock.jvm.kt) · SHA-256 `0211a3372a7b4af96e04477d05b112576b9358e85b86a9c8ea0e28cbe59b5fbb`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.util

import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock

internal actual class PlatformLock actual constructor() {
    private val delegate = ReentrantLock()

    actual fun <T> withLock(block: () -> T): T = delegate.withLock(block)
}
```
[complete-source-end]: #

## `composeApp/src/nonWebMain/kotlin/eu/friedcutlet/yokan/ui/image/ImageLoaderSetup.nonWeb.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/nonWebMain/kotlin/eu/friedcutlet/yokan/ui/image/ImageLoaderSetup.nonWeb.kt) · implementation · 8 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
7: internal actual fun imageDiskCache(cacheRoot: String): DiskCache? =
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/nonWebMain/kotlin/eu/friedcutlet/yokan/ui/image/ImageLoaderSetup.nonWeb.kt) · SHA-256 `420e3306641bdc4fa6cf1516f24fbb365b0aa03f4a34fc79574818759da64fa1`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.image

import coil3.disk.DiskCache
import okio.Path.Companion.toPath

// Only the singleton ImageLoader calls this: Coil forbids two caches on one directory.
internal actual fun imageDiskCache(cacheRoot: String): DiskCache? =
    DiskCache.Builder().directory(cacheRoot.toPath() / "image_cache").build()
```
[complete-source-end]: #

## `composeApp/src/nonWebMain/kotlin/eu/friedcutlet/yokan/util/Digests.nonWeb.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/nonWebMain/kotlin/eu/friedcutlet/yokan/util/Digests.nonWeb.kt) · implementation · 11 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
8: actual fun sha256(data: ByteArray): ByteArray = CryptographyProvider.Default.get(SHA256).hasher().hashBlocking(data)
11: actual fun sha1(data: ByteArray): ByteArray = CryptographyProvider.Default.get(SHA1).hasher().hashBlocking(data)
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/nonWebMain/kotlin/eu/friedcutlet/yokan/util/Digests.nonWeb.kt) · SHA-256 `1a8ab9c5e988b42e827f06bb8c359e5a9cb958d618d1eb69f6c623a61e3c85b7`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.util

import dev.whyoleg.cryptography.CryptographyProvider
import dev.whyoleg.cryptography.DelicateCryptographyApi
import dev.whyoleg.cryptography.algorithms.SHA1
import dev.whyoleg.cryptography.algorithms.SHA256

actual fun sha256(data: ByteArray): ByteArray = CryptographyProvider.Default.get(SHA256).hasher().hashBlocking(data)

@OptIn(DelicateCryptographyApi::class)
actual fun sha1(data: ByteArray): ByteArray = CryptographyProvider.Default.get(SHA1).hasher().hashBlocking(data)
```
[complete-source-end]: #

## `composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/ui/SecureScreen.wasm.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/ui/SecureScreen.wasm.kt) · implementation · 7 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.

Declaration checklist (source line numbers):
```text
7: internal actual fun SecureScreenEffect(secure: Boolean) = Unit
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/ui/SecureScreen.wasm.kt) · SHA-256 `cc92f033262c99d90ff48757848c8d88fd7ee52a89550294551777e99d82bc38`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui

import androidx.compose.runtime.Composable

// Browsers offer pages no way to block screenshots, recording or tab previews.
@Composable
internal actual fun SecureScreenEffect(secure: Boolean) = Unit
```
[complete-source-end]: #

## `composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/ui/components/Scrollbar.wasm.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/ui/components/Scrollbar.wasm.kt) · implementation · 16 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
10: internal actual fun BoxScope.PlatformVerticalScrollbar(state: LazyListState) = Unit
13: internal actual fun BoxScope.PlatformVerticalScrollbar(state: LazyGridState) = Unit
16: internal actual fun BoxScope.PlatformVerticalScrollbar(state: ScrollState) = Unit
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/ui/components/Scrollbar.wasm.kt) · SHA-256 `187af72d36701b91b619458c0ed81e18f68048b79126d2ed1263e69e7a0ef60e`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.components

import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.grid.LazyGridState
import androidx.compose.runtime.Composable

@Composable
internal actual fun BoxScope.PlatformVerticalScrollbar(state: LazyListState) = Unit

@Composable
internal actual fun BoxScope.PlatformVerticalScrollbar(state: LazyGridState) = Unit

@Composable
internal actual fun BoxScope.PlatformVerticalScrollbar(state: ScrollState) = Unit
```
[complete-source-end]: #

## `composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/ui/image/ImageLoaderSetup.wasm.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/ui/image/ImageLoaderSetup.wasm.kt) · implementation · 6 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
6: internal actual fun imageDiskCache(cacheRoot: String): DiskCache? = null
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/ui/image/ImageLoaderSetup.wasm.kt) · SHA-256 `f1a1dbb531cbf22c90cf345a134d1cca5df0d99442f5fcf46084571ce844d65d`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.image

import coil3.disk.DiskCache

// Coil has no disk cache in the browser; the browser's HTTP cache stands in.
internal actual fun imageDiskCache(cacheRoot: String): DiskCache? = null
```
[complete-source-end]: #

## `composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/ui/image/PlatformImageDecoders.wasm.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/ui/image/PlatformImageDecoders.wasm.kt) · implementation · 5 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
5: internal actual fun addPlatformImageDecoders(components: ComponentRegistry.Builder) = Unit
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/ui/image/PlatformImageDecoders.wasm.kt) · SHA-256 `9e9a01f3e26ab97c7107e0253af4a7aff7dc5da5cd07e922fa65841954276820`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.image

import coil3.ComponentRegistry

internal actual fun addPlatformImageDecoders(components: ComponentRegistry.Builder) = Unit
```
[complete-source-end]: #

## `composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/ui/navigation/PlatformNavigation.wasm.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/ui/navigation/PlatformNavigation.wasm.kt) · implementation · 3 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
3: internal actual fun usesCupertinoPageTransitions(): Boolean = false
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/ui/navigation/PlatformNavigation.wasm.kt) · SHA-256 `3f7994820fdb314dc673eef72a7005590718ec0e4a1b10358c2f0a5ff3fde722`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.navigation

internal actual fun usesCupertinoPageTransitions(): Boolean = false
```
[complete-source-end]: #

## `composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/ui/theme/MaterialYou.wasm.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/ui/theme/MaterialYou.wasm.kt) · implementation · 9 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
7: actual fun rememberMaterialYouScheme(isDark: Boolean): ColorScheme? = null
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/ui/theme/MaterialYou.wasm.kt) · SHA-256 `18fc2a987430b73c874cae9917bbbe37f9ee7b735b107faf773c88df1ba30aa6`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.theme

import androidx.compose.material3.ColorScheme
import androidx.compose.runtime.Composable

@Composable
actual fun rememberMaterialYouScheme(isDark: Boolean): ColorScheme? = null

actual val materialYouAvailable: Boolean = false
```
[complete-source-end]: #

## `composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/ui/theme/SystemBarTheme.wasm.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/ui/theme/SystemBarTheme.wasm.kt) · implementation · 5 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
3: actual fun applySystemBarTheme(isDark: Boolean) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/ui/theme/SystemBarTheme.wasm.kt) · SHA-256 `85b832387ef4c5bc7aa61abcffd8b67a3cd8c9c8b23c28d13bd1913e17745df0`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.theme

actual fun applySystemBarTheme(isDark: Boolean) {
    // No system bars in the browser.
}
```
[complete-source-end]: #

## `composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/util/Digests.wasm.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/util/Digests.wasm.kt) · implementation · 100 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
6: actual fun sha256(data: ByteArray): ByteArray {
49: actual fun sha1(data: ByteArray): ByteArray {
79: private fun mdPad(data: ByteArray, bigEndian: Boolean): ByteArray {
91: private fun IntArray.toBigEndianBytes(): ByteArray {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/util/Digests.wasm.kt) · SHA-256 `1c37ae065f36abe634be647eec0072810f805a583bf845e8c06824a1f9ed631d`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.util

// Hashes must be real (cache keys, tracker signatures), and SubtleCrypto's
// digest is async — so both digests are implemented in plain Kotlin.

actual fun sha256(data: ByteArray): ByteArray {
    val k = intArrayOf(
        0x428a2f98, 0x71374491, -0x4a3f0431, -0x164a245b, 0x3956c25b, 0x59f111f1, -0x6dc07d5c, -0x54e3a12b,
        -0x27f85568, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, -0x7f214e02, -0x6423f959, -0x3e640e8c,
        -0x1b64963f, -0x1041b87a, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
        -0x67c1aeae, -0x57ce3993, -0x4ffcd838, -0x40a68039, -0x391ff40d, -0x2a586eb9, 0x06ca6351, 0x14292967,
        0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, -0x7e3d36d2, -0x6d8dd37b,
        -0x5d40175f, -0x57e599b5, -0x3db47490, -0x3893ae5d, -0x2e6d17e7, -0x2966f9dc, -0xbf1ca7b, 0x106aa070,
        0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
        0x748f82ee, 0x78a5636f, -0x7b3787ec, -0x7338fdf8, -0x6f410006, -0x5baf9315, -0x41065c09, -0x398e870e,
    )
    var h0 = 0x6a09e667; var h1 = -0x4498517b; var h2 = 0x3c6ef372; var h3 = -0x5ab00ac6
    var h4 = 0x510e527f; var h5 = -0x64fa9774; var h6 = 0x1f83d9ab; var h7 = 0x5be0cd19
    val padded = mdPad(data, bigEndian = true)
    val w = IntArray(64)
    var block = 0
    while (block < padded.size) {
        for (t in 0 until 16) {
            val i = block + t * 4
            w[t] = ((padded[i].toInt() and 0xff) shl 24) or ((padded[i + 1].toInt() and 0xff) shl 16) or
                ((padded[i + 2].toInt() and 0xff) shl 8) or (padded[i + 3].toInt() and 0xff)
        }
        for (t in 16 until 64) {
            val s0 = w[t - 15].rotateRight(7) xor w[t - 15].rotateRight(18) xor (w[t - 15] ushr 3)
            val s1 = w[t - 2].rotateRight(17) xor w[t - 2].rotateRight(19) xor (w[t - 2] ushr 10)
            w[t] = w[t - 16] + s0 + w[t - 7] + s1
        }
        var a = h0; var b = h1; var c = h2; var d = h3; var e = h4; var f = h5; var g = h6; var h = h7
        for (t in 0 until 64) {
            val s1 = e.rotateRight(6) xor e.rotateRight(11) xor e.rotateRight(25)
            val ch = (e and f) xor (e.inv() and g)
            val temp1 = h + s1 + ch + k[t] + w[t]
            val s0 = a.rotateRight(2) xor a.rotateRight(13) xor a.rotateRight(22)
            val maj = (a and b) xor (a and c) xor (b and c)
            val temp2 = s0 + maj
            h = g; g = f; f = e; e = d + temp1; d = c; c = b; b = a; a = temp1 + temp2
        }
        h0 += a; h1 += b; h2 += c; h3 += d; h4 += e; h5 += f; h6 += g; h7 += h
        block += 64
    }
    return intArrayOf(h0, h1, h2, h3, h4, h5, h6, h7).toBigEndianBytes()
}

actual fun sha1(data: ByteArray): ByteArray {
    var h0 = 0x67452301; var h1 = -0x10325477; var h2 = -0x67452302; var h3 = 0x10325476; var h4 = -0x3c2d1e10
    val padded = mdPad(data, bigEndian = true)
    val w = IntArray(80)
    var block = 0
    while (block < padded.size) {
        for (t in 0 until 16) {
            val i = block + t * 4
            w[t] = ((padded[i].toInt() and 0xff) shl 24) or ((padded[i + 1].toInt() and 0xff) shl 16) or
                ((padded[i + 2].toInt() and 0xff) shl 8) or (padded[i + 3].toInt() and 0xff)
        }
        for (t in 16 until 80) w[t] = (w[t - 3] xor w[t - 8] xor w[t - 14] xor w[t - 16]).rotateLeft(1)
        var a = h0; var b = h1; var c = h2; var d = h3; var e = h4
        for (t in 0 until 80) {
            val (f, k) = when {
                t < 20 -> ((b and c) or (b.inv() and d)) to 0x5a827999
                t < 40 -> (b xor c xor d) to 0x6ed9eba1
                t < 60 -> ((b and c) or (b and d) or (c and d)) to -0x70e44324
                else -> (b xor c xor d) to -0x359d3e2a
            }
            val temp = a.rotateLeft(5) + f + e + k + w[t]
            e = d; d = c; c = b.rotateLeft(30); b = a; a = temp
        }
        h0 += a; h1 += b; h2 += c; h3 += d; h4 += e
        block += 64
    }
    return intArrayOf(h0, h1, h2, h3, h4).toBigEndianBytes()
}

/** Merkle–Damgård padding: 0x80, zeros, 64-bit big-endian bit length. */
private fun mdPad(data: ByteArray, bigEndian: Boolean): ByteArray {
    require(bigEndian)
    val bitLength = data.size.toLong() * 8
    val paddedSize = ((data.size + 8) / 64 + 1) * 64
    val padded = data.copyOf(paddedSize)
    padded[data.size] = 0x80.toByte()
    for (i in 0 until 8) {
        padded[paddedSize - 1 - i] = ((bitLength ushr (8 * i)) and 0xff).toByte()
    }
    return padded
}

private fun IntArray.toBigEndianBytes(): ByteArray {
    val out = ByteArray(size * 4)
    forEachIndexed { index, value ->
        out[index * 4] = (value ushr 24).toByte()
        out[index * 4 + 1] = (value ushr 16).toByte()
        out[index * 4 + 2] = (value ushr 8).toByte()
        out[index * 4 + 3] = value.toByte()
    }
    return out
}
```
[complete-source-end]: #

## `composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/util/PlatformLock.wasm.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/util/PlatformLock.wasm.kt) · implementation · 5 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
3: internal actual class PlatformLock actual constructor() {
4: actual fun <T> withLock(block: () -> T): T = block()
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/util/PlatformLock.wasm.kt) · SHA-256 `68328a75a93f97a05ae806fa9a7554041a4d6bba4cc6d514591a50b51e22a5ad`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.util

internal actual class PlatformLock actual constructor() {
    actual fun <T> withLock(block: () -> T): T = block()
}
```
[complete-source-end]: #

