Skip to content

Commit

Permalink
Add a way to query all routes from a router
Browse files Browse the repository at this point in the history
For example,

```
ctx.router.routes.map { it.path }.forEach { path ->
  P { Text(path) }
}
```

might create entries like:

/about
/home
/users/{user}

There are no future guarantees about the ordering, but for now it is
breadth-first, with siblings returned in alphabetical order.
  • Loading branch information
bitspittle committed Jul 16, 2024
1 parent ffcab46 commit c9a8b5a
Showing 1 changed file with 36 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,19 @@ class RouteInterceptorScope(pathQueryAndFragment: String) {
* The class responsible for navigating to different pages in a user's app.
*/
class Router {
/**
* A simple data class containing information about a route.
*
* @property path The route's path, e.g. "/a/b/c". If a route has a dynamic part, that part will be surrounded in
* curly braces, e.g. "/users/{user}/posts/{post}"
* @property isDynamic Whether the route has at least one dynamic part, which can be useful in case the user wants
* to filter these out.
*/
class RouteEntry(
val path: String,
val isDynamic: Boolean, // Whether the path is dynamic or not, in case users want to filter them out
)

/**
* Strategy for allowing flexibility when trying to resolve legacy, non-hyphenated routes.
*
Expand Down Expand Up @@ -114,6 +127,29 @@ class Router {
private val routeTree = RouteTree()
private val interceptors = mutableListOf<RouteInterceptorScope.() -> Unit>()

/**
* A sequence of all routes registered with this router.
*
* Users may want to filter out dynamic routes from the final list. Doing that looks like this:
*
* ```
* ctx.router.routes.filter { !it.isDynamic }.map { it.path }.forEach { routePath -> ... }
* ```
*/
val routes: Sequence<RouteEntry>
get() = routeTree.nodes.map { nodeList ->
RouteEntry(
nodeList.joinToString("/") { node ->
if (node is RouteTree.DynamicNode) {
"{${node.name}}"
} else {
node.name
}
},
nodeList.any { it is RouteTree.DynamicNode }
)
}

init {
PageContext.init(this)
window.onpopstate = {
Expand Down

0 comments on commit c9a8b5a

Please sign in to comment.