Yokan / rebuild
Course 1 8624561

02-compose-ui.md

.codex/skills/compose-kotlin-agent-skills/references/02-compose-ui.md

documentation / design asset438 lines
1# Compose UI — Composition, Recomposition, Material 3, Theming23## Contents45- Composition and recomposition deep dive6- Stability — @Stable, @Immutable, why it matters7- Modifier chain best practices8- Slot APIs and component design9- Material 3 — proper usage and tokens10- Dark/Light mode — custom color token architecture11- Premium UI systems — typography scale12- Adaptive layouts — WindowSizeClass, foldables1314## Composition and Recomposition1516### The Three Phases1718```19Composition → Layout → Drawing20(WHAT to show)  (WHERE to place)  (HOW to render)21```2223State reads in each phase only trigger work for that phase onward:24- State read in Composition → recomposition → relayout → redraw25- State read in Layout (via `Modifier.layout {}`) → relayout → redraw26- State read in Drawing (via `Modifier.drawBehind {}`) → redraw only2728**Performance insight:** defer state reads to the latest possible phase.2930```kotlin31// BAD — triggers full recomposition on every scroll offset change32@Composable33fun ParallaxHeader(scrollState: ScrollState) {34    val offset = scrollState.value  // read in Composition phase35    Image(36        modifier = Modifier.offset(y = (-offset / 2).dp)37    )38}3940// GOOD — offset read deferred to Layout phase, skips recomposition41@Composable42fun ParallaxHeader(scrollState: ScrollState) {43    Image(44        modifier = Modifier.offset {45            IntOffset(0, -scrollState.value / 2)  // read in Layout phase46        }47    )48}49```5051### Recomposition Scope5253Compose recomposes the nearest restartable scope. A scope = a non-inline `@Composable` function that returns `Unit`.5455```kotlin56// BAD — entire Column recomposes when name changes57@Composable58fun Profile(name: String, avatarUrl: String) {59    Column {60        Text(name)           // name changed61        Avatar(avatarUrl)    // recomposes unnecessarily62        SettingsButton()     // recomposes unnecessarily63    }64}6566// GOOD — extract into separate composables = separate scopes67@Composable68fun Profile(name: String, avatarUrl: String) {69    Column {70        NameText(name)       // own scope — only this recomposes71        Avatar(avatarUrl)    // skipped if avatarUrl unchanged72        SettingsButton()     // skipped — no params changed73    }74}7576@Composable77private fun NameText(name: String) {78    Text(name)79}80```8182### What Triggers Recomposition8384| Trigger | Example |85|---------|---------|86| `mutableStateOf` value changes | `var count by mutableStateOf(0); count++` |87| `StateFlow` emits new value | `_state.update { it.copy(name = "new") }` |88| Parent recomposes with new params | `ChildComposable(newParam)` |89| `CompositionLocal` value changes | `LocalAppTheme provides newTheme` |9091What does NOT trigger recomposition:92- Reading a non-state variable93- A `remember`ed value (unless its key changes)94- A stable parameter that equals the previous value (skipping)9596## Stability9798Compose compiler determines if parameters changed by checking **stability**. Stable types enable skipping — unstable types always recompose.99100### Automatically Stable101- Primitives (`Int`, `Float`, `Boolean`, `String`)102- `enum class`103- `@Immutable` annotated classes104- `@Stable` annotated classes105- Function types (lambdas) — but only if captured values are stable106107### Automatically Unstable108- `List`, `Map`, `Set` (mutable collection interfaces)109- Classes from external modules without Compose compiler110- Classes with `var` properties111112```kotlin113// UNSTABLE — List is a mutable interface, Compose can't prove immutability114data class AccountsUiState(115    val accounts: List<AuthAccount> = emptyList()  // unstable!116)117118// Fix 1: @Immutable annotation (promise to Compose compiler)119@Immutable120data class AccountsUiState(121    val accounts: List<AuthAccount> = emptyList()122)123124// Fix 2: Use kotlinx.collections.immutable125data class AccountsUiState(126    val accounts: ImmutableList<AuthAccount> = persistentListOf()127)128```129130**When to annotate:**131- `@Immutable` — value NEVER changes after construction. All properties `val`. Use for UiState.132- `@Stable` — value CAN change, but Compose is notified via snapshot system. Use for wrapper classes with `mutableStateOf` inside.133134**Strong skipping mode** (Compose compiler 2.0+): enabled by default. Lambdas auto-remembered, unstable params compared by `equals`. Reduces need for manual `@Stable` annotations but doesn't eliminate it for collection-heavy states.135136## Modifier Chain Best Practices137138### Order Matters — Mental Model139140Read modifiers outside → inside. Each modifier wraps the next one:141142```kotlin143Modifier144    .fillMaxWidth()                          // 1. take full width145    .padding(horizontal = 16.dp)             // 2. outer spacing (margin)146    .shadow(4.dp, RoundedCornerShape(12.dp)) // 3. shadow before clip147    .clip(RoundedCornerShape(12.dp))         // 4. clip shape148    .background(MaterialTheme.colorScheme.surface)  // 5. fill color149    .clickable { onClick() }                 // 6. ripple inside clipped area150    .padding(16.dp)                          // 7. inner spacing (padding)151```152153### Common Ordering Rules154155| Goal | Modifier Order |156|------|---------------|157| Card with shadow | `padding → shadow → clip → background → clickable → padding` |158| Clickable row | `fillMaxWidth → clip → clickable → padding` |159| Icon button | `size → clip(CircleShape) → clickable → padding` |160| Colored badge | `clip → background → padding` |161162### Gotcha — Clickable Before vs After Padding163164```kotlin165// Clickable BEFORE padding → touch target includes padding (bigger)166Modifier.clickable { }.padding(16.dp)167168// Clickable AFTER padding → touch target excludes padding (smaller)169Modifier.padding(16.dp).clickable { }170```171172For accessibility, touch targets should be at least 48dp. Put clickable BEFORE inner padding.173174## Slot APIs and Component Design175176Slot API = composable parameter instead of data parameter. Gives caller control over content.177178```kotlin179// BAD — rigid, can only show text180@Composable181fun AppCard(title: String, subtitle: String) {182    Card {183        Text(title)184        Text(subtitle)185    }186}187188// GOOD — slot API, caller decides content189@Composable190fun AppCard(191    modifier: Modifier = Modifier,192    header: @Composable () -> Unit = {},193    content: @Composable ColumnScope.() -> Unit,194    footer: @Composable () -> Unit = {}195) {196    Card(modifier = modifier) {197        header()198        Column(content = content)199        footer()200    }201}202203// Usage — flexible204AppCard(205    header = { Text("Account Details") },206    content = {207        AccountInfo(account)208        TimerProgress(timeRemaining)209    },210    footer = { CopyButton(onClick = onCopy) }211)212```213214**Component contract checklist:**2151. First param: `modifier: Modifier = Modifier` (always)2162. Slot params: `@Composable () -> Unit` with defaults2173. Action params: lambdas (`onClick: () -> Unit`)2184. Data params: domain types, not UI types2195. No ViewModel references220221## Material 3 — Tokens and Dynamic Color222223### Color Roles (Use These, Not Hardcoded Hex)224225```kotlin226MaterialTheme.colorScheme.primary          // brand color227MaterialTheme.colorScheme.onPrimary        // text/icon on primary228MaterialTheme.colorScheme.primaryContainer // lighter brand for containers229MaterialTheme.colorScheme.surface          // card/sheet background230MaterialTheme.colorScheme.onSurface        // text on surface231MaterialTheme.colorScheme.surfaceVariant   // secondary surface232MaterialTheme.colorScheme.error            // error state233MaterialTheme.colorScheme.outline          // borders, dividers234```235236### Dynamic Color (Android 12+)237238```kotlin239@Composable240fun AppTheme(content: @Composable () -> Unit) {241    val colorScheme = when {242        Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {243            val context = LocalContext.current244            if (isSystemInDarkTheme()) dynamicDarkColorScheme(context)245            else dynamicLightColorScheme(context)246        }247        isSystemInDarkTheme() -> darkColorScheme(/* custom dark */)248        else -> lightColorScheme(/* custom light */)249    }250    MaterialTheme(colorScheme = colorScheme, content = content)251}252```253254## Custom Color Token Architecture255256When M3 color roles don't cover your domain (timer colors, workout type colors, semantic states), build a custom token system:257258From Authenticator — `AppColors` with Light/Dark variants:259260```kotlin261object AppColors {262    object Light {263        val Primary = Color(0xFF6366F1)264        val Background = Color(0xFFF8FAFC)265        val Surface = Color(0xFFFFFFFF)266        val OnSurface = Color(0xFF0F172A)267        val CardBackground = Color(0xFFFFFFFF)268        val Success = Color(0xFF10B981)269        val Warning = Color(0xFFF59E0B)270        val Error = Color(0xFFEF4444)271        val TimerGood = Color(0xFF059669)272        val TimerWarning = Color(0xFFD97706)273        val TimerCritical = Color(0xFFDC2626)274    }275    object Dark {276        val Primary = Color(0xFF818CF8)      // lighter for dark bg277        val Background = Color(0xFF0F172A)278        val Surface = Color(0xFF1E293B)279        val OnSurface = Color(0xFFF8FAFC)280        val CardBackground = Color(0xFF1E293B)281        val Success = Color(0xFF34D399)282        val Warning = Color(0xFFFBBF24)283        val Error = Color(0xFFF87171)284        val TimerGood = Color(0xFF10B981)285        val TimerWarning = Color(0xFFF59E0B)286        val TimerCritical = Color(0xFFEF4444)287    }288}289```290291Deliver via `CompositionLocal`:292293```kotlin294data class AppTheme(295    val primary: Color,296    val background: Color,297    val surface: Color,298    val onSurface: Color,299    val cardBackground: Color,300    val success: Color,301    val warning: Color,302    val error: Color,303    val timerGood: Color,304    val timerWarning: Color,305    val timerCritical: Color,306    val isLight: Boolean307)308309val LocalAppTheme = compositionLocalOf<AppTheme> {310    error("No AppTheme provided — wrap your content in ProvideAppTheme")311}312313@Composable314fun ProvideAppTheme(315    themeManager: ThemeManager,316    content: @Composable () -> Unit317) {318    val themeMode by themeManager.themeMode.collectAsState()319    val isDark = when (themeMode) {320        ThemeMode.LIGHT -> false321        ThemeMode.DARK -> true322        ThemeMode.SYSTEM -> isSystemInDarkTheme()323    }324    val theme = if (isDark) AppTheme(325        primary = AppColors.Dark.Primary,326        background = AppColors.Dark.Background,327        // ... all dark tokens328        isLight = false329    ) else AppTheme(330        primary = AppColors.Light.Primary,331        background = AppColors.Light.Background,332        // ... all light tokens333        isLight = true334    )335    CompositionLocalProvider(LocalAppTheme provides theme, content = content)336}337```338339**Access anywhere:**340```kotlin341val theme = LocalAppTheme.current342Box(modifier = Modifier.background(theme.cardBackground))343Text(color = theme.onSurface, text = "Hello")344```345346## Typography Scale347348```kotlin349val AppTypography = Typography(350    displayLarge = TextStyle(351        fontFamily = FontFamily.SansSerif,352        fontWeight = FontWeight.ExtraBold,353        fontSize = 40.sp,354        lineHeight = 48.sp355    ),356    titleLarge = TextStyle(357        fontFamily = FontFamily.SansSerif,358        fontWeight = FontWeight.Bold,359        fontSize = 26.sp,360        lineHeight = 32.sp361    ),362    bodyLarge = TextStyle(363        fontFamily = FontFamily.SansSerif,364        fontWeight = FontWeight.Normal,365        fontSize = 16.sp,366        lineHeight = 24.sp367    ),368    labelLarge = TextStyle(369        fontFamily = FontFamily.SansSerif,370        fontWeight = FontWeight.Bold,371        fontSize = 15.sp,372        lineHeight = 20.sp373    )374)375376// Usage — always through MaterialTheme377Text(378    text = "Account Name",379    style = MaterialTheme.typography.titleLarge380)381```382383**Never use raw `fontSize` in composables.** Always reference typography tokens.384385## Adaptive Layouts — WindowSizeClass386387```kotlin388@Composable389fun AdaptiveApp() {390    val windowSizeClass = calculateWindowSizeClass(LocalContext.current as Activity)391392    when (windowSizeClass.widthSizeClass) {393        WindowWidthSizeClass.Compact -> {394            // Phone — single pane, bottom nav395            PhoneLayout()396        }397        WindowWidthSizeClass.Medium -> {398            // Small tablet / foldable — navigation rail399            TabletLayout(showRail = true)400        }401        WindowWidthSizeClass.Expanded -> {402            // Large tablet / desktop — two pane403            TwoPaneLayout()404        }405    }406}407```408409### Two-Pane Pattern410411```kotlin412@Composable413fun TwoPaneLayout() {414    Row(modifier = Modifier.fillMaxSize()) {415        // List pane — 40% width416        AccountsList(417            modifier = Modifier.weight(0.4f),418            onAccountSelected = { selectedId = it }419        )420        // Detail pane — 60% width421        AccountDetail(422            modifier = Modifier.weight(0.6f),423            accountId = selectedId424        )425    }426}427```428429**Foldable support:** use `WindowInfoTracker` from `androidx.window` to detect fold position and avoid placing content across the fold.430431## Anti-Patterns432433- **Hardcoded colors in composables** → use `MaterialTheme.colorScheme` or custom tokens via `CompositionLocal`434- **Raw `fontSize` / `fontWeight`** → use `MaterialTheme.typography` tokens435- **`remember { mutableStateOf() }` for ViewModel-level state** → survives recomposition, not config change. Use ViewModel + StateFlow436- **Nested scrolling without `nestedScroll`** → `LazyColumn` inside `Column(verticalScroll)` crashes. Use `LazyColumn` with mixed `item {}` blocks instead437- **`Box` with `Modifier.fillMaxSize()` as root** → use `Scaffold` for screens with top bar, bottom bar, FAB, snackbar438- **Ignoring `Modifier` parameter on public composables** → every public composable must accept `modifier: Modifier = Modifier` as first param439

Search chapters, reference and source filenames.