# lib/web — the shared browser design system

The tokens, base rules, app shell, `bf-*` components, HTML atoms, and client
runtime the two loopback pages draw with: the plan review
([`../../extensions/plan/web-page.ts`](../../extensions/plan/web-page.ts)) and
file browse ([`../../extensions/file-browse/view/styles.ts`](../../extensions/file-browse/view/styles.ts)).
The module-by-module inventory is the `web/` row of [`../README.md`](../README.md);
this file is the conventions those modules exist to make easy.

Both pages serve a same-origin document through the shared HTTP layer
([`../http/index.ts`](../http/index.ts)) under one CSP. The kit is the one policy
for how that document looks and moves — a second palette, focus ring, or dialog
is the bug this directory prevents.

## Compose the layers in order

A page calls `pageSheet(own)` ([`sheet.ts`](./sheet.ts)) and passes only its own rules: the
function lays down `WEB_BASE_CSS`, `WEB_THEME_CSS`, `WEB_LAYOUT_CSS`,
`WEB_COMPONENTS_CSS`, then the page's sheet. The order is the contract — a page
overrides a kit class at equal specificity, which only a later rule can — and it is
written once, so a fifth layer is one edit. Each block appears **once**: a repeated
block still renders, so only a count catches it, and every page suite counts its own
stylesheet (`pages.test.ts`, `web.test.ts`). A page rule is namespaced (`review-*`,
`browse-*`) and overrides a kit class rather than re-declaring it.

## One browser runtime, spliced in

Three surfaces render pages from a bundle held as a template literal, and each had written
the same three helpers for itself: an element builder, a "did this key land in a field?"
test, and a status line's paint. No type checker and no AST scan compares text inside a
string, so the plan's `el(tag, className)` and the board's `el(tag, className, text)` were
two builders, and the plan compared `INPUT` where the board lowercased the tag.

`client-runtime.ts` holds one body of each, as ordinary TypeScript, and exports
`CLIENT_RUNTIME_JS` — the eight functions as source, in the order a client reads them. A
page carries it the way it carries `plural` and its class table: the source crosses the
boundary, and the page runs the function instead of a copy of it.

The bodies are JavaScript on purpose — no annotation survives into the string, and no
backtick or `${` may appear in one. The DOM is reached through `globalThis`, because this
project compiles without a DOM lib; the cast names the guarantee the page makes.

What stays page-side: what a state *says*. `paintStatus` owns the text, its tooltip, and
the `bf-status--<tone>` class; `paintLive` owns the live state's tone modifier, its word,
and its tooltip — and the board composes `live · 3m` while browse puts the stream's own
`up 2m 14s · 37 requests` in the hover. A shared runtime that also decided the wording
would be a second copy of the page's voice.

`liveStream` draws that same line for the stream itself: one state machine, the page's
words. `connecting` is a stream that has not opened; `live` is one that has, which a frame
proves as well as an open event; `reconnecting` is a live one whose connection went while
the browser retries by itself; and `dead` is `attempts` failures in a row with no opening
between them — the one state a page answers with its `⟳ reload`. Counting attempts rather
than starting a clock is what makes a blip a word and not a reload, and a stream that never
comes back stops reading as `reconnecting` forever.

The two things a page would otherwise decide for itself ride the same call: the stream's
URL carries the page's `token`, appended here so no page splices a query of its own — a page
with none, like browse, passes `undefined` and says so — and the stream closes on
`pagehide`, which is the one teardown a browser leaves to the page.

## One toolbar, one bar, one footer

A served page's chrome is a fixed head and foot with one scroll box between them, and each
band has one job:

- `.bf-app__head` is two rows, split by a plain `.bf-app__rule`, on the page's own canvas and
  closed by one hairline: a bar above a flat sheet needs no elevation of its own. One atom writes
  it, `appHead`: a page passes its name, its subject, its facts and its controls, and a head with
  no control row is one row and gets no rule. `.bf-app__id`
  carries the lockup, the subject (`pageSubject`: mono, grows, truncates its head so a path keeps
  the folder being read), the live line and the reload, with `.bf-app__chrome` (key sheet, theme
  toggle) at the end; `.bf-app__ctl` is the page's own controls and nothing else, and a page adds
  its own class to either row with `identityClass` / `controlsClass`.
- `.bf-app__main` is the only scroller, so a lane's head or a column's caption pins to it.
- `.bf-app__foot` is one `.bf-footer__facts` line naming where the content came from and
  what it holds. It wraps rather than truncating, and it states no fact the head owns: the
  live state is the head's, not a footer clause.

The live state is `liveChip` plus `reloadChip`, and neither is a pill: a glyph and a word in
the tone's own colour, and a rule is what a state earns only when it is a tag. The line is
not a live region — the header is where a reader looks for the state, not a place to
announce every repaint — and the reload is the one action a page whose stream has gone can
offer. It is a control rather than a confirm dialog because nothing here has a consequence
to confirm: nothing is unsaved, and a modal over a stale page covers what the reader can
still use. Reloading is not a write, so the rule that a served page offers no write
surface holds.

## A body crosses as page source

A page holds a helper's *body*, under its own name: a fragment splices one function's source, because
a bundle has no import graph. The host transpiles an extension before it runs it, though, and it
rewrites a call to an **imported** binding into a member of that module's namespace — `sameLabel(a, b)`
becomes `(0, _sessionLabel.sameLabel)(a, b)` — so a body written in one module and needed in another
reached the page calling a module nothing holds: `_sessionLabel is not defined`, on the first paint,
with every static check green, because `bun`'s transpiler leaves the call site alone.

`pageSource` ([`../format.ts`](../format.ts)) writes the member back to the name it exports, in both
forms a body can use, so a spliced body may call a helper the page also holds whatever module declares
it — which is what the class table and the Markdown renderer already assumed. A default import it
refuses rather than splicing a page that throws: the local name it stood for is gone, and a body that
needs one belongs with it.

Every `*_JS` constant crosses through it, and [`test/spliced-bodies.test.ts`](../../test/spliced-bodies.test.ts)
holds each site to that.

## One inline Markdown renderer, spliced in

Two served pages read Markdown written by a model or a person: the plan review's document
and the board's card notes. Both need the same two answers — what an inline token is, and
which target a link may point at — so `markdown.ts` holds one body of each and exports
`INLINE_MARKDOWN_JS` for a bundle to splice. The review page's block half
([`../../extensions/plan/web-markdown.ts`](../../extensions/plan/web-markdown.ts)) calls
`renderInline` for the text inside a block; the board calls it for each note. A page that
writes its own is how one of them starts accepting a `javascript:` target the other refuses.

The renderer appends a text node or one of four atoms — `code`, `strong`, `em`, `a` — and
never parses markup, so the board's rule that a stored field is never `innerHTML` holds with
Markdown in play. A link is made only when `safeHref` allows the target: `http`, `https`, or
`mailto`, no credentials, and no protocol-relative or disguised relative target, resolved
against the page's own URL at call time.

The body is JavaScript on purpose, like the runtime's: no annotation survives into the
string, and no backtick or `${` may appear in one. It is the inline half only; the block half
is `markdown-blocks.ts`, the one scan a plan and a README share — a card note is one
sanitized line, so inline is the whole of it.

## Name a class once, in a table

A page's document is TypeScript and its client is a string inside a template literal, so
the two halves cannot import from each other: a class name used to be a literal in each,
and one assembled at runtime (`"board-card__reason" + kind`) could not be found by
reading either half. That is how a class reaches a stylesheet with no rule behind it —
an unstyled element, and nothing fails.

So a page declares its vocabulary once, in a `ClassNames` table beside its own modules,
and both halves read it: the document interpolates `${N.toolbar}`, the bundle carries
`namesScript(table)`. A name is then a symbol, and a test can compare the set a page
wears with the set its stylesheet draws, in both directions.

`namesScript` is the boundary, and it throws rather than trusting a caller: a value must
be `KEBAB` — lowercase, hyphenated — because the table is spliced into a template
literal, and a backtick would end the string while `${` would interpolate at build time.
The global it binds must be a JavaScript identifier. The table's *keys* are the page's
own English; its *values* are what CSS matches, and nothing else in the page may spell
one.

## Color is a role

`WEB_THEME_TOKENS` is the terminal's palette, per appearance, derived in `tokens.ts` from
`themes/bytefly-dark.json` and `bytefly-light.json`: a page and the terminal are one product, so a
TUI theme change restyles both. What a page states for itself is what a glyph grid cannot — see the
derivations below. The *shape* of the contract is what the kit keeps: one token name, one value per
appearance, and every component reading `var(--token)`.

A surface that cannot import TypeScript carries a **copy** of that palette, and a test holds it to
the owner: the documentation site ([`docs/assets/css/site.css`](../../docs/assets/css/site.css),
`test/theme.test.ts`) and the posting cards
([`assets/cards/cards.css`](../../assets/cards/cards.css), `scripts/cards.test.ts`), where Pages
serves the stylesheet as written and a poster opens from `file://`. The montage
(`scripts/shots/video.ts`) imports the tokens, and the tool gallery keeps the terminal's theme,
because its frames are the terminal.

What a theme cannot state, the kit derives, so no appearance can hand-pick it and drift:

- `--accent-soft` — the accent at 15% (dark) or 10% (light), for a selection or the active nav row.
- `--search-soft` — the theme's search highlight, stepped 40% (dark) toward `--canvas` and left as
  the theme's value in light. A terminal states that colour as a background behind its own
  foreground; the page sets 12px `--muted` on it as the plan lane's paper, where the theme's value
  reaches 4.05:1. The step puts it at 4.97:1 and keeps the amber.
- `--raised` — `--surface` mixed 6% (dark) or 3% (light) toward `--text`, for a block that has to
  read as a plane above the page rather than as an outline. The step is per appearance because one
  that reads on a dark canvas is invisible on a white one, and the light accent drops under AA at
  the dark one.
- `--dim` — `--muted` mixed 4% (dark) or 8% (light) toward `--canvas`. The theme's own `dim` is a
  terminal's 3:1 grey and reaches 4.08:1 on a raised plane, so this row is a step rather than a
  copy; the test holds the step to its inputs, because dark clears the floor by 0.14:1.
- `--border`/`--border-strong` — `--canvas` mixed 16%/26% (dark) or 11%/20% (light) toward
  `--text`. A terminal draws its borders on a cell grid at 3:1, which a page reads as a frame: every
  separator, record and footer took that weight, and the chrome read heavier than the content it
  held. The pair is a hairline and a step above it, so a separator and a border that means something
  can still be told apart; the case pins each step to its inputs and the ratio band it produces.

`--on-accent` (the canvas colour, because a label on the accent fill is a label on the page's own
paper), `--scrim` and `--shadow-1`/`--shadow-2` (elevation) are stated per appearance. No component
here takes `--shadow-1`: it is the docs site's overlay step, its search results and the drawer a
phone opens its nav in, and `test/theme.test.ts` pins the site's one `--shadow` to it because Pages
serves that stylesheet as written. A dialog takes `--shadow-2`. A card takes neither: it is a tint
and a hairline on the page's own plane, so nothing floats under a sheet that is part of the page. A
component may name one of the two shadows and nothing else; a literal blur fails the same test a
literal hex does.

**The face is part of the role.** `--font-ui` carries every label, control and heading, and
`--font-mono` is kept for what *is* code — a command, a card id, a file path, a key — because a
reader recognises those by their even spacing. A monospace button reads as a terminal key, and
an uppercased mono label reads as one twice.

Components read tokens only: no literal hex or `rgba()` in `components.ts`, and a
test fails one. Contrast is asserted, not assumed — text, muted, and accent at
4.5:1 on both surfaces, the primary label at 4.5:1 on the accent fill, `--dim` at
4.5:1 and never closer than 0.94 to `muted`, and the status colours at 3:1.

The theme layer emits the dark palette at `:root`, the explicit light override,
the system-light fallback, the `tok-*` syntax rules, and **last** a print block
that resets to the light palette: paper is white whatever the screen shows.

## The shell

`.bf-app` is a definite-height column — `100vh`, then `100dvh` — so the header,
sidebar, and main pane scroll inside it instead of the document. `.bf-app__body`
is a 260px sidebar plus main; at `SIDEBAR_COLLAPSE_MAX` (860) the sidebar becomes
a `<details>` disclosure and the page returns to normal scrolling. That collapse is
one body, `collapsedShell(maxWidth, own?)`: the shell ships it at 860, and a page whose
outline needs the room earlier asks for it at its own width — the plan review does, at
`1180` — passing its rules for that width as `own`, which land after the shell's inside
the same query. The narrow header is a second body, `narrowShell(maxWidth)`: the subject
takes a row of its own and a filter spans the control row. Keeping them apart is what lets
a page take the collapse early without turning a wide header into three rows — the body
has a pane, and the header has the window, so the two widths are different questions. A
page's other breakpoints (`820`) stay in its own stylesheet, since a media query cannot
read a custom property.

The collapse is a media query on purpose, and the reason is worth a paragraph because the
temptation recurs. `.bf-app` is a full-width flex column and `.bf-app__body` is its child, so the
body's inline size is the viewport's on every page — the pane and the window are one rectangle. A
container query also styles a container's descendants and never the box it queries, so the body's
own grid could not sit inside an `@container` keyed on the body; moving only the sidebar would
leave the grid on a media query, two mechanisms for one behaviour. The frame is the shape that
pays for itself: `.browse-measure .bf-md>.md-table-frame{container-type:inline-size}` with
`@container (max-width:600px)` in
[`../../extensions/file-browse/view/styles.ts`](../../extensions/file-browse/view/styles.ts) — a
box that really can be narrower than the window, because that page's sidebar takes the rest, with
a browse case pinning both strings. Neither number is derived, and saying so beats arithmetic:
`--measure-prose` is `78ch`, so 860 is a judgement written once in `SIDEBAR_COLLAPSE_MAX`, and
1180 is a product judgement written once in `PLAN_COLLAPSE_MAX` — the review needs the measure
more than it needs its outline beside it.

A `<details>` lays its content out in a wrapper with no definite height, so a
sidebar that must scroll on its own box positions its panel absolutely rather
than making the panel a flex child. `file-browse` does this; the rule and its
reason are in `layout.ts`.

## The `bf-*` kit

`bf-` marks the kit: brand and mark, toolbar and `bf-spacer`, title, context, buttons
(`--primary`, `--ghost`, `--icon`, `--danger`, `--sm` for one inside a line of text),
tags and their tones, tabs, field and input (`--button` is the prompt line a control
wears when it opens one), textarea, panel, gauge, status, note, badge, empty state,
dialog (head, body, actions, status, input, list, option), shortcut sheet and `bf-kbd`,
tree, crumbs, table and sort, record, row, lane, section, live state and reload, code,
media, Markdown body, comment, composer, and quote chip.

Four of those are renames: what the kit called a chip is a tag, a segmented control is a
tab, progress is a gauge, and a card is a record.

States are attributes, not classes, wherever a control has them:
`aria-pressed`, `aria-current`, `aria-sort`, `aria-expanded`, `hidden`. The base
layer's `[hidden]{display:none!important}` is what lets a `display:flex`
component disappear — do not add a page rule to hide it again.

## Element and script contracts

These names are one agreement between a page, its client, and tests:

| Contract | Owner |
|---|---|
| `#theme-toggle` with a `.theme-glyph` | `themeToggle()` (`markup.ts`) |
| `THEME_JS_PATH` served by both routers | `runtime.ts` |
| `pi-web-theme` in `localStorage` | `WEB_THEME_STORAGE_KEY` |
| `#keys-dialog` (hidden, `aria-modal`) and `#keys-close` | `keysSheet` (`markup.ts`) |
| `#keys-open` | `keysButton` (`markup.ts`) |
| `.bf-live` with a `.bf-live__text` child, and `#reload-hint` | `liveChip` / `reloadChip`, painted by `paintLive` (`client-runtime.ts`) |
| the page's own sheet trigger id | `keysDialogScript(triggerId)` |
| `window.bfKeys` — `open` / `toggle` / `close` / `isOpen` | `dialogScript` |

`dialogScript(options)` is the one modal implementation: it opens and closes,
closes on a backdrop click, traps `Tab` inside the panel, closes on `Esc` in the
capture phase (so a page's keymap cannot peel a different layer first), restores
focus to whatever opened it, and exposes `window[globalName]`. It renders nothing
when the element is absent, so a page can embed it unconditionally. A page adds
only its own confirm button's listener.

`THEME_JS` is the pre-paint bootstrap and lives in the head; `THEME_TOGGLE_JS`
paints the glyph, follows the system until the reader chooses, and then keeps the
choice. Neither page reloads for a theme.

## Markup atoms and escaping

`docHead`, `appHead`, `markIcon`, `tabTitle`, `themeToggle`, `chip`, `button`,
`keysSheet`, `keysButton`, `liveChip`, `reloadChip`, and `pageFooter` return strings.
`appHead` is the header's one entry: the lockup, the subject and the chrome zone are its own
parts, so a page names its product and subject rather than drawing the rows. `docHead` links the
mark as the tab icon — two SVG
data URIs from the same blocks the lockup draws, the dark one plain and the light
one behind `prefers-color-scheme` — because an icon is its own document and
cannot read the page's tokens.

`tabTitle` is where the three served pages' tab titles agree: `<page> · <subject> ·
<count>`, the page's name lowercase and the same word `appHead`'s `product` carries, a part
the page does not have left out rather than drawn empty. The board's count is live, so
its page repaints the title on every frame and the body crosses into the bundle as
`TAB_TITLE_JS`, the way `plural` does — one shape for the string, not two. Every dynamic **value** goes through `escapeHtml` from
[`../escape.ts`](../escape.ts); the fields documented as trusted (`css`, an
`icon` glyph, an attribute key, a client id) are code-authored constants, never
model or file text. A page that renders its own document follows the same rule.

The kit is HTML and CSS only; plan text stays out of the page markup and arrives
through the review's JSON island, so the client writes `textContent` and never
markup.

## Print and forced colours

`base.ts` owns both medias. Print un-constrains the shell and drops the toolbar,
sidebar, footer, gauge, skip link, and dialogs; a page adds what its own box clips
(a record, a code pane, a sticky hunk header). Under
`forced-colors:active` the hand-drawn task checkbox names system colours and the
focus ring stays `CanvasText`, because Windows High Contrast replaces colour but
not a drawn control.

## Keyboard

Every interactive element gets the one focus ring from `base.ts`; a component
must not declare its own, or the ring disappears surface by surface. A dialog
traps `Tab`. Within a page, `j`/`k`, arrows, and `?` follow the TUI's vocabulary
where they mean the same thing; the browse tree is one tab stop with arrows, and
`Enter` follows the focused link.

## Tests

[`web.test.ts`](./web.test.ts) pins the token anchors, the contrast ratios, each
emitted block, the atoms' escaping, and every contract above. A page's suite adds
its own: the stylesheet is shipped once, and the ids its client greps for exist in
the markup.
