Skip to content

Instantly share code, notes, and snippets.

@alashow
Created June 25, 2021 00:09
Show Gist options
  • Save alashow/e67a75d662a13ce5529317bde3e241c2 to your computer and use it in GitHub Desktop.
Save alashow/e67a75d662a13ce5529317bde3e241c2 to your computer and use it in GitHub Desktop.
@Composable
private fun App() {
val isDarkMode = isSystemInDarkTheme()
val (darkMode, setDarkMode) = remember { mutableStateOf(isDarkMode) }
AppTheme(darkTheme = darkMode) {
Switch(checked = darkMode, onCheckedChange = setDarkMode)
Text("${AppTheme.colors.onSurfaceInputBackground.toArgb()}")
}
}
private val DarkAppColors = AppColors(
onSurfaceInputBackground = Color.Red,
darkColors(
primary = Color.Black,
)
)
private val LightAppColors = AppColors(
onSurfaceInputBackground = Color.Blue,
lightColors(
primary = Color.White,
)
)
@Composable
fun AppTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
content: @Composable () -> Unit
) {
val colors = if (darkTheme) DarkAppColors else LightAppColors
ProvideAppColors(colors) {
MaterialTheme(
colors = colors.materialColors,
typography = Typography,
shapes = Shapes,
content = content
)
}
}
@Stable
class AppColors(
onSurfaceInputBackground: Color,
materialColors: Colors
) {
var onSurfaceInputBackground by mutableStateOf(onSurfaceInputBackground)
private set
var materialColors by mutableStateOf(materialColors)
private set
fun update(other: AppColors) {
onSurfaceInputBackground = other.onSurfaceInputBackground
materialColors = other.materialColors
}
fun copy() = AppColors(this.onSurfaceInputBackground, this.materialColors)
}
@Composable
fun ProvideAppColors(
colors: AppColors,
content: @Composable () -> Unit
) {
val appColors = remember { colors.copy() }.apply { update(colors) }
CompositionLocalProvider(
LocalAppColors provides appColors,
content = content
)
}
private val LocalAppColors = staticCompositionLocalOf<AppColors> {
error("No AppColors provided")
}
object AppTheme {
val colors: AppColors
@Composable
get() = LocalAppColors.current
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment