Searching Puzzle

Type to search Puzzle.

Routing

Map URLs to views, wrap them in layouts, nest and guard routes, and navigate in three router modes.

The router is what makes a Puzzle app feel like an application: it maps URLs to views, wraps them in layouts, delivers :param segments to data(), runs guards, and keeps browser history, scroll, and focus honest.

By default the router routes off the URL path. In that mode your server must serve index.html for every app route (the standard history-API fallback); puzzle dev and puzzle preview do it for you. For static hosts where you can't configure that fallback, hash mode carries the route in the URL fragment instead. A site built with output: 'static' has no router at all; see Static Builds.

Defining routes

Routes are an array of plain objects exported from routes.js and passed to PuzzleApp:

// routes.js
import HomeView from '@/views/Home.pzl';
import UserView from '@/views/User.pzl';
import NotFound from '@/views/NotFound.pzl';
import DefaultLayout from '@/layouts/Default.pzl';

export default [
  {
    path: '/',
    name: 'home',
    view: HomeView,
    layout: DefaultLayout,
    meta: { title: 'Home' },
  },
  {
    path: '/user/:id',
    name: 'user',
    view: UserView,
    layout: DefaultLayout,
    meta: { title: 'User Profile' },
  },
  {
    path: '*',
    name: 'not-found',
    view: NotFound,
    layout: DefaultLayout,
    meta: { title: 'Not Found' },
  },
];
FieldTypePurpose
pathstringURL pattern: static (/about) or with :param segments (/user/:id). A top-level path starts with /; '*' is the catch-all.
namestringRoute identifier. Match on names for active states.
viewPuzzleView class or lazy()The view rendered when the route matches.
layoutPuzzleView class or lazy()Layout that wraps the view. Top-level routes only.
childrenarrayNested child routes with relative paths. See Nested routes.
guardfunctionAllow, block, or redirect before anything loads. Covers this route and all its children. See Route guards.
metaobjectHead metadata: title, description, canonical, socialImage. See Head metadata.
transitionMode'sequential' or 'overlap'How this route's arrival animates. See Animations.
prerenderbooleanfalse writes an unrendered shell for this route in prerendered builds. See Static Builds.

Routes match in declaration order, first match wins, so declare a static route like /user/new before /user/:id (development warns when one shadows another). A dynamic segment is a complete :name segment; a : or * inside an otherwise static segment is literal text.

Dynamic segments and params

:param segments arrive as the first argument to the view's data():

// views/User.pzl <script>
export default class UserView extends PuzzleView {
  data(params, props) {
    // /user/42  →  params.id === '42'
    return { user: this.ctx.store.findOne('user', params.id) };
  }
}

Param values arrive as strings. Store lookups don't care: findOne('user', '42') finds the record whose id is the number 42, so no conversion is needed there. Convert only when you compare against numbers yourself.

Params are reactive: navigating from /user/42 to /user/7 re-runs the same view's data() with the new params rather than tearing the view down. You don't watch the URL; just read params in data(). The navigation commits once data() has settled, including any server fetches its store reads trigger.

Layouts and <Slot/>

A top-level route can name a layout: a normal .pzl component whose template contains a <Slot/>. The view is placed exactly where the <Slot/> sits, giving every page shared chrome without repeating markup:

<!-- layouts/Default.pzl -->
<puzzle-view class="shell">
  <header><h1>My App</h1></header>
  <main><Slot/></main>       <!-- the routed view renders here -->
  <footer>Made with Puzzle</footer>
</puzzle-view>

Layouts are full components with data(), events, and lifecycle hooks. Consecutive routes sharing a layout class reuse the layout instance and swap only the <Slot/> content; a different layout class remounts. A paired <Slot>fallback</Slot> shows its body when no child route fills the outlet.

Nested routes

A route can declare child routes with children: [...]. The parent's view then hosts its matched child at its own <Slot/>, the same mechanism layouts use. This builds a shell-with-panes section (a /settings shell whose panes swap while the chrome stays put) without one flat view per URL:

export default [
  {
    path: '/settings',
    name: 'settings',
    view: SettingsShell,      // renders the matched child at its <Slot/>
    layout: DefaultLayout,    // layout is top-level only
    meta: { title: 'Settings' },
    children: [
      { path: '',        name: 'settings-index',   view: SettingsHome },   // matches /settings
      { path: 'profile', name: 'settings-profile', view: ProfileView, meta: { title: 'Your Profile' } },
      { path: 'billing', name: 'settings-billing', view: BillingView },
    ],
  },
];
<!-- SettingsShell.pzl -->
<puzzle-view class="settings">
  <nav>
    <a href="{ link('/settings/profile') }">Profile</a>
    <a href="{ link('/settings/billing') }">Billing</a>
  </nav>
  <section><Slot/></section>   <!-- the matched child renders here -->
</puzzle-view>

Rules:

  • Child paths are relative: they compose onto the parent (/settings + profile becomes /settings/profile). An absolute child path throws at construction.
  • An index child with path: '' matches the bare parent URL. A parent with children but no index child doesn't match its own bare URL; that URL falls through to the catch-all.
  • layout is top-level only: children inherit the chain's layout, and a layout on a child throws.
  • Params merge down the chain: every level's data(params) receives the full merged params object.
  • meta fields resolve nearest-defined, leaf to root: /settings/profile uses the leaf's title, while /settings/billing (no leaf title) inherits 'Settings'.

Navigating between siblings reuses the shared part of the chain: going from /settings/profile to /settings/billing keeps the SettingsShell instance (its data() re-runs with the new params) and only swaps the pane.

The route snapshot: this.route

Inside any routed data() run, this.route describes the navigation that run belongs to: { path, pathname, query, hash, route, params, chain }, where route is the leaf route and chain the root-to-leaf list. Use it for anything derived from "where is the app navigating", most importantly active-nav highlighting:

// a parent view whose <Slot/> hosts several tab panes
data(params, props) {
  const name = this.route.route.name;   // leaf route name of THIS navigation
  return {
    isProfile: name === 'settings-profile',
    isBilling: name === 'settings-billing',
  };
}

Prefer this.route over window.location or router.current for active state: a routed data() runs before the URL commits, so both are one navigation stale in a reused ancestor, and they'd paint the previous tab as active. Match on route names rather than path, which can carry a query string or an #anchor. this.route is null in components the router doesn't manage, so pass route-derived state down as props.

Query strings and replace()

Filters, tabs, search terms, and pagination belong in the URL so they're shareable and survive a reload. The snapshot carries them parsed:

  • query is a frozen object: ?q=cabin gives { q: 'cabin' }, repeated keys become an array (?tag=a&tag=b gives { tag: ['a', 'b'] }), and a valueless key is ''.
  • pathname is the path without query or hash, and hash is '' or the fragment with its leading #.
  • Query values never merge into params; read them from this.route.query.

To write transient state, use router.replace(path): the same pipeline as push(), but it replaces the current history entry instead of adding one and leaves scroll where it is. A replace that reuses the full view chain keeps focus in place too, so typing in a filter field keeps working. A query-only change re-runs data() with the new snapshot:

<input type="search" value={ q } placeholder="Filter…" @input={ updateFilter(event) } />
data(params, props) {
  const q = this.route?.query?.q ?? '';
  const needle = q.trim().toLowerCase();
  const items = this.ctx.store.findMany('item')
    .filter((it) => it.title.toLowerCase().includes(needle));
  return { q, items };
}

events = {
  updateFilter: (event) => {
    const v = event.target.value;
    this.ctx.router.replace(v ? '/items?q=' + encodeURIComponent(v) : '/items');
  },
};

Use push() instead when the change should be a Back-button stop, such as moving between wizard steps.

Route guards

Any route can declare a guard: a function that runs before the navigation constructs views, loads data, or commits anything. A guard covers its route and every child, so guarding a top-level route locks down its whole section:

// routes.js
const requireAuth = ({ to, ctx }) => {
  if (ctx.store.findMany('session').length === 0) {
    return '/login?redirect=' + encodeURIComponent(to.path);
  }
};

export default [
  { path: '/login', name: 'login', view: LoginView, layout: MainLayout },
  {
    path: '/account',
    name: 'account',
    view: AccountShell,
    layout: MainLayout,
    guard: requireAuth,        // locks /account and every child below it
    children: [
      { path: '',      name: 'account-profile', view: ProfileView },
      { path: 'admin', name: 'account-admin',   view: AdminView, guard: requireAdmin },
    ],
  },
];

guard({ to, from, ctx }) receives the destination and current route snapshots (from is null on the first load) and the app context. What it returns decides the navigation:

ReturnEffect
undefined / trueAllow. The next guard in the chain runs, then the normal load and commit.
falseBlock and stay put. Nothing changes: no URL, history, title, view, or scroll.
a path stringRedirect. A denied link click or push() redirects with push(), so Back still returns to the page the user came from; a back/forward or first-load redirect replaces the current entry. The denied URL never enters history.
  • Guards run on every navigation, including back/forward, params-only and query-only changes, and the first load. A child's own guard runs after its parent's; the first non-allow verdict wins.
  • Guards may be async, and a guard that throws is logged and treated as a block. Restore a session in the app's beforeMount hook, which runs before the first navigation, so guards can stay quick synchronous store reads.
  • For redirect-after-login, the login view reads this.route.query.redirect after sign-in and calls this.ctx.router.replace() with it.
  • Guards are UX, not security. Your API must authorize every request itself. Prerendered pages are public files, so hybrid and static builds warn about guarded routes.

Head metadata

A route's meta carries four reserved head fields, each a static string (title and description may also be { t: 'key' }):

{
  path: '/',
  name: 'home',
  view: HomeView,
  layout: DefaultLayout,
  meta: {
    title: 'Puzzle Press',
    description: 'Notes on building the Puzzle framework.',
    canonical: 'https://example.com/',
    socialImage: 'https://example.com/og/home.png',
  },
},
  • Each field resolves on its own, nearest-defined from the leaf route up to the root. null suppresses an inherited value. Define defaults on your root routes so a child never shows a stale inherited value.
  • In the browser, the router sets document.title on every navigation.
  • description, canonical, and socialImage become the description, canonical, Open Graph, and Twitter tags, and only prerendered builds write them, once per page at build time. They are never updated at runtime, which is fine because crawlers and link unfurlers fetch each URL fresh. In a plain SPA build these three are accepted but inert.

Scroll and focus

By default the router manages window scroll: a new route starts at the top, and back/forward restores where you were. Saved positions survive a full page reload. You don't wire anything up.

NavigationDefault scroll
push() / linkScroll to top.
push() to a path with an #anchorScroll to that element; top if it isn't present.
replace()Untouched.
Back / forwardRestore the saved position; top if none.
First loadUntouched: the browser owns it.

Turn it off entirely with scrollBehavior: false (useful when your shell scrolls an inner panel rather than the window), or pass a function to decide per navigation:

const app = new PuzzleApp({
  target: '#app',
  routes,
  scrollBehavior: (to, from, savedPosition) => {
    if (savedPosition) return savedPosition;                 // back/forward
    if (to.path.startsWith('/account') && from?.path.startsWith('/account')) return null;
    return { x: 0, y: 0 };                                   // everything else: top
  },
});

The function returns { x, y } to scroll there, or a falsy value to leave scroll alone. savedPosition is non-null only on back/forward.

Focus works the same way. After each committed navigation the router focuses the incoming view's root (without scrolling and without drawing a focus ring) and announces the new title in a visually hidden live region. focusBehavior: false turns both off, and a function lets you choose the element to focus. The first load, memory mode, and static output skip it.

Lazy route views

Wrap a route's view or layout in lazy() to defer resolving it until navigation. With code splitting enabled, its module downloads on first navigation:

import { lazy } from '@magic-spells/puzzle';

export default [
  { path: '/', name: 'home', view: HomeView, layout: DefaultLayout },
  { path: '/admin', name: 'admin', view: lazy(() => import('./views/Admin.pzl')), layout: DefaultLayout },
];
  • The loader runs after guards allow the navigation, so a blocked route never downloads its code. Every lazy level of the matched chain loads in parallel.
  • There's no loading UI to write: the previous view stays on screen until the new one commits. A failed download is a failed navigation that commits nothing, and it's retried on the next attempt.
  • To split the view into its own file, set build: { splitting: true } in puzzle.config.js; otherwise the dynamic import is bundled into app.js.
  • A bare function in a view position is an error that points you at lazy().

Router modes

The router runs in one of three modes. Path routing is the default; hash and memory routing are imported factories, so apps that don't use them don't ship them.

Path mode (default)

Routes off the URL path. It needs the index.html fallback on your server. Nothing to configure: omit routerMode.

Hash mode

For static hosts you can't configure, such as GitHub Pages, an S3 bucket, or file://. The route rides in location.hash, so no server rewrite is needed:

import { hashRouter } from '@magic-spells/puzzle/router-modes';

const app = new PuzzleApp({
  target: '#app',
  routes,
  routerMode: hashRouter(),   // route lives in location.hash
});

Your code stays path-shaped in every mode: route definitions, push('/user/123'), router.current.path, and params.id are all unchanged, and hrefs built with link() become #/user/123 on their own. A bare <a href="#faq"> stays a native in-page anchor, but clicking it replaces the whole fragment and clobbers the route from the URL (the view survives and Back returns you), so hash-mode apps should avoid bare-anchor links. A leftover mode string such as routerMode: 'hash' throws at construction and names the import to use.

Memory mode

The route lives entirely in router state: location, history, and document.title are never touched. It's for tests and embedded or iframe apps that must not clobber the host page's URL or title:

import { memoryRouter } from '@magic-spells/puzzle/router-modes';

const app = new PuzzleApp({
  target: '#app',
  routes,
  routerMode: memoryRouter({ initialPath: '/dashboard' }),   // initialPath defaults to '/'
});

Back/forward is programmatic here (router.back(), forward(), go(n)), meta.title doesn't set the document title, and scroll and focus management are inert. Link interception is document-wide in every mode, so an embedded app should keep its links scoped.

Deploying under a sub-path

Deploying under a sub-path, like example.com/myapp/…, takes one config line. It works in path and hash modes and is inert in memory mode:

const app = new PuzzleApp({
  target: '#app',
  routes,
  routerBase: '/myapp',   // leading '/' ensured, trailing '/' trimmed
});

Your app code stays base-free: route definitions, push('/user/1'), router.current, params, and this.route never mention the base. Hrefs are real document URLs, so they need it; the link() function adds it for you ({ link('/user/1') } renders /myapp/user/1), or write the base or a relative href by hand.

404 / catch-all routes

Declare an optional catch-all with path: '*'. It always matches last, wherever it appears in the array:

import NotFound from '@/views/NotFound.pzl';

export default [
  { path: '/', name: 'home', view: HomeView, layout: DefaultLayout },
  { path: '*', name: 'not-found', view: NotFound, layout: DefaultLayout, meta: { title: 'Not Found' } },
];

Without a catch-all, an unmatched URL logs a warning and the current view stays put. In prerendered builds, the catch-all also renders to dist/404.html, the file static hosts serve for unknown paths.

Next