Modern Apps git

← Modern-Apps.git

library-ui: route-backed TabbedPagerScaffold and TvAppFrame (#nav)

Commit
d11b8b3d4bc8a0a986cb9893b5f1361d6d94dec5
Author
Vayun Mathur <[email protected]>
When
2026-11-16 19:40 UTC (19 days ago)
Parents
87837a9
The route audit (/tmp/route-audit.md section 3, A2 rows for
library/ui and library/tv) flags TabbedPagerScaffold and TvAppFrame
as the shared-library enablers of the pager/rail tab state machines
in a dozen apps: the selected major screen was held in pager or
index state instead of in the apps Route back stack, invisible to
back handling, deep links, and process restore. This adds the
route-backed APIs those app migrations will consume; no app is
migrated here.

library/ui: a route-backed overload of TabbedPagerScaffold for the
BottomNav style, driven by NavBackStack<T : NavKey> plus a list of
RouteTab(route, label, icon). Selecting a tab does
backStack.reset(route) (SiblingPage semantics) and re-selecting the
current tab is a no-op. It is deliberately not a pager: the content
slot is invoked with the route on top of the stack and renders that
destination, either directly (when (route) { ... }) or by hosting
MainNavigation for the same stack inside the slot (the calculator
rail pattern), in which case a non-tab destination pushed over a
tab renders with no tab selected. The chrome mirrors the pager
BottomNav branch exactly (BottomNavBar on compact/medium,
NavigationRail on expanded, leadingBottomBar, same inset
forwarding) and the parameter list mirrors the pager overload, so
migrating an app is mechanical: PagerTab(label, icon) { Page() }
becomes RouteTab(route, label, icon) plus the page moving into
the content slot or a MainNavigation entry registered with
SiblingPage(). The pager overload itself is untouched (existing
signature, no consumer breakage); its KDoc now states it is
in-screen-only: PrimaryTabRow tabs and other genuine sub-state of
a single screen remain legitimate pager state, app-level bottom
nav tabs do not.

library/tv: a NavBackStack-based TvAppFrame variant keyed by
TvRouteDestination(route, label, icon), delegating to the existing
rail UI; focusing or clicking a destination resets the stack to
its route. The Int-based overload stays, with KDoc steering
app-level destinations to the route variant. Supporting fix in the
Int overload: when nothing is selected (selected = -1, i.e. the
route variant showing a non-rail destination), there is no longer
a default focus restorer — restoring to FocusRequester.Default
landed focus on the first rail item, whose focus-select would have
hijacked the visible destination. In-range selections are
unaffected.

Tests: Robolectric compose tests for both libraries assert the
top route is rendered and that selecting a tab/destination resets
a stack with a pushed detail destination down to exactly that
route (reset, not push), and back again; the phone test also
covers re-select being a no-op. The TV test focuses the rail item
before clicking, as a real remote session does, since firing
OnClick on an unfocused TV surface starts its
move-focus-into-content from no focus.

Verified on devvm21958 (no push):
- ./gradlew :library:ui:compileDebugKotlin
  :library:tv:compileDebugKotlin :library:ui:testDebugUnitTest
  :library:tv:testDebugUnitTest :clock:compileDevKotlin — green
  (libraries expose compileDebugKotlin, not compileDevKotlin;
  clock is the unmodified consumer compile).

Diff

library/tv/src/main/java/com/vayunmathur/library/tv/TvAppFrame.kt
diff --git a/library/tv/src/main/java/com/vayunmathur/library/tv/TvAppFrame.kt b/library/tv/src/main/java/com/vayunmathur/library/tv/TvAppFrame.ktindex ba7d583dd2..e614fcde4f 100644--- a/library/tv/src/main/java/com/vayunmathur/library/tv/TvAppFrame.kt+++ b/library/tv/src/main/java/com/vayunmathur/library/tv/TvAppFrame.kt@@ -35,10 +35,24 @@ import androidx.tv.material3.MaterialTheme import androidx.tv.material3.SelectableSurfaceDefaults import androidx.tv.material3.Surface import androidx.tv.material3.Text+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.library.util.NavKey  /** One top-level destination in the rail. [icon] is an `IconXxx()` from `:library:ui`. */ class TvDestination(val label: String, val icon: @Composable () -> Unit) +/**+ * One top-level destination in the rail of the route-backed [TvAppFrame]:+ * a label, an `IconXxx()` from `:library:ui`, and the [route] it selects.+ * The destination's content is the caller's entry for [route] (see the+ * route-backed overload below).+ */+class TvRouteDestination<T : NavKey>(+    val route: T,+    val label: String,+    val icon: @Composable () -> Unit,+)+ /**  * The TV app shell: a slim fixed rail (icon over a short label, like the phone's bottom bar  * turned sideways) and the selected destination's content beside it. The rail never expands@@ -46,6 +60,13 @@ class TvDestination(val label: String, val icon: @Composable () -> Unit)  * from the content returns to the rail so the next BACK exits.  *  * @param backReturnsToRail pass `false` when this frame is not the top of the back stack.+ *+ * This index-based overload is for a rail whose selection genuinely lives+ * inside one screen. App-level TV destinations — the major screens of an+ * app — are navigation destinations, not an index: use the route-backed+ * overload below, where each destination is a route on a+ * [NavBackStack] and focusing/clicking it resets the stack (sibling+ * semantics), so back, deep links, and process restore see the real screen.  */ @Composable fun TvAppFrame(@@ -58,12 +79,15 @@ fun TvAppFrame( ) {     var railFocused by remember { mutableStateOf(false) }     val requesters = remember(destinations.size) { List(destinations.size) { FocusRequester() } }-    val selectedRequester = requesters.getOrElse(selected) { FocusRequester.Default }+    // Null when nothing is selected (route-backed frame showing a non-rail+    // destination): restoring focus to a default requester would land on the+    // first rail item and its focus-select would hijack the destination.+    val selectedRequester = requesters.getOrNull(selected)     val focusManager = LocalFocusManager.current      // Registered before content so screen-level BackHandlers (closing a panel, clearing search) win.     BackHandler(enabled = backReturnsToRail && !railFocused) {-        runCatching { selectedRequester.requestFocus() }+        selectedRequester?.let { runCatching { it.requestFocus() } }     }     Row(modifier.fillMaxSize().background(MaterialTheme.colorScheme.background)) {         Column(@@ -71,7 +95,7 @@ fun TvAppFrame(                 .fillMaxHeight()                 .width(TvDimens.Rail)                 .onFocusChanged { railFocused = it.hasFocus }-                .focusRestorer(selectedRequester)+                .then(if (selectedRequester != null) Modifier.focusRestorer(selectedRequester) else Modifier)                 .focusGroup()                 .padding(horizontal = 8.dp, vertical = TvDimens.SafeVertical),             verticalArrangement = Arrangement.spacedBy(6.dp, Alignment.CenterVertically),@@ -98,6 +122,49 @@ fun TvAppFrame(     } } +/**+ * Route-backed TV app shell: the same rail UI as the index-based+ * [TvAppFrame], but destinations are keyed by [NavKey] routes on a+ * [NavBackStack].+ *+ * Focusing or clicking a rail item calls `backStack.reset(destination.route)`+ * — sibling semantics: destinations are siblings, so switching replaces the+ * stack rather than pushing, and re-selecting the current destination is a+ * no-op. Register each destination with `SiblingPage()` metadata in+ * `MainNavigation` so switches crossfade instead of sliding like a push.+ *+ * [content] is invoked with the route on top of [backStack] and renders that+ * destination — either directly (`when (route) { ... }`) or by hosting the+ * `MainNavigation` for [backStack] inside the content slot, in which case+ * non-rail destinations pushed over a destination render here with no rail+ * item selected.+ *+ * The parameter list mirrors the index-based overload so migrations are+ * mechanical: `selected`/`onSelect` are replaced by [backStack], and each+ * `TvDestination(label, icon)` becomes a+ * `TvRouteDestination(route, label, icon)`.+ */+@Composable+fun <T : NavKey> TvAppFrame(+    backStack: NavBackStack<T>,+    destinations: List<TvRouteDestination<T>>,+    modifier: Modifier = Modifier,+    backReturnsToRail: Boolean = true,+    content: @Composable (T) -> Unit,+) {+    val current = backStack.last()+    TvAppFrame(+        destinations = destinations.map { TvDestination(it.label, it.icon) },+        selected = destinations.indexOfFirst { it.route == current },+        onSelect = { index ->+            val route = destinations[index].route+            if (current != route) backStack.reset(route)+        },+        modifier = modifier,+        backReturnsToRail = backReturnsToRail,+    ) { content(current) }+}+ @Composable private fun RailItem(     destination: TvDestination,
library/tv/src/test/java/com/vayunmathur/library/tv/TvRouteAppFrameTest.kt
diff --git a/library/tv/src/test/java/com/vayunmathur/library/tv/TvRouteAppFrameTest.kt b/library/tv/src/test/java/com/vayunmathur/library/tv/TvRouteAppFrameTest.ktnew file mode 100644index 0000000000..b1f1a0de5f--- /dev/null+++ b/library/tv/src/test/java/com/vayunmathur/library/tv/TvRouteAppFrameTest.kt@@ -0,0 +1,107 @@+package com.vayunmathur.library.tv++import androidx.compose.foundation.focusable+import androidx.compose.foundation.layout.Box+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performSemanticsAction+import androidx.tv.material3.Text+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.library.util.NavKey+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/**+ * Route-backed [TvAppFrame]: selecting a rail destination resets the back+ * stack to that destination's route (sibling semantics) and the content slot+ * renders the destination now on top of the stack.+ */+@RunWith(RobolectricTestRunner::class)+class TvRouteAppFrameTest {++    @get:Rule val rule = createComposeRule()++    private object Home : NavKey+    private object Films : NavKey+    private data class Detail(val id: Long) : NavKey++    private fun clickText(text: String) {+        // A TV rail item is focused before it is clicked, and focusing it is+        // what selects it in a real session — so focus first, then click,+        // instead of firing OnClick on an unfocused item (whose+        // move-focus-into-content would start from no focus and land on the+        // first rail item).+        val node = rule.onNode(androidx.compose.ui.test.hasText(text))+        node.performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.RequestFocus)+        rule.waitForIdle()+        val ok = node.fetchSemanticsNode()+            .config[androidx.compose.ui.semantics.SemanticsActions.OnClick].action?.invoke()+        assertTrue(ok == true, "no click action for '$text'")+    }++    private fun setRouteFrame(stack: NavBackStack<NavKey>) {+        rule.setContent {+            MaTvTheme(Color(0xFF3366FF)) {+                TvAppFrame(+                    backStack = stack,+                    destinations = listOf(+                        TvRouteDestination(Home, "Home") { Text("H") },+                        TvRouteDestination(Films, "Films") { Text("F") },+                    ),+                ) { route ->+                    // Focusable, like real TV content (a grid/button): the+                    // rail's click moves focus right into the content, and+                    // with nothing focusable there it would hunt back to the+                    // rail and focus-select the first destination.+                    Box(Modifier.focusable()) {+                        when (route) {+                            Home -> Text("Home content")+                            Films -> Text("Films content")+                            is Detail -> Text("Detail content")+                            else -> Text("Other content")+                        }+                    }+                }+            }+        }+    }++    @Test fun rendersTopRouteAndRailSelectResetsStack() {+        // A detail destination pushed over Home: selecting a rail destination+        // must reset (replace) the whole stack, not push.+        val stack = NavBackStack<NavKey>(arrayOf(Home, Detail(7)))+        setRouteFrame(stack)+        rule.onNodeWithText("Detail content").assertExists()+        rule.onNodeWithText("Home").assertExists()+        rule.waitForIdle()++        clickText("Films")+        rule.waitForIdle()++        assertEquals(listOf(Films), stack.backStack)+        rule.onNodeWithText("Films content").assertExists()+    }++    @Test fun railSelectFromDestinationReplacesAndRenders() {+        val stack = NavBackStack<NavKey>(arrayOf(Home))+        setRouteFrame(stack)+        rule.onNodeWithText("Home content").assertExists()++        clickText("Films")+        rule.waitForIdle()+        assertEquals(listOf(Films), stack.backStack)+        rule.onNodeWithText("Films content").assertExists()++        clickText("Home")+        rule.waitForIdle()+        assertEquals(listOf(Home), stack.backStack)+        rule.onNodeWithText("Home content").assertExists()+    }+}+
library/ui/src/main/java/com/vayunmathur/library/ui/TabbedPagerScaffold.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/TabbedPagerScaffold.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/TabbedPagerScaffold.ktindex 0ed1b69a6c..2c161baba7 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/TabbedPagerScaffold.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/TabbedPagerScaffold.kt@@ -1,11 +1,13 @@ package com.vayunmathur.library.ui +import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.calculateStartPadding import androidx.compose.foundation.layout.consumeWindowInsets import androidx.compose.foundation.layout.fillMaxHeight+import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.pager.HorizontalPager@@ -17,6 +19,8 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalLayoutDirection import com.vayunmathur.library.util.BottomNavBar import com.vayunmathur.library.util.BottomNavBarItem+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.library.util.NavKey import kotlinx.coroutines.launch  /** One tab in a [TabbedPagerScaffold]: a label, an optional icon, and its page. */@@ -26,6 +30,18 @@ data class PagerTab(     val content: @Composable () -> Unit, ) +/**+ * One tab in the route-backed [TabbedPagerScaffold]: a label, an optional icon,+ * and the [route] it selects. Unlike [PagerTab] it carries no content — the+ * destination's content is the caller's entry for [route] (see the route-backed+ * overload below).+ */+data class RouteTab<T : NavKey>(+    val route: T,+    val label: String,+    val icon: (@Composable () -> Unit)? = null,+)+ /** How [TabbedPagerScaffold] presents its tabs. */ enum class TabStyle {     /** A [BottomNavBar] at the bottom - the app-level "main tabs" case (music). */@@ -53,6 +69,15 @@ enum class TabStyle {  * tabs move into a [NavigationRail] on the left and only [leadingBottomBar]  * stays at the bottom, so tabbed apps get desktop chrome without touching  * their own code. Compact and medium windows keep the bottom bar.+ *+ * **In-screen tabs only.** This pager overload keeps the selected page in+ * pager state, so it must only host tabs that live *inside* one screen+ * ([TabStyle.PrimaryTabRow], or a [TabStyle.BottomNav] grouping that is+ * genuinely one destination's sub-state). App-level bottom-nav tabs — the+ * major screens of an app — are navigation destinations, not pages: use the+ * route-backed overload below, where each tab is a route on a+ * [NavBackStack] and switching tabs resets the stack (SiblingPage+ * semantics), so back, deep links, and process restore see the real screen.  */ @Composable fun TabbedPagerScaffold(@@ -164,6 +189,106 @@ fun TabbedPagerScaffold(     } } +/**+ * Route-backed tab host for app-level bottom-nav tabs: the same chrome as the+ * [TabStyle.BottomNav] pager overload (a [BottomNavBar] on compact/medium+ * windows, a [NavigationRail] on expanded ones, with [leadingBottomBar] above+ * the bottom bar), but driven by a [NavBackStack] instead of a pager.+ *+ * Selecting a tab calls `backStack.reset(tab.route)` — SiblingPage semantics:+ * tabs are siblings, so switching replaces the stack rather than pushing, and+ * re-selecting the current tab is a no-op. Register each tab destination with+ * `SiblingPage()` metadata in `MainNavigation` so tab switches crossfade+ * instead of sliding like a push.+ *+ * There is deliberately no pager and no swipe: [content] is invoked with the+ * route on top of [backStack] and renders that destination. It composes with+ * `MainNavigation` entries either directly —+ * `content = { route -> when (route) { ... } }` — or by hosting the+ * `MainNavigation` for [backStack] inside the content slot (the calculator+ * rail pattern), in which case the routes registered for non-tab+ * destinations pushed over a tab simply render here with no tab selected.+ *+ * The parameter list mirrors the pager overload so migrations are mechanical:+ * a `PagerTab(label, icon) { Page() }` becomes a+ * `RouteTab(route, label, icon)` plus the page moving into [content] (or into+ * a `MainNavigation` entry for that route).+ */+@Composable+fun <T : NavKey> TabbedPagerScaffold(+    backStack: NavBackStack<T>,+    tabs: List<RouteTab<T>>,+    modifier: Modifier = Modifier,+    topBar: @Composable () -> Unit = {},+    leadingBottomBar: @Composable () -> Unit = {},+    content: @Composable (T) -> Unit,+) {+    val current = backStack.last()+    val select: (RouteTab<T>) -> Unit = { tab ->+        if (current != tab.route) backStack.reset(tab.route)+    }++    if (isExpandedWidth()) {+        Scaffold(+            modifier = modifier,+            topBar = topBar,+            bottomBar = leadingBottomBar,+        ) { padding ->+            // Rail owns the start inset; content consumes the rest (same+            // forwarding as the pager overload's expanded branch).+            Row(Modifier.padding(padding)) {+                NavigationRail(Modifier.fillMaxHeight()) {+                    tabs.forEach { tab ->+                        NavigationRailItem(+                            selected = tab.route == current,+                            onClick = { select(tab) },+                            icon = tab.icon ?: {},+                            label = { Text(tab.label) },+                        )+                    }+                }+                val start = padding.calculateStartPadding(LocalLayoutDirection.current)+                Box(+                    Modifier+                        .weight(1f)+                        .fillMaxHeight()+                        .consumeWindowInsets(PaddingValues(start = start)),+                ) { content(current) }+            }+        }+    } else {+        Scaffold(+            modifier = modifier,+            topBar = topBar,+            bottomBar = {+                Column(Modifier.fillMaxWidth()) {+                    leadingBottomBar()+                    BottomNavBar {+                        tabs.forEach { tab ->+                            BottomNavBarItem(+                                selected = tab.route == current,+                                onClick = { select(tab) },+                                icon = tab.icon ?: {},+                                label = tab.label,+                            )+                        }+                    }+                }+            },+        ) { padding ->+            // Only the bottom inset is forwarded, as in the pager overload:+            // inner pages own their top bar and consume the top inset.+            val bottom = padding.calculateBottomPadding()+            Box(+                Modifier+                    .fillMaxSize()+                    .padding(bottom = bottom)+                    .consumeWindowInsets(PaddingValues(bottom = bottom)),+            ) { content(current) }+        }+    }+}+ /**  * A lightweight, non-swiping tab row - the "product tabs" look (travel). For swipeable page  * hosting use [TabbedPagerScaffold].
library/ui/src/test/java/com/vayunmathur/library/ui/RouteTabbedPagerScaffoldTest.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/RouteTabbedPagerScaffoldTest.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/RouteTabbedPagerScaffoldTest.ktnew file mode 100644index 0000000000..68a480ba06--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/RouteTabbedPagerScaffoldTest.kt@@ -0,0 +1,89 @@+package com.vayunmathur.library.ui++import androidx.compose.material3.Text+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+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++/**+ * Route-backed [TabbedPagerScaffold]: selecting a tab resets the back stack+ * to that tab's route (SiblingPage semantics) and the content slot renders+ * the destination now on top of the stack.+ */+@RunWith(RobolectricTestRunner::class)+class RouteTabbedPagerScaffoldTest {++    @get:Rule val rule = createComposeRule()++    private object First : NavKey+    private object Second : NavKey+    private data class Detail(val id: Long) : NavKey++    private fun setRouteScaffold(stack: NavBackStack<NavKey>) {+        rule.setContent {+            TabbedPagerScaffold(+                backStack = stack,+                tabs = listOf(+                    RouteTab(First, "First"),+                    RouteTab(Second, "Second"),+                ),+            ) { route ->+                when (route) {+                    First -> Text("Page one")+                    Second -> Text("Page two")+                    is Detail -> Text("Detail page")+                    else -> Text("Other page")+                }+            }+        }+    }++    @Test fun rendersTopRouteAndTabSelectResetsStack() {+        // A detail destination pushed over the first tab: selecting a tab+        // must reset (replace) the whole stack, not push.+        val stack = NavBackStack<NavKey>(arrayOf(First, Detail(7)))+        setRouteScaffold(stack)+        rule.onNodeWithText("Detail page").assertIsDisplayed()++        rule.onNodeWithText("Second").performClick()+        rule.waitForIdle()++        assertEquals(listOf(Second), stack.backStack)+        rule.onNodeWithText("Page two").assertIsDisplayed()+    }++    @Test fun tabSelectFromTabReplacesAndRendersDestination() {+        val stack = NavBackStack<NavKey>(arrayOf(First))+        setRouteScaffold(stack)+        rule.onNodeWithText("Page one").assertIsDisplayed()++        rule.onNodeWithText("Second").performClick()+        rule.waitForIdle()+        assertEquals(listOf(Second), stack.backStack)+        rule.onNodeWithText("Page two").assertIsDisplayed()++        rule.onNodeWithText("First").performClick()+        rule.waitForIdle()+        assertEquals(listOf(First), stack.backStack)+        rule.onNodeWithText("Page one").assertIsDisplayed()+    }++    @Test fun reselectingCurrentTabIsNoOp() {+        val stack = NavBackStack<NavKey>(arrayOf(First))+        setRouteScaffold(stack)++        rule.onNodeWithText("First").performClick()+        rule.waitForIdle()++        assertEquals(listOf(First), stack.backStack)+        rule.onNodeWithText("Page one").assertIsDisplayed()+    }+}