Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -91,4 +91,5 @@ dependencies {
androidTestImplementation(libs.androidx.ui.test.junit4)
debugImplementation(libs.androidx.ui.tooling)
debugImplementation(libs.androidx.ui.test.manifest)
testImplementation(kotlin("test"))
}
5 changes: 5 additions & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,11 @@
android:exported="true"
android:label="@string/app_name"
android:theme="@style/Theme.Nav3Recipes"/>
<activity
android:name=".navigator.basic.NavigatorActivity"
android:exported="true"
android:label="@string/app_name"
android:theme="@style/Theme.Nav3Recipes"/>
<activity
android:name=".basicdsl.BasicDslActivity"
android:exported="true"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
package com.example.nav3recipes.navigator.basic

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue

/**
* This class models navigation behavior. It provides a back stack
* as a Compose snapshot-state backed list that can be used with a `NavDisplay`.
*
* It supports a single level of nested navigation. Top level
* routes can be defined using the `Route` class and setting
* `isTopLevel` to `true`. It also supports shared routes.
* These are routes that can be nested under multiple top level
* routes, though only one instance of the route will ever be
* present in the stack. Shared routes can be defined using
* `Route.isShared`.
*
* The start route is always the first item in the back stack and
* cannot be moved. Navigating to the start route removes all other
* top level routes and their associated stacks.
*
* @param startRoute - The start route for the back stack.
* @param canTopLevelRoutesExistTogether - Determines whether other
* top level routes can exist together on the back stack. Default `false`,
* meaning other top level routes (and their stacks) will be popped off
* the back stack when navigating to a top level route.
*
* For example, if A, B and C are all top level routes:
*
* ```
* val navigator = Navigator<Route>(startRoute = A) // back stack is [A]
* navigator.navigate(B) // back stack [A, B]
* navigator.navigate(C) // back stack [A, C] - B is popped before C is added
*
* When set to `true`, the resulting back stack would be [A, B, C]
* ```
*
* @see `NavigatorTest`.
*/
class Navigator<T: Route>(
private val startRoute: T,
private val canTopLevelRoutesExistTogether: Boolean = false
) {

val backStack = mutableStateListOf(startRoute)
var topLevelRoute by mutableStateOf(startRoute)
private set

// Maintain a stack for each top level route
private var topLevelStacks : LinkedHashMap<T, MutableList<T>> = linkedMapOf(
startRoute to mutableListOf(startRoute)
)

// Maintain a map of shared routes to their parent stacks
private var sharedRoutes : MutableMap<T, T> = mutableMapOf()

private fun updateBackStack() =
backStack.apply {
clear()
addAll(topLevelStacks.flatMap { it.value })
}

private fun navigateToTopLevel(route: T){

if (route == startRoute){
clearAllExceptStartStack()
} else {

// Get the existing stack or create a new one.
val topLevelStack = topLevelStacks.remove(route) ?: mutableListOf(route)

if (!canTopLevelRoutesExistTogether) {
clearAllExceptStartStack()
}

topLevelStacks.put(route, topLevelStack)
}

topLevelRoute = route
}

private fun clearAllExceptStartStack(){
// Remove all other top level stacks, except the start stack
val startStack = topLevelStacks[startRoute] ?: mutableListOf(startRoute)
topLevelStacks.clear()
topLevelStacks.put(startRoute, startStack)
}

/**
* Navigate to the given route.
*/
fun navigate(route: T){
if (route.isTopLevel){
navigateToTopLevel(route)
} else {
if (route.isShared){
// If the key is already in a stack, remove it
val oldParent = sharedRoutes[route]
if (oldParent != null) {
topLevelStacks[oldParent]?.remove(route)
}
sharedRoutes[route] = topLevelRoute
}
topLevelStacks[topLevelRoute]?.add(route)
}
updateBackStack()
}

/**
* Go back to the previous route.
*/
fun goBack(){
if (backStack.size <= 1){
return
}
val removedKey = topLevelStacks[topLevelRoute]?.removeLastOrNull()
// If the removed key was a top level key, remove the associated top level stack
topLevelStacks.remove(removedKey)
topLevelRoute = topLevelStacks.keys.last()
updateBackStack()
}
}

abstract class Route(
val isTopLevel : Boolean = false,
val isShared : Boolean = false
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
/*
* Copyright 2025 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.nav3recipes.navigator.basic

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Face
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.navigation3.runtime.entry
import androidx.navigation3.runtime.entryProvider
import androidx.navigation3.ui.NavDisplay
import com.example.nav3recipes.content.ContentBlue
import com.example.nav3recipes.content.ContentGreen
import com.example.nav3recipes.content.ContentPink
import com.example.nav3recipes.content.ContentPurple
import com.example.nav3recipes.content.ContentRed
import com.example.nav3recipes.ui.setEdgeToEdgeConfig

private abstract class NavBarItem(
val icon: ImageVector,
val description: String
): Route(isTopLevel = true)
private data object Home : NavBarItem(icon = Icons.Default.Home, description = "Home")
private data object ChatList : NavBarItem(icon = Icons.Default.Face, description = "Chat list")
private data object ChatDetail : Route()
private data object Camera : NavBarItem(icon = Icons.Default.PlayArrow, description = "Camera")
private data object Search : Route(isShared = true)

private val TOP_LEVEL_ROUTES : List<NavBarItem> = listOf(Home, ChatList, Camera)

class NavigatorActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
setEdgeToEdgeConfig()
super.onCreate(savedInstanceState)
setContent {
val navigator = remember { Navigator<Route>(Home) }

Scaffold(
topBar = {
TopAppBarWithSearch { navigator.navigate(Search) }
},
bottomBar = {
NavigationBar {
TOP_LEVEL_ROUTES.forEach { topLevelRoute ->

val isSelected = topLevelRoute == navigator.topLevelRoute
NavigationBarItem(
selected = isSelected,
onClick = {
navigator.navigate(topLevelRoute)
},
icon = {
Icon(
imageVector = topLevelRoute.icon,
contentDescription = topLevelRoute.description
)
}
)
}
}
}
) { paddingValues ->
NavDisplay(
modifier = Modifier.padding(paddingValues),
backStack = navigator.backStack,
onBack = { navigator.goBack() },
entryProvider = entryProvider {
entry<Home>{
ContentRed("Home screen")
}
entry<ChatList>{
ContentGreen("Chat list screen"){
Button(onClick = { navigator.navigate(ChatDetail) }) {
Text("Go to conversation")
}
}
}
entry<ChatDetail>{
ContentBlue("Chat detail screen")

}
entry<Camera>{
ContentPurple("Camera screen")
}
entry<Search>{
ContentPink("Search screen"){
var text by rememberSaveable { mutableStateOf("") }
TextField(
value = text,
onValueChange = { newText -> text = newText},
label = { Text("Enter search here") },
singleLine = true
)
}
}
},
)
}
}
}
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TopAppBarWithSearch(
onSearchClick: () -> Unit
) {
TopAppBar(
title = {
Text("Navigator Activity")
},
actions = {
IconButton(onClick = onSearchClick) {
Icon(
imageVector = Icons.Filled.Search,
contentDescription = "Search"
)
}

},
)
}

33 changes: 0 additions & 33 deletions app/src/test/java/com/example/nav3recipes/ExampleUnitTest.kt

This file was deleted.

Loading