qat

Routing

The route table is a module named routes.js; its default export is the app's root component:

JavaScript23 lines
// routes.js
import { router, page, layout, guard, redirect, notFound } from '@qatjs/router'
import { api } from './api.js'
import { session } from './session.js'

export default router({
  '/': page('./pages/home.qx'),
  '/users': layout('./layouts/users.qx', {
    '/': page('./pages/users/list.qx', { load: ({ signal }) => api.users(signal) }),
    '/:id': page('./pages/users/detail.qx', {
      load: async ({ params, signal }) => {
        const user = await api.user(params.id, signal)
        if (!user) throw notFound()
        return user
      },
      keep: { max: 5 },
      catch: './pages/users/error.qx',
    }),
  }, { load: ({ signal }) => api.teams(signal) }),
  '/old': page('./pages/home.qx', { load: () => { throw redirect('/') } }),
  '/admin/**': guard(() => session.admin(), page('./pages/admin.qx'), { redirect: '/' }),
  '*': page('./pages/404.qx'),
})
JavaScript5 lines
// main.js
import { render } from '@qatjs/core'
import routes from './routes.js'

render(routes, document.getElementById('app'))
  • Patterns: static segments, :param, a trailing /** (the rest), and '*' for everything else. Each page file is a split point: its module loads when the route is first visited.
  • Layouts render their child page into <qat-outlet />, and a layout instance survives navigations between its children (its state, its DOM). What a layout provides, its pages can inject.
  • Lazy child tables: a layout's children can be a module whose default export is a table, layout('./layouts/admin.qx', () => import('./admin/routes.js')) under a '/admin/**' key. It loads on the first visit below the prefix (after the route's guard), and its routes then match under /admin. Federation's remote('payments', './routes') is this, with the remote's module (see federation).
  • Links are plain <a href>: same-origin clicks are routed (no modifier key, no target, no download); <a data-no-router> opts out.
  • Render modes: page(p, { mode: 'server' }) renders the route on the server and resumes it in the browser; also 'static', 'island', 'client' (the default), and 'auto', the build's choice (server rendering). resume: ['#search'] makes the listed parts interactive first; paths lists a route's entries for --static. See server rendering.
  • Audiences: page(p, { audience: ['officer', 'admin'] }) keeps the route only in those audiences' builds: qatjs compress --audience officer writes dist/officer/ without the routes that do not name officer, and without everything only they reach. A link to such a route from code another audience's build ships is a compile error. See audience builds.

Route data

A route's load({ params, query, signal, parent }) runs when the navigation starts; the page receives the result as props.data:

// pages/users/detail.qx
export default function Detail({ data }) {
  return <h1>{data.name}</h1>
}
  • The loads of the matched chain (layouts and page) run in parallel. A page's load can await parent() for its layout's data — sequential where it needs it, parallel otherwise.
  • A navigation superseded by another is aborted through signal; its page never renders.
  • throw redirect('/login') and throw notFound() (from a load or a guard) are handled by the router: a redirect replaces the URL, not-found renders the '*' route at the same URL.
  • catch: when a load fails, the route's own catch page renders with { error, retry }; without one, the nearest layout's; then the router's (router(table, { catch })). With none at all the navigation still happens: the layouts stay, and in the page's place stands the error's message as <p role="alert"> (and the error goes to onError). Give the router a catch page to say it your way. A guard that rejects is different: its navigation does not happen.
  • defer: true renders the page at once with data = { loading: true }, then { value } or { error }.
.qx11 linesOpen in the playground
// shell.qx
import routes from '../routes.js'

export default function Shell() {
  return (
    <div>
      {if (routes.pending())}<div class="progress" />{/if}
      <qat-outlet />
    </div>
  )
}
  • routes.pending() is true while a navigation runs; routes.pending.to() is where it is going.

  • To navigate from code, navigate(to, { replace? }) from @qatjs/router uses the app's router, so a page does not import routes.js:

    import { navigate } from '@qatjs/router'
    
    export default function Done() {
      mount(() => setTimeout(() => navigate('/'), 3000))
      return <p>Thanks! Back to the shop in a moment.</p>
    }
  • Navigations commit inside transition(): the new page is built, then swapped in one batch (and in a view transition, where the browser supports them). Scroll is restored on back/forward and reset (or moved to the #hash) otherwise.

  • Focus follows the navigation, so keyboard and screen-reader users land on the new page: after each client-side navigation (links, navigate(), back/forward — not the first render) focus moves to the last, in document order, of the [autofocus] elements, the <h1>s and the <qat-outlet>s: the page's own, since a layout's header comes before its outlet. There is no priority among them: an <input autofocus> above the page's <h1> loses to the <h1>, so put it after the heading. A target that is not focusable gets tabindex="-1"; a focusable one keeps its tab order. Focus stays where it is while the user types in a text field that is still on the page (a layout's search box), and query() writes never move it (they do not navigate). Screen readers read the focused <h1>, and the new page's title is announced in a polite live region (a visually hidden <p aria-live="polite"> the router appends to <body>).

  • A link to the page being shown has aria-current="page" — by its path, whatever its query or fragment — and loses it when the page is left: a screen reader says "current page", and a stylesheet selects it (nav a[aria-current='page'] { font-weight: 600 }). A link that comes later — a list that arrives, a menu that opens — is marked, and watched for prefetch, as it comes.

  • routes.navigate('/users/7', { replace }) navigates from code; routes.onNavigate((from, to) => …) runs before each navigation made by a link or navigate(), and returning false cancels it (unsaved changes). It does not run for back/forward, nor for the first render: Back is never cancelled. (Leaving the site is the browser's beforeunload.)

  • routes.prefetch(href) warms a route; links do it themselves: modules when a link enters the viewport, modules and loads on hover. page(…, { prefetch: false }) opts a route out. A route under a guard() is not prefetched on hover (neither modules nor loads: the guard has not decided yet); its modules still preload when a link to it is in view.

  • guard(check, target, { redirect }) calls check(to) (sync or async) before the route's loads: to.path, to.params, to.url — and on a server-rendered route to.request, the request being answered (server.md). False redirects.

Speculative navigation

page(p, { load, speculate: true }) builds the page detached on link hover or viewport entry, once its module and data are prefetched and the main thread is idle; the click only inserts it, then runs its mount and effects. Its load runs before any click, so it must be idempotent. At most 2 pages are held, each for 30 s, none on saveData, 2g or low memory, and only under a layout already shown. The compiler then loads @qatjs/router/speculate (1.46 kB, pnpm size).

keep

keep: true (≡ { max: 5 }) keeps instances of a page alive when you navigate away: state, form values and scroll positions come back. Instances are kept per key(params) (default: the path and query), least recently used first out; an evicted instance is disposed normally.

Params and the query string

// pages/products.qx
import { params, query } from '@qatjs/router'

export default function Products() {
  const p = params() // reactive: p.id
  const q = query('q', '') // a signal bound to ?q=
  const pageNo = query('page', 1) // numbers come back as numbers; `?page=abc` and `?page=` are the fallback, 1
  return <input aria-label="Search" bind:value={q} /> // (a signal in a const binds like a state)
}

Writing a query signal updates the URL (replacing the history entry); navigating updates it.

Typed routes

The compiler reads routes.js and generates routes.d.ts next to it (qatjs check and the build write it). Links are typed from the page files' names:

// nav.qx
import { to } from './routes.js'

export default function Nav({ id }) {
  return <a href={to.users.detail({ id })}>Profile</a>
}

to.users.detail({ id }) returns /users/<id>; a missing parameter is a type error, and so is a literal <a href="/userz/7"> that matches no route (external, #hash and ?query links are fine). Both are TypeScript's errors: qatjs check --no-types skips TypeScript, so it neither writes routes.d.ts nor reports them.