Routing
Two modules cooperate here, and it helps to keep them apart:
Routerturns a URL into a typed value, and a typed value back into a URL. It knows nothing about the browser.Navigationdeals with the browser: history entries, the back button, clicks on<a>elements.
You can use Router on its own - in a test, on a server - and that is a good sign it is doing only one job.
Defining routes
export const routes = Router.routes({
home: Router.path('/'),
users: Router.path('/users'),
// `IntFromString` rejects 'abc', 'NaN', 'Infinity' and non-integers, all of
// which bare `Schema.NumberFromString` would happily accept as an id.
user: Router.path('/users/:id', { id: Router.IntFromString }),
search: Router.path('/search').query(Schema.Struct({ q: Schema.String }))
})
// One union describing every route the application can be in.
export type Route = Router.RouteType<typeof routes>Router.IntFromString rather than Schema.NumberFromString is deliberate. In Effect 4 the bare version turns any string into a number - 'abc' becomes NaN and '' becomes 0 - so /users/abc would parse as a valid route with id: NaN.
RouteType gives you the union the rest of the application matches on:
type Route =
| { readonly _tag: 'home' }
| { readonly _tag: 'users' }
| { readonly _tag: 'user'; readonly params: { readonly id: number } }
| { readonly _tag: 'search'; readonly query: { readonly q: string } }Nobody wrote that type. It came from the route definitions, so it cannot drift away from them.
Parsing
Parsing can fail, so the page type is the routes plus one more case:
// Parsing can fail, so the page type is the routes plus one more case.
export type Page = Route | { readonly _tag: 'notFound' }
export const toPage = (location: Navigation.Location): Page =>
Router.parseOr(routes, location, { _tag: 'notFound' as const })parse returns an Option if you would rather handle the miss yourself; parseOr takes the fallback directly.
Routes are tried in definition order, first match wins. Put the more specific route first when two share a path shape.
Formatting
The same definition that parses also formats:
// The same definition that parses also formats, so the shape of a link cannot
// drift away from the route it points at - both come from one source. The value
// still has to satisfy the param schema; see the guide.
export const userUrl = (id: number): string => Router.format(routes.user, { id })
export const searchUrl = (q: string): string => Router.format(routes.search, { q })This is the payoff of bidirectional routing: the shape of a link cannot drift from the parser, because both come from one definition. Change /users/:id to /people/:id and every link changes with it.
The value still has to satisfy the param schema, though. format is total - when the encoder rejects a value it falls back to String(value) - so userUrl(3.14) type-checks, produces /users/3.14, and parse then refuses it. If you need the round trip guaranteed, keep the validated value at the call site.
The complete file, imports included
import { Schema } from 'effect'
import type * as Navigation from 'tea-effect/Navigation'
import * as Router from 'tea-effect/Router'
// #region routes
export const routes = Router.routes({
home: Router.path('/'),
users: Router.path('/users'),
// `IntFromString` rejects 'abc', 'NaN', 'Infinity' and non-integers, all of
// which bare `Schema.NumberFromString` would happily accept as an id.
user: Router.path('/users/:id', { id: Router.IntFromString }),
search: Router.path('/search').query(Schema.Struct({ q: Schema.String }))
})
// One union describing every route the application can be in.
export type Route = Router.RouteType<typeof routes>
// #endregion routes
// #region page
// Parsing can fail, so the page type is the routes plus one more case.
export type Page = Route | { readonly _tag: 'notFound' }
export const toPage = (location: Navigation.Location): Page =>
Router.parseOr(routes, location, { _tag: 'notFound' as const })
// #endregion page
// #region format
// The same definition that parses also formats, so the shape of a link cannot
// drift away from the route it points at - both come from one source. The value
// still has to satisfy the param schema; see the guide.
export const userUrl = (id: number): string => Router.format(routes.user, { id })
export const searchUrl = (q: string): string => Router.format(routes.search, { q })
// #endregion formatReacting to the browser
Navigation turns browser events into messages. Two of them matter:
onUrlRequest- somebody clicked a link. The browser has not navigated yet, so you get to decide.onUrlChange- the URL has already changed, frompushUrlor from the back button.
export const update = (msg: Msg, model: Model): readonly [Model, Cmd.Cmd<Msg>] => {
switch (msg.type) {
case 'LinkClicked':
switch (msg.request._tag) {
case 'Internal': {
// Rebuild the whole URL: `pathname` alone drops the query and hash,
// so a click on /search?q=hello would navigate to /search.
const { pathname, search, hash } = msg.request.location
return [model, Navigation.pushUrl(`${pathname}${search}${hash}`)]
}
case 'External':
// Leaves the program entirely - a real browser navigation.
return [model, Navigation.load(msg.request.href)]
}
// The URL has already changed by now, whether from pushUrl or the back button.
case 'UrlChanged':
return [{ page: toPage(msg.location) }, Cmd.none]
}
}pathname is not the URL
msg.request.location.pathname for /search?q=hello is just /search. Passing only that to pushUrl silently drops the query and the hash. Rebuild the URL from all three parts, as above.
Because the click is intercepted rather than followed, LinkClicked is where an "unsaved changes" guard belongs - returning Cmd.none simply leaves the user where they are.
Which entry the user is on
The browser keeps a list of entries for each tab and knows which one it is showing. A URL alone does not tell you that: the same address can be in the list twice, and a change can come from a push, from back or from forward. Every Location therefore says which entry it is:
state- whateverpushUrlorreplaceUrlstored with the entry. Back and forward hand it back.index- the entry's position.Navigation.programnumbers the entry it starts on0,pushUrladds one,replaceUrlkeeps the position, and back and forward restore the position the browser kept.key- an id for the entry. EverypushUrlandreplaceUrlgives the entry it writes a new key, and an entry the user returns to has the key it had when it was left.
None of this changes how a program works, and you can ignore all three. They are there for decisions that need to know which entry the user is on:
- Compare the new
indexwith the one in your model to tell back from forward. back(n)orforward(n)with the difference between two positions returns the user to an entry without adding a new one.- Keep view state that does not belong in the URL - a selected row, an open panel - in your model under the
keyof the entry it belongs to, and give it back when that key comes back. It stays in the model; the browser only says which entry it is.
case 'UrlChanged': {
// Remember the selection of the entry being left, under its key.
const left = model.location.key
const selections =
left === null ? model.selections : { ...model.selections, [left]: model.selected }
// Restore the selection of the entry being entered, if there was one.
const selected = (msg.location.key === null ? undefined : selections[msg.location.key]) ?? []
return [{ ...model, location: msg.location, selections, selected }, Cmd.none]
}index and key are null for an entry tea-effect did not write - one made by other code calling history.pushState, or stored by a version before 0.11.0 - and index stays null for entries pushed after such an entry, because their position cannot be known. A link click is a request, not an entry yet, so its location has neither.
tea-effect keeps the position and key next to your state inside history.state, whose shape is therefore its own. Read your state through Location.state, not from window.history.state.
The view
export const view =
(model: Model): TeaReact.Html<Msg> =>
() => {
// Every route is a case here, and TypeScript will not let you forget one.
switch (model.page._tag) {
case 'home':
return (
<nav>
<a href={userUrl(1)}>The first user</a>
</nav>
)
case 'users':
return <h1>All users</h1>
case 'user':
return <h1>User {model.page.params.id}</h1>
case 'search':
return <h1>Results for {model.page.query.q}</h1>
case 'notFound':
return <h1>No such page</h1>
}
}The switch is exhaustive over the generated union. Add a route to Router.routes and this stops compiling until you handle it.
Wiring it up
// Navigation.program wires up link interception and URL changes for you, and
// hands `init` the location the page was opened at.
export const App = Navigation.program({
init: (location) => [{ page: toPage(location) }, Cmd.none],
update,
view,
title,
onUrlRequest: (request): Msg => ({ type: 'LinkClicked', request }),
onUrlChange: (location): Msg => ({ type: 'UrlChanged', location })
})Navigation.program subscribes to link clicks and URL changes for you, batches them with any subscriptions of your own, and hands init the location the page was opened at. It is the equivalent of Elm's Browser.application.
The complete file, imports included
import * as Cmd from 'tea-effect/Cmd'
import * as Navigation from 'tea-effect/Navigation'
import type * as TeaReact from 'tea-effect/React'
import { toPage, userUrl, type Page } from './routes'
export type Model = { readonly page: Page }
export type Msg =
| { readonly type: 'LinkClicked'; readonly request: Navigation.UrlRequest }
| { readonly type: 'UrlChanged'; readonly location: Navigation.Location }
// #region update
export const update = (msg: Msg, model: Model): readonly [Model, Cmd.Cmd<Msg>] => {
switch (msg.type) {
case 'LinkClicked':
switch (msg.request._tag) {
case 'Internal': {
// Rebuild the whole URL: `pathname` alone drops the query and hash,
// so a click on /search?q=hello would navigate to /search.
const { pathname, search, hash } = msg.request.location
return [model, Navigation.pushUrl(`${pathname}${search}${hash}`)]
}
case 'External':
// Leaves the program entirely - a real browser navigation.
return [model, Navigation.load(msg.request.href)]
}
// The URL has already changed by now, whether from pushUrl or the back button.
case 'UrlChanged':
return [{ page: toPage(msg.location) }, Cmd.none]
}
}
// #endregion update
// #region view
export const view =
(model: Model): TeaReact.Html<Msg> =>
() => {
// Every route is a case here, and TypeScript will not let you forget one.
switch (model.page._tag) {
case 'home':
return (
<nav>
<a href={userUrl(1)}>The first user</a>
</nav>
)
case 'users':
return <h1>All users</h1>
case 'user':
return <h1>User {model.page.params.id}</h1>
case 'search':
return <h1>Results for {model.page.query.q}</h1>
case 'notFound':
return <h1>No such page</h1>
}
}
// #endregion view
// #region title
// The title is a function of the model, like the view. Navigation.program writes
// it to document.title whenever an update changes it.
export const title = (model: Model): string => {
switch (model.page._tag) {
case 'home':
return 'Home'
case 'users':
return 'All users'
case 'user':
return `User ${model.page.params.id}`
case 'search':
return `Results for ${model.page.query.q}`
case 'notFound':
return 'No such page'
}
}
// #endregion title
// #region program
// Navigation.program wires up link interception and URL changes for you, and
// hands `init` the location the page was opened at.
export const App = Navigation.program({
init: (location) => [{ page: toPage(location) }, Cmd.none],
update,
view,
title,
onUrlRequest: (request): Msg => ({ type: 'LinkClicked', request }),
onUrlChange: (location): Msg => ({ type: 'UrlChanged', location })
})
// #endregion programThe page title
// The title is a function of the model, like the view. Navigation.program writes
// it to document.title whenever an update changes it.
export const title = (model: Model): string => {
switch (model.page._tag) {
case 'home':
return 'Home'
case 'users':
return 'All users'
case 'user':
return `User ${model.page.params.id}`
case 'search':
return `Results for ${model.page.query.q}`
case 'notFound':
return 'No such page'
}
}Give Navigation.program a title and it keeps document.title in step with the model: on startup and after each update, it computes the title from the current model and writes it only if it differs from document.title, so an update that keeps the title writes nothing. The function is pure, like the view; the program performs the write. It is the title of the Document that Elm's Browser.application asks the view for.
Without title the program never touches document.title, so a page that sets it some other way keeps working.
Doing it by hand
If you would rather not use Navigation.program, subscribe yourself:
const subscriptions = (): Sub.Sub<Msg> =>
Sub.batch([
Navigation.linkClicks((request): Msg => ({ type: 'LinkClicked', request })),
Navigation.urlChanges((location): Msg => ({ type: 'UrlChanged', location }))
])urlChanges does not emit the initial location - read it with Navigation.getLocation() in init.
Only Navigation.program numbers the entry it starts on, so without it every index is null. Keys still work: each entry that pushUrl or replaceUrl writes gets one.
Next
- Composition - giving each page its own module.
- Gotchas - the routing mistakes worth knowing in advance.