Chapter 9

Styling and theming

All styling is done with theme tokens, not CSS. Themes are frozen objects; overrides are deep-merged.

9.1 Palette API: theme, text and accent colours#

The quickest way to brand a form is to describe it with three colour groups. createFormTheme() derives every other token from them: hover and pressed shades, focus ring, selection, tracks, disabled and placeholder text, and a contrast-safe text colour on the accent.

import { createFormTheme, checkContrast } from './lib';

const theme = createFormTheme(
  {
    mode: 'light',                        // base for anything not given ('light' | 'dark')
    theme: {                              // "theme colors": surfaces and lines
      background: 0xf5f7fb,               //   page / canvas
      surface: 0xffffff,                  //   fields, cards, menus
      border: 0xd0d7e2,                   //   field borders (borderHover is derived)
    },
    text: {                               // "text colors"
      primary: 0x0f172a,                  //   values and labels
      secondary: 0x475569,                //   helper text, descriptions, icons
      // disabled, placeholder and onAccent are derived if omitted
    },
    accent: {                             // "accent colors" (or just: accent: 0x0f766e)
      base: 0x0f766e,                     //   buttons, focus border, checked states
      // hover, pressed, focusRing, selection, caret are derived if omitted
    },
    status: { error: 0xc81e1e },          // optional: error, warning, success
  },
  { radius: 12, fontSize: 16 },           // optional non-colour tokens
);

console.warn(checkContrast(theme));       // [] when every text pair meets WCAG AA
new FormUI(app, { theme });
Group Keys Derived when omitted
theme background, surface, border, borderHover, shadow borderHover from border + text; hover and disabled surfaces; tracks
text primary, secondary, disabled, placeholder, onAccent secondary from primary; disabled and placeholder by blending with the surface; onAccent = white or near-black, whichever contrasts better
accent base, hover, pressed, focusRing, selection, caret Shades of base (lighter in dark mode, darker in light mode)
status error, warning, success Base theme's values

Presets: presetTheme(name, mode) with name from accentPalettes: indigo, teal, rose, amber, violet, slate. Each has a tuned light and dark accent. The demo's app-bar swatches use these.

ui.setTheme(presetTheme('teal', 'dark'));

Contrast helpers: contrastRatio(a, b), luminance(c), readableOn(bg), and checkContrast(theme), which checks text, helper, button, error and focus colours against WCAG AA and lists any failures.

9.2 Four levels of control#

import { lightTheme, darkTheme, createTheme, themeFromSeed } from './lib';

// 1. Choose a base, or derive one from your brand colour
const ui = new FormUI(app, { theme: themeFromSeed(0x0f766e) });

// 2. Override any token globally
const brand = createTheme(lightTheme, {
  fontFamily: ['Inter', 'system-ui', 'sans-serif'],
  radius: 14, controlHeight: 52, buttonRadius: 26, borderWidth: 2,
  colors: { primary: 0xe11d48, primaryHover: 0xbe123c, borderFocus: 0xe11d48, focusRing: 0xfda4af, caret: 0xe11d48 },
});
const ui2 = new FormUI(app, { theme: brand });   // or: new FormUI(app, { theme: lightTheme, themeOverrides: {...} })

// 3. Switch at runtime: every control redraws
ui.setTheme(darkTheme);
app.renderer.background.color = darkTheme.colors.background;

// 4. Per-control overrides
new Button(ui, { name: 'delete', text: 'Delete account', variant: 'danger', theme: { buttonRadius: 4 } });
otp.setThemeOverride({ fontFamily: ['ui-monospace', 'monospace'], fontSize: 22 });

Per-control overrides stay in effect across setTheme() calls: they're re-applied on top of the new base.

9.3 Size and typography tokens#

Token Light/dark default Used by
fontFamily system-ui stack All text
fontSize / fontWeight 15 / 400 Field text, labels of inline controls
labelFontSize / labelFontWeight 13 / 600 Labels above controls
helperFontSize 12 Helper and error lines, counters
titleFontSize 22 Label title variant
lineHeight 1.45 Multiplier for all text
radius 10 Fields, select, menus
borderWidth 1.5 Field borders
controlHeight 44 TextInput, PasswordInput, Select
paddingX / paddingY 14 / 10 Text inside fields
labelGap / helperGap 7 / 6 Label→field, field→helper spacing
focusRingWidth / focusRingOffset 3 / 2 Keyboard focus ring
buttonHeight / buttonRadius 44 / 10 Button
checkboxSize 20 Checkbox and radio
toggleWidth / toggleHeight 44 / 26 Switch
sliderTrackHeight / sliderThumbSize 6 / 22 Slider
caretWidth / caretBlinkMs 1.5 / 530 Text caret
dropdownItemHeight / dropdownMaxVisible 38 / 6 Select menu
animationSpeed 0.25 Checkbox/switch/radio/meter animations (0–1)

9.4 Colour tokens#

Colours are numbers (0xRRGGBB).

Group Tokens
Surfaces background, surface, surfaceHover, surfaceDisabled, overlay, shadow
Borders and focus border, borderHover, borderFocus, focusRing
Text text, textMuted, textDisabled, placeholder
Brand primary, primaryHover, primaryPressed, primaryText
Secondary buttons secondary, secondaryHover, secondaryText
Status error, warning, success
Editing selection, caret
Range controls track, thumb
Inverse (toast, privacy screen) inverseSurface, inverseText

Utilities: mix(a, b, t) blends two colours; themeFromSeed(seed, dark?) derives primary, hover, pressed, focus and selection colours from one brand colour.

9.5 Fonts#

Canvas text needs fonts that are already loaded when measured:

/* public/fonts.css (same origin: the CSP allows font-src 'self') */
@font-face { font-family: 'Inter'; src: url('/fonts/Inter.woff2') format('woff2'); font-display: block; }
await document.fonts.load('15px Inter');
await document.fonts.ready;
const ui = new FormUI(app, { theme: createTheme(lightTheme, { fontFamily: ['Inter', 'system-ui', 'sans-serif'] }) });

If you swap fonts after creating the UI, call ui.setTheme(ui.theme) to re-measure.

9.6 Dark mode#

const mq = matchMedia('(prefers-color-scheme: dark)');
const apply = () => {
  const t = presetTheme('indigo', mq.matches ? 'dark' : 'light');   // or darkTheme / lightTheme
  ui.setTheme(t);
  app.renderer.background.color = t.colors.background;
};
mq.addEventListener('change', apply);

9.7 Changing how a built-in control draws#

Subclass it and override the protected hooks:

Hook Purpose
drawBody() Repaint the body. Call super.drawBody() first to add decorations.
drawTrailing(w, h) Text fields: draw an icon on the right; reserve space with this.trailingWidth = 36.
handleTrailingClick(e) Text fields: handle clicks there; return true if consumed.
footerMessage() / footerColor() Customise the helper line (text and colour).
drawFocus(x, y, w, h, r) Draw the standard focus ring around any rectangle.
placeInfo(parent, x, cy) / infoIconSpace() Place the ⓘ icon in an inline-label layout and reserve space for it (see Checkbox).
textStyle(kind, fill?, wrapWidth?) Get a themed text style ('body' | 'label' | 'helper').

Example: a search field with a clear (×) button (also in src/examples/SearchInput.ts).

import { Graphics, TextInput, Icons, type FederatedPointerEvent, type TextInputOptions, type FormUI } from './lib';

export class SearchInput extends TextInput {
  private readonly clearIcon = new Graphics();
  constructor(ui: FormUI, opts: TextInputOptions) {
    super(ui, { inputMode: 'search', enterKeyHint: 'search', ...opts });
    this.trailingWidth = 36;
    this.body.addChild(this.clearIcon);
    this.redraw();
  }
  protected override drawTrailing(w: number, h: number): void {
    if (!this.clearIcon) return;                       // may run before the field exists
    this.clearIcon.clear();
    if (!this.isEmpty()) Icons.close(this.clearIcon, w - 20, h / 2, 18, this.theme.colors.textMuted);
  }
  protected override handleTrailingClick(e: FederatedPointerEvent): boolean {
    if (e.getLocalPosition(this.body).x < this.layoutWidth - 36 || this.isEmpty()) return false;
    this.setValue('');
    return true;
  }
}