# Navigation

> Links, forms and Back in place; navigate() in code; shallow navigation; scroll positions.

The first request for a page gets HTML, rendered on the server. After that, Fondu's client takes over the app's
links and forms: it asks the server for the next page's props as JSON and swaps the page in place. The layouts stay
mounted, with their state, and the browser doesn't reload.

There is no router to set up and no special link component: links are `<a>`, forms are `<form>`. Without
JavaScript, they work the same way, as plain links and forms.

## Links

Link to a page with a plain `<a>`, and build its URL with [`href()`](https://fondu.dev/docs/type-safety.md), which is typed after your
routes:

```tsx
import { href } from 'fondu/client'

export function UserLink({ user }: { user: { id: number; name: string } }) {
  return <a href={href('/users/:id', { id: user.id })}>{user.name}</a>
}
```

When the link is clicked, the client loads `/users/7` in place. The new page starts at the top, or at its
`#fragment` (`/docs#setup`). A query and a fragment are `href()`'s too:
`href('/search', { query: { q }, hash: 'results' })`.

The page's code is loaded before the click, once the pointer rests on the link or a touch starts on it, so the click
has less to wait for. The data of a static page is asked for then too (its file, which runs nothing, used by the clicks of the next 30 seconds); another page's data is asked for
at the click, and its loader runs for a visit only.
Nothing is loaded ahead when the browser's data saver is on.

A link to the page on the screen can say so with `aria-current`, which CSS can style (`a[aria-current='page']`):

```tsx
const { url } = usePage()
const to = href('/users')
return <a href={to} aria-current={url === to ? 'page' : undefined}>Users</a>
```

The client takes a click only when it is a link to one of the app's pages, as the files in `app/routes/` define
them. The browser handles every other link, as it would without Fondu:

| Link                                                            | Handled by                  |
| --------------------------------------------------------------- | --------------------------- |
| a page of the app: `/users/7`                                   | the client, in place        |
| a `#fragment` of the current page: `#setup`                     | the browser, scrolls to it  |
| a file of the site: `/llms.txt`, `/report.pdf`                  | the browser, loads the file |
| an HTTP route (a `.ts` file): `/api/health`                     | the browser                 |
| a URL no route answers: `/nope`                                 | the browser, shows the 404  |
| another site                                                    | the browser                 |
| with `target` (`_blank`…), `download`, or Ctrl, ⌘, Shift or Alt | the browser                 |
| without `target`, in a page whose `<base target>` isn't `_self` | the browser                 |
| an SVG `<a>`, or an `<area>`                                    | the browser                 |

### A full page load

A link without its own `target` has the document's `<base target>`, as in the browser: `_blank` there opens every such
link in a new tab, and the client leaves the click alone. A `target="_self"` on the link itself overrides it. Links in
an SVG (`<a>`) and image maps (`<area>`) are always the browser's.

To make a link to a page load as a whole document, without the client, add `target="_top"`. In a page that isn't in
a frame, it opens in the same tab, as any link, but the browser loads it:

```tsx
<a href={href('/admin')} target="_top">
  Admin
</a>
```

Use it when the next page needs a fresh document, such as a page of another `<html lang>`, or one whose scripts must
run again. In code, `loadDocument(url)` does the same.

A catch-all page route (`docs/[...slug].tsx`) covers every URL below it, files included. A link to a file there,
`/docs/manual.pdf`, takes `download` or `target="_top"`, so the browser loads the file.

## Navigating in code

`navigate()` from `fondu/client` goes to a URL as a link to it would:

```tsx
import { href, navigate } from 'fondu/client'

navigate(href('/orders', { query: { page: 2 } }))
```

- A page of the app loads in place, in a new history entry.
- `{ replace: true }` replaces the current history entry instead, so Back skips it.
- `{ keep: true }` shows the answer as `reload()` does: the page keeps its state (a focused input, what was typed) and
  the scroll position, and nothing is announced. The loader still runs for `url`. If another page answers, it is shown
  as any navigation's, from the top.
- Any other URL loads as a document: `mailto:` and other sites too. A `javascript:` URL throws an `Error`, in
  `navigate()` and in `loadDocument()`.

### Search as you type

An input whose value goes into the URL, and a loader that answers the results. Without `keep`, each new query would
mount the page anew: the input would lose its focus and what was typed meanwhile.

```tsx
import { defineHandler, render } from 'fondu'
import { href, navigate } from 'fondu/client'
import { useRef, useState } from 'react'

export const loader = defineHandler((c) => {
  const q = new URL(c.req.url).searchParams.get('q') ?? ''
  return render(c, Search, { q, results: findProducts(q) })
})

export default function Search({ q, results }: { q: string; results: string[] }) {
  const [value, setValue] = useState(q)
  const timer = useRef<ReturnType<typeof setTimeout>>(undefined)
  const change = (next: string) => {
    setValue(next)
    clearTimeout(timer.current)
    timer.current = setTimeout(
      () => navigate(href('/search', { query: { q: next } }), { replace: true, keep: true }),
      250,
    )
  }
  return (
    <>
      <input type="search" value={value} onChange={(event) => change(event.target.value)} />
      <ul>
        {results.map((name) => (
          <li key={name}>{name}</li>
        ))}
      </ul>
    </>
  )
}
```

`replace` makes one history entry for the search, not one per letter. A navigation in flight is aborted by the next,
so a fast typist sees only the last answer. Why not `fetch()` from an effect: the URL holds the search, so Back, a
reload and a shared link all work, and the loader is the one place the results are computed.

| Export                                  | Does                                                                                                                 |
| --------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
| `navigate(url, { replace?, keep? })`    | goes to `url` as a link would; `keep`: the page keeps its state and scroll, as `reload()` does                       |
| `navigate(url, { shallow: true, ... })` | changes the query or `#fragment` of this page, with no request; `replace?`, no `keep` ([below](#shallow-navigation)) |
| `closeShallow(to)`                      | closes what a shallow navigation opened, one step: Back, or `to` in place of this entry                              |
| `loadDocument(url)`                     | loads `url` as a document (a full page load)                                                                         |
| `reload()`                              | asks for the current page's props again; state and scroll stay                                                       |
| `reload({ only: ['stats'] })`           | asks for those props alone, quietly: [deferred props](https://fondu.dev/docs/pages.md#deferred-props)                                    |

## Forms

A `<form method="post">` is sent by the client too, and its answer is shown in place. When the answer is the same
page (back with validation errors, or `back(c)`), the page is updated where it is: the scroll position and what was
typed stay. When it is another page, it is a new entry in the history. [Forms and validation](https://fondu.dev/docs/forms.md) covers
actions, errors and pending states.

## Scroll positions

| After                                                                    | The page is                             |
| ------------------------------------------------------------------------ | --------------------------------------- |
| a link, or `navigate()`                                                  | at the top, or at the URL's `#fragment` |
| Back or Forward                                                          | where it was when you left it           |
| a reload                                                                 | where it was when you left it           |
| a form's answer at the same URL, `reload()`, or `navigate()` with `keep` | where it is                             |
| a shallow navigation, and Back or Forward between the entries it shares  | where it is                             |

Back and Forward show the page at once, as it was left, then put the server's fresh page in its place. The pages
kept for this are in memory only, and they are all forgotten once a form is sent, as the form may have changed
them (or signed the user out).

## Shallow navigation

Some state belongs in the URL without being a page: an open dialog or drawer, a selected item, a tab. A shallow
navigation changes the query or the `#fragment` of the page on the screen, and asks for nothing. No request is made and
the loader does not run. The page keeps its props, its state and the scroll position.

```tsx
import { navigate } from 'fondu/client'

navigate('?item=7', { shallow: true }) // a new history entry
navigate('?item=8', { shallow: true, replace: true }) // this entry's URL changes
navigate('#settings/profile', { shallow: true })
```

In markup, mark the link with `data-shallow`:

```tsx
<a href="?item=7" data-shallow>
  Order 7
</a>
```

A plain left click on it is a shallow navigation. A click with Ctrl, Cmd, Shift or Alt, or a link with `target` or
`download`, is the browser's, as for any link. A `data-shallow` link to another pathname is an ordinary link: it is a
visit, and it is prefetched as any link is. Without JavaScript every link is a plain link, so the loader should render
what the URL asks for. A document load at `/orders?item=7` has the drawer open, and the click only skips the request.

- Only the query and the `#fragment` change. A URL with another pathname throws an error, and a trailing slash is
  another pathname. The pathname is compared with the page on the screen.
- `shallow` and `keep` do not go together: a shallow navigation keeps the page anyway. TypeScript and the runtime both
  refuse it.
- Before the app has started, `navigate(…, { shallow: true })` is a document load.
- While a visit is being put on the screen (its URL is in the address bar, its page is not shown yet), a shallow
  navigation is an ordinary one: it supersedes that visit, as any navigation does.

### What the page has

`usePage().url` follows the address bar: its path and query. The props do not. They are the loader's answer for the URL
that got the page, so read what the query holds from `url`. A shallow navigation also drops the page's `flash` and
`errors`: they belonged to the answer before it.

```tsx
import { usePage } from 'fondu/client'

const { url } = usePage()
const item = new URL(url, 'http://localhost').searchParams.get('item')
```

A `#fragment` is not in `url`. Read it with `useSyncExternalStore` on `hashchange`. A shallow navigation to a new
`#fragment` dispatches a `hashchange`, as the browser's own does:

```tsx
import { useSyncExternalStore } from 'react'

const subscribe = (notify: () => void) => {
  addEventListener('hashchange', notify)
  return () => removeEventListener('hashchange', notify)
}
const useHash = () => useSyncExternalStore(subscribe, () => location.hash, () => '') // '' on the server
```

Back and Forward between two shallow entries that differ in both the query and the `#fragment` may not fire `hashchange` (browsers fire it only when the rest of the URL is the same). Read `location.hash` on `popstate` too if that matters.

A shallow `#fragment` is not a fragment navigation of the browser. The page does not scroll to the element it names,
and `:target` does not follow it. For that, use a link without `data-shallow`: a link to a `#fragment` of the page on
the screen is the browser's.

### A dialog or a drawer

The URL holds the open state. `closeShallow()` closes it:

```tsx
import { closeShallow, navigate, usePage } from 'fondu/client'

export default function Orders({ orders }: { orders: Order[] }) {
  const { url } = usePage()
  const id = new URL(url, 'http://localhost').searchParams.get('order')
  const index = orders.findIndex((order) => String(order.id) === id)
  const next = orders[(index + 1) % orders.length]
  return (
    <>
      <ul>
        {orders.map((order) => (
          <li key={order.id}>
            <a href={`?order=${order.id}`} data-shallow>
              {order.name}
            </a>
          </li>
        ))}
      </ul>
      {index >= 0 && (
        <Drawer onClose={() => closeShallow(url)}>
          <h2>{orders[index].name}</h2>
          <button onClick={() => navigate(`?order=${next.id}`, { shallow: true, replace: true })}>
            Next
          </button>
        </Drawer>
      )}
    </>
  )
}
```

- `closeShallow(to)` closes one level, and never leaves the page. When the current entry was pushed by a shallow
  navigation, it goes Back, to the entry below. Otherwise (a document loaded at this URL, a reload, an entry that was
  replaced) it replaces the current entry with `to`, a URL of this page, with no request and no new entry. Pass the
  URL without the state, as `usePage().url` has it.
- Switching between items inside an open drawer uses `replace`, so the drawer is one history entry: one close, or one
  Back, returns to the page under it.
- Overlays nest, one level per close: a tab opened over a drawer is closed first, then the drawer.
- A second `closeShallow()` before the first one's Back has landed does nothing, so a double click closes one level.
- The browser's own `#fragment` entries are not shallow entries. A native `#fragment` link clicked over an open drawer
  adds an entry that `closeShallow()` replaces, as it replaces any other.

If the drawer needs data the list does not have, ask for it with `reload({ only: ['order'] })` (the loader sees the
query), or with `fetch()` from a `.ts` route.

A form in the dialog is posted as any form. Its answer at the same page (back with errors, or `back(c)`) keeps the
`#fragment` on the screen, so the dialog stays open, with its errors or its result.

### Back and Forward

The entries that show the same page share it: the one that got the page, those added by shallow navigations, and the
browser's own `#fragment` entries. Back and Forward between them change `url` and nothing else. No request is made,
and the state stays. A visit still on its way is given up, as with any Back.

An answer from the server on a shallow entry belongs to that entry alone. It ends the sharing, and the other entries
become normal ones: Back to them asks, as it does for any page. This is the case for:

- `reload()` and `reload({ only })`, asked at the entry's URL, so the loader sees its query;
- a form's answer;
- deferred props asked at that URL.

Deferred props already on their way when the shallow navigation happens are the loader's answer for the page. They
arrive in it, and the entries keep sharing it.

A browser reload of a shallow URL is a document load, and the entries before it are documents of their own. A close
that goes Back to one of them loads it.

### A prerendered page

A [prerendered page](https://fondu.dev/docs/static-pages.md) is a file made without a query. Once it has hydrated, its `usePage().url` has
the query of the address bar, so a state in the query works on a direct load, as it does after a click. The loader did
not see that query: it ran at build time. Whatever a page must have for a query, a prerendered page cannot get from its
loader.

## While a page loads

`useNavigation()` from `fondu/client` says what is on its way, from a click or a submit until the next page is on
the screen:

| Field   | Is                                                                                                                                                   |
| ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| `state` | `'idle'`; `'submitting'`, a form's POST; `'loading'`, any other (a link, `navigate()`…); `'failed'`, a form's POST that could not be sent (offline…) |
| `to`    | where to: a path with its query and fragment (`/users/7?tab=posts`), or `null` when idle                                                             |
| `form`  | the form being sent (a GET form's too), or `null`                                                                                                    |

```tsx
import { useNavigation } from 'fondu/client'

export function Spinner() {
  const { state } = useNavigation()
  return state === 'loading' || state === 'submitting' ? <span aria-label="Loading">…</span> : null
}
```

`failed` lasts until the next navigation starts; the form stays as it was, to send again. A GET that fails is loaded as
a document instead, where the browser says what is wrong. Code that read "not `idle`" as "pending" compares with
`loading` and `submitting`.

A navigation that takes longer than 350 ms also shows a thin progress bar at the top of the page. Configure it in
`vite.config.ts`:

```ts
fondu({
  target: 'node',
  progress: {
    color: 'var(--brand)', // default: the page's text color
    delay: 500, // ms before it shows (default 350)
    forms: false, // not for forms' submissions: their buttons show it
  },
})
```

`progress: false` removes it, when your own indicator uses `useNavigation()`.

## Other answers

- Screen readers announce the new page's title after each navigation.
- An answer that isn't a page, such as a file or a proxy's error page, is shown as the browser would show it.
- A redirect to another site (`c.redirect('https://…')`) loads that site.
- After a deploy, the next navigation from a tab opened before it loads the page as a document, so the browser runs
  the new version.

Protocol notes: `X-Fondu-Location` (with status 409)
means "load this URL as a document". `X-Fondu-Redirect` means "follow this path in place", as a navigation.
