Navigation details
The rules, options and costs behind the Navigation guide. The core runs all of them, so they are the same in every library unless a table says otherwise.
The order of one navigation
- A click on a link waits one animation frame and the task after it, so the click's own styles show first.
app.navigation.repaint: falseskips the wait. Anavigate()from code, a hash-only click, back and forward never wait. page:beforeNavigate,onBeforeNavigate, theLink's ownonBeforeNavigate, thehamur:beforenavigateevent, the blockers, the leave and update guards, the route middleware,beforeEach,page:start.- The page chunks and the data load.
pendingturns true afterpendingMsand the pending component shows. onNavigateand thehamur:navigateevent. The navigation then waits untilpendingMinMshave passed sincependingturned true.- The history entry is written and the page changes: in a view transition, in a page or layout transition, or as a plain swap.
page:finish, the scroll, the focus, the announcement,idle,page:rendered,onAfterNavigate, thehamur:afternavigateevent,afterEach, the route hooks,onPageActivatedandonPageDeactivated, andpage:transition:finishonce the enter ended.
A key under app in hamur.config.ts is known at build time. A key in a page's meta is read in the browser after the route middleware, which may set it on to.meta. Only speculation in a route rule or meta.rules is read by the build.
import { defineConfig } from "hamur"
export default defineConfig({
framework: "react",
app: {
pageTransition: { name: "fade", mode: "out-in" },
layoutTransition: { name: "slide", duration: { enter: 250, leave: 150 } },
viewTransition: { types: ["slide"] },
keepalive: { max: 5 },
navigation: { pendingMs: 400, pendingMinMs: 300, focus: "heading", scrollKey: "path", repaint: true },
routeAnnouncer: { politeness: "polite" },
link: { prefetchOn: "interaction", prefetchDelay: 100, pendingClass: "is-pending", prefetchedClass: "is-ready" },
speculationRules: { prefetch: "moderate", prerender: false },
},
routeRules: {
"/r/**": { speculation: false },
},
})
The router
useRouter() documents each function and option. On the server resolve, getRoutes, hasRoute and currentRoute work, and navigate throws only available in the browser.
| To | Call |
|---|---|
| go to a page | navigate(to, options), also named push, or replace(to, options) |
| move in the history | back(), forward(), go(delta), canGoBack() |
| get the URL of a route | resolve(to) |
| run code around every navigation | beforeEach(guard), afterEach(hook), onError(handler) |
run every load again on the way | navigate(to, { refreshAll: true }), or refresh: ["posts:list"] for some keys |
| load the target as a document | navigate(to, { document: true }) |
| know the routes | getRoutes(), hasRoute(name), currentRoute |
import { onAfterNavigate, onBeforeNavigate, useRoute, useRouter } from "@hamur/adapter-react"
import { useEffect } from "react"
export default function Shell() {
const router = useRouter()
const route = useRoute()
useEffect(() => {
const removeGuard = router.beforeEach((to) =>
to.path.startsWith("/admin") && route.meta.public !== true ? { name: "login" } : undefined,
)
const removeAfter = router.afterEach((to, from, failure) => {
if (!failure) console.log(`${from.path} to ${to.path}`)
})
const removeError = router.onError((error, to) => console.error(`navigation to ${to?.path} failed`, error))
return () => {
removeGuard()
removeAfter()
removeError()
}
}, [router, route.meta.public])
onBeforeNavigate((navigation) => {
if (navigation.type === "leave" && document.hidden) navigation.cancel()
})
onAfterNavigate((navigation) => console.log(navigation.type, navigation.to?.path))
const target = router.resolve({ name: "blog-slug", params: { slug: "hello" } })
return (
<a
href={target.href}
onClick={(event) => (event.preventDefault(), void router.push(target.path, { refreshAll: true }))}
>
{target.path}
</a>
)
}
tois an app path: Hamur addsapp.baseURLto a path that starts with/.withBasebuilds such anhrefyourself.- A target on another origin rejects with a
TypeErrorunless you passexternal: true.clearError({ redirect })takes noexternal. shallow: trueto another route runs a full navigation.history.pushStateandreplaceStateto a URL of the same route act as a shallow navigation.navigateTodoes the same outside components, andredirectwith{ document: true }from aloador middleware makes the browser load the target as a document.onBeforeNavigate,onNavigateandonAfterNavigaterun in a component,onEnter,onStayandonLeaveare exports of a page.useRoute()also hasstatus,renderModeandnavigationType.
Links
Link documents its path, replace, state, relative and active classes. These props belong to navigation:
| Prop | What it does |
|---|---|
external | a plain link: rel="external", no prefetch, never intercepted |
target, noRel | _blank or another origin gets rel="noopener noreferrer" (app.link.externalRelAttribute); noRel adds none |
prefetch, prefetchOn, prefetchDelay | the prefetch |
prefetchedClass | a class the link gets once its prefetch is done |
pendingClass | the class while a navigation to it is under way |
scroll | false keeps the scroll position |
viewTransition | true, false or { types } (View transitions) |
onBeforeNavigate(nav) | runs for a navigation this link started, after the component hooks; nav.cancel() stops it |
- The same options work on a hand-written link or on an element around it:
data-hamur-reload,-replace,-prefetch,-prefetch-delay,-scroll,-keepfocusand-view-transition. The closest element counts, and"false"turns one off.<body data-hamur-prefetch="hover">covers the links of a Markdown page. Linkhas nokeepFocusprop: putdata-hamur-keepfocuson the link or around it.defineLinkanduseLinkmake your own link. A children function (a scoped slot in Vue, a snippet in Svelte, a callback in html) gets the sameLinkSlot, andLinkrenders only what it returns.Navigateredirects when it renders.- In
hamur deva link whose path matches no page, noGETserver route, nopublic/file and noproxy,redirectorrewriterule logs HAMUR_W3014 once per path. The server checks the links it renders, the browser those after a navigation.externallinks and other origins are not checked.
import { Link, useRouter } from "@hamur/adapter-react"
export default function Menu() {
const router = useRouter()
return (
<nav>
<Link to="/blog" prefetchOn="visibility">
Blog
</Link>
<Link to="/pricing" prefetch={false}>
Pricing
</Link>
<button type="button" onClick={() => router.navigate("/login", { replace: true })}>
Sign in
</button>
</nav>
)
}
import { Link, Navigate, defineLink, useLink } from "@hamur/adapter-react"
import type { ReactNode } from "react"
const NavLink = defineLink({ activeClass: "current", prefetchOn: "visibility" })
function ButtonLink({ to, children }: { to: string; children: ReactNode }) {
const link = useLink(to, { replace: true })
return (
<a {...link.attrs} className={link.pending ? "button busy" : "button"}>
{children}
</a>
)
}
export default function Menu() {
return (
<nav>
<NavLink to="/blog">Blog</NavLink>
<Link to="/docs" prefetchOn="render" prefetchedClass="ready">
Docs
</Link>
<Link
to="/help"
pendingClass="busy"
scroll={false}
onBeforeNavigate={(nav) => nav.to?.path === "/help" && console.log(nav.type)}
>
Help
</Link>
<Link to="https://example.com" external>
Example
</Link>
<Link to="/tab">
{(link) => (
<button type="button" aria-pressed={link.active} onClick={(event) => void link.navigate(event)}>
Tab
</button>
)}
</Link>
<ButtonLink to="/pricing">Pricing</ButtonLink>
</nav>
)
}
export function Old() {
return <Navigate to="/new" replace />
}
Time writes a date with the same text on the server and in the browser:
import { Time } from "@hamur/adapter-react"
export default function Post({ publishedAt }: { publishedAt: string }) {
return (
<p>
<Time datetime={publishedAt} dateStyle="long" /> (
<Time datetime={publishedAt} relative relativeInterval={30_000} />)
</p>
)
}
Links the browser loads itself
A link is a normal page load when:
- it has a
targetother than_self,download,rel="external"ordata-hamur-reload, or is clicked with a modifier key; - it points to another origin or to a path outside
app.baseURL; - its path is a
GETserver route that no page shares, a file inpublic/, or a path with aproxyrule; - its path ends in a file extension, as in
/feed.xml, and no page claims it; - its path has a
redirectrule, so the server decides; - no route matches it, or the chunk of its page fails to load.
Link protocols
A target may carry only a scheme of app.linkProtocols: http, https, mailto, tel and sms by default. The scheme is read as the browser reads it, so " JaVa\tScript:x" is javascript.
| Where | A refused target |
|---|---|
Link | renders href="#"; hamur dev logs HAMUR_W3003 once per scheme |
navigate(), navigateTo(), redirect(), sendRedirect | throws HAMUR_E3015 with status 400; a load that returns such a redirect shows a 400 error |
A listed scheme other than http and https, such as mailto:, needs { external: true } in navigate(). Add a scheme in the config.
Prefetch
prefetchOn | Starts | Fetches | Held back by |
|---|---|---|---|
"interaction" (default) | on hover or focus, after prefetchDelay ms | the page's JavaScript and CSS, and its load data: one request that runs the load files | data saver, 2g, prefers-reduced-data |
"visibility" | when the link scrolls into view | JavaScript and CSS only; at most 4 at a time, when the browser is idle | the same |
"render" | when the link is in the page, after hydration or a navigation | as "visibility" | the same |
"tap" | on pointerdown (touchstart without PointerEvent), about 100 ms before a click | what the click would fetch | nothing |
An object, such as { visibility: true, interaction: true }, turns on several. The data is the costly part: a hover on a long list of links is a long list of requests. Use "visibility" for such a list, a prefetchDelay for a menu the mouse crosses, and prefetch={false} for a page with a side effect.
import { Link, useRouter } from "@hamur/adapter-react"
export default function Triggers() {
const router = useRouter()
return (
<nav>
<Link to="/a">Hover or focus (default)</Link>
<Link to="/b" prefetchOn="interaction" prefetchDelay={150}>
Hover, after 150 ms
</Link>
<Link to="/c" prefetchOn="visibility">
In view
</Link>
<Link to="/d" prefetchOn="tap">
Pointer down
</Link>
<Link to="/e" prefetchOn="render">
As soon as it is in the page
</Link>
<Link to="/f" prefetchOn={{ visibility: true, interaction: true }}>
In view and hover
</Link>
<Link to="/g" prefetch={false}>
Never
</Link>
<button type="button" onClick={() => void router.prefetch("/h", { data: false })}>
Chunks of /h only
</button>
<a href="/i" data-hamur-prefetch="visible">
A plain anchor
</a>
</nav>
)
}
- A prefetched answer lives 30 seconds and is used once.
router.prefetch(to)always runs;{ data: false }loads the chunks only.useRouterlists its results.- A link to a page the browser loads as a document adds one
<link rel="prefetch" as="document">instead. - A production build also prefetches, when idle, the chunks that the page on screen loads with
import(), as<link rel="prefetch">, once per file. It setscrossoriginwhereapp.crossOrigindoes. hamur devprefetches chunks only, on hover, focus and tap, unlessdevServer.prefetchistrue.- A hand-written link takes
data-hamur-prefetchwithhover,visible,taporrender, also when it is added later.
Speculation Rules
app.speculationRules: { prefetch?, prerender? } lets the browser load documents ahead. Each is "conservative", "moderate", "eager", "immediate" or false. It writes one <script type="speculationrules"> in every page document, with the request's nonce or hash.
| Document | Links the rules cover |
|---|---|
without a client (scripts: false) | every same-origin link below app.baseURL |
| with a client | a[data-hamur-reload] and a[rel~="external"]; every other link is a client navigation |
- Left out:
<baseURL>_hamur/*,GETserver routes, public files,proxy,redirectandrewriterules,[data-hamur-prefetch="none"], and routes withspeculation: false. - The request carries
Sec-Purpose: prefetchand the visitor's cookies, and runs middleware andloadas a click would. - The navigator does not prefetch a link the rules cover.
A page whose GET has a side effect must set speculation: false, in a route rule or on the page. The page then gets no rules script either. meta.speculation is HAMUR_E1051.
import type { PageMeta } from "hamur/app"
export const meta = { scripts: false, rules: { speculation: false } } satisfies PageMeta
export default function Counter() {
return <p>This page counts a view on every GET, so the browser must not load it ahead.</p>
}
Page and layout transitions
app.pageTransition and app.layoutTransition are false or { name, mode?, appear?, duration? } (PageTransition). meta.pageTransition and meta.layoutTransition of the target page override them: false is off, true is the app's value, an object is merged over it.
| Option | Values |
|---|---|
name | the class prefix: <name>-enter-from, <name>-enter-active, <name>-enter-to, and the same three with leave |
mode | "default" (both at once), "out-in" (the old page leaves first) or "in-out" (the new page enters first) |
appear | true also animates the first page the browser renders, never a hydrated one |
duration | milliseconds, or { enter, leave }; without it, the first transitionend or animationend of the element, or its longest CSS time |
import type { PageMeta } from "hamur/app"
export const meta = {
pageTransition: { name: "slide", mode: "out-in" },
layoutTransition: false,
} satisfies PageMeta
export default function Report() {
return (
<article>
<h1>Report</h1>
<nav data-hamur-transition="none">Breadcrumb</nav>
</article>
)
}
| Change on screen | Runs |
|---|---|
| another page, or the same with new params | the page transition |
| another layout or app root | the layout transition; none when layoutTransition is off |
| another query or hash | none |
the first load, a shallow navigation, refresh(), an intercepted route, the error page, prefers-reduced-motion: reduce | none |
- The old page animates as a copy without ids, marked
inert,aria-hiddenanddata-hamur-ghost. The copy cannot submit, play or run anything. An element that is or holds a custom element leaves without an animation. - An element that should not animate carries
data-hamur-transition="none", such as a breadcrumb the layout mounts on every navigation. - A page that stays mounted while its params change has no element to animate, and
hamur devlogs HAMUR_W3002. Give it ameta.keythat changes with the param. - A newer navigation ends the running transition and removes its classes and copies.
page:transition:finish(route)is an app hook in the browser that runs once, after the last enter.- A wrong config value fails at load:
app.pageTransition must be false or { name, mode?, appear?, duration? } (got "fade"). A wrongmetavalue logs HAMUR_W3001 and the page swaps.
In html the elements to animate come from the comments <!--hamur-page--> and <!--hamur-layout--> around the page and layout, because each update replaces the whole root. In the other libraries the core observes what the update added and removed.
View transitions
app.viewTransition is false, true, "always" or { enabled?, types? } (ViewTransitionOption). The option of navigate or Link comes first, then meta.viewTransition, then the config.
import { Link, transitionName, useRouter } from "@hamur/adapter-react"
import type { PageMeta } from "hamur/app"
export const meta = { viewTransition: { types: ["card"] } } satisfies PageMeta
export default function Shop() {
const router = useRouter()
return (
<ul>
<li>
<img src="/lamp.jpg" alt="Lamp" {...transitionName("product-lamp")} />
<Link to="/shop/lamp" viewTransition>
Lamp
</Link>
<Link to="/shop/lamp/specs" viewTransition={{ types: ["slide"] }}>
Specs
</Link>
<Link to="/cart" viewTransition={false}>
Cart
</Link>
<button type="button" onClick={() => router.navigate("/shop/lamp", { viewTransition: { types: ["card"] } })}>
Open
</button>
</li>
</ul>
)
}
- Where the browser has no View Transitions, the page or layout transition runs instead. The two never run together.
prefers-reduced-motion: reduceturns it off, unless the value is"always".- It does not run for the first load, a hash-only or shallow navigation or
refresh(). It does for another query of the same page. - Its types are the app's, the page's, the link's, and
"forward"or"back".<html data-hamur-direction>holds the same word for CSS.
transitionName(name) names an element that moves between two pages. The name must be a CSS identifier and unique on the page: two elements with one name make the browser skip the transition.
:root:active-view-transition-type(card)::view-transition-group(product-lamp) {
animation-duration: 300ms;
}
html[data-hamur-direction="back"]::view-transition-old(product-lamp) {
animation-duration: 150ms;
}
hamur/transitions.css has ready-made fade and slide animations for both kinds of transition.
- The browser holds the page's paint until the update is done, so a
scrollBehaviorpromise must not wait for a frame or forpage:transition:finish. - The app hook
page:view-transition:start(transition)getsready,finished,updateCallbackDoneandskipTransition(). - A newer navigation skips the running transition.
- React's own
<ViewTransition>does nothing during a Hamur navigation.
Keep-alive
app.keepalive: true, or { max } with a default of 10, keeps every page hidden with its state. meta.keepalive overrides it per page. A kept page still runs its load as the client data cache decides.
A kept page is dropped when the entry above it leaves the screen, when the layout changes, or when more than max pages are kept, the least recently shown first. All pages share one count.
| Library | A kept page |
|---|---|
| React | is in <Activity mode="hidden">, which unmounts its effects |
| Vue | is in <KeepAlive> |
| Preact, Svelte, Solid | is in <div data-hamur-keepalive="<key>">, hidden; its effects keep running. The div is there from the server render on, so main > article does not match |
| html | is not kept: there is no component state. app.keepalive warns with HAMUR_W0197 |
onPageActivated and onPageDeactivated run when the page is shown and hidden, and on mount and unmount. The html adapter has neither.
The loading indicator
LoadingIndicator lists its props and useLoadingIndicator, which draws your own bar. It also shows for a form submission, not for refresh(). A strict style-src allows it, and a view transition does not freeze it.
import type { ReactNode } from "react"
import { Announcer, LoadingIndicator, RouteAnnouncer } from "@hamur/adapter-react"
export default function App({ children }: { children?: ReactNode }) {
return (
<>
<LoadingIndicator color="#0a7" height={2} />
<RouteAnnouncer />
<Announcer />
<main>{children}</main>
</>
)
}
Pending thresholds and the link state
| Setting | Default | What it does |
|---|---|---|
app.navigation.pendingMs, or meta.pendingMs | 1000 | after this time useNavigation().pending is true and the pending component shows |
app.navigation.pendingMinMs, or meta.pendingMinMs | 500 | once pending, the new page waits at least this long, so nothing flashes |
- A navigation that ends before
pendingMsis never held. The clock starts after the leave guards and blockers let it go on. - A navigation that replaces a pending one starts pending, so a redirect chain does not flash.
- The link that started it is marked at once:
aria-busy="true"and the pending class,router-link-pendingby default and none for"". A redirect moves the mark to the links of the new target. Links are marked, and hand-written links withdata-hamur-prefetchordata-hamur-pending-class.useLinkStatus()reads the state inside aLink.
import type { ReactNode } from "react"
import { Link, useLinkStatus, useLoadingIndicator, useNavigation } from "@hamur/adapter-react"
import type { PageMeta } from "hamur/app"
export const meta = { pendingMs: 150, pendingMinMs: 400 } satisfies PageMeta
function Label({ children }: { children: ReactNode }) {
const { pending } = useLinkStatus()
return (
<>
{children}
{pending ? " ..." : null}
</>
)
}
export default function Reports() {
const navigation = useNavigation()
const indicator = useLoadingIndicator({ throttle: 100 })
return (
<nav aria-busy={navigation.pending}>
<Link to="/reports" pendingClass="is-pending">
<Label>Reports</Label>
</Link>
<progress value={indicator.progress} max={100} hidden={!indicator.isLoading} />
</nav>
)
}
Focus after a navigation
After the scroll the focus moves, without scrolling, to the first of these that can take it:
- the element the
#hashnames, byidorname; - an element with
autofocusin the new part of the page; - the first
h1in the new part of the page, else the firsth1of the app; - the app root.
An element that cannot take the focus gets tabindex="-1" until it loses it. app.navigation.focus is "heading" (the order above), "root" (always the app root) or "none".
The focus stays where it is:
- for another query or hash of the same page,
shallow,refreshAllandrefresh,keepFocus: trueandscroll: false; - for a link inside
data-hamur-keepfocus;"false"on a closer element turns it back on; - while the visitor is in a text field, a
select, acontenteditableelement or atextbox,searchboxorcomboboxrole; - when your own code focused an element of the new page.
Announcing a page
After the focus the navigator writes the page's title into a hidden live region, #__hamur_announcer, so a screen reader reads it. Without a title it is the first h1 of the new part, else the path.
app.routeAnnouncer | The region |
|---|---|
{ politeness: "polite" } (default) | aria-live="polite", role="status" |
{ politeness: "assertive" } | aria-live="assertive", role="alert" |
{ politeness: "off" } | aria-live="off", no role |
false | none, and nothing is announced |
- The text is cleared and written 50 ms later, so the same text is read twice. In a view transition the focus and the text wait for the update.
- Nothing is announced on the first load, for another query or hash only,
shallow,refreshAllandrefresh. useRouteAnnouncer().set("3 results")replaces the text of the navigation under way.<RouteAnnouncer />places the region in your layout. Render it once (HAMUR_W3004).useAnnouncer()is for changes inside a page.
import { useAnnouncer, useRouteAnnouncer } from "@hamur/adapter-react"
import { useEffect } from "react"
export default function Results({ count }: { count: number }) {
const route = useRouteAnnouncer()
const { assertive } = useAnnouncer()
useEffect(() => route.set(`${count} results`), [count])
return (
<button type="button" onClick={() => assertive("Saved")}>
Save
</button>
)
}
Scroll
A navigation scrolls by the first rule that fits:
- Back and forward go to the saved position.
scroll: falsekeeps the position.- A
#hashgoes to its element. meta.scrollToTop: false, or a function that returnsfalse, keeps the position.- Otherwise the page goes to the top.
scrollToTop: (to, from) => booleanalso works in a folder config, for a whole section.data-hamur-scroll-restore="<id>"saves the position of an element that scrolls, such as a sidebar, and restores it on back, forward and reload. At most 16 per history entry.data-hamur-scroll="false"on a link or around it isscroll={false}.app.navigation.scrollKey: "path"saves positions per path, so a link to a page you left scrolled restores it, unless the link has a#hashorscroll: false.- With a page or layout transition the scroll runs when the leave ended, with a view transition inside its update.
disableScrollHandling()keeps the position of the navigation that runs.
Router options
app/router.options.ts replaces the scroll rule with your own. defineRouterOptions lists what scrollBehavior may return. It is client code; the server never imports it.
import { defineRouterOptions } from "hamur/app"
export default defineRouterOptions({
scrollBehavior(to, from, saved) {
if (saved) return { type: "position", x: saved.x, y: saved.y }
if (to.hash) return { type: "hash", id: to.hash.slice(1) }
return to.path === from.path ? { type: "none" } : { type: "top" }
},
})
The other router settings are config keys, which the server and the build read too:
| Setting | Key |
|---|---|
| history mode | app.history: "browser" (default) or "hash", which keeps the path in location.hash (#/about) and needs ssr: false. The static presets then serve index.html for every path |
| slash and case | app.trailingSlash and app.caseSensitive (Trailing slashes and case) |
memoryHistory keeps the history in memory, for tests and embedded widgets:
import { memoryHistory } from "hamur/app"
const history = memoryHistory("/blog")
history.push("/blog/hello", null)
history.go(-1)
export const at = history.location
Leaving a page
| Tool | What it does |
|---|---|
onBeforeRouteLeave, onBeforeRouteUpdate | run when the page is left, or stays with new params or a new query; false cancels. Never in a layout or the root |
useBlocker, usePreventNavigate | hold the navigation until your dialog answers, and show the browser's dialog when the tab closes |
onBeforeNavigate | navigation.cancel() stops any navigation |
import { onBeforeRouteLeave, useBlocker, useRouter, useSnapshot } from "@hamur/adapter-react"
import { useRef, useState } from "react"
export default function Editor() {
const [dirty, setDirty] = useState(false)
const note = useRef<HTMLTextAreaElement>(null)
const router = useRouter()
const blocker = useBlocker(({ to }) => dirty && to !== null)
onBeforeRouteLeave((to) => (to.path === "/login" ? true : !dirty))
useSnapshot("note", {
capture: () => note.current?.value ?? "",
restore: (value) => void (note.current && (note.current.value = value)),
})
return (
<form>
<textarea ref={note} onChange={() => setDirty(true)} />
<button type="button" onClick={() => router.pushState("", { step: 2 })}>
Next step
</button>
{blocker.state === "blocked" && (
<dialog open>
Leave without saving?{" "}
<button type="button" onClick={blocker.proceed}>
Leave
</button>{" "}
<button type="button" onClick={blocker.reset}>
Stay
</button>
</dialog>
)}
</form>
)
}
Every guard must let a navigation go; the first that blocks ends the list. A form's own navigation is never blocked, and a hash-only navigation runs none of these. They guard no data: that check is in the handler.
History state and snapshots
| To keep | Use |
|---|---|
| a value with a new history entry | navigate(to, { state }) or <Link state={…}>, read with useRoute().state |
| a modal or a step with its own entry, loading nothing | router.pushState(url, state) and router.replaceState(url, state); "" keeps the URL |
| what was typed, for back, forward and reload | useSnapshot(key, { capture, restore }) |
import { useRoute, useRouter } from "@hamur/adapter-react"
export default function Wizard() {
const route = useRoute()
const router = useRouter()
const step = Number(route.state.step ?? 1)
return (
<div>
<p>Step {step}</p>
<button type="button" onClick={() => router.pushState("", { step: step + 1 })}>
Next
</button>
<button type="button" onClick={() => router.replaceState("", { step })}>
Keep
</button>
<button type="button" onClick={() => router.navigate("/wizard/done", { state: { from: step } })}>
Finish
</button>
</div>
)
}
Each value is at most 65,536 characters serialized. A user can edit history entries, so treat the state as input. A snapshot is kept in sessionStorage, so capture() must never return a secret. useRouter has the exact rules.
Events
A script outside the app, such as analytics, listens on document. Each event is a CustomEvent that does not bubble, with detail { type, from, to, delta?, appId }. from and to are full paths, or null when there is no page on that side; appId tells several apps on one page apart.
| Event | When | Cancelable |
|---|---|---|
hamur:beforenavigate | after onBeforeNavigate; preventDefault() is nav.cancel() | yes |
hamur:navigate | after onNavigate, before the page changes | no |
hamur:afternavigate | after onAfterNavigate, and once with type: "enter" after the first page mounted | no |
A hash-only or shallow navigation fires none. The events are typed once the app imports hamur.
import "@hamur/adapter-react"
document.addEventListener("hamur:beforenavigate", (event) => {
if (event.detail.to?.startsWith("/admin") && !document.cookie.includes("admin=1")) event.preventDefault()
})
document.addEventListener("hamur:navigate", (event) => console.log("leaving", event.detail.from))
document.addEventListener("hamur:afternavigate", (event) => {
console.log(event.detail.type, event.detail.to)
})
Clicks during hydration
In React, Preact and Solid a click on a link before the page hydrated is held and becomes a client navigation, which replaces the hydration in progress. app:mounted still runs once. In Vue, Svelte and html such a click loads the document.