From ed1f0a923b29c9ee93b78b19f0bd662b71f158a7 Mon Sep 17 00:00:00 2001 From: Mark Allison Date: Mon, 27 Jan 2025 15:39:20 +0000 Subject: [PATCH] Adds section on using Haze in deep UI hierarchies. (#494) --- docs/usage.md | 85 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) diff --git a/docs/usage.md b/docs/usage.md index e09d0f93..21eeaef5 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -26,6 +26,91 @@ Box { ) } ``` +## Deep UI hierarchies + +You can pass `HazeState` objects to composables as arguments. For example: + +```kotlin hl_lines="3 7 11" +@Composable +fun HazeExample(modifier: Modifier = Modifier) { + val hazeState = remember { HazeState() } + + Box(modifier = modifier) { + Background( + hazeState = hazeState, + modifier = Modifier.fillMaxSize() + ) + Foreground( + hazeState = hazeState, + modifier = Modifier.fillMaxSize() + ) + } +} +``` + +You can then use the argument to configure `hazeSource` and `hazeEffect`: + +```kotlin hl_lines="4 13-16" +@OptIn(ExperimentalHazeMaterialsApi::class) +@Composable +fun Foreground( + hazeState: HazeState, + modifier: Modifier = Modifier +) { + Box(modifier = modifier) { + Text( + text = stringResource(R.string.haze_text), + modifier = modifier + .align(Alignment.Center) + .wrapContentSize() + .hazeEffect( + state = hazeState, + style = HazeMaterials.ultraThin() + ) + ) + } +} +``` + +However, this can problematic in deep hierarchies when you need to pass the `HazeState` instances +down through many levels. To avoid this you can use a composition local to pass the `HazeState` +down to the descendants in the hierarchy: + +```kotlin hl_lines="1 5 7 12 20 28" +val LocalHazeState = compositionLocalOf { HazeState() } + +@Composable +fun HazeExample(modifier: Modifier = Modifier) { + val hazeState = remember { HazeState() } + + CompositionLocalProvider(LocalHazeState provides hazeState) { + Box(modifier = modifier) { + Background(modifier = Modifier.fillMaxSize()) + Foreground(modifier = Modifier.fillMaxSize()) + } + } +} +. +. +. +@OptIn(ExperimentalHazeMaterialsApi::class) +@Composable +fun Foreground(modifier: Modifier = Modifier) { + val hazeState = LocalHazeState.current + Box(modifier = modifier) { + Text( + text = stringResource(R.string.haze_text), + modifier = modifier + .align(Alignment.Center) + .wrapContentSize() + .hazeEffect( + state = hazeState, + style = HazeMaterials.ultraThin() + ) + ) + } +} +``` ## Styling