-
Notifications
You must be signed in to change notification settings - Fork 8
/
NavGraph.kt
58 lines (44 loc) · 1.49 KB
/
NavGraph.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package me.sujanpoudel.playdeals.common.navigation
import androidx.compose.runtime.Composable
typealias PathIdentifier = Enum<*>
typealias Content = @Composable () -> Unit
data class NavDestination(val path: PathIdentifier, val content: Content)
interface NavGraphBuilder {
fun destination(
path: PathIdentifier,
content: Content,
)
var homePath: PathIdentifier
}
class NavGraph(buildBy: NavGraphBuilder.() -> Unit) {
private val destinations: MutableMap<PathIdentifier, NavDestination>
private val startingPath: PathIdentifier
init {
val builder = NavGraphBuilderImpl().apply(buildBy)
destinations = builder.buildDestination()
startingPath = builder.homePath
}
fun getDestination(identifier: PathIdentifier): NavDestination {
return destinations[identifier]
?: throw Error("No destination found for '$identifier'")
}
fun getStartingDestination(): NavDestination {
return getDestination(startingPath)
}
private class NavGraphBuilderImpl : NavGraphBuilder {
private val destinations: MutableMap<PathIdentifier, NavDestination> = mutableMapOf()
override fun destination(
path: PathIdentifier,
content: Content,
) {
destinations[path] = NavDestination(path, content)
}
override lateinit var homePath: PathIdentifier
fun buildDestination(): MutableMap<PathIdentifier, NavDestination> {
if (!this::homePath.isInitialized) {
throw Error("homePath is missing")
}
return destinations
}
}
}