jsMain.app.softwork.routingcompose.HashRouter.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of routing-compose Show documentation
Show all versions of routing-compose Show documentation
A multiplatform library for routing to use with JetPack Compose Web and Desktop
package app.softwork.routingcompose
import androidx.compose.runtime.*
import kotlinx.browser.*
/**
* This [Router] implementation uses `/#/path` to persistent the current route in [window.location.hash].
*
* Every request will always request `GET /`, so your server needs only to listen and serve this endpoint,
* or using a SaaS `/index.html`.
*/
@Composable
public fun HashRouter(
initPath: String,
routeBuilder: @Composable RouteBuilder.() -> Unit
) {
HashRouter().route(initPath, routeBuilder)
}
internal class HashRouter : Router {
override val currentPath: Path
get() = Path.from(currentHash.value)
private val currentHash: MutableState = mutableStateOf(window.location.hash.currentURL() ?: "")
@Composable
override fun getPath(initPath: String): State {
LaunchedEffect(Unit) {
currentHash.value = window.location.hash.currentURL() ?: initPath
window.onhashchange = {
currentHash.value = window.location.hash.currentURL() ?: ""
Unit
}
}
return currentHash
}
private fun String.currentURL() = removePrefix("#")
.removePrefix("/")
.ifBlank { null }
override fun navigate(to: String, hide: Boolean) {
if (hide) {
currentHash.value = to.currentURL() ?: ""
} else if (window.location.hash.currentURL() == to.currentURL()) {
currentHash.value = to.removePrefix("#")
} else {
window.location.hash = to
}
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy