Modern Apps git

← Modern-Apps.git

nav: shared pushOrReplace/popTo on NavBackStack

Commit
a94bc2934cedb64e9d659c060863b1da0e99dd72
Author
Vayun Mathur <[email protected]>
When
2026-11-20 22:39 UTC (15 days ago)
Parents
201862c
The replace-or-push logic existed as hand-rolled copies in
contacts, euicc and music screens (and proper helpers in six
apps). NavBackStack now offers pushOrReplace (same-type top
is replaced, predicate form for interchangeable tops) and
popTo/popToType with files' exact semantics (absent = no-op,
root never popped). Six new tests pin the contracts; the three
hand-rolled screens adopt the shared helpers with identical
behaviour.

Verified: :library tests (nav class 16/16) and compile for
contacts, euicc, music.

Diff

contacts/src/main/java/com/vayunmathur/contacts/ui/TabsCallbacks.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/ui/TabsCallbacks.kt b/contacts/src/main/java/com/vayunmathur/contacts/ui/TabsCallbacks.ktindex 8246c3f81d..c4b01cac02 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/ui/TabsCallbacks.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/TabsCallbacks.kt@@ -26,12 +26,10 @@ internal fun rememberTabsCallbacks( ): TabsCallbacks = remember(backStack) {     TabsCallbacks(         onContactClick = { contact ->-            val last = backStack.last()-            val isDetail = last is Route.ContactDetail || last is Route.EditContact-            if (isDetail) {-                backStack.setLast(Route.ContactDetail(contact.id))-            } else {-                backStack.add(Route.ContactDetail(contact.id))+            // An open detail or editor is replaced, not stacked: on two-pane the list+            // stays beside it, so a second tap must not pile detail on detail.+            backStack.pushOrReplace(Route.ContactDetail(contact.id)) {+                it is Route.ContactDetail || it is Route.EditContact             }         },         onAddContactClick = {
euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccHomeScreen.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccHomeScreen.kt b/euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccHomeScreen.ktindex e7c19ff4ef..8b5e2a52a1 100644--- a/euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccHomeScreen.kt+++ b/euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccHomeScreen.kt@@ -109,10 +109,7 @@ private fun ProfileRow(profile: Profile, backStack: NavBackStack<Route>) {     SettingsRow(         title = profile.displayName,         supportingText = profile.serviceProvider.ifBlank { profile.iccidDisplay },-        onClick = {-            if (backStack.last() is Route.ProfileDetail) backStack.setLast(Route.ProfileDetail(profile.iccid))-            else backStack.add(Route.ProfileDetail(profile.iccid))-        },+        onClick = { backStack.pushOrReplace(Route.ProfileDetail(profile.iccid)) },         leadingContent = { IconSim() },         titleSharedKey = "euicc-profile-name-${profile.iccid}",     )
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 b1c8b5a128..68443d7792 100644--- a/library/src/main/java/com/vayunmathur/library/util/Navigation.kt+++ b/library/src/main/java/com/vayunmathur/library/util/Navigation.kt@@ -106,6 +106,64 @@ class NavBackStack<T: NavKey>(initial: Array<out T>) {         backend.clear()         backend.addAll(keys)     }++    /**+     * Push [value], replacing the current top instead when it is already a destination of the+     * same type.+     *+     * The detail-over-list case this exists for: on a two-pane layout the list stays visible+     * beside its detail, so tapping a second item of the same kind would otherwise pile one+     * detail on another and back would step through stale details instead of returning to+     * the list. Class equality rather than `is`, matching the hand-rolled helpers this+     * promotes (education's `pushChain`, photos' `pushPhoto`): a subclass instance is a+     * different destination, not a refresh of this one. On an empty stack this is [add].+     */+    fun pushOrReplace(value: T) {+        if (backend.isNotEmpty() && backend.last()::class == value::class) setLast(value) else add(value)+    }++    /**+     * [pushOrReplace] with the replace decision left to [replaceIf] on the current top.+     *+     * For the tops that are interchangeable but not the same type - contacts replaces an+     * open editor as readily as an open detail, maps swaps a place sheet for an admin+     * label - where the same-type rule alone would stack instead of replacing. The new+     * [value] need not be of the type [replaceIf] matches. On an empty stack this is [add].+     */+    fun pushOrReplace(value: T, replaceIf: (T) -> Boolean) {+        if (backend.isNotEmpty() && replaceIf(backend.last())) setLast(value) else add(value)+    }++    /**+     * Pop until [target] is the current destination, reporting whether it was there at all.+     *+     * Returns false and changes nothing when the target is absent, so a caller can fall+     * back to pushing rather than unwinding the whole stack looking for something that was+     * never on it (files' breadcrumb navigation is the model). Never pops the root: a+     * target that is only reachable by emptying the stack cannot be produced here, and an+     * absent target leaves even the root untouched. With duplicate entries it stops at the+     * topmost one.+     */+    fun popTo(target: T): Boolean {+        if (target !in backend) return false+        while (backend.size > 1 && backend.last() != target) pop()+        return true+    }++    /**+     * [popTo] by predicate: pop until the top satisfies [predicate], to its topmost match.+     *+     * Same contract as [popTo] by value - false with no change when nothing matches, and+     * the root is never popped, so a predicate matching only the root leaves just the root.+     */+    fun popTo(predicate: (T) -> Boolean): Boolean {+        if (backend.none(predicate)) return false+        while (backend.size > 1 && !predicate(backend.last())) pop()+        return true+    }++    /** [popTo] to the topmost destination of type [R]; false with no change when there is none. */+    inline fun <reified R : T> popToType(): Boolean = popTo { it is R } }  // LocalNavResultRegistry lives in NavigationResults.kt.
library/src/test/java/com/vayunmathur/library/util/LibraryCoverageNavTest.kt
diff --git a/library/src/test/java/com/vayunmathur/library/util/LibraryCoverageNavTest.kt b/library/src/test/java/com/vayunmathur/library/util/LibraryCoverageNavTest.ktindex a023ea26d5..c0b27013fa 100644--- a/library/src/test/java/com/vayunmathur/library/util/LibraryCoverageNavTest.kt+++ b/library/src/test/java/com/vayunmathur/library/util/LibraryCoverageNavTest.kt@@ -22,6 +22,7 @@ import org.robolectric.RobolectricTestRunner import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith+import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue@@ -62,6 +63,71 @@ class LibraryCoverageNavTest {         assertTrue(stack.backStack.isEmpty())     } +    // ---- pushOrReplace / popTo (promoted from maps/files/photos/education helpers) ----++    @Test fun pushOrReplaceSameTypeReplacesTopDifferentTypePushes() {+        val stack = NavBackStack<NavKey>(arrayOf(Screen("home")))+        stack.pushOrReplace(Screen("detail"))+        assertEquals(listOf<NavKey>(Screen("detail")), stack.backStack, "same class replaces instead of stacking")+        stack.pushOrReplace(Other("other"))+        assertEquals(listOf<NavKey>(Screen("detail"), Other("other")), stack.backStack, "different class pushes")+        stack.pushOrReplace(Other("other2"))+        assertEquals(listOf<NavKey>(Screen("detail"), Other("other2")), stack.backStack)+    }++    @Test fun pushOrReplaceOnEmptyPushesInsteadOfFailing() {+        val stack = NavBackStack<Screen>(emptyArray())+        stack.pushOrReplace(Screen("first"))+        assertEquals(listOf("first"), stack.backStack.map { it.route })+        val emptyKeyed = NavBackStack<NavKey>(emptyArray())+        emptyKeyed.pushOrReplace(Screen("first")) { true }+        assertEquals(listOf<NavKey>(Screen("first")), emptyKeyed.backStack, "predicate form never consults a missing top")+    }++    @Test fun pushOrReplacePredicateReplacesInterchangeableTypesOnly() {+        // Contacts' shape: an open detail OR editor is replaced by the next detail.+        val stack = NavBackStack<NavKey>(arrayOf(Screen("home"), Other("editor")))+        stack.pushOrReplace(Screen("detail")) { it is Screen || it is Other }+        assertEquals(listOf<NavKey>(Screen("home"), Screen("detail")), stack.backStack)+        // A predicate that rejects the top pushes, leaving the top in place below.+        stack.pushOrReplace(Other("dialog")) { it is Other }+        assertEquals(listOf<NavKey>(Screen("home"), Screen("detail"), Other("dialog")), stack.backStack)+    }++    @Test fun popToTargetPopsToTopmostMatchAndAbsentChangesNothing() {+        val stack = NavBackStack(arrayOf(Screen("a"), Screen("b"), Screen("a"), Screen("c")))+        assertTrue(stack.popTo(Screen("a")))+        assertEquals(listOf("a", "b", "a"), stack.backStack.map { it.route }, "stops at the topmost match")+        assertTrue(stack.popTo(Screen("a")), "already on top is a successful no-op")+        assertEquals(3, stack.backStack.size)+        assertFalse(stack.popTo(Screen("missing")))+        assertEquals(listOf("a", "b", "a"), stack.backStack.map { it.route }, "absent target unwinds nothing")+    }++    @Test fun popToNeverPopsTheRoot() {+        val stack = NavBackStack(arrayOf(Screen("root"), Screen("b"), Screen("c")))+        assertTrue(stack.popTo(Screen("root")))+        assertEquals(listOf("root"), stack.backStack.map { it.route })+        assertFalse(stack.popTo(Screen("gone")))+        assertEquals(listOf("root"), stack.backStack.map { it.route })+        val single = NavBackStack(arrayOf(Screen("only")))+        assertTrue(single.popTo(Screen("only")))+        assertEquals(1, single.backStack.size)+    }++    @Test fun popToPredicateAndTypePopToTopmostMatch() {+        val stack = NavBackStack<NavKey>(arrayOf(Screen("home"), Other("x"), Screen("detail"), Other("y")))+        assertTrue(stack.popTo { it is Screen })+        assertEquals(listOf<NavKey>(Screen("home"), Other("x"), Screen("detail")), stack.backStack)+        assertTrue(stack.popToType<Other>())+        assertEquals(listOf<NavKey>(Screen("home"), Other("x")), stack.backStack)+        assertFalse(stack.popTo { (it as? Screen)?.route == "missing" })+        assertEquals(2, stack.backStack.size, "no predicate match changes nothing")+        val screensOnly = NavBackStack<NavKey>(arrayOf(Screen("home"), Screen("detail")))+        assertFalse(screensOnly.popToType<Other>())+        assertEquals(2, screensOnly.backStack.size)+    }+     // ---- EntryProviderScope ----      @Test fun entryProviderMatchesSupertypeAndCarriesMetadata() {
music/src/main/java/com/vayunmathur/music/ui/ArtistDetailScreen.kt
diff --git a/music/src/main/java/com/vayunmathur/music/ui/ArtistDetailScreen.kt b/music/src/main/java/com/vayunmathur/music/ui/ArtistDetailScreen.ktindex 0fbd4a939e..b2967cfd52 100644--- a/music/src/main/java/com/vayunmathur/music/ui/ArtistDetailScreen.kt+++ b/music/src/main/java/com/vayunmathur/music/ui/ArtistDetailScreen.kt@@ -140,8 +140,7 @@ fun ArtistDetailScreen(backStack: NavBackStack<Route>, musicViewModel: MusicView                     modifier = Modifier.clickable {                         // Another album off the same artist replaces the detail instead of                         // stacking AlbumDetail on AlbumDetail.-                        val route = Route.AlbumDetail(album.id)-                        if (backStack.last() is Route.AlbumDetail) backStack.setLast(route) else backStack.add(route)+                        backStack.pushOrReplace(Route.AlbumDetail(album.id))                     },                     supportingContent = { Text(albumYear) },                     trailingContent = { Text(formatDuration(albumDurationMs)) },