Theme.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/theme/Theme.kt
1package eu.friedcutlet.yokan.ui.theme23import androidx.compose.foundation.isSystemInDarkTheme4import androidx.compose.foundation.shape.RoundedCornerShape5import androidx.compose.material3.ColorScheme6import androidx.compose.material3.MaterialTheme7import androidx.compose.material3.Shapes8import androidx.compose.material3.Typography9import androidx.compose.runtime.Composable10import androidx.compose.runtime.getValue11import androidx.compose.runtime.produceState12import androidx.compose.runtime.remember13import androidx.compose.ui.graphics.Color14import androidx.compose.ui.graphics.luminance15import androidx.compose.ui.text.TextStyle16import androidx.compose.ui.text.font.FontFamily17import androidx.compose.ui.text.font.FontWeight18import androidx.compose.ui.unit.dp19import com.materialkolor.PaletteStyle20import com.materialkolor.dynamiccolor.ColorSpec21import com.materialkolor.ktx.themeColor22import com.materialkolor.rememberDynamicColorScheme23import eu.friedcutlet.yokan.ui.image.decodeImageBitmap24import kotlinx.coroutines.Dispatchers25import kotlinx.coroutines.withContext26import yokan.composeapp.generated.resources.Res27import yokan.composeapp.generated.resources.atkinson_hyperlegible_regular28import yokan.composeapp.generated.resources.inter_regular29import yokan.composeapp.generated.resources.jetbrains_mono_regular30import yokan.composeapp.generated.resources.lexend_variable31import yokan.composeapp.generated.resources.nunito_regular32import yokan.composeapp.generated.resources.open_sans_regular33import yokan.composeapp.generated.resources.opendyslexic_bold34import yokan.composeapp.generated.resources.opendyslexic_regular35import yokan.composeapp.generated.resources.poppins_regular36import yokan.composeapp.generated.resources.roboto_regular37import yokan.composeapp.generated.resources.roboto_slab_regular3839// Material 3 defaults. FlexColorScheme only overrides component subthemes40// (24dp inputs/chips); it does not globally tighten card and dialog shapes.41private val YokanShapes = Shapes(42 extraSmall = RoundedCornerShape(4.dp),43 small = RoundedCornerShape(8.dp),44 medium = RoundedCornerShape(12.dp),45 large = RoundedCornerShape(16.dp),46 extraLarge = RoundedCornerShape(28.dp),47)4849private fun buildYokanTypography(family: FontFamily): Typography {50 val base = Typography()51 return base.copy(52 displayLarge = base.displayLarge.withFamily(family),53 displayMedium = base.displayMedium.withFamily(family),54 displaySmall = base.displaySmall.withFamily(family),55 headlineLarge = base.headlineLarge.withFamily(family),56 headlineMedium = base.headlineMedium.withFamily(family),57 headlineSmall = base.headlineSmall.withFamily(family),58 titleLarge = base.titleLarge.withFamily(family),59 titleMedium = base.titleMedium.withFamily(family),60 titleSmall = base.titleSmall.withFamily(family),61 bodyLarge = base.bodyLarge.withFamily(family),62 bodyMedium = base.bodyMedium.withFamily(family),63 bodySmall = base.bodySmall.withFamily(family),64 labelLarge = base.labelLarge.withFamily(family),65 labelMedium = base.labelMedium.withFamily(family),66 labelSmall = base.labelSmall.withFamily(family),67 )68}6970/** Named font choices exposed in the Appearance picker, ordered for the dropdown. */71val AppFontFamilyChoices: List<String> = listOf(72 "Default", "Sans", "Serif", "Monospace",73 "Inter", "Roboto", "Roboto Slab", "Open Sans", "Nunito", "Poppins", "JetBrains Mono",74)7576/**77 * Resolve the persisted `appFontFamily` setting to a [FontFamily].78 *79 * - The four system names ("Default", "Sans", "Serif", "Monospace") use the80 * platform's stock families so they cost nothing to render.81 * - The named Google Fonts load from bundled regular-weight TTFs in82 * `composeResources/font/`. Compose Multiplatform synthesises the bold and83 * italic variants from the actual glyph metrics, which is fine for an app-84 * wide UI font (we don't need a paragraph-level type system).85 */86@Composable87fun resolveAppFontFamily(name: String?): FontFamily {88 val n = name?.lowercase().orEmpty()89 return when (n) {90 "serif" -> FontFamily.Serif91 "sans" -> FontFamily.SansSerif92 "monospace" -> FontFamily.Monospace93 "inter" -> rememberGoogleFontFamily(Res.font.inter_regular)94 "roboto" -> rememberGoogleFontFamily(Res.font.roboto_regular)95 "roboto slab" -> rememberGoogleFontFamily(Res.font.roboto_slab_regular)96 "open sans" -> rememberGoogleFontFamily(Res.font.open_sans_regular)97 "nunito" -> rememberGoogleFontFamily(Res.font.nunito_regular)98 "poppins" -> rememberGoogleFontFamily(Res.font.poppins_regular)99 "jetbrains mono" -> rememberGoogleFontFamily(Res.font.jetbrains_mono_regular)100 else -> FontFamily.Default101 }102}103104/** Resolve fonts offered specifically by the novel reader; Default follows the app choice. */105@Composable106fun resolveNovelFontFamily(name: String?, appFontFamily: String?): FontFamily = when (name?.lowercase()) {107 "opendyslexic" -> rememberNovelFontFamily(108 Res.font.opendyslexic_regular,109 Res.font.opendyslexic_bold,110 )111 "lexend" -> rememberNovelFontFamily(Res.font.lexend_variable)112 "atkinson" -> rememberNovelFontFamily(Res.font.atkinson_hyperlegible_regular)113 else -> resolveAppFontFamily(appFontFamily)114}115116@Composable117private fun rememberNovelFontFamily(118 regular: org.jetbrains.compose.resources.FontResource,119 bold: org.jetbrains.compose.resources.FontResource? = null,120): FontFamily {121 val regularFont = org.jetbrains.compose.resources.Font(regular, FontWeight.Normal)122 val boldFont = bold?.let { org.jetbrains.compose.resources.Font(it, FontWeight.Bold) }123 return remember(regular, bold) {124 if (boldFont == null) FontFamily(regularFont) else FontFamily(regularFont, boldFont)125 }126}127val LocalYokanScaffoldColor = androidx.compose.runtime.staticCompositionLocalOf {128 Color.Unspecified129}130131/** True in e-ink display mode: screens drop motion that would ghost on an e-paper panel. */132val LocalEinkMode = androidx.compose.runtime.staticCompositionLocalOf { false }133134private val EinkGray = Color(0xFFE0E0E0)135136/** Pure black on white with gray containers: tonal tints and subtle contrasts vanish on e-paper. */137private val EinkColorScheme = androidx.compose.material3.lightColorScheme(138 primary = Color.Black, onPrimary = Color.White,139 primaryContainer = EinkGray, onPrimaryContainer = Color.Black,140 inversePrimary = Color.White,141 secondary = Color.Black, onSecondary = Color.White,142 secondaryContainer = EinkGray, onSecondaryContainer = Color.Black,143 tertiary = Color.Black, onTertiary = Color.White,144 tertiaryContainer = EinkGray, onTertiaryContainer = Color.Black,145 background = Color.White, onBackground = Color.Black,146 surface = Color.White, onSurface = Color.Black,147 surfaceVariant = EinkGray, onSurfaceVariant = Color.Black,148 surfaceTint = Color.White,149 inverseSurface = Color.Black, inverseOnSurface = Color.White,150 error = Color.Black, onError = Color.White,151 errorContainer = EinkGray, onErrorContainer = Color.Black,152 outline = Color.Black, outlineVariant = Color(0xFF808080),153 scrim = Color.Black,154 surfaceBright = Color.White, surfaceDim = EinkGray,155 surfaceContainerLowest = Color.White, surfaceContainerLow = Color.White,156 surfaceContainer = Color(0xFFF0F0F0), surfaceContainerHigh = EinkGray, surfaceContainerHighest = EinkGray,157)158159@Composable160fun YokanScaffold(161 modifier: androidx.compose.ui.Modifier = androidx.compose.ui.Modifier,162 topBar: @Composable () -> Unit = {},163 bottomBar: @Composable () -> Unit = {},164 snackbarHost: @Composable () -> Unit = {},165 floatingActionButton: @Composable () -> Unit = {},166 floatingActionButtonPosition: androidx.compose.material3.FabPosition =167 androidx.compose.material3.FabPosition.End,168 contentColor: Color = MaterialTheme.colorScheme.onSurface,169 contentWindowInsets: androidx.compose.foundation.layout.WindowInsets =170 androidx.compose.material3.ScaffoldDefaults.contentWindowInsets,171 content: @Composable (androidx.compose.foundation.layout.PaddingValues) -> Unit,172) {173 androidx.compose.material3.Scaffold(174 modifier = modifier,175 topBar = topBar,176 bottomBar = bottomBar,177 snackbarHost = snackbarHost,178 floatingActionButton = floatingActionButton,179 floatingActionButtonPosition = floatingActionButtonPosition,180 containerColor = LocalYokanScaffoldColor.current,181 contentColor = contentColor,182 contentWindowInsets = contentWindowInsets,183 content = content,184 )185}186@Composable187private fun yokanDividerColor(): Color =188 if (MaterialTheme.colorScheme.surface.luminance() < 0.5f) {189 Color.White.copy(alpha = 31f / 255f)190 } else {191 Color.Black.copy(alpha = 31f / 255f)192 }193194@Composable195fun YokanHorizontalDivider(196 modifier: androidx.compose.ui.Modifier = androidx.compose.ui.Modifier,197 thickness: androidx.compose.ui.unit.Dp = 1.dp,198 color: Color = yokanDividerColor(),199) {200 androidx.compose.material3.HorizontalDivider(201 modifier = modifier,202 thickness = thickness,203 color = color,204 )205}206207208private data class ResolvedThemeColors(209 val scheme: ColorScheme,210 val scaffold: Color,211)212213@Composable214private fun rememberGoogleFontFamily(215 resource: org.jetbrains.compose.resources.FontResource,216): FontFamily {217 val font = org.jetbrains.compose.resources.Font(resource, FontWeight.Normal)218 return remember(resource) { FontFamily(font) }219}220221private fun TextStyle.withFamily(family: FontFamily): TextStyle =222 copy(fontFamily = family)223224fun resolveDarkMode(followSystem: Boolean, themeIsDark: Boolean, systemDark: Boolean): Boolean =225 if (followSystem) systemDark else themeIsDark226227@Composable228fun YokanTheme(229 darkTheme: Boolean,230 schemeIndex: Int = 2,231 pureBlackDark: Boolean = false,232 blendLevel: Float = 0.1f,233 uiScale: Float = 1.0f,234 seedColorArgb: Int? = null,235 seedImagePath: String? = null,236 materialYou: Boolean = false,237 materialExpressive: Boolean = false,238 paletteStyleName: String = "TonalSpot",239 fontFamily: FontFamily = FontFamily.Default,240 eink: Boolean = false,241 content: @Composable () -> Unit,242) {243 val themed = resolveThemeColors(244 darkTheme = darkTheme,245 schemeIndex = schemeIndex,246 pureBlackDark = pureBlackDark,247 blendLevel = blendLevel,248 seedColorArgb = seedColorArgb,249 seedImagePath = seedImagePath,250 materialYou = materialYou,251 materialExpressive = materialExpressive,252 paletteStyleName = paletteStyleName,253 )254 val resolvedColors = if (eink) ResolvedThemeColors(EinkColorScheme, Color.White) else themed255 val clampedScale = uiScale.coerceIn(0.75f, 2.0f)256 val baseDensity = androidx.compose.ui.platform.LocalDensity.current257 val scaledDensity = androidx.compose.ui.unit.Density(258 density = baseDensity.density * clampedScale,259 fontScale = baseDensity.fontScale,260 )261 androidx.compose.runtime.CompositionLocalProvider(262 androidx.compose.ui.platform.LocalDensity provides scaledDensity,263 LocalYokanScaffoldColor provides resolvedColors.scaffold,264 LocalEinkMode provides eink,265 // Ripples animate for hundreds of milliseconds and ghost on e-paper.266 androidx.compose.material3.LocalRippleConfiguration provides267 if (eink) null else androidx.compose.material3.LocalRippleConfiguration.current,268 ) {269 // `MaterialExpressiveTheme` is not yet stable in Compose Multiplatform's270 // material3 surface (1.4 marks it `internal`). To still honour the271 // user's Expressive toggle we feed `PaletteStyle.Expressive` +272 // `ColorSpec.SPEC_2025` into the color scheme (see `resolvePaletteStyle`),273 // which is the runtime-visible half of the spec. Motion/typography274 // upgrades land once material3 exposes the expressive APIs publicly.275 val typography = remember(fontFamily) { buildYokanTypography(fontFamily) }276 MaterialTheme(277 colorScheme = resolvedColors.scheme,278 typography = typography,279 shapes = YokanShapes,280 content = content,281 )282 }283}284285@Composable286private fun resolveThemeColors(287 darkTheme: Boolean,288 schemeIndex: Int,289 pureBlackDark: Boolean,290 blendLevel: Float,291 seedColorArgb: Int?,292 seedImagePath: String?,293 materialYou: Boolean,294 materialExpressive: Boolean,295 paletteStyleName: String,296): ResolvedThemeColors {297 // Material You: defer to the OS palette when the user opted in and the298 // platform actually exposes one (Android 12+).299 if (materialYou) {300 rememberMaterialYouScheme(darkTheme)?.let {301 return ResolvedThemeColors(scheme = it, scaffold = it.background)302 }303 }304305 val legacyFallback = remember(schemeIndex, darkTheme, pureBlackDark, blendLevel) {306 val scheme = FlexSchemes.getOrElse(schemeIndex) { FlexSchemes[2] }307 if (darkTheme) {308 ResolvedThemeColors(309 scheme = buildDarkScheme(scheme.dark, scheme.light, blendLevel),310 scaffold = buildDarkScaffoldColor(scheme.dark, blendLevel, pureBlackDark),311 )312 } else {313 ResolvedThemeColors(314 scheme = buildLightScheme(scheme.light, blendLevel),315 scaffold = buildLightScaffoldColor(scheme.light, blendLevel),316 )317 }318 }319320 // Decoding and quantizing the seed image is file I/O + CPU work: keep it off composition.321 val fallbackPrimary = legacyFallback.scheme.primary322 val imageSeed: Color? by produceState<Color?>(null, seedImagePath, fallbackPrimary) {323 value = seedImagePath?.takeIf { it.isNotBlank() }?.let { path ->324 withContext(Dispatchers.Default) { decodeImageBitmap(path)?.themeColor(fallback = fallbackPrimary) }325 }326 }327 // Mangayomi's normal path is FlexThemeData built from the selected328 // FlexSchemeColor. Do not reinterpret that palette as a Material You seed:329 // doing so changes every container, badge, tab, and navigation color.330 if (seedColorArgb == null && imageSeed == null && !materialExpressive) {331 return legacyFallback332 }333334 // Precedence: image > explicit seed > legacy palette primary.335 val seed = imageSeed336 ?: seedColorArgb?.let { Color(it.toLong() and 0xFFFFFFFFL) }337 ?: legacyFallback.scheme.primary338 val style = resolvePaletteStyle(paletteStyleName, materialExpressive)339 val dynamicScheme = rememberDynamicColorScheme(340 seedColor = seed,341 isDark = darkTheme,342 isAmoled = pureBlackDark && darkTheme,343 style = style,344 // SPEC_2025 is required for Material Expressive — when the toggle is off345 // we still opt into it so users get the latest tonal mapping.346 specVersion = ColorSpec.SpecVersion.SPEC_2025,347 )348 return ResolvedThemeColors(scheme = dynamicScheme, scaffold = dynamicScheme.background)349}350351private fun resolvePaletteStyle(name: String, materialExpressive: Boolean): PaletteStyle {352 // Material Expressive overrides whatever the user picked because the spec353 // pairs Expressive motion with the Expressive palette.354 if (materialExpressive) return PaletteStyle.Expressive355 return PaletteStyle.entries.firstOrNull { it.name.equals(name, ignoreCase = true) } ?: PaletteStyle.TonalSpot356}357358/** Names of MaterialKolor palette styles exposed in the settings dropdown. */359val PaletteStyleChoices: List<String>360 get() = PaletteStyle.entries.map { it.name }361362@Composable363fun rememberSystemDark(): Boolean = isSystemInDarkTheme()364