Routing
Fable.Ripple.Dom.Routing connects the address bar to a signal. A router holds CurrentRoute: Signal<'Route option>; the view reads it like any other signal, and navigating writes the URL.
A hash router
HashRouter takes two functions, parse and print. Pair it with UrlParser's two-way codecs and both come from the same definition:
open Browser
open Fable.Ripple.Dom
open Fable.Ripple.Dom.Routing
open Fable.UrlParser.UrlCodec
type Route =
| Home
| User of id: int
// The codecs, as on the UrlParser pages.
let toUrl (route: Route) =
match RouteCodec.tryToHash codecs route with
| Some url -> url
| None -> failwith $"no codec builds %A{route}"
let parse (hash: string) =
match RouteCodec.tryParseHash codecs hash with
| Ok route -> Some route
| Error message ->
console.warn $"cannot parse '%s{hash}': %s{message}"
None
let router = new HashRouter<Route>(parse, toUrl)
Reading the route
CurrentRoute is a Signal<'Route option> - None when the URL parses as nothing. Switch views on it with Html.switch:
Html.switch
router.CurrentRoute
(function
| Some Home -> Html.p "home"
| Some(User id) -> Html.p [ Html.text (fun () -> $"user %d{id}") ]
| None -> Html.p "not found")
Navigating
router.Href route
The URL string, for a plain <a href>. Clicking the link changes the hash and the router follows - no click handler needed.
router.NewUrl route
Navigate, pushing a history entry. Back returns to the previous route.
router.ModifyUrl route
Navigate, rewriting the current entry. Paging pushes; typing replaces, so a search does not bury the back button under one entry per keystroke.
router.Jump n
Move through history, like the back and forward buttons.
The router is an IDisposable; disposing it stops listening to the address bar.
Path routing
PathRouter is the same API over the path instead of the hash, for a host that serves your page on every URL.
The pieces
Routing.Advanced exposes what the routers are built from: useHash () and usePath () return the raw location as a Signal<string> plus a disposable; newUrl, modifyUrl and jump wrap the History API.