library: swipe-between-routes for sibling route groups
- Commit
b27eed2e3a85d4c2c318eafdefaff610089576ed- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-06 04:24 UTC (6 hours ago)
- Parents
2791743
Sibling routes are real NavKey destinations under one parent, and switching between them must not grow the back stack or move host chrome. :library gains the pure navigation half (SiblingRoutes.kt: siblingRouteAt, NavBackStack.navigateToSibling / navigateToSiblingOffset with replace-or-pop-to-sibling semantics, and siblingRouteForIndex for legacy index selectors/deep links), and :library:ui gains the gesture/host half: Modifier.swipeBetweenRoutes (a horizontal swipe/fling on a content region becomes a +1/-1 sibling switch; inner horizontal scrollers and vertical lists win their gestures, nothing is consumed until the drag is clearly horizontal) and SwipeRouteHost (top bar, PrimaryTabRow, bottom bar and FAB are rendered by the host, outside the swiping content and outside any MainNavigation hosted inside it). MainNavigation documents the same stillness for its bottomBar slot: the bar is composed once beside the NavDisplay, a switch updates only its selected item. Route transitions stay the destinations' SiblingPage() crossfade from NavigationMotion; no raw animation at call sites. Tests: SiblingRoutesTest covers adjacent order, ends, back-to-parent, deep-link index clamping, detail-on-top and group entry; SwipeRouteHostTest swipes/taps between routes asserting the stack never grows and the host bottom bar stays rendered. Verified: :library:lint, :library:ui:lint, :library:lintVitalRelease, :library:ui:lintVitalRelease, :library:testDevUnitTest and :library:ui:testDevUnitTest all pass.
Diff
library/AGENTS.md
diff --git a/library/AGENTS.md b/library/AGENTS.mdindex 51dfb51a0f..5a7eb0e442 100644--- a/library/AGENTS.md+++ b/library/AGENTS.md@@ -45,6 +45,7 @@ ### util/ — navigation, intents, messenger, storage, games glue - com/vayunmathur/library/util/Navigation.kt — `NavKey` + `MainNavigation` + `rememberNavBackStack` - com/vayunmathur/library/util/NavigationBottomBar.kt+- com/vayunmathur/library/util/SiblingRoutes.kt — ordered sibling-route groups: adjacent/replace navigation (`navigateToSibling*`) so swipe/tab switches never grow the back stack; index/deep-link resolution for legacy selectors - com/vayunmathur/library/util/NavigationMotion.kt - com/vayunmathur/library/util/NavigationResults.kt - com/vayunmathur/library/util/AssistantIntent.kt
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 4e6b66e276..5798b34220 100644--- a/library/src/main/java/com/vayunmathur/library/util/Navigation.kt+++ b/library/src/main/java/com/vayunmathur/library/util/Navigation.kt@@ -462,6 +462,11 @@ fun Modifier.sharedContent(key: Any): Modifier { * opaque `colorScheme.background`. Pass [Color.Transparent] when something behind the * activity window has to show through - the launcher needs the wallpaper visible, and an * opaque scaffold paints over it.+ *+ * Host chrome stays still: [bottomBar] is rendered beside the `NavDisplay`, never inside+ * it, so route transitions (including sibling switches driven by+ * `SwipeRouteHost`/`swipeBetweenRoutes` in `:library:ui`) animate only the content above+ * it. The bar is composed once; a switch updates its selected item, nothing else. */ @OptIn(ExperimentalMaterial3AdaptiveApi::class, ExperimentalSharedTransitionApi::class) @Composable
library/src/main/java/com/vayunmathur/library/util/SiblingRoutes.kt
diff --git a/library/src/main/java/com/vayunmathur/library/util/SiblingRoutes.kt b/library/src/main/java/com/vayunmathur/library/util/SiblingRoutes.ktnew file mode 100644index 0000000000..fc1fb298f1--- /dev/null+++ b/library/src/main/java/com/vayunmathur/library/util/SiblingRoutes.kt@@ -0,0 +1,62 @@+package com.vayunmathur.library.util++/**+ * Ordered sibling routes: peers under one parent (recipes/ingredients,+ * logging leaderboards, search kinds). Members are real [NavKey]+ * destinations, not pages inside one screen, so each has its own entry,+ * saved state, deep link and screenshot. Switching between them is a+ * sibling switch, never a push: the back stack keeps exactly one member+ * on top of the group's parent, so Back returns to that parent however+ * many sibling switches happened first.+ */++/** The sibling [offset] steps from [current] in [siblings], or null at an end / when absent. */+fun <T : NavKey> siblingRouteAt(siblings: List<T>, current: T, offset: Int): T? {+ val index = siblings.indexOf(current)+ if (index < 0) return null+ return siblings.getOrNull(index + offset)+}++/**+ * Switch the top of this stack to [target], a member of [siblings],+ * without growing the stack. When the top is a sibling it is replaced;+ * when a sibling sits under pushed destinations (a detail opened over a+ * sibling) the stack pops back to it and replaces it; when no sibling is+ * present the target is pushed (the caller is entering the group).+ * Returns true when the top actually changed.+ */+fun <T : NavKey> NavBackStack<T>.navigateToSibling(siblings: List<T>, target: T): Boolean {+ require(target in siblings) { "target is not a member of the sibling group" }+ if (backStack.lastOrNull() == target) return false+ val siblingIndex = backStack.indexOfLast { it in siblings }+ when {+ siblingIndex < 0 -> add(target)+ siblingIndex == backStack.lastIndex -> setLast(target)+ else -> {+ while (backStack.size > siblingIndex + 1) pop()+ setLast(target)+ }+ }+ return true+}++/**+ * [navigateToSibling] by [offset] (+1 = next sibling, -1 = previous)+ * from the current top. Returns the new top, or null when there is no+ * adjacent sibling (swipe past either end does nothing) or the top is+ * not a member of the group (a pushed detail owns its own gestures).+ */+fun <T : NavKey> NavBackStack<T>.navigateToSiblingOffset(siblings: List<T>, offset: Int): T? {+ val current = backStack.lastOrNull() ?: return null+ val target = siblingRouteAt(siblings, current, offset) ?: return null+ return if (navigateToSibling(siblings, target)) target else null+}++/**+ * Resolve a legacy/deep-link selector (an index a caller stored before+ * the group became routes, e.g. `Route.Logging(tab)`) to its sibling,+ * clamped to the group. The resolved route is the destination to put on+ * the stack; the selector itself never needs to stay on the stack.+ */+fun <T : NavKey> siblingRouteForIndex(siblings: List<T>, index: Int): T =+ siblings[index.coerceIn(0, siblings.lastIndex)]
library/src/test/java/com/vayunmathur/library/util/SiblingRoutesTest.kt
diff --git a/library/src/test/java/com/vayunmathur/library/util/SiblingRoutesTest.kt b/library/src/test/java/com/vayunmathur/library/util/SiblingRoutesTest.ktnew file mode 100644index 0000000000..fb773c452f--- /dev/null+++ b/library/src/test/java/com/vayunmathur/library/util/SiblingRoutesTest.kt@@ -0,0 +1,86 @@+package com.vayunmathur.library.util++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** Sibling-route switching: order, replace semantics, deep-link resolution. */+class SiblingRoutesTest {+ private object Parent : NavKey++ private object First : NavKey++ private object Second : NavKey++ private object Third : NavKey++ private data class Detail(+ val id: Long,+ ) : NavKey++ private val siblings = listOf<NavKey>(First, Second, Third)++ @Test fun swipeStepsToAdjacentSiblingWithoutGrowingStack() {+ val stack = NavBackStack(arrayOf<NavKey>(Parent, First))+ assertEquals(Second, stack.navigateToSiblingOffset(siblings, 1))+ assertEquals(listOf(Parent, Second), stack.backStack)+ assertEquals(Third, stack.navigateToSiblingOffset(siblings, 1))+ assertEquals(listOf(Parent, Third), stack.backStack)+ assertEquals(Second, stack.navigateToSiblingOffset(siblings, -1))+ assertEquals(listOf(Parent, Second), stack.backStack)+ }++ @Test fun swipePastEitherEndDoesNothing() {+ val stack = NavBackStack(arrayOf<NavKey>(Parent, First))+ assertNull(stack.navigateToSiblingOffset(siblings, -1))+ assertEquals(listOf(Parent, First), stack.backStack)+ stack.navigateToSiblingOffset(siblings, 1)+ stack.navigateToSiblingOffset(siblings, 1)+ assertNull(stack.navigateToSiblingOffset(siblings, 1))+ assertEquals(listOf(Parent, Third), stack.backStack)+ }++ @Test fun backAfterSiblingSwitchesReturnsToParent() {+ val stack = NavBackStack(arrayOf<NavKey>(Parent, First))+ stack.navigateToSiblingOffset(siblings, 1)+ stack.navigateToSiblingOffset(siblings, 1)+ stack.pop()+ assertEquals(listOf(Parent), stack.backStack)+ }++ @Test fun siblingDeepLinkIndexResolvesClamped() {+ assertEquals(First, siblingRouteForIndex(siblings, 0))+ assertEquals(Third, siblingRouteForIndex(siblings, 2))+ assertEquals(Third, siblingRouteForIndex(siblings, 99))+ assertEquals(First, siblingRouteForIndex(siblings, -1))+ // A deep link lands as [parent, sibling]: one entry over the parent.+ val stack = NavBackStack(arrayOf<NavKey>(Parent, siblingRouteForIndex(siblings, 2)))+ assertEquals(listOf(Parent, Third), stack.backStack)+ }++ @Test fun reselectingCurrentSiblingIsNoOp() {+ val stack = NavBackStack(arrayOf<NavKey>(Parent, Second))+ assertFalse(stack.navigateToSibling(siblings, Second))+ assertEquals(listOf(Parent, Second), stack.backStack)+ }++ @Test fun swipeOnPushedDetailDoesNothing() {+ val stack = NavBackStack(arrayOf<NavKey>(Parent, First, Detail(7)))+ assertNull(stack.navigateToSiblingOffset(siblings, 1))+ assertEquals(listOf(Parent, First, Detail(7)), stack.backStack)+ }++ @Test fun tabSwitchFromDetailPopsBackToSiblingAndReplaces() {+ val stack = NavBackStack(arrayOf<NavKey>(Parent, First, Detail(7)))+ assertTrue(stack.navigateToSibling(siblings, Third))+ assertEquals(listOf(Parent, Third), stack.backStack)+ }++ @Test fun enteringGroupPushesFirstSibling() {+ val stack = NavBackStack(arrayOf<NavKey>(Parent))+ assertTrue(stack.navigateToSibling(siblings, Second))+ assertEquals(listOf(Parent, Second), stack.backStack)+ }+}
library/ui/AGENTS.md
diff --git a/library/ui/AGENTS.md b/library/ui/AGENTS.mdindex 020c6ae62f..2d5d5f04e4 100644--- a/library/ui/AGENTS.md+++ b/library/ui/AGENTS.md@@ -34,6 +34,8 @@ - com/vayunmathur/library/ui/DetailScaffold.kt - com/vayunmathur/library/ui/LazyListScaffold.kt - com/vayunmathur/library/ui/TabbedPagerScaffold.kt+- com/vayunmathur/library/ui/SwipeBetweenRoutes.kt — `Modifier.swipeBetweenRoutes`: horizontal swipe/fling on a content region becomes a sibling-route switch (inner horizontal scrollers and vertical lists win their gestures)+- com/vayunmathur/library/ui/SwipeRouteHost.kt — sibling-route host: top bar + tab row + bottom bar/FAB rendered outside the swiping content (and outside any hosted `MainNavigation`), so host chrome stays still and only content takes the route transition - com/vayunmathur/library/ui/SetupScaffold.kt - com/vayunmathur/library/ui/ListPage.kt ### Theme + tokens
library/ui/src/main/java/com/vayunmathur/library/ui/SwipeBetweenRoutes.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/SwipeBetweenRoutes.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/SwipeBetweenRoutes.ktnew file mode 100644index 0000000000..9caf0afe53--- /dev/null+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/SwipeBetweenRoutes.kt@@ -0,0 +1,89 @@+package com.vayunmathur.library.ui++import androidx.compose.foundation.gestures.awaitEachGesture+import androidx.compose.foundation.gestures.awaitFirstDown+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.rememberUpdatedState+import androidx.compose.ui.Modifier+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.input.pointer.util.VelocityTracker+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.unit.dp+import kotlin.math.abs++/**+ * Turns a horizontal swipe/fling on this content region into a sibling+ * route switch: leftward moves to the next sibling (+1), rightward to+ * the previous (-1), via [onNavigate]. This is the gesture half of the+ * swipe-between-routes pattern; the navigation half (replace, never+ * push, so Back still returns to the group's parent) is+ * `NavBackStack.navigateToSiblingOffset` in `:library`.+ *+ * Inner horizontal scrollers win: the detector only claims a gesture+ * once its accumulated movement is dominated by the X axis, and bails+ * for the whole gesture as soon as any change arrives already consumed+ * (a horizontal list, grid or pager inside the region got there first)+ * or the vertical axis wins past touch slop (the region's own vertical+ * list scrolls instead). Until it claims, it consumes nothing.+ *+ * Apply it to the content region only — never to a host scaffold as a+ * whole. Host chrome (top bar, sibling tab row, bottom navigation bar)+ * lives outside this modifier in [SwipeRouteHost]/`MainNavigation`, so+ * the bar is rendered once and stays still; only the content region+ * responds to the swipe and takes part in the route transition.+ *+ * A switch fires on release when the drag travelled at least 48dp, or+ * on a fling past 400dp/s in the drag direction, however far it got.+ */+@Composable+fun Modifier.swipeBetweenRoutes(onNavigate: (Int) -> Unit): Modifier {+ val latestOnNavigate by rememberUpdatedState(onNavigate)+ val density = LocalDensity.current+ val distanceThreshold = with(density) { 48.dp.toPx() }+ val velocityThreshold = with(density) { 400.dp.toPx() }+ return pointerInput(Unit) {+ awaitEachGesture {+ val down = awaitFirstDown(requireUnconsumed = false)+ val tracker = VelocityTracker()+ tracker.addPosition(down.uptimeMillis, down.position)+ var claimed = false+ var totalDx = 0f+ var totalDy = 0f+ var bailed = false+ while (true) {+ val event = awaitPointerEvent()+ val change = event.changes.firstOrNull { it.id == down.id } ?: break+ if (!change.pressed) {+ if (claimed && !bailed) {+ val velocity = tracker.calculateVelocity().x+ val byDistance = abs(totalDx) >= distanceThreshold+ val byFling = abs(velocity) >= velocityThreshold &&+ (velocity < 0f) == (totalDx < 0f)+ if ((byDistance || byFling) && totalDx != 0f) {+ latestOnNavigate(if (totalDx < 0f) 1 else -1)+ }+ }+ break+ }+ // An inner horizontal scroller already claimed this one.+ if (change.isConsumed && !claimed) bailed = true+ tracker.addPosition(change.uptimeMillis, change.position)+ totalDx += change.position.x - change.previousPosition.x+ totalDy += change.position.y - change.previousPosition.y+ if (!claimed && !bailed) {+ val pastSlop = abs(totalDx) > viewConfiguration.touchSlop ||+ abs(totalDy) > viewConfiguration.touchSlop+ when {+ // Vertical wins: the region's list scrolls, not us.+ pastSlop && abs(totalDy) >= abs(totalDx) -> bailed = true+ // Clearly horizontal (bias, as in SwipeActionsBox).+ abs(totalDx) > viewConfiguration.touchSlop &&+ abs(totalDx) > 2f * abs(totalDy) -> claimed = true+ }+ }+ if (claimed) change.consume()+ }+ }+ }+}
library/ui/src/main/java/com/vayunmathur/library/ui/SwipeRouteHost.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/SwipeRouteHost.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/SwipeRouteHost.ktnew file mode 100644index 0000000000..6e4a85e96c--- /dev/null+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/SwipeRouteHost.kt@@ -0,0 +1,92 @@+package com.vayunmathur.library.ui++import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.library.util.NavKey+import com.vayunmathur.library.util.navigateToSibling+import com.vayunmathur.library.util.navigateToSiblingOffset++/**+ * Host for one ordered sibling-route group (see `SiblingRoutes.kt` in+ * `:library`): a top bar, a [PrimaryTabRow] naming the siblings, an+ * optional bottom bar, and the current sibling's content.+ *+ * Chrome stays still; only content moves. Everything in the scaffold+ * slots — [topBar], the tab row, [bottomBar], the FAB — is rendered by+ * this host, outside the swiping content region and outside any+ * `NavDisplay` the caller hosts in [content] (the health pattern:+ * `SwipeRouteHost { MainNavigation(...) }`). A sibling switch therefore+ * updates the row's selected indicator and crossfades/slides the+ * content (per the destination's `SiblingPage()` metadata) while the+ * bars themselves are rendered once and never slide, shrink or+ * recompose as part of the page transition. The same holds one level+ * up: `MainNavigation` renders its `bottomBar` beside, not inside, its+ * `NavDisplay`, so an app bottom navigation bar over a sibling group+ * is still by construction.+ *+ * Gestures: the content region carries [swipeBetweenRoutes]; tapping a+ * tab and swiping are the same switch (both go through+ * `navigateToSibling`, which replaces the group's top entry instead of+ * pushing, so Back returns to the group's parent). Register every+ * sibling destination with `SiblingPage()` metadata so the route+ * transition is the directionless sibling crossfade.+ *+ * [showChrome] hides the top bar + tab row when the stack top is not a+ * group member (a detail/dialog pushed over a sibling, or the group's+ * parent) while keeping this host — and any [MainNavigation] inside+ * [content] — in the same place in the tree. [bottomBar] is not gated:+ * bottom navigation is app chrome, present over pushed destinations+ * exactly as the caller's own bar policy decides.+ */+@Composable+fun <T : NavKey> SwipeRouteHost(+ backStack: NavBackStack<T>,+ tabs: List<RouteTab<T>>,+ modifier: Modifier = Modifier,+ showChrome: (T) -> Boolean = { it in tabs.map { tab -> tab.route } },+ topBar: @Composable () -> Unit = {},+ bottomBar: @Composable () -> Unit = {},+ floatingActionButton: @Composable (T) -> Unit = {},+ content: @Composable (T) -> Unit,+) {+ val current = backStack.last()+ val routes = tabs.map { it.route }+ val selectedIndex = routes.indexOf(current)+ Scaffold(+ modifier = modifier,+ topBar = {+ if (showChrome(current)) {+ Column(Modifier.fillMaxWidth()) {+ topBar()+ PrimaryTabRow(selectedTabIndex = selectedIndex.coerceAtLeast(0)) {+ tabs.forEach { tab ->+ Tab(+ selected = tab.route == current,+ onClick = { backStack.navigateToSibling(routes, tab.route) },+ text = { Text(tab.label) },+ icon = tab.icon,+ )+ }+ }+ }+ }+ },+ bottomBar = bottomBar,+ floatingActionButton = { floatingActionButton(current) },+ ) { padding ->+ Box(+ Modifier+ .fillMaxSize()+ .padding(padding)+ .swipeBetweenRoutes { offset ->+ backStack.navigateToSiblingOffset(routes, offset)+ },+ ) { content(current) }+ }+}
library/ui/src/test/java/com/vayunmathur/library/ui/SwipeRouteHostTest.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/SwipeRouteHostTest.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/SwipeRouteHostTest.ktnew file mode 100644index 0000000000..c133567b4c--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/SwipeRouteHostTest.kt@@ -0,0 +1,102 @@+package com.vayunmathur.library.ui++import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.material3.Text+import androidx.compose.ui.Modifier+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTouchInput+import androidx.compose.ui.test.swipeLeft+import androidx.compose.ui.test.swipeRight+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.library.util.NavKey+import kotlin.test.Test+import kotlin.test.assertEquals+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/**+ * [SwipeRouteHost] over sibling routes: a swipe switches the route on top+ * of the stack (never grows it, so Back still lands on the parent), tab+ * taps are the same switch, and the host's bottom bar is rendered by the+ * host — outside the swiping content — throughout.+ */+@RunWith(RobolectricTestRunner::class)+class SwipeRouteHostTest {+ @get:Rule val rule = createComposeRule()++ private object Parent : NavKey++ private object First : NavKey++ private object Second : NavKey++ private object Third : NavKey++ private fun setHost(stack: NavBackStack<NavKey>) {+ rule.setContent {+ SwipeRouteHost(+ backStack = stack,+ tabs = listOf(+ RouteTab(First, "First"),+ RouteTab(Second, "Second"),+ RouteTab(Third, "Third"),+ ),+ bottomBar = { Text("Bottom bar") },+ ) { route ->+ Box(Modifier.fillMaxSize()) {+ Text(+ when (route) {+ First -> "Page one"+ Second -> "Page two"+ Third -> "Page three"+ else -> "Other page"+ },+ )+ }+ }+ }+ }++ @Test fun swipeLeftMovesToNextSiblingWithoutGrowingStack() {+ val stack = NavBackStack(arrayOf<NavKey>(Parent, First))+ setHost(stack)+ rule.onNodeWithText("Page one").assertIsDisplayed()+ rule.onNodeWithText("Bottom bar").assertIsDisplayed()++ rule.onRoot().performTouchInput { swipeLeft() }+ rule.waitForIdle()++ assertEquals(listOf(Parent, Second), stack.backStack)+ rule.onNodeWithText("Page two").assertIsDisplayed()+ rule.onNodeWithText("Bottom bar").assertIsDisplayed()+ }++ @Test fun swipeRightMovesToPreviousSiblingAndBackReturnsToParent() {+ val stack = NavBackStack(arrayOf<NavKey>(Parent, Second))+ setHost(stack)++ rule.onRoot().performTouchInput { swipeRight() }+ rule.waitForIdle()++ assertEquals(listOf(Parent, First), stack.backStack)+ stack.pop()+ assertEquals(listOf(Parent), stack.backStack)+ }++ @Test fun tabTapIsSameSwitchAsSwipe() {+ val stack = NavBackStack(arrayOf<NavKey>(Parent, First))+ setHost(stack)++ rule.onNodeWithText("Third").performClick()+ rule.waitForIdle()++ assertEquals(listOf(Parent, Third), stack.backStack)+ rule.onNodeWithText("Page three").assertIsDisplayed()+ }+}