Skip to content

Commit

Permalink
Add redirect in noMatch handler (#170)
Browse files Browse the repository at this point in the history
Co-authored-by: hfhbd <[email protected]>
  • Loading branch information
hfhbd and hfhbd authored Jun 6, 2022
1 parent c1fe888 commit ebe7bca
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 5 deletions.
19 changes: 15 additions & 4 deletions integrationTest/src/jsMain/kotlin/demo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -97,10 +97,7 @@ fun RouteBuilder.Routing() {
}
redirect("redirect", target = "users", hide = true)
if (enableAnswer) {
route("answer") {
Br()
Text("The Answer to the Ultimate Question of Life, the Universe, and Everything is 42.")
}
answer()
}
noMatch {
P {
Expand Down Expand Up @@ -145,6 +142,20 @@ fun RouteBuilder.Routing() {
}
}

@Routing
@Composable
fun RouteBuilder.answer() {
route("answer") {
int {
Br()
Text("The Answer to the Ultimate Question of Life, the Universe, and Everything is $it.")
}
noMatch {
redirect("42")
}
}
}

@Composable
fun RedirectButton() {
Text("You could also hide navigations and redirect path to other routes.")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,17 @@ public class RouteBuilder internal constructor(private val basePath: String, pri
}
}

public class NoMatch(public val remainingPath: String, public val parameters: Parameters?)
@Routing
public class NoMatch(public val remainingPath: String, public val parameters: Parameters?) {
@Routing
@Composable
public fun redirect(target: String, hide: Boolean = false) {
val router = Router.current
LaunchedEffect(Unit) {
router.navigate(target, hide)
}
}
}
}

private class DelegatingRouter(val basePath: String, val router: Router) : Router by router {
Expand All @@ -159,13 +169,16 @@ private class DelegatingRouter(val basePath: String, val router: Router) : Route
to.startsWith("/") -> {
router.navigate(to, hide)
}

basePath == "/" -> {
router.navigate("/$to", hide)
}

to.startsWith(".") -> {
val newPath = router.currentPath.relative(to)
router.navigate(newPath.path)
}

else -> {
router.navigate("$basePath/$to", hide)
}
Expand Down
24 changes: 24 additions & 0 deletions src/jsTest/kotlin/app/softwork/routingcompose/RedirectTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,28 @@ class RedirectTest {
waitForChanges()
assertEquals("foo", root.innerHTML, "Second")
}

@Test
fun redirectingNoMatchTest() = runTest {
val router = MockRouter()
composition {
router("/bar") {
route("foo") {
Text("foo")
}
route("bar") {
Text("bar")
}
noMatch {
redirect("foo", hide = true)
}
}
}
assertEquals("bar", root.innerHTML)

router.navigate("/asdf")
waitForChanges()
waitForChanges()
assertEquals("foo", root.innerHTML)
}
}

0 comments on commit ebe7bca

Please sign in to comment.