Implementation chapter · Coverage index
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 and the reviewed source archive when reconstructing the app. See the architecture review for changes.
composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/ui/SecureScreen.android.kt
- Source · 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):
9: internal actual fun SecureScreenEffect(secure: Boolean) {
Exact file bytes / download · SHA-256 06f313db55910284fee12336d24e36a963d8d48bc2e4697498c4c2f5ad996b2a.
Complete file
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 { }
}
}
composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/ui/components/Scrollbar.android.kt
- Source · 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):
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
Exact file bytes / download · SHA-256 187af72d36701b91b619458c0ed81e18f68048b79126d2ed1263e69e7a0ef60e.
Complete file
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
composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/ui/image/PlatformImageDecoders.android.kt
- Source · 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):
5: internal actual fun addPlatformImageDecoders(components: ComponentRegistry.Builder) = Unit
Exact file bytes / download · SHA-256 9e9a01f3e26ab97c7107e0253af4a7aff7dc5da5cd07e922fa65841954276820.
Complete file
package eu.friedcutlet.yokan.ui.image
import coil3.ComponentRegistry
internal actual fun addPlatformImageDecoders(components: ComponentRegistry.Builder) = Unit
composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/ui/theme/MaterialYou.android.kt
- Source · 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):
11: actual fun rememberMaterialYouScheme(isDark: Boolean): ColorScheme? {
Exact file bytes / download · SHA-256 b712ba06fd6188929878f9dfd600be0717bf95bed159bcf3d31e401b9011190b.
Complete file
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
composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/ui/theme/SystemBarTheme.android.kt
- Source · 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):
9: actual fun applySystemBarTheme(isDark: Boolean) {
Exact file bytes / download · SHA-256 1d47ff5aee8a5613d67b7cec7cb881db78b0ec056d6892ba853b09fe6bde8ed1.
Complete file
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 },
)
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/App.kt
- Source · 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):
104: fun YokanApp() {
154: private fun YokanReadyApp(owner: ProfileSession, initialDeepLink: String?, catalogEnrollmentEnabled: Boolean) {
175: private fun YokanAppContent(
Exact file bytes / download · SHA-256 a36e2c0fbfa61da590fb31f3b557483179b159d001051aead516a497e3e5717d.
Complete file
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)
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/Formatting.kt
- Source · 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):
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()
Exact file bytes / download · SHA-256 d659ab3e1776b75112db50f5e585691a598b9988c7a8448faee4f03f7826c1f8.
Complete file
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()
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/SecureScreen.kt
- Source · 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):
11: internal expect fun SecureScreenEffect(secure: Boolean)
Exact file bytes / download · SHA-256 982e6676373f55eb2acfb6e2d06664862bf62db76ac1037b3e576cf0122d3ec3.
Complete file
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)
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/ChoiceDialog.kt
- Source · 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):
36: fun <T> ChoiceDialog(
Exact file bytes / download · SHA-256 6d3c378f66967de5b63f80f9f3ee54b1455d7f6714ef22c071bc8cad9b38b60e.
Complete file
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)) }
},
)
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/ConfirmDialog.kt
- Source · 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):
21: fun ConfirmDialog(
Exact file bytes / download · SHA-256 46376386a5c7d74fcbea8deca90f528ec2e993b668c456561aa4f1029470d91e.
Complete file
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) }
},
)
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/ContentPadding.kt
- Source · 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):
17: fun adaptiveContentPadding(): PaddingValues {
Exact file bytes / download · SHA-256 68f37b5dd4fb466a842e74a6496ce9ec7d4f1ec2d78b8f7caec7447b9d9fea45.
Complete file
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)
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/CoverImage.kt
- Source · 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):
21: fun CoverImage(
Exact file bytes / download · SHA-256 82d19560bf50525fa6cd6cbef41708a6ef54822a2b643190cb5531a75c799c26.
Complete file
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 },
)
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/DialogWidth.kt
- Source · 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):
11: fun Modifier.compactDialogWidth(): Modifier =
14: fun Modifier.compactSheetWidth(): Modifier =
Exact file bytes / download · SHA-256 75c6fb54abb5f5ec050a5157b81f0d967c2150d3610364fd2b893bc712de82d3.
Complete file
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()
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/Modern.kt
- Source · 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):
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(
Exact file bytes / download · SHA-256 2b9d44389ebade7f99417b6026fba56236619af8eab4d101d9812c89c9e526bb.
Complete file
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),
)
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/Reorderable.kt
- Source · 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):
38: fun <T> ReorderableColumn(
Exact file bytes / download · SHA-256 6604a4db1dcb476ca408c070a6e81e33852ba9a531451f955a9fde12ffd77ecb.
Complete file
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)
}
}
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/RouteScaffold.kt
- Source · 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):
14: internal fun RouteScaffold(
Exact file bytes / download · SHA-256 22837de15fc1fcbf2658b20793d61a56d689c42cf28fdaf2540cb5fe31b8803c.
Complete file
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,
)
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/Scrollable.kt
- Source · 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):
34: fun ScrollableLazyColumn(
65: fun ScrollableLazyVerticalGrid(
95: private suspend fun LazyListState.scrollBy(amount: Float) {
100: private suspend fun LazyGridState.scrollBy(amount: Float) {
Exact file bytes / download · SHA-256 53a876779d360c9d65899e319e5fe48902e5b38ea072e6a6b288247ad8c29f67.
Complete file
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) }
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/Scrollbar.kt
- Source · 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):
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)
Exact file bytes / download · SHA-256 e107feafc3c355108d3642a7975cfa83fb232cf597522fa4df63b516d9c53351.
Complete file
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)
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/SearchField.kt
- Source · 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):
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 =
Exact file bytes / download · SHA-256 7570c1d213a351cee852555017ec6c43925853e5545955ab0676b3105f5b0705.
Complete file
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)
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/StateViews.kt
- Source · 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):
37: fun EmptyState(
84: fun LoadingState(
110: fun ErrorState(
Exact file bytes / download · SHA-256 186759e863ea8f27bfa32bedc2b5d5c93c1ed957aeeec23abea04f56666ceaea.
Complete file
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)) }
}
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/Tooltips.kt
- Source · 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):
24: fun TooltipIconButton(
45: fun TooltipIconButton(
Exact file bytes / download · SHA-256 8b261171292f47a3e6f603cb08a4106ca4789709e72a39aece55b79fb97ae5bd.
Complete file
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)
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/components/TypeDot.kt
- Source · 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):
14: fun TypeDot(itemType: ItemType, modifier: Modifier = Modifier) {
Exact file bytes / download · SHA-256 27bf2ec8da7d7fe27ae3a512ca367756857c6e721aa90235b00ed3d96b42264e.
Complete file
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),
)
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/image/ImageDataSaverInterceptor.kt
- Source · 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):
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 {
Exact file bytes / download · SHA-256 69902448adaa8d176b0316b6e8a06f327b9896762bcebcade2942d6537ca88d0.
Complete file
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]
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/image/ImageDecoder.kt
- Source · 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):
16: internal fun decodeImageBitmap(path: String): ImageBitmap? =
Exact file bytes / download · SHA-256 88662fe380b485d2fc64c29270799b623f607ec872daf8dc711d4d122b254a2f.
Complete file
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()
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/image/ImageLoaderSetup.kt
- Source · 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):
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() {
Exact file bytes / download · SHA-256 34182c1dd6d195a6bbbb1b1ca029dbd0694ab8aa762a1d2a5b1109f92b3810d3.
Complete file
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()
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/image/PlatformImageDecoders.kt
- Source · 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):
6: internal expect fun addPlatformImageDecoders(components: ComponentRegistry.Builder)
Exact file bytes / download · SHA-256 1876d553db48e9642f8e9d7658973d9f59dd192853a0b2d352b1a57eba404c60.
Complete file
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)
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/image/ProfileImageHttpClient.kt
- Source · 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):
27: internal class ProfileImageHttpClient(
72: suspend fun closeAndJoin() = withContext(NonCancellable) {
77: private suspend fun release() = withContext(NonCancellable) {
Exact file bytes / download · SHA-256 c9a5cb81cfa3351b8fbe5be7007b9f9a961cf927b761e328fab374aff1a2f12e.
Complete file
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
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/ReadingSessionClock.kt
- Source · 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):
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 {
Exact file bytes / download · SHA-256 fc2b086fd3df2a89fc1ae6432bf13fafd64175bab6350dd831033d6e06f6a9b9.
Complete file
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()
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/onboarding/Onboarding.kt
- Source · 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):
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) {
Exact file bytes / download · SHA-256 ae21f07124a6bee66a796ea68bcb7e804fc3ec903ddb48f25438b368641dd774.
Complete file
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)
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/theme/FlexColorMath.kt
- Source · 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):
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(
Exact file bytes / download · SHA-256 f1f25ac9f41993a77d9a552f93b7c2a48e35b0e86f2ac4c8fe1531a228d6e02f.
Complete file
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()),
)
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/theme/FlexSchemes.kt
- Source · 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):
3: data class FlexPalette(
12: data class FlexScheme(
Exact file bytes / download · SHA-256 4222c25469d833029200adf77acc298b05d54baff519491674bb79377514a5a2.
Complete file
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),
),
)
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/theme/MaterialYou.kt
- Source · 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):
13: expect fun rememberMaterialYouScheme(isDark: Boolean): ColorScheme?
Exact file bytes / download · SHA-256 13b83927e613f9202498c4516fd97904e402affe9d297343cd3d0953fe203834.
Complete file
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
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/theme/SystemBarTheme.kt
- Source · 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):
9: expect fun applySystemBarTheme(isDark: Boolean)
Exact file bytes / download · SHA-256 34659137c48d8613e7e6a80fcd1bf7f5d90c802ad77a1552f395f7241353784d.
Complete file
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)
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/theme/Theme.kt
- Source · 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):
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()
Exact file bytes / download · SHA-256 3eddc2c0ebefc2af19e0960bb85eb2bffface3acf6442b788bba343498954c66.
Complete file
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()
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/theme/YokanThemeFromSettings.kt
- Source · 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):
11: fun YokanThemeFromSettings(db: DbSettings, themeIsDark: Boolean, content: @Composable () -> Unit) {
Exact file bytes / download · SHA-256 70acb6d7c9f0455ce3c68086259ceeaf058b373cffe32ea79d2766f244cc831f.
Complete file
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,
)
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/tv/TvFocusEngine.kt
- Source · 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):
14: fun resolveTvUiScale(
31: fun resolveTvAnimeOnly(
39: fun shouldHideNavSectionForTv(
58: fun handleTvDpadNavigation(
Exact file bytes / download · SHA-256 527d849581e76c4bef5b1592957ae2077c83e98f4e5ed8e2c69254be22392e41.
Complete file
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
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/util/Digests.kt
- Source · 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):
3: expect fun sha256(data: ByteArray): ByteArray
4: expect fun sha1(data: ByteArray): ByteArray
Exact file bytes / download · SHA-256 b1e2439b224c116e23337210e77e3dda4efcc6c865caf89de01bf8f868a98d0a.
Complete file
package eu.friedcutlet.yokan.util
expect fun sha256(data: ByteArray): ByteArray
expect fun sha1(data: ByteArray): ByteArray
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/util/HtmlEntities.kt
- Source · 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):
28: internal fun decodeHtmlEntities(value: String): String {
Exact file bytes / download · SHA-256 307aaf7e9b650b21fc72125c5e1e42f8f8867a89e62175dc341b90186dabb3a6.
Complete file
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 (`'`, `'`) and common named HTML entities in one pass, so `&quot;`
* stays `"`. Unknown or out-of-range entities are kept verbatim; ` ` 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()}"
}
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/util/PlatformLock.kt
- Source · 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):
4: internal expect class PlatformLock() {
5: fun <T> withLock(block: () -> T): T
Exact file bytes / download · SHA-256 fa10dc07355461bef09303e04d58dd2f99f4caffb2a479656d4a651dc456d91c.
Complete file
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
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/util/Time.kt
- Source · 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):
4: internal fun nowMillis(): Long = kotlin.time.Clock.System.now().toEpochMilliseconds()
Exact file bytes / download · SHA-256 8919aac81dba5177f5a121978bb659435003e46be502d9294a3ac13ae4d495ab.
Complete file
package eu.friedcutlet.yokan.util
@OptIn(kotlin.time.ExperimentalTime::class)
internal fun nowMillis(): Long = kotlin.time.Clock.System.now().toEpochMilliseconds()
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/ParityStateContractTest.kt
- Source · 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):
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(
Exact file bytes / download · SHA-256 f6c078cf891628dff95650ded0d656a73701d0d0cecc0447083cfd573f268fb8.
Complete file
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,
)
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/ViewModelTestHost.kt
- Source · 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):
13: internal class ViewModelTestHost {
20: fun <T : ViewModel> create(init: () -> T): T = init().also { store.put("vm${count++}", it) }
22: fun close() {
Exact file bytes / download · SHA-256 58d3ad130ffde39e4ffe8c38c916389529605c9586189d9af7a1656faa725f00.
Complete file
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()
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/image/ProfileImageHttpClientTest.kt
- Source · 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):
38: class ProfileImageHttpClientTest {
120: private suspend fun response() = HttpResponseData(HttpStatusCode.OK, GMTDate(), Headers.Empty,
Exact file bytes / download · SHA-256 75e46729c6ce40b7f58ee0117c783cfc4c23e8d644339fbb7ab06a6d50c3c9a1.
Complete file
@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())
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/ReadingSessionClockTest.kt
- Source · 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):
10: class ReadingSessionClockTest {
12: fun countsOnlyForegroundIntervalsAndTakesThemOnce() {
28: fun finishedClockNeitherCountsNorResumes() {
Exact file bytes / download · SHA-256 075806eb106865b7762ececcdbaf585684b853349f68454bc9e75763b11186d1.
Complete file
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())
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/theme/ThemeParityTest.kt
- Source · 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):
9: class ThemeParityTest {
11: fun darkModeFollowsSystemOnlyWhenEnabled() {
18: fun userSurfaceBlendDoesNotChangeFixedOnBlendRoles() {
41: fun brownOrangeLightMatchesMangayomiFlexThemeData() {
99: fun brownOrangeDarkMatchesMangayomiFlexThemeData() {
161: fun pureBlackOnlyChangesMangayomiScaffold() {
177: private fun assertRoleSnapshot(
Exact file bytes / download · SHA-256 fdccdafba336e34ca1ba5d829757812da3b9d0f1fef27c8919245b2dbf9f0553.
Complete file
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")
}
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/tv/TvFocusEngineTest.kt
- Source · 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):
11: class TvFocusEngineTest {
14: fun resolveTvUiScaleOnTvUsesTvScaleWithClamping() {
33: fun resolveTvUiScaleOffTvUsesUiScaleOrAutoUiScale() {
42: fun resolveTvAnimeOnlyDefaultsToTrueOnTvAndFalseOffTv() {
53: fun shouldHideNavSectionForTvHidesMangaAndNovelOnlyWhenTvAnimeOnlyIsActive() {
73: fun handleTvDpadNavigationMovesBetweenContentAndRail() {
Exact file bytes / download · SHA-256 245237dfb8b96a4dd4bd8e745f03b3487d06d0563fe8d1c3066f24b8d142e1d6.
Complete file
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)
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/util/HtmlEntitiesTest.kt
- Source · 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):
6: class HtmlEntitiesTest {
8: fun decodesNamedEntitiesCaseInsensitively() {
14: fun decodesDecimalHexAndSupplementaryCodePoints() {
20: fun decodesInOnePassAndKeepsUnknownOrInvalidEntities() {
Exact file bytes / download · SHA-256 5056796cda9a56d30e2553bbf82b7ab0a7fd17ca91d49d5fca32ccb7f11c6ae6.
Complete file
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 & Jerry "<b>" it's © — …"))
assertEquals("a b", decodeHtmlEntities("a b"))
}
@Test
fun decodesDecimalHexAndSupplementaryCodePoints() {
assertEquals("it's it's", decodeHtmlEntities("it's it's"))
assertEquals("A😀", decodeHtmlEntities("A😀"))
}
@Test
fun decodesInOnePassAndKeepsUnknownOrInvalidEntities() {
assertEquals(""", decodeHtmlEntities("&quot;"))
assertEquals("&unknown; � & alone", decodeHtmlEntities("&unknown; � & alone"))
}
}
composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/ui/SecureScreen.desktop.kt
- Source · 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):
8: internal actual fun SecureScreenEffect(secure: Boolean) = Unit
Exact file bytes / download · SHA-256 b8f2ed00d84136ab8657d31164473fa2d21734a7cb163c5ae0af2e2871b7fae9.
Complete file
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
composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/ui/components/Scrollbar.desktop.kt
- Source · 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):
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) {
Exact file bytes / download · SHA-256 5efdb6754e8faf15d72a1f7d700b245cab56c81fe84e48c6e0a01e05926411d6.
Complete file
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),
)
}
composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/ui/image/AvifImageDecoder.kt
- Source · 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):
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 {
Exact file bytes / download · SHA-256 e1bee64d229cd41a855827bd87e31301b9b94ee07e6c6298e5d7b669d7864b02.
Complete file
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
}
composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/ui/image/PlatformImageDecoders.desktop.kt
- Source · 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):
5: internal actual fun addPlatformImageDecoders(components: ComponentRegistry.Builder) {
Exact file bytes / download · SHA-256 522f221cd5a8e27b266caf58714b14684c1835d222a06b327cc1f84fba8a8f4a.
Complete file
package eu.friedcutlet.yokan.ui.image
import coil3.ComponentRegistry
internal actual fun addPlatformImageDecoders(components: ComponentRegistry.Builder) {
components.add(AvifImageDecoder.Factory())
}
composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/ui/theme/MaterialYou.desktop.kt
- Source · 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):
7: actual fun rememberMaterialYouScheme(isDark: Boolean): ColorScheme? = null
Exact file bytes / download · SHA-256 18fc2a987430b73c874cae9917bbbe37f9ee7b735b107faf773c88df1ba30aa6.
Complete file
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
composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/ui/theme/SystemBarTheme.desktop.kt
- Source · 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):
3: actual fun applySystemBarTheme(isDark: Boolean) = Unit
Exact file bytes / download · SHA-256 17941a7e2d5fad634ba283190f7e1ac657b8549b70d61f5dbd45223ccec86b56.
Complete file
package eu.friedcutlet.yokan.ui.theme
actual fun applySystemBarTheme(isDark: Boolean) = Unit
composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/HardcodedUiStringsTest.kt
- Source · 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):
12: class HardcodedUiStringsTest {
Exact file bytes / download · SHA-256 dbbd20542c8833c58c5335c0357d775eb1a3cf5af25e455209315df054a9c8a1.
Complete file
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")
}
}
composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/image/AvifImageDecoderTest.kt
- Source · 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):
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 =
Exact file bytes / download · SHA-256 fe007a20adf0ac144a19586da08deb9a8bff4a97c88863e5a3415d4133aea3cb.
Complete file
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() }
}
composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/image/ImageDataSaverInterceptorTest.kt
- Source · 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):
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)
Exact file bytes / download · SHA-256 4bdcfb9a6dce0b19dd604e90911340e33abc2e08238bca82fa9209f76b50454f.
Complete file
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)
}
}
composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/ui/SecureScreen.ios.kt
- Source · 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):
22: internal actual fun SecureScreenEffect(secure: Boolean) {
33: private object IosPrivacyShield {
45: private fun observe() {
55: private fun refresh() {
Exact file bytes / download · SHA-256 d06a7fdba2218031f511d4d2f9e7bb670111f9595d63cd12cd373a5332a2e5ec.
Complete file
@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)
}
}
}
composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/ui/components/Scrollbar.ios.kt
- Source · 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):
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
Exact file bytes / download · SHA-256 187af72d36701b91b619458c0ed81e18f68048b79126d2ed1263e69e7a0ef60e.
Complete file
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
composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/ui/image/PlatformImageDecoders.ios.kt
- Source · 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):
5: internal actual fun addPlatformImageDecoders(components: ComponentRegistry.Builder) = Unit
Exact file bytes / download · SHA-256 9e9a01f3e26ab97c7107e0253af4a7aff7dc5da5cd07e922fa65841954276820.
Complete file
package eu.friedcutlet.yokan.ui.image
import coil3.ComponentRegistry
internal actual fun addPlatformImageDecoders(components: ComponentRegistry.Builder) = Unit
composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/ui/theme/MaterialYou.ios.kt
- Source · 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):
7: actual fun rememberMaterialYouScheme(isDark: Boolean): ColorScheme? = null
Exact file bytes / download · SHA-256 18fc2a987430b73c874cae9917bbbe37f9ee7b735b107faf773c88df1ba30aa6.
Complete file
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
composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/ui/theme/SystemBarTheme.ios.kt
- Source · 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):
4: object IosSystemBarThemeBridge {
8: fun register(handler: (Boolean) -> Unit) {
13: fun unregister() {
17: internal fun setTheme(isDark: Boolean) {
23: actual fun applySystemBarTheme(isDark: Boolean) {
Exact file bytes / download · SHA-256 e8215e74fb3012949d8b9a1750ba8a865b05c94802c0254bf062bd4007c41d29.
Complete file
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)
}
composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/util/PlatformLock.ios.kt
- Source · 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):
5: internal actual class PlatformLock actual constructor() {
8: actual fun <T> withLock(block: () -> T): T {
Exact file bytes / download · SHA-256 d1738c416db1aa0745416d82844f39058d70dc69d736cb9b708e17ada0ece8e3.
Complete file
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()
}
}
}
composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/util/PlatformLock.jvm.kt
- Source · 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):
6: internal actual class PlatformLock actual constructor() {
9: actual fun <T> withLock(block: () -> T): T = delegate.withLock(block)
Exact file bytes / download · SHA-256 0211a3372a7b4af96e04477d05b112576b9358e85b86a9c8ea0e28cbe59b5fbb.
Complete file
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)
}
composeApp/src/nonWebMain/kotlin/eu/friedcutlet/yokan/ui/image/ImageLoaderSetup.nonWeb.kt
- Source · 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):
7: internal actual fun imageDiskCache(cacheRoot: String): DiskCache? =
Exact file bytes / download · SHA-256 420e3306641bdc4fa6cf1516f24fbb365b0aa03f4a34fc79574818759da64fa1.
Complete file
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()
composeApp/src/nonWebMain/kotlin/eu/friedcutlet/yokan/util/Digests.nonWeb.kt
- Source · 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):
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)
Exact file bytes / download · SHA-256 1a8ab9c5e988b42e827f06bb8c359e5a9cb958d618d1eb69f6c623a61e3c85b7.
Complete file
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)
composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/ui/SecureScreen.wasm.kt
- Source · 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):
7: internal actual fun SecureScreenEffect(secure: Boolean) = Unit
Exact file bytes / download · SHA-256 cc92f033262c99d90ff48757848c8d88fd7ee52a89550294551777e99d82bc38.
Complete file
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
composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/ui/components/Scrollbar.wasm.kt
- Source · 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):
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
Exact file bytes / download · SHA-256 187af72d36701b91b619458c0ed81e18f68048b79126d2ed1263e69e7a0ef60e.
Complete file
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
composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/ui/image/ImageLoaderSetup.wasm.kt
- Source · 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):
6: internal actual fun imageDiskCache(cacheRoot: String): DiskCache? = null
Exact file bytes / download · SHA-256 f1a1dbb531cbf22c90cf345a134d1cca5df0d99442f5fcf46084571ce844d65d.
Complete file
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
composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/ui/image/PlatformImageDecoders.wasm.kt
- Source · 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):
5: internal actual fun addPlatformImageDecoders(components: ComponentRegistry.Builder) = Unit
Exact file bytes / download · SHA-256 9e9a01f3e26ab97c7107e0253af4a7aff7dc5da5cd07e922fa65841954276820.
Complete file
package eu.friedcutlet.yokan.ui.image
import coil3.ComponentRegistry
internal actual fun addPlatformImageDecoders(components: ComponentRegistry.Builder) = Unit
composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/ui/theme/MaterialYou.wasm.kt
- Source · 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):
7: actual fun rememberMaterialYouScheme(isDark: Boolean): ColorScheme? = null
Exact file bytes / download · SHA-256 18fc2a987430b73c874cae9917bbbe37f9ee7b735b107faf773c88df1ba30aa6.
Complete file
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
composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/ui/theme/SystemBarTheme.wasm.kt
- Source · 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):
3: actual fun applySystemBarTheme(isDark: Boolean) {
Exact file bytes / download · SHA-256 85b832387ef4c5bc7aa61abcffd8b67a3cd8c9c8b23c28d13bd1913e17745df0.
Complete file
package eu.friedcutlet.yokan.ui.theme
actual fun applySystemBarTheme(isDark: Boolean) {
// No system bars in the browser.
}
composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/util/Digests.wasm.kt
- Source · 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):
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 {
Exact file bytes / download · SHA-256 1c37ae065f36abe634be647eec0072810f805a583bf845e8c06824a1f9ed631d.
Complete file
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
}
composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/util/PlatformLock.wasm.kt
- Source · 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):
3: internal actual class PlatformLock actual constructor() {
4: actual fun <T> withLock(block: () -> T): T = block()
Exact file bytes / download · SHA-256 68328a75a93f97a05ae806fa9a7554041a4d6bba4cc6d514591a50b51e22a5ad.
Complete file
package eu.friedcutlet.yokan.util
internal actual class PlatformLock actual constructor() {
actual fun <T> withLock(block: () -> T): T = block()
}