Modern Apps git

← Modern-Apps.git

library: name the motion vocabulary so screens stop hand-rolling it

Commit
a2db12754a7f97c6f93fef884bfdcbc2b15c2d07
Author
vayun-mathur <[email protected]>
When
2026-08-31 16:13 UTC (3 months ago)
Parents
0fff85f

Diff

library/src/main/java/com/vayunmathur/library/util/Navigation.kt
diff --git a/library/src/main/java/com/vayunmathur/library/util/Navigation.kt b/library/src/main/java/com/vayunmathur/library/util/Navigation.ktindex 9914830ddf..11701a87cd 100644--- a/library/src/main/java/com/vayunmathur/library/util/Navigation.kt+++ b/library/src/main/java/com/vayunmathur/library/util/Navigation.kt@@ -12,10 +12,12 @@ import androidx.compose.animation.core.LinearEasing import androidx.compose.animation.core.Spring import androidx.compose.animation.core.spring import androidx.compose.animation.core.tween+import androidx.compose.animation.expandVertically import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.animation.scaleIn import androidx.compose.animation.scaleOut+import androidx.compose.animation.shrinkVertically import androidx.compose.animation.slideInHorizontally import androidx.compose.animation.slideOutHorizontally import androidx.compose.animation.slideOutVertically@@ -48,6 +50,7 @@ import androidx.compose.runtime.compositionLocalOf import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.remember import androidx.compose.runtime.staticCompositionLocalOf+import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Rect import androidx.compose.ui.graphics.Color@@ -322,7 +325,7 @@ private fun rememberNavTransitions(): NavTransitions {  * default, 0.6 for fast). An overshoot on a bounds morph means the element visibly flies past its  * target and rubber-bands back, which is far more obvious across a long travel than on a short slide.  */-private const val NavMorphMillis = 350+internal const val NavMorphMillis = 220  /** M3's emphasized curve: slow start, quick middle, gentle settle. */ private val NavMorphEasing = CubicBezierEasing(0.2f, 0f, 0f, 1f)@@ -582,6 +585,79 @@ fun Modifier.exitDownward(): Modifier {     } } +/**+ * [sharedContainer] for text.+ *+ * Scales the glyphs to the animating bounds instead of laying them out again at each intermediate+ * size. That difference is the whole point: the same name is `bodyLarge` in a list row and+ * `headlineMedium` in a header, and remeasuring between the two re-wraps the string on nearly every+ * frame, which reads as the text garbling rather than growing. Scaling interpolates it smoothly.+ *+ * Use [sharedContainer] instead when the two ends hold genuinely different content - a read-only row+ * becoming a text field - where a reflow is correct and scaling would distort.+ */+@OptIn(ExperimentalSharedTransitionApi::class)+@Composable+fun Modifier.sharedText(key: Any): Modifier {+    if (LocalNavMultiPane.current) return this+    val shared = LocalSharedTransitionScope.current ?: return this+    val animated = LocalEntryAnimatedScope.current ?: return this+    return with(shared) {+        [email protected](+            rememberSharedContentState(key),+            animated,+            enter = fadeIn(NavMorphContentFade),+            exit = fadeOut(NavMorphContentFade),+            boundsTransform = NavMorphBoundsTransform,+            resizeMode = SharedTransitionScope.ResizeMode.scaleToBounds(),+        )+    }+}++/**+ * Enters by unfurling from a flat horizontal line into full height, rather than fading in.+ *+ * For a block of fields arriving as a unit: it reads as the form opening up in place, which suits a+ * destination whose content is a stack of rows. A fade makes the same block look like it was already+ * there and merely became visible.+ *+ * Duration-based, so it stays seekable under a predictive-back gesture.+ *+ * No-ops outside a [MainNavigation].+ */+@Composable+fun Modifier.expandFromLine(): Modifier {+    val scope = LocalEntryAnimatedScope.current ?: return this+    return with(scope) {+        [email protected](+            enter = expandVertically(+                animationSpec = tween(NavMorphMillis, easing = NavMorphEasing),+                expandFrom = Alignment.CenterVertically,+                initialHeight = { 0 },+            ) + fadeIn(NavMorphContentFade),+            exit = shrinkVertically(+                animationSpec = tween(NavMorphMillis, easing = NavMorphEasing),+                shrinkTowards = Alignment.CenterVertically,+                targetHeight = { 0 },+            ) + fadeOut(NavMorphContentFade),+        )+    }+}++/**+ * True while a shared element is mid-flight between two destinations.+ *+ * For content that would otherwise be visible in both places at once: a field can hide its own text+ * while the copy travelling in from the previous screen is on screen, so there is one piece of text+ * rather than two, and reveal it as the morph lands.+ *+ * False outside a [MainNavigation], so a screen on its own always shows its content.+ */+@OptIn(ExperimentalSharedTransitionApi::class)+@Composable+fun isNavMorphing(): Boolean =+    LocalSharedTransitionScope.current?.isTransitionActive == true+ fun DialogPage() = DialogSceneStrategy.dialog()  @OptIn(ExperimentalMaterial3AdaptiveApi::class)
library/src/main/java/com/vayunmathur/library/util/SharedEditableText.kt
diff --git a/library/src/main/java/com/vayunmathur/library/util/SharedEditableText.kt b/library/src/main/java/com/vayunmathur/library/util/SharedEditableText.ktnew file mode 100644index 0000000000..44ff39cd81--- /dev/null+++ b/library/src/main/java/com/vayunmathur/library/util/SharedEditableText.kt@@ -0,0 +1,81 @@+package com.vayunmathur.library.util++import androidx.compose.foundation.layout.Box+import androidx.compose.material3.LocalTextStyle+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.alpha+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.text.TextStyle+import kotlinx.coroutines.delay++/**+ * When the field's own text comes back, measured from the *start* of the morph.+ *+ * [isNavMorphing] stays true until every part of the transition has settled, including the long tail+ * of the spring on the screen change, so revealing when it clears puts the text back well after the+ * travelling copy has arrived. Timing it from the start instead lands the reveal just before the+ * bounds travel finishes, which is where it belongs - hence a fraction of [NavMorphMillis] rather+ * than a literal that has to be kept in step with it by hand.+ */+private const val RevealDelayMillis = NavMorphMillis * 2L / 3L++/**+ * Wraps the inner text of an editable field so the read-only text carrying the same [key] on the+ * previous screen morphs into it.+ *+ * Call this from a text field's `decorationBox` around its `innerTextField`, and pass the [style]+ * the field draws its text in.+ *+ * A field cannot simply carry [sharedText] itself. Its inner text fills the field's whole width -+ * it has to, or tapping to the right of the value could not place the cursor - so a content-sized+ * text on the other screen pairs against that full width, balloons out to it and then snaps back to+ * its real size on arrival. This keeps the real editable line full-width and *unkeyed*, and puts the+ * key on a transparent copy of [value], which measures to the glyphs and so gives the arriving text+ * a destination its own size.+ *+ * The real text is hidden with [alpha] rather than by not composing it: the field keeps its focus,+ * its cursor and its measured size throughout, and nothing about the app's state changes for the+ * sake of an animation. There is no fade on the reveal either - a fade reads as the letters+ * resolving out of a blur, and the point is that the letters that just travelled here *are* these+ * letters.+ *+ * A null [key] is the non-morphing case and simply emits [innerTextField] unchanged, so a field+ * shared by screens that do and do not morph needs no branch of its own.+ */+@Composable+fun SharedEditableText(+    key: Any?,+    value: String,+    style: TextStyle = LocalTextStyle.current,+    innerTextField: @Composable () -> Unit,+) {+    if (key == null) {+        innerTextField()+        return+    }+    Box {+        val morphing = isNavMorphing()+        var revealed by remember(morphing) { mutableStateOf(!morphing) }+        LaunchedEffect(morphing) {+            if (morphing) {+                delay(RevealDelayMillis)+                revealed = true+            }+        }+        Box(Modifier.alpha(if (revealed) 1f else 0f)) { innerTextField() }+        Text(+            text = value,+            style = style,+            color = Color.Transparent,+            maxLines = 1,+            modifier = Modifier.sharedText(key),+        )+    }+}
library/ui/src/main/java/com/vayunmathur/library/ui/BannerVisibility.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/BannerVisibility.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/BannerVisibility.ktnew file mode 100644index 0000000000..b9351a9486--- /dev/null+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/BannerVisibility.kt@@ -0,0 +1,40 @@+package com.vayunmathur.library.ui++import androidx.compose.animation.AnimatedVisibility+import androidx.compose.animation.core.FiniteAnimationSpec+import androidx.compose.animation.fadeIn+import androidx.compose.animation.fadeOut+import androidx.compose.animation.slideInVertically+import androidx.compose.animation.slideOutVertically+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.IntOffset++/**+ * Drops [content] in over the top edge of the screen and takes it back out the same way.+ *+ * For an unsolicited announcement laid over a screen the user is already using - an achievement, an+ * unlock. The direction carries the meaning: it arrives from off-screen because it came from outside+ * what the user was doing, which a fade in place does not say.+ *+ * Only correct for something anchored at the top and drawn *over* the layout. A banner that belongs+ * in a column wants [ExpandVisibility], and a control that owns a fixed spot wants [PopVisibility].+ */+@Composable+fun BannerVisibility(+    visible: Boolean,+    modifier: Modifier = Modifier,+    content: @Composable () -> Unit,+) {+    val scheme = MaterialTheme.motionScheme+    val offset: FiniteAnimationSpec<IntOffset> = scheme.defaultSpatialSpec()+    val fade: FiniteAnimationSpec<Float> = scheme.defaultEffectsSpec()+    AnimatedVisibility(+        visible = visible,+        modifier = modifier,+        enter = slideInVertically(offset) { -it } + fadeIn(fade),+        exit = slideOutVertically(offset) { -it } + fadeOut(fade),+    ) {+        content()+    }+}
library/ui/src/main/java/com/vayunmathur/library/ui/ExpandVisibility.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/ExpandVisibility.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/ExpandVisibility.ktnew file mode 100644index 0000000000..b8788c2795--- /dev/null+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/ExpandVisibility.kt@@ -0,0 +1,41 @@+package com.vayunmathur.library.ui++import androidx.compose.animation.AnimatedVisibility+import androidx.compose.animation.core.FiniteAnimationSpec+import androidx.compose.animation.expandVertically+import androidx.compose.animation.fadeIn+import androidx.compose.animation.fadeOut+import androidx.compose.animation.shrinkVertically+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.IntSize++/**+ * Opens [content] out of a flat line into its full height, and closes the space up again when+ * [visible] goes false.+ *+ * For a block that belongs to a column and pushes what is below it: a section attached under the+ * header that expanded it, a form's advanced options. The point is that the space appears and+ * disappears with the content - fading a block in and out leaves a gap the size of it behind, so the+ * column looks broken rather than collapsed.+ *+ * Content is measured at full size throughout and clipped, so text does not re-wrap on every frame.+ */+@Composable+fun ExpandVisibility(+    visible: Boolean,+    modifier: Modifier = Modifier,+    content: @Composable () -> Unit,+) {+    val scheme = MaterialTheme.motionScheme+    val size: FiniteAnimationSpec<IntSize> = scheme.defaultSpatialSpec()+    val fade: FiniteAnimationSpec<Float> = scheme.defaultEffectsSpec()+    AnimatedVisibility(+        visible = visible,+        modifier = modifier,+        enter = expandVertically(size) + fadeIn(fade),+        exit = shrinkVertically(size) + fadeOut(fade),+    ) {+        content()+    }+}
library/ui/src/main/java/com/vayunmathur/library/ui/FadeVisibility.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/FadeVisibility.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/FadeVisibility.ktnew file mode 100644index 0000000000..e98eb86aff--- /dev/null+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/FadeVisibility.kt@@ -0,0 +1,36 @@+package com.vayunmathur.library.ui++import androidx.compose.animation.AnimatedVisibility+import androidx.compose.animation.core.FiniteAnimationSpec+import androidx.compose.animation.fadeIn+import androidx.compose.animation.fadeOut+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier++/**+ * Fades [content] in and out without moving or resizing it.+ *+ * For something drawn *over* other content, where nothing has to make room for it and any movement+ * would be movement of the thing underneath: player controls over a video, an overlay on a photo, a+ * result banner over a quiz.+ *+ * Deliberately the plainest of the three. Prefer [PopVisibility] for a control that owns its spot and+ * [ExpandVisibility] for a block in a column - a fade leaves the space it occupied behind it, which+ * is only correct when the content was floating above the layout in the first place.+ */+@Composable+fun FadeVisibility(+    visible: Boolean,+    modifier: Modifier = Modifier,+    content: @Composable () -> Unit,+) {+    val fade: FiniteAnimationSpec<Float> = MaterialTheme.motionScheme.defaultEffectsSpec()+    AnimatedVisibility(+        visible = visible,+        modifier = modifier,+        enter = fadeIn(fade),+        exit = fadeOut(fade),+    ) {+        content()+    }+}
library/ui/src/main/java/com/vayunmathur/library/ui/FormComponents.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/FormComponents.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/FormComponents.ktindex eda5c98cc3..25dea767ca 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/FormComponents.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/FormComponents.kt@@ -4,6 +4,11 @@ import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.interaction.MutableInteractionSource+import androidx.compose.foundation.text.BasicTextField+import androidx.compose.ui.graphics.SolidColor+import com.vayunmathur.library.util.SharedEditableText+import com.vayunmathur.library.util.expandFromLine import com.vayunmathur.library.util.sharedContainer import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth@@ -86,7 +91,36 @@ fun LabeledTextField(     placeholder: String? = null,     leadingIcon: (@Composable () -> Unit)? = null,     trailingIcon: (@Composable () -> Unit)? = null,+    /**+     * Pairs the *text inside* this field with the same key elsewhere, so a read-only value morphs into+     * the editable one.+     *+     * Deliberately not a modifier on the field. A key on the field itself pairs the other screen's text+     * with this whole box, so the text grows to the box's width and then snaps to its real size on+     * arrival. Reaching the inner text means driving the field from [BasicTextField] and supplying+     * Material's own decoration around it, which is what the keyed branch below does.+     */+    sharedTextKey: Any? = null, ) {+    if (sharedTextKey != null) {+        SharedTextLabeledField(+            value = value,+            onValueChange = onValueChange,+            label = label,+            sharedTextKey = sharedTextKey,+            modifier = modifier,+            enabled = enabled,+            readOnly = readOnly,+            singleLine = singleLine,+            keyboardType = keyboardType,+            visualTransformation = visualTransformation,+            isError = isError,+            placeholder = placeholder,+            leadingIcon = leadingIcon,+            trailingIcon = trailingIcon,+        )+        return+    }     OutlinedTextField(         value = value,         onValueChange = onValueChange,@@ -105,6 +139,63 @@ fun LabeledTextField(     ) } +/**+ * [LabeledTextField] with its inner text exposed as a shared element.+ *+ * A separate branch rather than the default one for everybody: this rebuilds the field from+ * [BasicTextField] plus [OutlinedTextFieldDefaults.DecorationBox], and while that is the documented way+ * to keep Material's outline, label and label-cutout, it is still a reimplementation. Fields that do+ * not morph keep using [OutlinedTextField] directly, so nothing changes for them.+ */+@Composable+private fun SharedTextLabeledField(+    value: String,+    onValueChange: (String) -> Unit,+    label: String,+    sharedTextKey: Any,+    modifier: Modifier,+    enabled: Boolean,+    readOnly: Boolean,+    singleLine: Boolean,+    keyboardType: KeyboardType,+    visualTransformation: VisualTransformation,+    isError: Boolean,+    placeholder: String?,+    leadingIcon: (@Composable () -> Unit)?,+    trailingIcon: (@Composable () -> Unit)?,+) {+    val interactionSource = remember { MutableInteractionSource() }+    BasicTextField(+        value = value,+        onValueChange = onValueChange,+        modifier = modifier,+        enabled = enabled,+        readOnly = readOnly,+        textStyle = LocalTextStyle.current.copy(color = MaterialTheme.colorScheme.onSurface),+        keyboardOptions = KeyboardOptions(keyboardType = keyboardType),+        singleLine = singleLine,+        visualTransformation = visualTransformation,+        interactionSource = interactionSource,+        cursorBrush = SolidColor(MaterialTheme.colorScheme.primary),+    ) { innerTextField ->+        OutlinedTextFieldDefaults.DecorationBox(+            value = value,+            innerTextField = {+                SharedEditableText(key = sharedTextKey, value = value) { innerTextField() }+            },+            enabled = enabled,+            singleLine = singleLine,+            visualTransformation = visualTransformation,+            interactionSource = interactionSource,+            isError = isError,+            label = { Text(label) },+            placeholder = placeholder?.let { { Text(it) } },+            leadingIcon = leadingIcon,+            trailingIcon = trailingIcon,+        )+    }+}+ /**  * A repeatable list of typed detail rows, each with a value field, a type  * dropdown and a remove button, plus an "add" affordance.@@ -158,55 +249,88 @@ fun <T> FormDetailGroup(      * contact can still have a second mobile number.      */     isMandatory: (Int) -> Boolean = { false },+    /**+     * Makes each row unfurl from a flat line on arrival instead of sliding into place.+     *+     * Per row rather than per group on purpose: expanding the whole group as one block reads as a+     * single slab growing, which does not match a list of separate fields.+     */+    expandOnEnter: Boolean = false, ) {     Column(modifier = modifier, verticalArrangement = Arrangement.spacedBy(Spacing.sm)) {+        // Hoisted out of the row loop so the add button below can unfurl the same way the rows do.+        val enterModifier = if (expandOnEnter) Modifier.expandFromLine() else Modifier         items.forEachIndexed { index, item ->             val rowKey = sharedKey?.invoke(item)             val rowModifier = if (rowKey == null) Modifier else Modifier.sharedContainer(rowKey)-            OutlinedTextField(-                value = value(item),-                onValueChange = { v: String -> onValueChange(index, v) },-                label = { Text(label) },-                visualTransformation = visualTransformation,-                leadingIcon = leadingIcon?.let { { it(item) } },-                trailingIcon = {-                    Row {-                        var expanded by remember { mutableStateOf(false) }-                        TextButton({ expanded = true }) {-                            Text(typeLabel(item))-                            IconArrowDropDown()-                        }-                        DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) {-                            typeOptions.forEach { option ->-                                DropdownMenuItem(-                                    text = { Text(optionLabel?.invoke(option) ?: option.toString()) },-                                    onClick = {-                                        onTypeChange(index, option)-                                        expanded = false-                                    },-                                )-                            }+            // Hoisted so both branches below draw the same trailing controls.+            val rowTrailing: @Composable () -> Unit = {+                Row {+                    var expanded by remember { mutableStateOf(false) }+                    TextButton({ expanded = true }) {+                        Text(typeLabel(item))+                        IconArrowDropDown()+                    }+                    DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) {+                        typeOptions.forEach { option ->+                            DropdownMenuItem(+                                text = { Text(optionLabel?.invoke(option) ?: option.toString()) },+                                onClick = {+                                    onTypeChange(index, option)+                                    expanded = false+                                },+                            )                         }-                        // A mandatory row cannot be taken away, so its button clears the value instead-                        // - and only appears when there is something to clear, since an always-present-                        // button on an empty row invites a tap that would do nothing.-                        if (isMandatory(index)) {-                            if (value(item).isNotEmpty()) {-                                IconButton(onClick = { onValueChange(index, "") }) {-                                    IconRemoveCircle()-                                }-                            }-                        } else {-                            IconButton(onClick = { onRemove(index) }) {+                    }+                    // A mandatory row cannot be taken away, so its button clears the value instead+                    // - and only appears when there is something to clear, since an always-present+                    // button on an empty row invites a tap that would do nothing.+                    if (isMandatory(index)) {+                        if (value(item).isNotEmpty()) {+                            IconButton(onClick = { onValueChange(index, "") }) {                                 IconRemoveCircle()                             }                         }+                    } else {+                        IconButton(onClick = { onRemove(index) }) {+                            IconRemoveCircle()+                        }                     }-                },-                keyboardOptions = KeyboardOptions(keyboardType = keyboardType),-                singleLine = true,-                modifier = rowModifier.fillMaxWidth(),-            )+                }+            }+            if (rowKey == null) {+                OutlinedTextField(+                    value = value(item),+                    onValueChange = { v: String -> onValueChange(index, v) },+                    label = { Text(label) },+                    visualTransformation = visualTransformation,+                    leadingIcon = leadingIcon?.let { { it(item) } },+                    trailingIcon = rowTrailing,+                    keyboardOptions = KeyboardOptions(keyboardType = keyboardType),+                    singleLine = true,+                    modifier = enterModifier.fillMaxWidth(),+                )+            } else {+                // Two pairings at once: the field's box morphs from the read-only row's box, and the+                // text inside it morphs from the text inside that row. Keying only the box would drag+                // the old row's text along as cargo and crossfade it out in the wrong place.+                SharedTextLabeledField(+                    value = value(item),+                    onValueChange = { v: String -> onValueChange(index, v) },+                    label = label,+                    sharedTextKey = "$rowKey-text",+                    modifier = rowModifier.then(enterModifier).fillMaxWidth(),+                    enabled = true,+                    readOnly = false,+                    singleLine = true,+                    keyboardType = keyboardType,+                    visualTransformation = visualTransformation,+                    isError = false,+                    placeholder = null,+                    leadingIcon = leadingIcon?.let { { it(item) } },+                    trailingIcon = rowTrailing,+                )+            }             if (isCustom(item) && onLabelChange != null) {                 Spacer(Modifier.height(Spacing.xs))                 OutlinedTextField(@@ -220,7 +344,10 @@ fun <T> FormDetailGroup(             }             Spacer(Modifier.height(Spacing.xs))         }-        FilledTonalButton(onClick = onAdd, modifier = Modifier.fillMaxWidth()) {+        FilledTonalButton(+            onClick = onAdd,+            modifier = enterModifier.fillMaxWidth(),+        ) {             addIcon?.invoke() ?: IconAdd()             Spacer(Modifier.width(Spacing.sm))             Text(addLabel)
library/ui/src/main/java/com/vayunmathur/library/ui/Motion.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/Motion.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/Motion.ktindex 9121e97235..d695f80c46 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/Motion.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/Motion.kt@@ -106,4 +106,14 @@ object Motion {      /** A page snapping into place, on `PagedView`'s own curve rather than a spring. */     fun <T> pageSnap(): FiniteAnimationSpec<T> = tween(PageSnapMillis, easing = Scroll)++    /**+     * A movement whose only interesting property is how long it takes, on [FastOutSlowIn].+     *+     * The escape hatch for a genuinely one-off duration, so a screen can say "over this many+     * milliseconds" without reaching for `tween` itself. A duration that shows up twice wants a+     * named entry above instead.+     */+    fun <T> over(durationMillis: Int): FiniteAnimationSpec<T> =+        tween(durationMillis, easing = FastOutSlowIn) }
library/ui/src/main/java/com/vayunmathur/library/ui/MotionValues.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/MotionValues.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/MotionValues.ktnew file mode 100644index 0000000000..7c21773937--- /dev/null+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/MotionValues.kt@@ -0,0 +1,143 @@+package com.vayunmathur.library.ui++import androidx.compose.animation.animateColorAsState+import androidx.compose.animation.core.FiniteAnimationSpec+import androidx.compose.animation.core.animateDpAsState+import androidx.compose.animation.core.animateFloatAsState+import androidx.compose.animation.core.animateIntAsState+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.lazy.LazyItemScope+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.alpha+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.Shape+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.IntOffset+import androidx.compose.ui.unit.dp+import kotlinx.coroutines.delay++/**+ * The animated values a screen needs, on the theme's motion scheme.+ *+ * Companion to [Motion], which names durations and curves: these name the *interactions* that were+ * being rebuilt by hand at each call site. Screens reach for these rather than+ * `animate*AsState`/`animateItem` directly, which is also what keeps compose-animation out of the+ * app modules - a spec written at a call site carries no intent, and the ones written with no spec+ * at all silently took Compose's own default rather than the scheme this app is themed with.+ *+ * Every spec here is a scheme spring, which is right for a state change *within* a screen: a spring+ * is interruptible from wherever it has got to, so a second tap does not have to wait out the first.+ * Anything driven by a predictive-back gesture needs a duration instead, and lives in+ * `com.vayunmathur.library.util` with the navigation transitions.+ */++/**+ * A [Dp] that animates to [target] on the scheme's spatial spec - a size, an offset, an elevation.+ *+ * Spatial rather than effects: this is a value that moves something.+ */+@Composable+fun animatedDp(+    target: Dp,+    spec: FiniteAnimationSpec<Dp> = MaterialTheme.motionScheme.defaultSpatialSpec(),+): Dp {+    val value by animateDpAsState(targetValue = target, animationSpec = spec)+    return value+}++/**+ * A [Float] that animates to [target] on the scheme's effects spec - an alpha, a progress fraction.+ *+ * Pass a spatial spec explicitly when the float drives movement rather than an effect: mixing the+ * two up is what makes a fade look like it lags the thing it belongs to.+ */+@Composable+fun animatedFloat(+    target: Float,+    spec: FiniteAnimationSpec<Float> = MaterialTheme.motionScheme.defaultEffectsSpec(),+): Float {+    val value by animateFloatAsState(targetValue = target, animationSpec = spec)+    return value+}++/** A [Color] that animates to [target] - a container tinting as its section opens. */+@Composable+fun animatedColor(+    target: Color,+    spec: FiniteAnimationSpec<Color> = MaterialTheme.motionScheme.defaultEffectsSpec(),+): Color {+    val value by animateColorAsState(targetValue = target, animationSpec = spec)+    return value+}++/**+ * The corner radius under a finger: a round avatar or tile squares off on press and springs back on+ * release.+ *+ * A percentage rather than a [Dp], so it reads the same on a 50dp list avatar and the 100dp one on a+ * detail page, and on the bouncy `fast` spring because a press wants to feel like it gives.+ */+@Composable+fun pressedShape(pressed: Boolean, restingPercent: Int = 50, pressedPercent: Int = 30): Shape {+    val percent by animateIntAsState(+        targetValue = if (pressed) pressedPercent else restingPercent,+        animationSpec = MaterialTheme.motionScheme.fastSpatialSpec(),+    )+    return RoundedCornerShape(percent)+}++/**+ * Lets a lazy item fade in, fade out and slide to its new position as the list changes around it.+ *+ * On the scheme's specs rather than `animateItem`'s own defaults, so a list reordering matches the+ * rest of the app. [placementSpec] overrides just the travel, for a list whose reordering has its+ * own timing - a launcher page rearranging under a drag, say, where [Motion.reorder] is the platform+ * duration for it.+ *+ * Only meaningful on items with a stable `key`; without one the list has no way to tell that an item+ * moved rather than that its content changed.+ */+@Composable+fun LazyItemScope.itemMotion(placementSpec: FiniteAnimationSpec<IntOffset>? = null): Modifier {+    val scheme = MaterialTheme.motionScheme+    val fade: FiniteAnimationSpec<Float> = scheme.defaultEffectsSpec()+    return Modifier.animateItem(+        fadeInSpec = fade,+        placementSpec = placementSpec ?: scheme.defaultSpatialSpec(),+        fadeOutSpec = fade,+    )+}++/** How far apart consecutive sections start their entrance. */+private const val StaggerStepMillis = 45L++/** How far a section rises through as it arrives. */+private val StaggerLift = 12.dp++/**+ * A short rise-and-fade so a page of sections reads as assembling under its header rather than+ * appearing all at once. [index] is the section's position in that sequence.+ *+ * [arriving] is captured on first composition rather than observed: a section composed later -+ * scrolled to after the entrance is over - should simply be visible rather than animate in.+ */+@Composable+fun Modifier.staggeredEntrance(index: Int, arriving: Boolean): Modifier {+    var shown by remember { mutableStateOf(!arriving) }+    LaunchedEffect(Unit) {+        if (!shown) {+            delay(index * StaggerStepMillis)+            shown = true+        }+    }+    return this+        .offset(y = animatedDp(if (shown) 0.dp else StaggerLift))+        .alpha(animatedFloat(if (shown) 1f else 0f))+}
library/ui/src/main/java/com/vayunmathur/library/ui/PopVisibility.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/PopVisibility.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/PopVisibility.ktnew file mode 100644index 0000000000..62b8342557--- /dev/null+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/PopVisibility.kt@@ -0,0 +1,40 @@+package com.vayunmathur.library.ui++import androidx.compose.animation.AnimatedVisibility+import androidx.compose.animation.core.FiniteAnimationSpec+import androidx.compose.animation.fadeIn+import androidx.compose.animation.fadeOut+import androidx.compose.animation.scaleIn+import androidx.compose.animation.scaleOut+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier++/**+ * Shows [content] by growing it out of its own centre, and scales it away again when [visible] goes+ * false.+ *+ * For a small thing that owns a fixed spot on the screen and comes and goes there - a floating action+ * button, a badge, a chip. It reads as the button leaving rather than being cut, which a plain fade+ * does not: a fade keeps the full-size shape occupying its space for the whole animation.+ *+ * Wrong for a block inside a list or a column, which needs the space it leaves to close up behind it:+ * use [ExpandVisibility] there.+ */+@Composable+fun PopVisibility(+    visible: Boolean,+    modifier: Modifier = Modifier,+    content: @Composable () -> Unit,+) {+    val scheme = MaterialTheme.motionScheme+    val scale: FiniteAnimationSpec<Float> = scheme.defaultSpatialSpec()+    val fade: FiniteAnimationSpec<Float> = scheme.defaultEffectsSpec()+    AnimatedVisibility(+        visible = visible,+        modifier = modifier,+        enter = scaleIn(scale) + fadeIn(fade),+        exit = scaleOut(scale) + fadeOut(fade),+    ) {+        content()+    }+}
library/ui/src/main/java/com/vayunmathur/library/ui/SwappedContent.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/SwappedContent.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/SwappedContent.ktnew file mode 100644index 0000000000..8b9047c002--- /dev/null+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/SwappedContent.kt@@ -0,0 +1,29 @@+package com.vayunmathur.library.ui++import androidx.compose.animation.Crossfade+import androidx.compose.animation.core.FiniteAnimationSpec+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier++/**+ * Dissolves one content into another in the same spot as [state] changes.+ *+ * For a surface whose *contents* are replaced while the surface itself stays put and stays the same+ * size - a panel that becomes a delete target mid-drag, artwork that becomes lyrics. Nothing moves,+ * because nothing has moved: the box is where it was and only what is inside it is different.+ *+ * Wrong for a bar that a mode takes over, which wants direction to say where the new bar came from -+ * use [SwappedTopBar]. Wrong for content that comes and goes rather than being replaced, which wants+ * one of the `*Visibility` helpers.+ */+@Composable+fun <T> SwappedContent(+    state: T,+    modifier: Modifier = Modifier,+    content: @Composable (T) -> Unit,+) {+    val fade: FiniteAnimationSpec<Float> = MaterialTheme.motionScheme.defaultEffectsSpec()+    Crossfade(targetState = state, modifier = modifier, animationSpec = fade) { current ->+        content(current)+    }+}
library/ui/src/main/java/com/vayunmathur/library/ui/SwappedTopBar.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/SwappedTopBar.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/SwappedTopBar.ktnew file mode 100644index 0000000000..27f33d496d--- /dev/null+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/SwappedTopBar.kt@@ -0,0 +1,52 @@+package com.vayunmathur.library.ui++import androidx.compose.animation.AnimatedContent+import androidx.compose.animation.core.FiniteAnimationSpec+import androidx.compose.animation.fadeIn+import androidx.compose.animation.fadeOut+import androidx.compose.animation.slideInVertically+import androidx.compose.animation.slideOutVertically+import androidx.compose.animation.togetherWith+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.IntOffset++/**+ * How far the two bars travel as they swap, as a fraction of the bar's height. A third: enough to+ * read as a push, short enough that neither bar is ever mostly off its own strip.+ */+private const val SwapTravel = 3++/**+ * Swaps a top bar for another one that slides down over it, and lets the first slide back down into+ * place when it is dismissed.+ *+ * For a bar that is taken over by a mode rather than replaced by a different screen - a selection bar+ * over a search field, an in-place search bar over a title. [content] is given the current state, so+ * it emits one bar or the other exactly as an `if` would.+ *+ * The direction is the whole point and is why this is not a crossfade: the overlay comes *from above*+ * and leaves back upwards, so the two bars read as one surface being pushed in and out of the strip+ * rather than as two unrelated bars dissolving into each other.+ */+@Composable+fun SwappedTopBar(+    showingOverlay: Boolean,+    modifier: Modifier = Modifier,+    content: @Composable (Boolean) -> Unit,+) {+    val scheme = MaterialTheme.motionScheme+    val offset: FiniteAnimationSpec<IntOffset> = scheme.defaultSpatialSpec()+    val fade: FiniteAnimationSpec<Float> = scheme.defaultEffectsSpec()+    AnimatedContent(+        targetState = showingOverlay,+        modifier = modifier,+        transitionSpec = {+            val towards = if (targetState) -1 else 1+            (fadeIn(fade) + slideInVertically(offset) { towards * it / SwapTravel })+                .togetherWith(fadeOut(fade) + slideOutVertically(offset) { -towards * it / SwapTravel })+        },+    ) { overlay ->+        content(overlay)+    }+}