All Downloads are FREE. Search and download functionalities are using the official Maven repository.

jvmMain.app.softwork.routingcompose.DesktopRouter.kt Maven / Gradle / Ivy

Go to download

A multiplatform library for routing to use with JetPack Compose Web, HTML and Desktop

There is a newer version: 0.4.0
Show newest version
package app.softwork.routingcompose

import androidx.compose.runtime.*

/**
 * Creates a new [DesktopRouter] with the initial route [initRoute] and the route builder [navBuilder].
 *
 * To get the current [Router] inside the [navBuilder] `@Composable` tree call [Router.current].
 */
@Routing
@Composable
public fun DesktopRouter(initRoute: String, navBuilder: @Composable RouteBuilder.() -> Unit) {
    DesktopRouter().route(initRoute, navBuilder)
}

internal class DesktopRouter : Router {
    override val currentPath: Path
        get() = Path.from(stack.last().path)

    private data class Entry(val path: String, val hide: Boolean)

    private val stack = mutableStateListOf()

    @Composable
    override fun getPath(initPath: String): State = remember {
        derivedStateOf {
            stack.lastOrNull {
                !it.hide
            }?.path ?: initPath
        }
    }

    override fun navigate(to: String, hide: Boolean) {
        stack.add(Entry(to, hide))
    }

    internal fun navigateBack() {
        stack.removeAt(stack.lastIndex)
    }
}

public fun Router.navigateBack() {
    if (this is DesktopRouter) {
        navigateBack()
    } else {
        (this as DelegateRouter).router.navigateBack()
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy