Skip to content

Adding a Page

Claude edited this page Nov 12, 2026 · 2 revisions

Checked against v0.7.6 on November 13, 2026.

Adding a page

A page in Kestrel is a route, a Jinja template and, when it needs behavior beyond htmx, a script. Since 0.7.0 every page script runs on a page lifecycle, because a click on the sidebar no longer loads a new document. The window, the sidebar and the scene art stay, and only the content is swapped (in-place navigation). A page therefore has to start cleanly, stop cleanly, and start again without doubling anything. This page is the contract: the template blocks, KUI.page, what may run at the top of a script, how navigation and history treat a page, and the leak test every page copies. Related pages: Architecture overview, Testing, Contributing, Benchmarking (the Model check page is a small worked example).

The runtime is kestrel/web/static/js/kestrel-ui.js. Read its two comment-headed sections, "page lifecycle" and "in-place navigation", before changing either.

The template

A page template extends base.html and fills four blocks. This is the head of kestrel/web/templates/bench.html:

{% extends "base.html" %}
{% block title %}Model check · Kestrel{% endblock %}
{% block legacy_css %}<link rel="stylesheet" href="{{ static_url('css/shell.css') }}">{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="{{ static_url('css/models.css') }}">{% endblock %}
{% block page_name %}bench{% endblock %}
{% block page_scripts %}<script src="{{ static_url('js/model_combo.js') }}" defer></script><script src="{{ static_url('js/bench.js') }}" defer></script>{% endblock %}
{% block content %}
Block Rule
page_name The page's name. base.html writes it into the content root, <main class="container" data-k-page="bench">, and the script defines the same name. The default is page, which nothing defines, so a template without a name mounts nothing.
page_scripts The page's script, defer. base.html places this block after kestrel-ui.js and palette.js and before Alpine, so KUI.page.define exists when the script runs. Do not put the script in head_extra: it would run before kestrel-ui.js and KUI would not be there.
legacy_css, head_extra Stylesheets. A converted screen overrides legacy_css with its own sheet (or nothing, to drop kestrel.css) and adds more in head_extra. All colors come from theme tokens (css/tokens.css).
content The page body, inside <main>. In-place navigation swaps this element's children.

Rules that go with the blocks:

  • Every static file is {{ static_url('path') }}, never a bare /static/.... The URL carries the build's fingerprint and is cached for good. tests/test_static_cache.py fails on a template link without it.
  • A partial the content includes may carry its own <link rel="stylesheet"> or <script src> (the model picker's script is one). In-place navigation loads those ahead of the swap so they are ready when the content arrives.
  • A route must answer a plain GET with the whole page. See Navigation below.

The script

A page script defines its page and starts nothing at the top. This is kestrel/web/static/js/models.js, trimmed:

(function (root) {
  'use strict';
  var doc = root.document;
  if (!doc || !root.KUI || !root.KUI.page) return;

  function onSortClick(e) { /* ... */ }
  function onMenuClick(e) { /* ... */ }
  function closeMenus() { /* ... */ }
  function onKeyDown(e) { if (e.key === 'Escape') closeMenus(); }

  root.KUI.page.define('models', {
    mount: function (main, ctx) {
      ctx.on(doc, 'click', onSortClick);
      ctx.on(doc, 'click', onMenuClick);
      ctx.on(doc, 'keydown', onKeyDown);
      ctx.on(root, 'scroll', closeMenus, true);
      ctx.onUnmount(closeMenus);  // an open row menu is fixed to the viewport: it goes with the page
    }
  });
})(window);

KUI.page

Call Meaning
KUI.page.define(name, { mount(root, ctx), unmount() }) Registers the page and starts nothing. mount is required (a TypeError without it); unmount is optional. A second define of a name replaces the definition for the next mount.
mount(root, ctx) Called with the content root (<main data-k-page="...">) and a context that owns everything the page starts.
ctx.signal An AbortSignal, aborted at unmount. Pass it to fetch.
ctx.on(target, type, fn, options) addEventListener tied to the signal. options is a boolean (capture) or { capture, passive, once }. Returns an off() function. An identical second registration is counted once, as the browser would.
ctx.every(ms, fn), ctx.after(ms, fn) setInterval and setTimeout, cleared at unmount. Both return the timer id, and ctx.clear(id) stops one early.
ctx.observe(observer) Calls observer.disconnect() at unmount and returns the observer. Calling its own disconnect() early also lets the context forget it.
ctx.onUnmount(fn) Any other cleanup. Cleanups run last to first.
KUI.page.start() base.html's ready path. Mounts the document's page once; does nothing if a page is already mounted.
KUI.page.mount([name, root]), unmount() The same steps for the navigation controller and the leak tests. mount() mounts the page [data-k-page] names, or a given one, and unmounts whatever was mounted first, so only one page ever runs.
KUI.page.current(), KUI.page._stats() The mounted name, and { name, listeners, timers, observers } live counts for leak tests.

Unmount order: the definition's unmount(), then the signal aborts (every ctx.on listener and any fetch given the signal), timers are cleared, observers disconnect, and the onUnmount cleanups run. A throw in mount or unmount is rethrown on a fresh task, so it still shows as a page error, and never stops the rest. Once unmounted, a context starts nothing: every and after return 0, on does nothing, observe disconnects at once and onUnmount runs at once.

base.html mounts the document's page once at DOMContentLoaded, after every deferred script, page scripts included, has run. The listener is added while the head is parsed, ahead of htmx's own start, so the page still hears htmx's first htmx:load events.

What may run at the top level

Only KUI.page.define(...) and pure helper definitions: functions and constants. Every listener, timer, observer, poll, history write and one-shot start-up goes into mount and is tied to ctx. Document- and window-level listeners go through ctx.on.

tests/test_page_lifecycle_g1.py enforces this by reading the scripts as text, with comments removed: each must define its page, and none may contain addEventListener, setInterval, setTimeout, clearTimeout, clearInterval, DOMContentLoaded, MutationObserver, ResizeObserver, pushState or replaceState. It also checks that each page's template names itself and loads its script after kestrel-ui.js and before Alpine. Follow the same rule for a new page.

Shared singletons are never run per page: kestrel-ui.js, palette.js, htmx, the Alpine root (kChrome), the bell, the sidebar status poll. model_combo.js is one too: it binds each picker once (a WeakSet), guards its own definition, and does not use KUI.page, because it belongs to no page.

Rules learned migrating the existing pages:

  • Make each handler a named top-level function and list the ctx.on calls in mount in the order the file used to add them. A capture-phase guard must stay ahead of the click it guards (Profile's leave guard sits ahead of its tab click).
  • Keep per-visit state in top-level vars that mount resets, and keep the context (cx = ctx) for helpers that start timers.
  • A fetch takes signal: ctx.signal, and its handlers return when signal.aborted. Give it a .catch, or an aborted fetch surfaces as an unhandled rejection. An action that must outlive the page, such as a toast's Undo, deliberately does not use the signal.
  • A flag set on an element (el.__x) blocks a second mount on the same nodes. Use a per-mount WeakSet or list.
  • A ctx.on on an element the page later replaces holds that element until unmount. Keep its off() and call it when the element leaves.
  • A per-visit global (window.kLeaveGuard, a tour object) is set in mount and removed in onUnmount, and only if it is still the page's own.
  • An inline <script> in a partial that htmx swaps in must scope its listeners to the swapped element, so a later swap does not double them. G4_LISTENER_PROBE_JS in tests/browser.py counts live listeners on matching elements for this.

Navigation

The controller is KUI.navigate(url) in kestrel-ui.js. Architecture overview lists its steps. What a page author needs:

Every route must answer a plain GET with the full page. The controller fetches with Accept: text/html and no HX-Request header. A route that returns a fragment for an htmx request (GET /bench checks request.headers.get("HX-Request")) must return the whole page otherwise. A reply that is not a Kestrel page (no main.container[data-k-page], not text/html, another origin) makes the window do a classic page load instead.

Classic page loads. Put data-k-reload on a link, or on a container, to force a full load (the track switches use it because the sidebar labels change). Settings > Preferences > Classic page loads (ui.classic_nav, data-k-nav="0" on <html>) turns the controller off for everyone who needs it. HX-Redirect replies stay full loads. Another build of the app, a different set of sidebar pages, a page script that is not on the lifecycle, a failed fetch and assets that take over 8 seconds also fall back.

Scripted navigation. Use KUI.go(url) in a page script, the palette or a toast action, never location.href = url. It changes the page in place when the controller is on and falls back to location.assign when it is not. Both KUI.go and KUI.navigate(url, { pop, replace }) return a promise that resolves true when the page changed in place and false otherwise (a classic load started, or the leave guard refused). go also takes { guarded: true } when the caller has already asked the leave guard. Pipeline's go() helper and the Help link in role.js are the models:

function go(url) {
  if (root.KUI && root.KUI.go) root.KUI.go(url); else root.location.href = url;
}

The leave guard. A page with unsaved edits sets window.kLeaveGuard = fn in mount and removes it in onUnmount (Profile does). fn returns false to refuse. The controller asks it before a click, a palette jump or a KUI.go, and again if the page was edited while the next one loaded. Back and Forward are refused by undoing the move with history.go, so the page keeps its edits.

Leaving. The controller dispatches a k-page-leave event on document before it reads the next page, so a page holding back a save can send it first. Sources listens with ctx.on(doc, 'k-page-leave', flush).

Focus and scroll. After a change the new page's <h1> takes focus (data-k-landing) unless the person is using something else, and the controller restores each entry's scroll position.

htmx history entries and the history stamp

Every history entry made while the app is open is stamped history.state.kNav = { inst, idx, kind }, whoever makes it. inst names the page instance, idx orders the entries, and kind is one of:

Kind Made by Back or Forward to it
doc The controller, for a page it showed Shown again in place.
hx htmx, from hx-push-url Shown again in place (see below).
page The page's own history.pushState (Pipeline's ?open=) The page on screen restores it with its own popstate listener, registered with ctx.on(root, 'popstate', ...).

An htmx entry is the pattern for a tab or a Prev and Next control that swaps part of the page and still gets a real URL. The link carries an href and an hx-get for the same address, and hx-push-url="true". This is the Prev link in partials/role_body.html:

<a class="k-btn k-btn--sm" href="/opportunities/{{ seq.prev }}" hx-get="/opportunities/{{ seq.prev }}"
   hx-target="#rl-body" hx-swap="outerHTML" hx-push-url="true">‹ Prev</a>

The controller removes htmx's own htmx flag from such an entry (so htmx's body-snapshot restore stands down, and htmx's history cache is turned off). Back to it fetches that URL as a full page and swaps it in place. That is why the same address must answer a plain GET with the full page: the fragment route and the page route are one URL. A page that writes its own history entries (Pipeline's history.pushState({ pl: id }, '', url)) does so only while mounted and reads them in its own popstate listener. The controller adds kNav beside the page's state object, so the page's fields survive.

The leak test

Every page has a remount test, written in its *_browser.py file and gated like the other live-browser tests (KESTREL_LIVE_BROWSER=1; Edge if present, else a Chromium, launch_sync in tests/browser.py). Two helpers do the counting:

  • TIMER_PROBE_JS is an init script. Add it with page.add_init_script(TIMER_PROBE_JS) before goto. It records every timer and the call stack that started it, so the check can tell what the page's own script left pending or fired. A timer htmx starts for a declarative poll belongs to htmx and goes with its element.
  • assert_page_remounts_clean(page, name, script, settle_ms=2600, quiet_ms=3000) starts from the page base.html mounted. It checks that KUI.page.current() is name, waits settle_ms for one-shot entrance timers, and reads KUI.page._stats() (the first mount must hold at least one listener). It then unmounts and asserts the stats equal { name: None, listeners: 0, timers: 0, observers: 0 }, that no timer from /static/js/<script> is pending, and that none fires during quiet_ms. It mounts again and asserts the stats equal the first mount's. It returns the first mount's counts.

A typical test, from tests/test_models_browser.py:

page.add_init_script(TIMER_PROBE_JS)
page.goto(f"{base}/models")
page.wait_for_selector(".mo-page")
wait_for_layout(page)
first = assert_page_remounts_clean(
    page, "models", "models.js", settle_ms=400, quiet_ms=600)
assert first["timers"] == 0 and first["observers"] == 0

Then add one interaction that a doubled listener would break: one j moves one row, one fold click opens one fold, one click on a column header sorts once. A page with no listeners of its own, such as Model check, cannot use the helper (it requires a listener on the first mount) and checks KUI.page._stats() directly in its own test.

tests/test_page_lifecycle_g1.py is the cloud-safe companion: it needs no browser. tests/test_nav_browser.py covers navigation itself: a sidebar change swaps in place and Back and Forward follow, the scene art stays when the next page draws the same scene, a page's own history entries still work after an in-place arrival, unsaved Profile changes hold a sidebar click, the palette and Back, Classic page loads and data-k-reload load a new document, a reply that is not a Kestrel page loads the classic way, and every sidebar page changes in place and comes back with one set of listeners.

Checklist for a new page

  1. Template: page_name, page_scripts (after kestrel-ui.js), stylesheets in legacy_css or head_extra, every file through static_url.
  2. Script: KUI.page.define and nothing else at the top; every listener, timer, observer and fetch tied to ctx.
  3. Route: the full page for a plain GET, a fragment only for HX-Request.
  4. Links: plain <a href> for another page; data-k-reload only where a full load is needed; KUI.go instead of location.href.
  5. History: hx-push-url entries use the same URL for the fragment and the page; a page's own pushState has its own popstate listener through ctx.
  6. Tests: the remount leak test in the page's browser test, one doubled-listener interaction, and the page named in tests/test_page_lifecycle_g1.py if it joins that group.
  7. Run uv run --extra dev python scripts/check.py and push only when it ends with Ready to push.

Clone this wiki locally