# Navigation details

The rules, options and costs behind the [Navigation](/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

1. 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: false` skips the wait. A `navigate()` from code, a hash-only click, back and forward never wait.
2. `page:beforeNavigate`, `onBeforeNavigate`, the `Link`'s own `onBeforeNavigate`, the `hamur:beforenavigate` event, the blockers, the leave and update guards, the route middleware, `beforeEach`, `page:start`.
3. The page chunks and the data load. `pending` turns true after `pendingMs` and the pending component shows.
4. `onNavigate` and the `hamur:navigate` event. The navigation then waits until `pendingMinMs` have passed since `pending` turned true.
5. The history entry is written and the page changes: in a view transition, in a page or layout transition, or as a plain swap.
6. `page:finish`, the scroll, the focus, the announcement, `idle`, `page:rendered`, `onAfterNavigate`, the `hamur:afternavigate` event, `afterEach`, the route hooks, `onPageActivated` and `onPageDeactivated`, and `page:transition:finish` once 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.

````ts [navigation/config.ts]
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()`](/api-reference/adapters#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](/data#refreshing-by-key) |
| load the target as a document     | `navigate(to, { document: true })`                                                                          |
| know the routes                   | `getRoutes()`, `hasRoute(name)`, `currentRoute`                                                             |

````tsx [react/router-api.tsx]
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>
  )
}
````

- `to` is an app path: Hamur adds `app.baseURL` to a path that starts with `/`. [`withBase`](/api-reference/app#withbase-withoutbase) builds such an `href` yourself.
- A target on another origin rejects with a `TypeError` unless you pass `external: true`. `clearError({ redirect })` takes no `external`.
- `shallow: true` to another route runs a full navigation. `history.pushState` and `replaceState` to a URL of the same route act as a shallow navigation.
- [`navigateTo`](/api-reference/app#navigateto-navigatetooptions) does the same outside components, and [`redirect`](/api-reference/app#redirect-isredirect-hamurredirect) with `{ document: true }` from a `load` or middleware makes the browser load the target as a document.
- [`onBeforeNavigate`, `onNavigate` and `onAfterNavigate`](/api-reference/adapters#onbeforenavigate-onnavigate-onafternavigate) run in a component, [`onEnter`, `onStay` and `onLeave`](/api-reference/app#page-exports-onenter-onstay-onleave) are exports of a page.
- [`useRoute()`](/api-reference/adapters#useroute) also has `status`, `renderMode` and `navigationType`.

## Links

[`Link`](/api-reference/adapters#link-linkprops-linkslot) 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](#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](#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`, `-keepfocus` and `-view-transition`. The closest element counts, and `"false"` turns one off. `<body data-hamur-prefetch="hover">` covers the links of a Markdown page.
- `Link` has no `keepFocus` prop: put `data-hamur-keepfocus` on the link or around it.
- [`defineLink` and `useLink`](/api-reference/adapters#definelink-uselink-linkdefaults-uselinkoptions) make your own link. A children function (a scoped slot in Vue, a snippet in Svelte, a callback in html) gets the same `LinkSlot`, and `Link` renders only what it returns.
- [`Navigate`](/api-reference/adapters#navigate-navigateprops) redirects when it renders.
- In `hamur dev` a link whose path matches no page, no `GET` server route, no `public/` file and no `proxy`, `redirect` or `rewrite` rule logs [HAMUR_W3014](/errors/HAMUR_W3014) once per path. The server checks the links it renders, the browser those after a navigation. `external` links and other origins are not checked.

````tsx [react/navigation.tsx]
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>
  )
}
````

````tsx [navigation/link.tsx]
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`](/api-reference/adapters#time-timeprops) writes a date with the same text on the server and in the browser:

````tsx [navigation/time.tsx]
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 `target` other than `_self`, `download`, `rel="external"` or `data-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 `GET` server route that no page shares, a file in `public/`, or a path with a `proxy` rule;
- its path ends in a file extension, as in `/feed.xml`, and no page claims it;
- its path has a `redirect` rule, 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](/errors/HAMUR_W3003) once per scheme                              |
| `navigate()`, `navigateTo()`, `redirect()`, `sendRedirect` | throws [HAMUR_E3015](/errors/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](/configuration#hosts-links-and-more).

## 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.

````tsx [navigation/prefetch.tsx]
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. [`useRouter`](/api-reference/adapters#userouter) lists 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 sets `crossorigin` where `app.crossOrigin` does.
- `hamur dev` prefetches chunks only, on hover, focus and tap, unless `devServer.prefetch` is `true`.
- A hand-written link takes `data-hamur-prefetch` with `hover`, `visible`, `tap` or `render`, 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/*`, `GET` server routes, public files, `proxy`, `redirect` and `rewrite` rules, `[data-hamur-prefetch="none"]`, and routes with `speculation: false`.
- The request carries `Sec-Purpose: prefetch` and the visitor's cookies, and runs middleware and `load` as 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](/errors/HAMUR_E1051).

````tsx [navigation/speculation.tsx]
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`](/api-reference/app#pagetransition-transitionmode)). `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 |

````tsx [navigation/page-transition.tsx]
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-hidden` and `data-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 dev` logs [HAMUR_W3002](/errors/HAMUR_W3002). Give it a [`meta.key`](/api-reference/routing-details#remounting-a-page) that 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 wrong `meta` value logs [HAMUR_W3001](/errors/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`](/api-reference/app#viewtransitionoption-viewtransitioncall-viewtransitionhandle)). The option of `navigate` or `Link` comes first, then `meta.viewTransition`, then the config.

````tsx [navigation/view-transition.tsx]
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: reduce` turns 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)`](/api-reference/adapters#transitionname) 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.

````css [navigation/view-transition.css]
: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`](/api-reference/app#hamurtransitionscss) 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 `scrollBehavior` promise must not wait for a frame or for `page:transition:finish`.
- The app hook `page:view-transition:start(transition)` gets `ready`, `finished`, `updateCallbackDone` and `skipTransition()`.
- 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](/data#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](/errors/HAMUR_W0197)                                                        |

[`onPageActivated` and `onPageDeactivated`](/api-reference/adapters#onpageactivated-onpagedeactivated) run when the page is shown and hidden, and on mount and unmount. The html adapter has neither.

## The loading indicator

[`LoadingIndicator`](/api-reference/adapters#loadingindicator-loadingindicatorprops-useloadingindicator) 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.

````tsx [navigation/root.tsx]
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 `pendingMs` is 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-pending` by default and none for `""`. A redirect moves the mark to the links of the new target.
- `Link`s are marked, and hand-written links with `data-hamur-prefetch` or `data-hamur-pending-class`. [`useLinkStatus()`](/api-reference/adapters#uselinkstatus) reads the state inside a `Link`.

````tsx [navigation/pending.tsx]
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:

1. the element the `#hash` names, by `id` or `name`;
2. an element with `autofocus` in the new part of the page;
3. the first `h1` in the new part of the page, else the first `h1` of the app;
4. 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`, `refreshAll` and `refresh`, `keepFocus: true` and `scroll: 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`, a `contenteditable` element or a `textbox`, `searchbox` or `combobox` role;
- 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`, `refreshAll` and `refresh`.
- `useRouteAnnouncer().set("3 results")` replaces the text of the navigation under way. `<RouteAnnouncer />` places the region in your layout. Render it once ([HAMUR_W3004](/errors/HAMUR_W3004)).
- [`useAnnouncer()`](/api-reference/adapters#routeannouncer-userouteannouncer-announcer-useannouncer-routeannouncerprops) is for changes inside a page.

````tsx [navigation/announcer.tsx]
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:

1. Back and forward go to the saved position.
2. `scroll: false` keeps the position.
3. A `#hash` goes to its element.
4. `meta.scrollToTop: false`, or a function that returns `false`, keeps the position.
5. Otherwise the page goes to the top.

- `scrollToTop: (to, from) => boolean` also works in a [folder config](/api-reference/routing-details#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 is `scroll={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 `#hash` or `scroll: false`.
- With a page or layout transition the scroll runs when the leave ended, with a view transition inside its update.
- [`disableScrollHandling()`](/api-reference/app#disablescrollhandling) keeps the position of the navigation that runs.

## Router options

`app/router.options.ts` replaces the scroll rule with your own. [`defineRouterOptions`](/api-reference/app#definerouteroptions-routeroptions-scrollaction-scrollposition) lists what `scrollBehavior` may return. It is client code; the server never imports it.

````ts [routing/router.options.ts]
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](/api-reference/routing-details#trailing-slashes-and-case))                                                   |

[`memoryHistory`](/api-reference/app#memoryhistory-history) keeps the history in memory, for tests and embedded widgets:

````ts [routing/memory-history.ts]
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`](/api-reference/adapters#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`](/api-reference/adapters#useblocker-usepreventnavigate-blocker-blockerargs-useblockeroptions) | hold the navigation until your dialog answers, and show the browser's dialog when the tab closes                   |
| [`onBeforeNavigate`](/api-reference/adapters#onbeforenavigate-onnavigate-onafternavigate)                                         | `navigation.cancel()` stops any navigation                                                                         |

````tsx [react/leave-guards.tsx]
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 })`](/api-reference/adapters#usesnapshot-snapshotoptions) |

````tsx [react/history-state.tsx]
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`](/api-reference/adapters#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`.

````ts [navigation/events.ts]
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.
