From ff4983398024ad9793c33bfaedbab56deedec5ec Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 23 Oct 2026 13:19:57 +0000 Subject: [PATCH] Motion: dithered accent wipe between every screen, rings and gauges fill in, sections and the Log sheet animate, press feedback on cards Claude-Session: https://claude.ai/code/session_01P1t1aUqSUPd3whKXmgVm7w --- AGENTS.md | 15 ++ .../java/com/pulseloop/ui/PulseLoopApp.kt | 30 +++- .../pulseloop/ui/components/ActivityRings.kt | 4 +- .../com/pulseloop/ui/components/TodayTiles.kt | 5 +- .../pulseloop/ui/components/VitalRingGauge.kt | 4 +- .../pulseloop/ui/screens/ActivityScreen.kt | 2 +- .../java/com/pulseloop/ui/screens/LogSheet.kt | 66 +++++---- .../com/pulseloop/ui/screens/MyHealthUi.kt | 12 +- .../com/pulseloop/ui/screens/ReadinessUi.kt | 9 +- .../com/pulseloop/ui/screens/TodayGlance.kt | 5 +- .../pulseloop/ui/theme/DitherTransition.kt | 138 ++++++++++++++++++ .../java/com/pulseloop/ui/theme/Motion.kt | 49 +++++++ 12 files changed, 297 insertions(+), 42 deletions(-) create mode 100644 app/src/main/java/com/pulseloop/ui/theme/DitherTransition.kt create mode 100644 app/src/main/java/com/pulseloop/ui/theme/Motion.kt diff --git a/AGENTS.md b/AGENTS.md index 33f98c74..e810541b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1127,3 +1127,18 @@ clutter came from ignoring one of them: Settings row (Drinks used to be one). - **A goal saved anywhere goes through `GoalSync.afterManualSave`** — it is what stops the field following the coach, sends the step goal to the ring and republishes the widget. + +## Motion: one transition, a small vocabulary + +- **Every navigation destination goes through `DitherTransitionBox`** (`theme/DitherTransition.kt`), + via `screen(...)` / `paddedComposable(...)` in `PulseLoopApp`. A new route registered with a bare + `composable(...)` skips the wipe and pops in. The wipe draws *both* screens from one Bayer mask + (incoming keeps the swept cells, outgoing keeps the rest), because the navigator puts the + outgoing screen on top for a back press; a reveal drawn only on the incoming screen would be + hidden there. NavHost's own fade (0.99 alpha) exists only to keep both screens composed for + `DURATION_MS`. Fairy mode uses a smooth gradient, like every other dither. +- **In-screen motion uses `theme/Motion.kt`**: `sweepIn` for rings, gauges and bars (fill from empty + on first show, glide between values) and `pressScale` for tappable cards. Collapsible sections + expand with `AnimatedVisibility`. Prefer these over one-off specs, so the app moves one way. +- All of it runs on Compose's clock, which honours the system "Remove animations" setting; don't + drive motion from a hand-rolled `delay` loop that would ignore it. diff --git a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt index f4394585..ec8658f7 100644 --- a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt +++ b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt @@ -36,6 +36,7 @@ import androidx.navigation.NavDestination.Companion.hierarchy import androidx.navigation.NavGraph.Companion.findStartDestination import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable +import com.pulseloop.ui.theme.DitherTransitionBox import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.compose.rememberNavController import com.pulseloop.AppServices @@ -388,7 +389,13 @@ fun PulseLoopApp() { Scaffold( containerColor = com.pulseloop.ui.theme.PulseColors.background, floatingActionButton = { - if (showLogFab) { + // Pops in on the tabs that have it and out on the ones that don't, rather than + // blinking with the screen change. + androidx.compose.animation.AnimatedVisibility( + visible = showLogFab, + enter = androidx.compose.animation.scaleIn() + androidx.compose.animation.fadeIn(), + exit = androidx.compose.animation.scaleOut() + androidx.compose.animation.fadeOut(), + ) { ExtendedFloatingActionButton( onClick = { LaunchRequests.openLog.value = com.pulseloop.ui.screens.LogStep.MENU }, icon = { Icon(Icons.Filled.Add, contentDescription = null) }, @@ -585,17 +592,26 @@ fun PulseLoopApp() { route: String, content: @Composable (androidx.navigation.NavBackStackEntry) -> Unit, ) = composable(route) { entry -> - Box(Modifier.fillMaxSize().padding(padding)) { content(entry) } + DitherTransitionBox { Box(Modifier.fillMaxSize().padding(padding)) { content(entry) } } } + // Every destination takes part in the dither wipe (theme/DitherTransition.kt). + fun androidx.navigation.NavGraphBuilder.screen( + route: String, + content: @Composable (androidx.navigation.NavBackStackEntry) -> Unit, + ) = composable(route) { entry -> DitherTransitionBox { content(entry) } } NavHost( navController = navController, startDestination = "today", modifier = Modifier.hazeSource(hazeState), + enterTransition = { com.pulseloop.ui.theme.DitherTransition.enter }, + exitTransition = { com.pulseloop.ui.theme.DitherTransition.exit }, + popEnterTransition = { com.pulseloop.ui.theme.DitherTransition.enter }, + popExitTransition = { com.pulseloop.ui.theme.DitherTransition.exit }, ) { - composable("today") { TodayScreen(navController, todayVM, coordinator, vitalsVM, sleepVM, topBarPadding = topPad, bottomBarPadding = tabPad) } - composable("vitals") { VitalsScreen(navController = navController, viewModel = vitalsVM, coordinator = coordinator, topBarPadding = topPad, bottomBarPadding = tabPad) } - composable("sleep") { SleepScreen(navController = navController, viewModel = sleepVM, onOpen = { coordinator.syncSleepNow() }, topBarPadding = topPad, bottomBarPadding = tabPad) } - composable("activity") { ActivityScreen(navController = navController, viewModel = activityVM, liveWorkout = liveWorkout, topBarPadding = topPad, bottomBarPadding = tabPad) } + screen("today") { TodayScreen(navController, todayVM, coordinator, vitalsVM, sleepVM, topBarPadding = topPad, bottomBarPadding = tabPad) } + screen("vitals") { VitalsScreen(navController = navController, viewModel = vitalsVM, coordinator = coordinator, topBarPadding = topPad, bottomBarPadding = tabPad) } + screen("sleep") { SleepScreen(navController = navController, viewModel = sleepVM, onOpen = { coordinator.syncSleepNow() }, topBarPadding = topPad, bottomBarPadding = tabPad) } + screen("activity") { ActivityScreen(navController = navController, viewModel = activityVM, liveWorkout = liveWorkout, topBarPadding = topPad, bottomBarPadding = tabPad) } paddedComposable("activity_detail/{id}") { backStackEntry -> val id = backStackEntry.arguments?.getString("id") ?: return@paddedComposable WorkoutSummaryScreen(sessionId = id, onBack = { navController.popBackStack() }) @@ -612,7 +628,7 @@ fun PulseLoopApp() { } // Coach draws full-bleed under the glass top/bottom bars (like the other tabs), so // the chat frosts under its header and the composer can clear the keyboard itself. - composable("coach") { + screen("coach") { CoachScreen( navController = navController, viewModel = coachVM, diff --git a/app/src/main/java/com/pulseloop/ui/components/ActivityRings.kt b/app/src/main/java/com/pulseloop/ui/components/ActivityRings.kt index a0080bd1..bd3724f5 100644 --- a/app/src/main/java/com/pulseloop/ui/components/ActivityRings.kt +++ b/app/src/main/java/com/pulseloop/ui/components/ActivityRings.kt @@ -62,6 +62,8 @@ fun ActivityRings( val name = labels.getOrNull(i) ?: trf("ring {0}", i + 1) if (ring.value == null) trf("{0} unavailable", name) else "$name ${(ring.progress * 100).toInt()}%" }.joinToString(", ") + // Each ring fills from empty on first show, then glides to new totals. + val shown = rings.map { com.pulseloop.ui.theme.sweepIn(it.progress.toFloat()) } Canvas(modifier.size(size).clearAndSetSemantics { contentDescription = description }) { val strokePx = strokeWidth.toPx() val spacingPx = ringSpacing.toPx() @@ -90,7 +92,7 @@ fun ActivityRings( style = stroke, ) // Progress arc from 12 o'clock, clockwise. - val sweep = (360.0 * ring.progress).toFloat() + val sweep = 360f * shown[index] if (sweep > 0f) { drawArc( color = ring.color, diff --git a/app/src/main/java/com/pulseloop/ui/components/TodayTiles.kt b/app/src/main/java/com/pulseloop/ui/components/TodayTiles.kt index b510ef78..955d4adf 100644 --- a/app/src/main/java/com/pulseloop/ui/components/TodayTiles.kt +++ b/app/src/main/java/com/pulseloop/ui/components/TodayTiles.kt @@ -1,5 +1,6 @@ package com.pulseloop.ui.components +import com.pulseloop.ui.theme.pressScale import com.pulseloop.ui.i18n.trf import com.pulseloop.ui.i18n.tr @@ -108,8 +109,10 @@ fun TodayTile( content: @Composable ColumnScope.() -> Unit, ) { val shape = RoundedCornerShape(TodayTileMetrics.corner) + val press = remember { androidx.compose.foundation.interaction.MutableInteractionSource() } Column( modifier = modifier + .pressScale(press) // A floor, not a fixed height — see [TodayTileMetrics.minHeight]. The grid row measures // its tiles with IntrinsicSize.Min and stretches both to match, so this grows to fit // whatever the tile actually contains instead of clipping it. @@ -117,7 +120,7 @@ fun TodayTile( .clip(shape) .background(PulseColors.card) .border(1.dp, PulseColors.borderSubtle, shape) - .then(if (onTap != null) Modifier.clickable(onClick = onTap) else Modifier) + .then(if (onTap != null) Modifier.clickable(interactionSource = press, indication = androidx.compose.foundation.LocalIndication.current, onClick = onTap) else Modifier) .padding(12.dp), verticalArrangement = Arrangement.spacedBy(6.dp), ) { diff --git a/app/src/main/java/com/pulseloop/ui/components/VitalRingGauge.kt b/app/src/main/java/com/pulseloop/ui/components/VitalRingGauge.kt index 75f25ddc..986cf1ef 100644 --- a/app/src/main/java/com/pulseloop/ui/components/VitalRingGauge.kt +++ b/app/src/main/java/com/pulseloop/ui/components/VitalRingGauge.kt @@ -77,6 +77,8 @@ fun VitalRingGauge( return ((v - domain.start) / span).coerceIn(0.0, 1.0) } + // The marker sweeps up from the bottom of the scale on first show, then glides between readings. + val shownValue = com.pulseloop.ui.theme.sweepIn(value.toFloat(), from = domain.start.toFloat()).toDouble() // One spoken summary for the whole gauge (value, unit, status), plus its position on the scale. val description = listOfNotNull(centerValue, centerUnit, centerStatus, subtitle).joinToString(" ") Box( @@ -152,7 +154,7 @@ fun VitalRingGauge( zones.lastOrNull()?.let { drawRoundTip(tipCenter(1.0), 1.0, strokePx, it.colorToken.toColor().copy(alpha = 0.32f)) } // Value arc from the start up to the current value (rounded leading tip looks intentional). - val valueFraction = fraction(value) + val valueFraction = fraction(shownValue) if (valueFraction > 0) { drawArc( color = valueColor, diff --git a/app/src/main/java/com/pulseloop/ui/screens/ActivityScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/ActivityScreen.kt index 521f9fb9..ce7e5d92 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/ActivityScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/ActivityScreen.kt @@ -580,7 +580,7 @@ private fun ProgressRing( stroke: androidx.compose.ui.unit.Dp = 9.dp, center: @Composable () -> Unit, ) { - val progress = if (max <= 0) 0f else (value / max).coerceIn(0.0, 1.0).toFloat() + val progress = com.pulseloop.ui.theme.sweepIn(if (max <= 0) 0f else (value / max).coerceIn(0.0, 1.0).toFloat()) Box(contentAlignment = Alignment.Center, modifier = Modifier.size(size)) { androidx.compose.foundation.Canvas(Modifier.fillMaxSize()) { val strokePx = stroke.toPx() diff --git a/app/src/main/java/com/pulseloop/ui/screens/LogSheet.kt b/app/src/main/java/com/pulseloop/ui/screens/LogSheet.kt index 80cd871e..e0d43231 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/LogSheet.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/LogSheet.kt @@ -34,6 +34,7 @@ import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp +import androidx.compose.animation.togetherWith import com.pulseloop.data.PulseLoopDatabase import com.pulseloop.data.entity.DrinkEntryEntity import com.pulseloop.service.DrinkPrefs @@ -77,32 +78,47 @@ fun LogSheet( Modifier.fillMaxWidth().verticalScroll(rememberScrollState()).padding(horizontal = 16.dp).padding(bottom = 32.dp), verticalArrangement = Arrangement.spacedBy(8.dp), ) { - when (step) { - LogStep.MENU -> { - Text(tr("Log"), fontSize = 18.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) - SheetOption(tr("Meal"), tr("Photo, barcode or by hand"), Icons.Filled.Restaurant) { step = LogStep.MEAL } - SheetOption(tr("Drink"), tr("One tap for the usual ones"), Icons.Filled.LocalBar) { step = LogStep.DRINK } - SheetOption(tr("Medication or supplement"), tr("Mark today's doses"), Icons.Filled.Medication, onMeds) - SheetOption(tr("Period"), tr("Started or ended today, or a past one"), Icons.Filled.WaterDrop, onPeriod) - SheetOption(tr("Tag your day"), tr("Alcohol, stress, a late meal…"), Icons.Filled.LocalOffer) { step = LogStep.TAGS } - SheetOption(tr("Workout"), tr("Start one now"), Icons.Filled.DirectionsRun, onWorkout) - } - LogStep.MEAL -> { - Text(tr("Log a meal"), fontSize = 18.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) - SheetOption(tr("Photo"), tr("Snap your plate; the AI estimates it"), Icons.Filled.CameraAlt) { onMeal("photo") } - SheetOption(tr("Barcode"), tr("Scan a packaged food"), Icons.Filled.QrCodeScanner) { onMeal("barcode") } - SheetOption(tr("Add by hand"), tr("Type the name and calories"), Icons.Filled.Add) { onMeal("add") } + // Each step slides in from the side it was reached from, so the sheet reads as one + // place with pages rather than a panel that blinks. + androidx.compose.animation.AnimatedContent( + targetState = step, + transitionSpec = { + val forward = targetState != LogStep.MENU + (androidx.compose.animation.fadeIn(androidx.compose.animation.core.tween(220)) + + androidx.compose.animation.slideInHorizontally(androidx.compose.animation.core.tween(220)) { w -> if (forward) w / 6 else -w / 6 }) togetherWith + androidx.compose.animation.fadeOut(androidx.compose.animation.core.tween(150)) + }, + label = "logStep", + ) { shownStep -> + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + when (shownStep) { + LogStep.MENU -> { + Text(tr("Log"), fontSize = 18.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + SheetOption(tr("Meal"), tr("Photo, barcode or by hand"), Icons.Filled.Restaurant) { step = LogStep.MEAL } + SheetOption(tr("Drink"), tr("One tap for the usual ones"), Icons.Filled.LocalBar) { step = LogStep.DRINK } + SheetOption(tr("Medication or supplement"), tr("Mark today's doses"), Icons.Filled.Medication, onMeds) + SheetOption(tr("Period"), tr("Started or ended today, or a past one"), Icons.Filled.WaterDrop, onPeriod) + SheetOption(tr("Tag your day"), tr("Alcohol, stress, a late meal…"), Icons.Filled.LocalOffer) { step = LogStep.TAGS } + SheetOption(tr("Workout"), tr("Start one now"), Icons.Filled.DirectionsRun, onWorkout) + } + LogStep.MEAL -> { + Text(tr("Log a meal"), fontSize = 18.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + SheetOption(tr("Photo"), tr("Snap your plate; the AI estimates it"), Icons.Filled.CameraAlt) { onMeal("photo") } + SheetOption(tr("Barcode"), tr("Scan a packaged food"), Icons.Filled.QrCodeScanner) { onMeal("barcode") } + SheetOption(tr("Add by hand"), tr("Type the name and calories"), Icons.Filled.Add) { onMeal("add") } + } + LogStep.DRINK -> QuickDrinks(db, onMoreDrinks) + LogStep.TAGS -> JournalTagsCard(db, java.time.LocalDate.now(), tr("Tag your day"), allowYesterday = true) { + Text( + tr("See what affects you"), + fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.accent, + modifier = Modifier + .heightIn(min = 48.dp) + .clickable(role = Role.Button, onClick = onSeeEffects) + .wrapContentHeight(Alignment.CenterVertically), + ) + } } - LogStep.DRINK -> QuickDrinks(db, onMoreDrinks) - LogStep.TAGS -> JournalTagsCard(db, java.time.LocalDate.now(), tr("Tag your day"), allowYesterday = true) { - Text( - tr("See what affects you"), - fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.accent, - modifier = Modifier - .heightIn(min = 48.dp) - .clickable(role = Role.Button, onClick = onSeeEffects) - .wrapContentHeight(Alignment.CenterVertically), - ) } } } diff --git a/app/src/main/java/com/pulseloop/ui/screens/MyHealthUi.kt b/app/src/main/java/com/pulseloop/ui/screens/MyHealthUi.kt index f675106c..f3623c42 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/MyHealthUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/MyHealthUi.kt @@ -41,6 +41,7 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.scale +import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color @@ -112,9 +113,16 @@ internal fun Section( Text(title, fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) if (!open) Text(summary!!, fontSize = 12.sp, color = PulseColors.textMuted, maxLines = 2, overflow = TextOverflow.Ellipsis) } - Text(if (open) "⌃" else "⌄", fontSize = 18.sp, color = PulseColors.textMuted) + val turn by androidx.compose.animation.core.animateFloatAsState(if (open) 180f else 0f, label = "chevron") + Text("⌄", fontSize = 18.sp, color = PulseColors.textMuted, modifier = Modifier.graphicsLayer { rotationZ = turn }) + } + androidx.compose.animation.AnimatedVisibility( + visible = open, + enter = androidx.compose.animation.expandVertically() + androidx.compose.animation.fadeIn(), + exit = androidx.compose.animation.shrinkVertically() + androidx.compose.animation.fadeOut(), + ) { + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { content() } } - if (open) content() } else { Text(title.uppercase(), fontSize = 11.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted) content() diff --git a/app/src/main/java/com/pulseloop/ui/screens/ReadinessUi.kt b/app/src/main/java/com/pulseloop/ui/screens/ReadinessUi.kt index bc103462..a3efeb2a 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/ReadinessUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/ReadinessUi.kt @@ -93,6 +93,9 @@ fun ScoreRing( centerText: String = value?.toString() ?: "—", centerSize: Int = 22, ) { + // Fills from empty on first show and counts the number up with it. + val shown = com.pulseloop.ui.theme.sweepIn((value ?: 0).coerceIn(0, 100).toFloat()) + val text = if (value != null && centerText == value.toString()) shown.roundToInt().toString() else centerText Box( Modifier.size(size).clearAndSetSemantics { // One spoken value instead of a bare number; an empty ring says so. @@ -109,16 +112,16 @@ fun ScoreRing( color = PulseColors.borderStrong, startAngle = 135f, sweepAngle = 270f, useCenter = false, topLeft = Offset(inset, inset), size = arcSize, style = Stroke(w, cap = StrokeCap.Round), ) - if (value != null && value > 0) { + if (value != null && shown > 0f) { drawArc( - color = color, startAngle = 135f, sweepAngle = 270f * (value.coerceIn(0, 100) / 100f), + color = color, startAngle = 135f, sweepAngle = 270f * (shown / 100f), useCenter = false, topLeft = Offset(inset, inset), size = arcSize, style = Stroke(w, cap = StrokeCap.Round), ) } } Text( - centerText, fontSize = centerSize.sp, fontWeight = FontWeight.SemiBold, + text, fontSize = centerSize.sp, fontWeight = FontWeight.SemiBold, color = if (value != null) PulseColors.textPrimary else PulseColors.textMuted, ) } diff --git a/app/src/main/java/com/pulseloop/ui/screens/TodayGlance.kt b/app/src/main/java/com/pulseloop/ui/screens/TodayGlance.kt index a91bba51..fde7fbe9 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/TodayGlance.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/TodayGlance.kt @@ -1,5 +1,6 @@ package com.pulseloop.ui.screens +import com.pulseloop.ui.theme.pressScale import com.pulseloop.ui.i18n.trf import com.pulseloop.ui.i18n.tr @@ -174,13 +175,15 @@ fun LastNightCard( @Composable internal fun SheetOption(title: String, subtitle: String, icon: ImageVector, onClick: () -> Unit) { val shape = RoundedCornerShape(8.dp) + val press = androidx.compose.runtime.remember { androidx.compose.foundation.interaction.MutableInteractionSource() } Row( Modifier .fillMaxWidth() + .pressScale(press) .clip(shape) .background(PulseColors.card) .border(1.dp, PulseColors.borderSubtle, shape) - .clickable(onClick = onClick) + .clickable(interactionSource = press, indication = androidx.compose.foundation.LocalIndication.current, onClick = onClick) .padding(16.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), diff --git a/app/src/main/java/com/pulseloop/ui/theme/DitherTransition.kt b/app/src/main/java/com/pulseloop/ui/theme/DitherTransition.kt new file mode 100644 index 00000000..92085e3e --- /dev/null +++ b/app/src/main/java/com/pulseloop/ui/theme/DitherTransition.kt @@ -0,0 +1,138 @@ +package com.pulseloop.ui.theme + +import androidx.compose.animation.AnimatedVisibilityScope +import androidx.compose.animation.EnterExitState +import androidx.compose.animation.EnterTransition +import androidx.compose.animation.ExitTransition +import androidx.compose.animation.ExperimentalAnimationApi +import androidx.compose.animation.core.FastOutSlowInEasing +import androidx.compose.animation.core.LinearEasing +import androidx.compose.animation.core.animateFloat +import androidx.compose.animation.core.tween +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.drawWithContent +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.BlendMode +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.CompositingStrategy +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.graphics.drawscope.DrawScope +import androidx.compose.ui.graphics.graphicsLayer +import kotlin.math.abs + +/** + * The app's screen transition: the new screen dissolves in through the same 4×4 Bayer dither the + * rest of the UI is drawn with, along a gradient that sweeps from the top down, and the sweep's + * front edge glitters in the accent colour. Fairy mode swaps the dots for a smooth fade, as the + * rest of the dither does. + * + * Both screens are drawn: the incoming one keeps the cells the sweep has passed, the outgoing one + * keeps the rest, from the same mask. So whichever of the two the navigator puts on top (it puts + * the outgoing one on top for a back press), the picture is the same. + */ +object DitherTransition { + /** Long enough to read as a wipe, short enough not to hold anyone up. */ + const val DURATION_MS = 420 + + /** How much of the screen's height the dithered gradient at the front spans. */ + private const val GRADIENT = 0.35f + + /** Horizontal bands the gradient is cut into; one per dither step reads as smooth. */ + private const val BANDS = 32 + + /** + * NavHost's own transitions only hold both screens on screen for [DURATION_MS]: the alpha + * barely moves, and the picture is the mask drawn by [DitherTransitionBox]. + */ + val enter: EnterTransition = fadeIn(tween(DURATION_MS, easing = LinearEasing), initialAlpha = 0.99f) + val exit: ExitTransition = fadeOut(tween(DURATION_MS, easing = LinearEasing), targetAlpha = 0.99f) + + /** Share of the cells revealed at height [t] (0 top, 1 bottom) when the sweep is at [p]. */ + internal fun coverage(t: Float, p: Float): Float { + val front = p * (1f + GRADIENT) + return ((front - t) / GRADIENT).coerceIn(0f, 1f) + } + + /** The accent glitter: strongest in the middle of the gradient, none outside it. */ + internal fun sparkle(t: Float, p: Float): Float { + val mid = p * (1f + GRADIENT) - GRADIENT / 2f + return (1f - abs(t - mid) / (GRADIENT / 2f)).coerceIn(0f, 1f) * 0.55f + } + + /** + * Draws the mask over content already drawn in an offscreen layer: [entering] keeps the + * revealed cells, the outgoing screen removes them. Then the accent edge on top. + */ + internal fun DrawScope.drawWipe(p: Float, entering: Boolean, accent: Color) { + val keepMode = if (entering) BlendMode.DstIn else BlendMode.DstOut + if (FairyMode.on) { + val stops = (0..BANDS).map { i -> val t = i / BANDS.toFloat(); t to Color.Black.copy(alpha = coverage(t, p)) } + drawRect(Brush.verticalGradient(*stops.toTypedArray()), blendMode = keepMode) + val glow = (0..BANDS).map { i -> val t = i / BANDS.toFloat(); t to accent.copy(alpha = sparkle(t, p) * 0.6f) } + drawRect(Brush.verticalGradient(*glow.toTypedArray())) + return + } + val bandH = size.height / BANDS + for (i in 0 until BANDS) { + val t = (i + 0.5f) / BANDS + val lit = Dither.steps(coverage(t, p)) + val top = i * bandH + val brush: Brush? = when { + // Entering keeps everything here; leaving keeps nothing. + lit >= Dither.STEPS -> if (entering) null else SolidColor(Color.Black) + // Entering keeps nothing here; leaving keeps everything. + lit == 0 -> if (entering) SolidColor(Color.Transparent) else null + else -> with(Dither) { brush(Color.Black, lit, cellPx()) } + } + if (brush != null) { + drawRect(brush, topLeft = Offset(0f, top), size = Size(size.width, bandH + 1f), blendMode = keepMode) + } + val glitter = Dither.steps(sparkle(t, p)) + if (glitter > 0) { + drawRect( + with(Dither) { brush(accent, glitter, cellPx()) }, + topLeft = Offset(0f, top), size = Size(size.width, bandH + 1f), + ) + } + } + } +} + +/** + * Wraps one navigation destination so it takes part in the dither wipe. Use it inside the + * destination's content, where the navigator's [AnimatedVisibilityScope] is the receiver. + */ +@OptIn(ExperimentalAnimationApi::class) +@Composable +fun AnimatedVisibilityScope.DitherTransitionBox(content: @Composable () -> Unit) { + val shown by transition.animateFloat( + transitionSpec = { tween(DitherTransition.DURATION_MS, easing = LinearEasing) }, + label = "ditherWipe", + ) { if (it == EnterExitState.Visible) 1f else 0f } + val entering = transition.targetState == EnterExitState.Visible + // Eased once here so both screens read the same position off the same curve. + val p = FastOutSlowInEasing.transform(if (entering) shown else 1f - shown) + val accent = PulseColors.accent + val settled = entering && shown >= 1f + Box( + Modifier + .fillMaxSize() + .then( + if (settled) Modifier + else Modifier + .graphicsLayer { compositingStrategy = CompositingStrategy.Offscreen } + .drawWithContent { + drawContent() + with(DitherTransition) { drawWipe(p, entering, accent) } + }, + ), + ) { content() } +} diff --git a/app/src/main/java/com/pulseloop/ui/theme/Motion.kt b/app/src/main/java/com/pulseloop/ui/theme/Motion.kt new file mode 100644 index 00000000..c9716d09 --- /dev/null +++ b/app/src/main/java/com/pulseloop/ui/theme/Motion.kt @@ -0,0 +1,49 @@ +package com.pulseloop.ui.theme + +import androidx.compose.animation.core.Animatable +import androidx.compose.animation.core.FastOutSlowInEasing +import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.animation.core.spring +import androidx.compose.animation.core.tween +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.collectIsPressedAsState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier +import androidx.compose.ui.composed +import androidx.compose.ui.graphics.graphicsLayer + +/** + * The app's motion vocabulary, kept small so every screen moves the same way: + * + * - [sweepIn] fills a ring, gauge or bar from empty when it first appears, then glides to each new + * value instead of jumping. + * - [pressScale] gives a tappable card a slight press-in, so a tap is felt before the screen moves. + * + * All of it runs on Compose's animation clock, which honours the system "Remove animations" + * setting: with animations off, every value lands at once. + */ +object Motion { + /** A ring filling, a number counting up: long enough to see, short enough not to wait for. */ + const val FILL_MS = 900 +} + +/** + * [target] (0..1 or any range starting at [from]), animated from [from] the first time it is shown + * and from its previous value after that. + */ +@Composable +fun sweepIn(target: Float, from: Float = 0f): Float { + val anim = remember { Animatable(from) } + LaunchedEffect(target) { anim.animateTo(target, tween(Motion.FILL_MS, easing = FastOutSlowInEasing)) } + return anim.value +} + +/** Scales the element to 97% while it is pressed through [interaction]. */ +fun Modifier.pressScale(interaction: MutableInteractionSource): Modifier = composed { + val pressed by interaction.collectIsPressedAsState() + val scale by animateFloatAsState(if (pressed) 0.97f else 1f, spring(stiffness = 600f), label = "press") + graphicsLayer { scaleX = scale; scaleY = scale } +}