03-animations.md
.codex/skills/compose-kotlin-agent-skills/references/03-animations.md
1# Animations — Springs, Canvas, Gestures, Shared Elements23## Contents45- Animation decision tree6- AnimatedVisibility, AnimatedContent, Crossfade7- animate*AsState — float, dp, color8- Spring physics — dampingRatio, stiffness tuning9- rememberInfiniteTransition — shimmer, pulse, breathing10- Canvas-based custom animations11- Gesture-driven animations12- Shared element transitions (Navigation 3)1314## Animation Decision Tree1516```17Need to show/hide content?18 → AnimatedVisibility (enter/exit transitions)1920Need to swap between states?21 → AnimatedContent (with transitionSpec)22 → Crossfade (simple fade between states)2324Need to animate a single value?25 → animate*AsState (fire-and-forget)26 → Animatable (coroutine-driven, full control)2728Need continuous animation?29 → rememberInfiniteTransition (loop forever)3031Need gesture-driven?32 → Animatable + pointerInput (drag, fling, snap)3334Need Canvas-level custom?35 → DrawScope + rotate/translate + animated values36```3738## AnimatedVisibility3940```kotlin41var isVisible by remember { mutableStateOf(false) }4243AnimatedVisibility(44 visible = isVisible,45 enter = fadeIn(animationSpec = tween(300)) +46 slideInVertically(initialOffsetY = { -it / 2 }),47 exit = fadeOut(animationSpec = tween(200)) +48 slideOutVertically(targetOffsetY = { -it / 2 })49) {50 AccountCard(account)51}52```5354**Gotcha:** `AnimatedVisibility` keeps content in composition during exit animation. Don't null-check inside.5556## AnimatedContent5758```kotlin59AnimatedContent(60 targetState = selectedTab,61 transitionSpec = {62 // Slide in from right + fade in, slide out to left + fade out63 (slideInHorizontally { it } + fadeIn()) togetherWith64 (slideOutHorizontally { -it } + fadeOut()) using65 SizeTransform(clip = false)66 },67 label = "tab_content"68) { tab ->69 when (tab) {70 Tab.Home -> HomeScreen()71 Tab.Settings -> SettingsScreen()72 }73}74```7576## animate*AsState — Fire and Forget7778```kotlin79// Float — alpha, scale, rotation80val alpha by animateFloatAsState(81 targetValue = if (isSelected) 1f else 0.5f,82 animationSpec = tween(300),83 label = "alpha"84)8586// Dp — size, offset, padding87val elevation by animateDpAsState(88 targetValue = if (isPressed) 2.dp else 8.dp,89 animationSpec = spring(dampingRatio = Spring.DampingRatioMediumBouncy),90 label = "elevation"91)9293// Color — smooth theme transitions94val backgroundColor by animateColorAsState(95 targetValue = if (isDark) Color(0xFF1E293B) else Color(0xFFFFFFFF),96 animationSpec = tween(500),97 label = "bg_color"98)99```100101**Always provide `label`** — shows in Layout Inspector animation preview.102103## Spring Physics104105Springs feel natural because they don't have fixed duration. They respond to velocity.106107### Tuning Guide108109| dampingRatio | Behavior | Use for |110|-------------|----------|---------|111| `DampingRatioHighBouncy` (0.2) | Very bouncy, multiple oscillations | Playful UI, game-like |112| `DampingRatioMediumBouncy` (0.5) | Moderate bounce, 1-2 overshoots | Buttons, cards, toggles |113| `DampingRatioLowBouncy` (0.75) | Slight bounce, settles fast | Subtle feedback |114| `DampingRatioNoBouncy` (1.0) | No bounce, smooth settle | Professional, subtle |115116| stiffness | Behavior | Use for |117|-----------|----------|---------|118| `StiffnessHigh` (10000) | Snappy, fast | Button press, quick feedback |119| `StiffnessMedium` (1500) | Balanced | General transitions |120| `StiffnessMediumLow` (400) | Relaxed | Page transitions, large elements |121| `StiffnessLow` (200) | Slow, gentle | Ambient animations |122| `StiffnessVeryLow` (1) | Very slow | Background effects |123124From AnimatedClock — bouncy seconds unit:125126```kotlin127val scale by animateFloatAsState(128 targetValue = if (value == 0) 1.3f else 1f,129 animationSpec = spring(130 dampingRatio = Spring.DampingRatioMediumBouncy,131 stiffness = Spring.StiffnessLow132 ),133 label = "scale"134)135136Column(modifier = Modifier.graphicsLayer(scaleX = scale, scaleY = scale)) {137 Text(text = formatted, fontSize = 32.sp, fontWeight = FontWeight.Bold)138}139```140141**Gotcha:** `stiffness = 0f` crashes. Minimum is `Spring.StiffnessVeryLow` (1f).142143## rememberInfiniteTransition144145For animations that loop forever — shimmer, pulse, breathing, rotation.146147From AnimatedClock — ice glow pulse:148149```kotlin150val infiniteTransition = rememberInfiniteTransition(label = "effects")151152val glowAlpha by infiniteTransition.animateFloat(153 initialValue = 0.4f,154 targetValue = 0.9f,155 animationSpec = infiniteRepeatable(156 animation = tween(3000, easing = FastOutSlowInEasing),157 repeatMode = RepeatMode.Reverse // ping-pong158 ),159 label = "glow"160)161162val rotation by infiniteTransition.animateFloat(163 initialValue = 0f,164 targetValue = 360f,165 animationSpec = infiniteRepeatable(166 animation = tween(60_000, easing = LinearEasing),167 repeatMode = RepeatMode.Restart // continuous spin168 ),169 label = "rotation"170)171```172173### Shimmer Effect174175```kotlin176@Composable177fun ShimmerBox(modifier: Modifier = Modifier) {178 val transition = rememberInfiniteTransition(label = "shimmer")179 val translateX by transition.animateFloat(180 initialValue = -300f,181 targetValue = 300f,182 animationSpec = infiniteRepeatable(183 animation = tween(1200, easing = LinearEasing),184 repeatMode = RepeatMode.Restart185 ),186 label = "shimmer_x"187 )188 Box(189 modifier = modifier190 .clip(RoundedCornerShape(8.dp))191 .background(192 brush = Brush.linearGradient(193 colors = listOf(194 Color.LightGray.copy(alpha = 0.3f),195 Color.LightGray.copy(alpha = 0.7f),196 Color.LightGray.copy(alpha = 0.3f)197 ),198 start = Offset(translateX, 0f),199 end = Offset(translateX + 200f, 0f)200 )201 )202 )203}204```205206## Canvas-Based Custom Animations207208From AnimatedClock — full analog clock with animated hands:209210### Snowflake Particle System211212```kotlin213data class Snowflake(214 val startX: Float,215 val startY: Float,216 val size: Float,217 val alpha: Float,218 val amplitude: Float,219 val phase: Float220)221222@Composable223fun SnowfallBackground() {224 val snowflakes = remember { List(150) {225 Snowflake(226 startX = Random.nextFloat() * 1000f,227 startY = -Random.nextFloat() * 200f,228 size = Random.nextFloat() * 3f + 1f,229 alpha = Random.nextFloat() * 0.6f + 0.2f,230 amplitude = Random.nextFloat() * 30f + 10f,231 phase = Random.nextFloat() * 2f * PI.toFloat()232 )233 }}234235 val infiniteTransition = rememberInfiniteTransition(label = "snowfall")236 val progress by infiniteTransition.animateFloat(237 initialValue = 0f,238 targetValue = 1f,239 animationSpec = infiniteRepeatable(240 animation = tween(20_000, easing = LinearEasing),241 repeatMode = RepeatMode.Restart242 ),243 label = "snow_progress"244 )245246 Canvas(modifier = Modifier.fillMaxSize()) {247 snowflakes.forEach { flake ->248 val y = (flake.startY + (size.height + 100) * progress) % (size.height + 200)249 val x = flake.startX + sin(y * 0.01f + flake.phase) * flake.amplitude250 drawCircle(251 color = Color.White.copy(alpha = flake.alpha),252 radius = flake.size,253 center = Offset(x, y)254 )255 }256 }257}258```259260**Pattern:** data class for particle state + `remember` for initial state + infinite transition for progress + Canvas for rendering.261262### Clock Hands with rotate()263264```kotlin265fun DrawScope.drawClockHands(hour: Int, minute: Int, second: Int) {266 val center = size.center267 val radius = size.minDimension / 2 * 0.85f268269 val hourAngle = (hour % 12) * 30f + minute * 0.5f270 val minuteAngle = minute * 6f + second * 0.1f271 val secondAngle = second * 6f272273 // Hour hand — rotate() handles all trig274 rotate(hourAngle, center) {275 drawLine(276 brush = Brush.linearGradient(277 listOf(Color(0xFF87CEEB), Color.White, Color(0xFF4169E1))278 ),279 start = center,280 end = Offset(center.x, center.y - radius * 0.5f),281 strokeWidth = 12f,282 cap = StrokeCap.Round283 )284 }285286 // Minute hand287 rotate(minuteAngle, center) {288 drawLine(289 brush = Brush.linearGradient(290 listOf(Color(0xFF4169E1), Color.White, Color(0xFF87CEEB))291 ),292 start = center,293 end = Offset(center.x, center.y - radius * 0.7f),294 strokeWidth = 8f,295 cap = StrokeCap.Round296 )297 }298299 // Second hand with counterweight300 rotate(secondAngle, center) {301 drawLine(302 color = Color(0xFFFF4444),303 start = center,304 end = Offset(center.x, center.y - radius * 0.8f),305 strokeWidth = 3f,306 cap = StrokeCap.Round307 )308 drawLine(309 color = Color(0xFFFF4444),310 start = center,311 end = Offset(center.x, center.y + radius * 0.2f),312 strokeWidth = 6f,313 cap = StrokeCap.Round314 )315 }316}317```318319**Key insight:** `rotate(degrees, pivot)` in `DrawScope` handles all trigonometry. Draw the hand pointing up, rotate to the correct angle. Never manually calculate sin/cos for each hand.320321## Gesture-Driven Animations322323### Drag to Dismiss324325```kotlin326@Composable327fun SwipeToDismiss(onDismiss: () -> Unit, content: @Composable () -> Unit) {328 val offsetX = remember { Animatable(0f) }329 val scope = rememberCoroutineScope()330331 Box(332 modifier = Modifier333 .offset { IntOffset(offsetX.value.roundToInt(), 0) }334 .pointerInput(Unit) {335 detectHorizontalDragGestures(336 onDragEnd = {337 scope.launch {338 if (abs(offsetX.value) > size.width / 3) {339 offsetX.animateTo(340 targetValue = if (offsetX.value > 0) size.width.toFloat()341 else -size.width.toFloat(),342 animationSpec = tween(200)343 )344 onDismiss()345 } else {346 offsetX.animateTo(347 targetValue = 0f,348 animationSpec = spring(349 dampingRatio = Spring.DampingRatioMediumBouncy350 )351 )352 }353 }354 },355 onHorizontalDrag = { _, dragAmount ->356 scope.launch { offsetX.snapTo(offsetX.value + dragAmount) }357 }358 )359 }360 ) {361 content()362 }363}364```365366### Press Scale Effect367368```kotlin369fun Modifier.pressEffect(targetScale: Float = 0.95f): Modifier = composed {370 var isPressed by remember { mutableStateOf(false) }371 val scale by animateFloatAsState(372 targetValue = if (isPressed) targetScale else 1f,373 animationSpec = spring(374 dampingRatio = Spring.DampingRatioMediumBouncy,375 stiffness = Spring.StiffnessHigh376 ),377 label = "press_scale"378 )379 this380 .graphicsLayer(scaleX = scale, scaleY = scale)381 .pointerInput(Unit) {382 detectTapGestures(383 onPress = {384 isPressed = true385 tryAwaitRelease()386 isPressed = false387 }388 )389 }390}391```392393## Shared Element Transitions (Navigation 3)394395```kotlin396// Nav 3 shared element — experimental as of 2025397NavHost(navController = navController, startDestination = "list") {398 composable("list") {399 LazyColumn {400 items(accounts, key = { it.id }) { account ->401 SharedTransitionLayout {402 AccountCard(403 account = account,404 modifier = Modifier.sharedElement(405 state = rememberSharedContentState(key = "account-${account.id}"),406 animatedVisibilityScope = this@composable407 )408 )409 }410 }411 }412 }413 composable("detail/{id}") { backStackEntry ->414 SharedTransitionLayout {415 AccountDetail(416 modifier = Modifier.sharedElement(417 state = rememberSharedContentState(418 key = "account-${backStackEntry.arguments?.getString("id")}"419 ),420 animatedVisibilityScope = this@composable421 )422 )423 }424 }425}426```427428**Gotcha:** shared element keys must match exactly between source and destination. Use the same key generation logic.429430## Anti-Patterns431432- **`tween(0)` to skip animation** → use `snap()` spec instead, or don't animate at all433- **Animating in `LaunchedEffect` with `delay`** → use animation APIs. Manual delay = janky, can't be interrupted434- **`animate*AsState` for gesture tracking** → use `Animatable` — it supports `snapTo()` and velocity-aware `animateTo()`435- **Missing `label` on animations** → Layout Inspector can't identify them. Always add labels436- **`rememberInfiniteTransition` for one-shot** → infinite = forever. Use `Animatable.animateTo()` for one-shot437