@margoengine/ui 0.1.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,708 +1,1225 @@
1
- # @margoengine/ui
2
-
3
- Import `margoengine/ui` from the `margoengine` package, or `@margoengine/ui` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
4
-
5
- Game UI that is drawn inside the engine, so it works in fullscreen and in exported games, with no DOM on top of the
6
- canvas:
7
-
8
- - **Widgets:** panels, labels, buttons, toggles, sliders, progress and health bars, lists, inventory grids, menus,
9
- dialogs, toasts and tooltips.
10
- - **Layout:** anchors, flex-style rows and columns, grids, scrolling, safe areas.
11
- - **Scaling:** a reference resolution, the device pixel ratio and the user's text size, with text that stays sharp
12
- because it is drawn by `@margoengine/text` as signed distance fields.
13
- - **Themes:** a good-looking dark theme by default, a light theme, a high contrast theme, and `createTheme` for your own.
14
- All status colours come from the colour-blind-safe Okabe-Ito palette and meaning never rests on colour alone.
15
-
16
- The package is optional and tree-shakable and adds nothing to core. `Ui` holds the widgets and produces a list of
17
- rectangles and text in pixels; it touches neither the GPU nor the DOM, so it runs in Node and in tests.
18
- `UiRenderer` is the engine plugin that draws that list, on WebGPU and on core's WebGL2 preview backend alike.
19
-
20
- ```ts
21
- import { Engine } from '@margoengine/core';
22
- import { Ui, UiRenderer, Menu } from '@margoengine/ui';
23
-
24
- const engine = await Engine.create(document.querySelector('canvas')!);
25
- const ui = new Ui(); // dark theme, 1 UI unit = 1 CSS pixel, system font
26
- UiRenderer.attach(engine, ui); // steps the UI every frame and draws it over the finished frame
27
-
28
- ui.add(
29
- new Menu({
30
- title: 'Paused',
31
- items: [
32
- { label: 'Resume', onSelect: () => ui.toast('Back in the game') },
33
- { label: 'Quit', onSelect: async () => (await ui.confirm('Quit to the title screen?')) && location.reload() },
34
- ],
35
- }),
36
- );
37
- ```
38
-
39
- ## Building a screen
40
-
41
- Every widget is a class you construct with an options object. Put them in a `Panel` (a column by default) and add the
42
- panel to `ui`. Layout options are on every widget.
43
-
44
- ```ts
45
- import { Ui, Panel, Label, Button, Toggle, Slider } from '@margoengine/ui';
46
-
47
- const ui = new Ui();
48
- const settings = new Panel({
49
- background: 'surface',
50
- border: true,
51
- shadow: true,
52
- padding: 24,
53
- gap: 12,
54
- width: 360,
55
- anchor: 'center',
56
- children: [
57
- new Label({ text: 'Settings', size: 'title' }),
58
- new Slider({ text: 'Volume', value: 0.8, onChange: (e) => console.log('volume', e.value) }),
59
- new Toggle({ text: 'Subtitles', checked: true, onChange: (e) => console.log('subtitles', e.value) }),
60
- new Button({ text: 'Done', variant: 'primary', onClick: () => settings.removeFromParent() }),
61
- ],
62
- });
63
- ui.add(settings);
64
- ```
65
-
66
- `on(type, handler)` works on every widget and returns a function that unsubscribes; it is also disposable, so
67
- `using off = button.on('click', fn)` ends the subscription at the end of the block. Option callbacks (`onClick`,
68
- `onChange`, `onSelect`) are shortcuts for `on('click' | 'change' | 'select', ...)`.
69
-
70
- ## Layout
71
-
72
- Sizes are UI units. By default one unit is one CSS pixel; see Scaling.
73
-
74
- `arrange` shares measurements of the same node and available width within one call. A custom
75
- `LayoutNode.measure` returns a stable content size for that width during the call. The next call
76
- measures again, so direct edits to styles, children or content take effect without an invalidation API.
77
- The cache belongs to that call, including when a measurer starts a separate layout.
78
-
79
- ```ts
80
- import { arrange, type LayoutNode } from '@margoengine/ui';
81
-
82
- const label: LayoutNode = {
83
- style: {}, children: [], rect: { x: 0, y: 0, width: 0, height: 0 },
84
- measure: (width) => ({ width: Math.min(80, width), height: 20 }),
85
- };
86
- const row: LayoutNode = {
87
- style: { direction: 'row', align: 'center' }, children: [label],
88
- rect: { x: 0, y: 0, width: 0, height: 0 },
89
- };
90
- arrange(row, { x: 0, y: 0, width: 200, height: 100 });
91
- console.log(label.rect); // { x: 0, y: 40, width: 80, height: 20 }
92
- ```
93
-
94
-
95
- | Option | Default | Meaning |
96
- | --- | --- | --- |
97
- | `direction` | `'column'` | `'row'`, `'column'`, `'stack'` (children anchored over each other) or `'grid'` |
98
- | `gap` | `0` | space between children; a number or `[column gap, row gap]` |
99
- | `align` | stretch (column), center (row) | cross-axis placement: `'start'`, `'center'`, `'end'`, `'stretch'` |
100
- | `justify` | `'start'` | main-axis placement: `'start'`, `'center'`, `'end'`, `'space-between'`, `'space-around'`, `'space-evenly'` |
101
- | `padding`, `margin` | `0` | a number, `[vertical, horizontal]` or `[top, right, bottom, left]` |
102
- | `width`, `height` | `'auto'` | a number, `'auto'` (fit content), `'fill'` or a percentage such as `'50%'` |
103
- | `minWidth`, `maxWidth`, `minHeight`, `maxHeight` | none | bounds in UI units |
104
- | `grow`, `shrink` | `0`, `1` | shares of the free or missing main-axis space |
105
- | `alignSelf` | the parent's `align` | cross-axis placement of this child |
106
- | `anchor` | `'stretch'` in a stack | `'top-left'`, `'top'`, `'top-right'`, `'left'`, `'center'`, `'right'`, `'bottom-left'`, `'bottom'`, `'bottom-right'` or `'stretch'`; `margin` is the distance from the edges |
107
- | `position` | `'flow'` | `'absolute'` takes the child out of a row or column and anchors it |
108
- | `offset` | `[0, 0]` | shift after layout, for animation |
109
- | `bleed` | `false` | in a stack, ignore the parent's padding and the safe area |
110
- | `columns`, `cellWidth`, `cellHeight` | `1`, widest, tallest | for `direction: 'grid'` |
111
- | `overflow` | `'visible'` | `'hidden'` clips; `'scroll'` clips and scrolls on the main axis (a wrapping row scrolls its lines vertically) |
112
- | `wrap` | `false` | in a `'row'`, children that do not fit move onto new lines below |
113
-
114
- The screen layer is a stack, so a widget with an `anchor` sits at that corner or edge of the screen, inside the safe area:
115
-
116
- ```ts
117
- import { Ui, Panel, Label } from '@margoengine/ui';
118
-
119
- const ui = new Ui();
120
- ui.add(
121
- new Panel({ background: 'scrim', direction: 'row', gap: 12, padding: [8, 16], anchor: 'top-left', margin: 16,
122
- children: [new Label({ text: 'Gold' }), new Label({ text: '1,250', color: 'warning' })] }),
123
- new Label({ text: 'Press E to open', anchor: 'bottom', margin: 48, outline: true }),
124
- );
125
- ui.update(1 / 60); // lays out the tree
126
- const [hud] = ui.root.children;
127
- console.log(hud.rect); // { x, y, width, height } in UI units
128
- ```
129
-
130
- Safe areas keep the HUD out of notches, rounded corners and the TV overscan. `new Ui({ safeArea: 'auto' })` (the default)
131
- reads the device's `env(safe-area-inset-*)`; `ui.setSafeArea([top, right, bottom, left])` sets it in CSS pixels. A widget
132
- with `bleed: true` (a full-screen backdrop, say) ignores it.
133
-
134
- ### Wrapping rows
135
-
136
- A row with `wrap: true` moves the children that do not fit onto new lines, so tag lists and toolbars reflow when the
137
- panel narrows or the text grows. Each line shares its own free space (`grow`, `shrink`, `justify`) and is as tall as
138
- its tallest child, which `align` places children within; the second number of `gap` separates the lines. A child
139
- wider than the row gets a line to itself and shrinks to fit.
140
-
141
- ```ts
142
- import { Ui, Panel, Label } from '@margoengine/ui';
143
-
144
- const ui = new Ui();
145
- const tags = ['fire', 'ice', 'poison', 'holy', 'shadow', 'storm'].map((text) => new Label({ text }));
146
- const bar = new Panel({ direction: 'row', wrap: true, gap: [8, 4], width: 200, anchor: 'top-left', children: tags });
147
- ui.add(bar);
148
- ui.update(1 / 60);
149
- console.log(new Set(tags.map((tag) => tag.rect.y)).size); // the number of lines
150
- bar.setStyle({ width: 600 });
151
- ui.update(1 / 60); // wide enough now: one line
152
- ```
153
-
154
- ## Widgets
155
-
156
- | Widget | Use | Key options |
157
- | --- | --- | --- |
158
- | `Panel` | container with an optional background, outline and shadow | `background`, `border`, `shadow`, `radius` |
159
- | `Label` | text that wraps and scales | `text`, `size`, `color`, `align`, `wrap`, `outline` |
160
- | `Button` | push button, 44 units tall at least | `text`, `icon`, `variant`, `onClick` |
161
- | `Toggle` | switch or checkbox | `text`, `checked`, `variant`, `onChange` |
162
- | `Slider` | horizontal slider | `min`, `max`, `step`, `value`, `text`, `format`, `onChange` |
163
- | `ProgressBar` | meter with its value written in it | `value`, `max`, `text`, `variant`, `display` |
164
- | `HealthBar` | progress bar for hit points, with a damage trail | `value`, `max` |
165
- | `List` | scrolling list of selectable rows | `items`, `selected`, `onSelect` |
166
- | `VirtualList` | list that builds only the rows in view, for thousands of entries | `count`, `row`, `rowHeight`, `onSelect` |
167
- | `Inventory` | grid of item slots; drag, or pick up and put down | `columns`, `slots`, `items`, `onMove`, `onUse` |
168
- | `Menu` | titled column of buttons | `title`, `items` |
169
-
170
- `ui.dialog()`, `ui.confirm()` and `ui.alert()` show modal dialogs that return promises, and `ui.toast()` shows a
171
- message that fades. `AbortSignal` closes a dialog from code.
172
-
173
- ```ts
174
- import { Ui, HealthBar, Inventory, Button } from '@margoengine/ui';
175
-
176
- const ui = new Ui();
177
- const health = new HealthBar({ max: 100, width: 260, anchor: 'top-left', margin: 16 });
178
- const bag = new Inventory({
179
- columns: 4,
180
- slots: 12,
181
- anchor: 'bottom-right',
182
- margin: 16,
183
- items: [{ id: 'potion', name: 'Potion', icon: '🧪', count: 3, description: 'Restores 25 health' }],
184
- });
185
- bag.on('use', (e) => {
186
- health.value += 25;
187
- ui.toast(`Used ${(e.item as { name: string }).name}`, { kind: 'success' });
188
- });
189
- ui.add(health, bag);
190
-
191
- health.value = 40; // eases down; the old value lingers as a pale chip
192
- const respawn = new Button({ text: 'Respawn options' });
193
- respawn.on('press', async () => {
194
- const controller = new AbortController();
195
- const answer = await ui.dialog({
196
- title: 'Respawn?',
197
- message: 'You fell off the map.',
198
- buttons: [{ label: 'Respawn', value: 'respawn' }, { label: 'Quit', value: 'quit' }],
199
- signal: controller.signal, // controller.abort() closes it and rejects
200
- });
201
- console.log(answer);
202
- });
203
- ui.add(respawn);
204
- ```
205
-
206
- Status never relies on colour alone: bars write their value inside, toasts carry a symbol and a word for screen readers,
207
- and a switch moves its knob.
208
-
209
- ### Virtual lists
210
-
211
- ```ts
212
- import { Ui, VirtualList } from '@margoengine/ui';
213
-
214
- const ui = new Ui();
215
- const entries = Array.from({ length: 50_000 }, (_, i) => ({ time: i * 0.25, text: `Event ${i}` }));
216
- const log = new VirtualList({
217
- count: entries.length,
218
- row: (i) => ({ label: entries[i].text, detail: `${entries[i].time.toFixed(2)} s` }),
219
- height: 240,
220
- width: 360,
221
- anchor: 'top-left',
222
- margin: 16,
223
- onSelect: (e) => console.log('picked', e.index),
224
- });
225
- ui.add(log);
226
- ui.update(0);
227
- console.log(log.range); // [0, 10]: the 6 rows in view and 4 more, the only widgets built
228
- log.scrollToIndex(40_000); // jump; the rows around it are built on the next update
229
- ```
230
-
231
- A `VirtualList` asks `row(index)` only for the rows in view plus `overscan` (default 4) on each side, and stands two
232
- spacers in for the rest, so scrolling, the scroll bar range and the wheel behave as in a full list while a
233
- hundred-thousand-row log costs what a screenful does. Every row has the same `rowHeight` (default 44). Arrow keys and
234
- the d-pad move through all rows, scrolling and building as they go. Set `count` when rows are added or removed, and
235
- call `refresh()` when their data changes. A focused row that scrolls out of the built range gives up the focus.
236
- The screen reader mirror reads it as a listbox of the built rows, each telling its place in the whole list.
237
-
238
- ## Forms, text fields, images, keyboard, languages and a layout editor
239
-
240
- Six more entries are separate imports, so a screen that does not use them does not load them.
241
-
242
- - `@margoengine/ui/input` has `TextInput` (single line, or a password that draws one bullet per grapheme) and `TextArea` (several lines). Options: `value`, `placeholder`, `type` (`'text'` or `'password'`), `readOnly`, `maxLength`, `autocomplete` (default `'off'`), `spellcheck`, `required`, `invalid`, `onChange` and `onSubmit`. The canvas paints the text and caret, while a real DOM control that `attachTextInputs(ui, target)` mounts gives you the browser's selection, undo, mobile keyboards and IME. Call `attachTextInputs` after the `UiRenderer`; it returns a function that detaches it.
243
- - `@margoengine/ui/forms` has `Select`, `Checkbox` (a `Toggle` drawn as a checkbox), `RadioGroup`, `Tabs` and `ColorPicker`. `Select`, `RadioGroup` and `Tabs` take `options`, a list of `{label, value, disabled}` with unique string values, plus `value` and `onChange`; `Tabs` options also carry the `panel` widget that shows while its tab is chosen. `ColorPicker` has HSV, RGB and alpha sliders and a hex field, takes `value` as `#rrggbb` or `#rrggbbaa` (default `#ffffff`) and calls `onChange`. `attachFormsMirror(ui, target)` adds the radio, tab and select ARIA states to the accessibility mirror; attach it after the `UiRenderer`.
244
- - `@margoengine/ui/image` has `ImageTexture` (decode a URL with cancellation, or copy a decoded image, video frame or canvas) and the `Image` widget. `Image` options: `texture`, `source` (a pixel rectangle), `fit` (`contain` by default, `cover` crops, `fill` stretches), `slice` and `borderScale` for nine-slice borders, and `tint`.
245
- - `@margoengine/ui/keyboard` has `VirtualKeyboard`, a panel for headsets and touch screens that types into the focused `TextInput` of the same `Ui`. Options: `target`, `rows` (a QWERTY layout with numbers, punctuation and editing keys by default) and `keyWidth`, the minimum width of a normal key (44 UI pixels by default).
246
- - `@margoengine/ui/i18n` has `Localization`: message tables per locale with `{name}` substitutions and plural forms, a fallback chain, text direction taken from the locale's script (or set with `directions`), and `missing: 'error'` to throw on a missing key instead of showing the key. `bind` ties a translation to a widget, so a locale change reflows the layout on the next frame.
247
- - `@margoengine/ui/editor` has `LayoutDocument` (a markup layout with undo and redo, validated before each edit commits, saved as a project string) and `LayoutEditor`, a browser editor over it (options `ui`, `canvas`, `actions` and `signal`). Action handlers named in the markup come only from the options you pass, never from the saved project.
248
-
249
- ## Theming
250
-
251
- `themes.dark` is the default (`themeForPreferences()` picks high contrast, light or dark from the user's settings).
252
- `createTheme` makes your own from any base:
253
-
254
- ```ts
255
- import { Ui, createTheme, themes } from '@margoengine/ui';
256
-
257
- const forest = createTheme({ name: 'forest', colors: { primary: '#7bd88f', onPrimary: '#06210d' }, radius: 12 }, themes.dark);
258
- const ui = new Ui({ theme: forest });
259
- ui.theme = themes.highContrast; // restyles everything on the next frame
260
- ```
261
-
262
- | Theme | Notes |
263
- | --- | --- |
264
- | `themes.dark` | default; every text colour is at least 4.5:1 on what it is drawn on |
265
- | `themes.light` | same contrast rules on light surfaces |
266
- | `themes.highContrast` | black, white, yellow and cyan; 7:1 text, thick outlines, 4-unit focus ring, no shadows or motion |
267
-
268
- The colour roles (`primary`, `success`, `warning`, `danger`, `info`, `accent`, `focus`, `surface`, `text`, ...) are
269
- documented on `ThemeColors`. The tests check text contrast for every built-in theme and that the success, warning and
270
- danger colours stay apart for protan, deutan and tritan viewers (`simulateColorBlindness`, `contrastRatio` and
271
- `colorDifference` are exported so you can check your own theme the same way).
272
-
273
- ## Scaling
274
-
275
- ```ts
276
- import { Ui } from '@margoengine/ui';
277
-
278
- const ui = new Ui({
279
- scale: { reference: [1280, 720], match: 0.5 }, // design for 720p; the UI scales with the window
280
- textScale: 1.25, // the user's text size preference, 0.5 to 3
281
- });
282
- ui.resize(1920, 1080, window.devicePixelRatio);
283
- console.log(ui.width, ui.height, ui.scale); // 1280 720 1.5 (with a pixel ratio of 1)
284
- ```
285
-
286
- UI units become CSS pixels by the resolution scale and device pixels by the pixel ratio on top; text is laid out in UI
287
- units and drawn as signed distance fields at the final pixel size, so it stays sharp. `UiRenderer` calls `resize` from
288
- the canvas every frame. `textScale` multiplies every text size and reflows the layout.
289
-
290
- ## Arabic, Indic and right-to-left text
291
-
292
- ```ts
293
- import { Label, Panel, Ui } from '@margoengine/ui';
294
-
295
- const ui = new Ui({ ligatures: true }); // Latin words draw as shaped runs too, so fi and fl join
296
- ui.add(
297
- new Panel({
298
- anchor: 'top-left',
299
- children: [
300
- new Label({ text: 'مرحبا بالعالم', width: 300 }), // joined Arabic letters, at the right edge of its box
301
- new Label({ text: 'नमस्ते दुनिया', width: 300 }), // Devanagari conjuncts and vowel signs
302
- new Label({ text: 'office flow', width: 300 }),
303
- ],
304
- }),
305
- );
306
- console.log(ui.textDirection('مرحبا')); // 'rtl'
307
- ```
308
-
309
- UI text is laid out by `@margoengine/text`, which hands each Arabic and Indic word (Devanagari, Bengali, Tamil and the
310
- other Indic scripts) to the browser's shaper as one run, so letters join, conjuncts form and vowel signs sit where they
311
- belong. `ligatures: true` does the same for Latin words. Each text reads in the direction of its first strong letter
312
- (`ui.textDirection(text)`), and `'start'` alignment is its reading start: the right edge for Arabic and Hebrew.
313
- `direction: 'rtl'` or `'ltr'` sets one direction for all UI text instead. Both can be changed later (`ui.ligatures`,
314
- `ui.direction`), which lays the text out again.
315
-
316
- ## Mouse, touch, keyboard and gamepad
317
-
318
- `UiRenderer.attach(engine, ui)` connects the engine's canvas for you (`{ input: false }` turns that off; a headless canvas in Node has no pointer events, so it is left out and the UI only draws). Everything works
319
- with every device:
320
-
321
- | Input | What it does |
322
- | --- | --- |
323
- | Mouse, pen | hover, click, drag sliders and inventory items, wheel scrolls lists |
324
- | Touch | tap, drag, scroll; touch never hovers |
325
- | Arrow keys, d-pad, left stick | move focus to the nearest widget in that direction (holding repeats); a focused slider takes left and right |
326
- | Tab, Shift+Tab, bumpers | step through the widgets; Tab past the last one hands the keyboard back to the page |
327
- | Enter, Space, gamepad A | press the focused widget |
328
- | Escape, gamepad B | close the tooltip, then the dialog |
329
-
330
- The focus ring shows for the keyboard and gamepad and hides for the mouse and touch. A dialog traps focus, puts it on its
331
- first button and gives it back when it closes. A press that lands on a widget never reaches other listeners on the canvas
332
- (it will not also orbit the camera) and `ui.wantsPointer(x, y)` tells your own code when the pointer is over the UI. Keys
333
- go to the UI only while a widget has focus or a dialog is open; set `ui.captureKeys = true` while a full-screen menu shows
334
- so the arrows work from the first press.
335
-
336
- ```ts
337
- import { Input } from '@margoengine/input';
338
- import { Ui, uiActions } from '@margoengine/ui';
339
-
340
- const ui = new Ui();
341
- // Gamepad (and, with { keyboard: true }, keys) as Input actions; merge your own actions in the same object.
342
- const input = new Input({ ...uiActions(), jump: [{ type: 'key', code: 'Space' }] });
343
- ui.bindInput(input); // reads the ui.* actions each ui.update(); call input.update() before it
344
-
345
- ui.captureKeys = true; // a full-screen menu is open
346
- ui.navigate('down'); // the same thing the arrow keys, the d-pad and the stick do
347
- ui.accept(); // Enter, Space, gamepad A
348
- ui.cancel(); // Escape, gamepad B: returns false when there was nothing to close
349
- console.log(ui.focused?.label, ui.inputMode); // 'keyboard'
350
- ```
351
-
352
- To handle the events yourself, call `ui.pointerMove`, `ui.pointerDown`, `ui.pointerUp`, `ui.wheel`, `ui.navigate`,
353
- `ui.tab`, `ui.accept` and `ui.cancel` (or `ui.execute(command)`) from your own listeners, or attach a different element with
354
- `attachInput(ui, element, { signal })`, which returns a function that detaches it and is also disposable.
355
-
356
- ```ts
357
- import { Ui, Panel, Button, attachInput } from '@margoengine/ui';
358
-
359
- const ui = new Ui();
360
- ui.add(new Panel({ children: [new Button({ text: 'Play', tooltip: 'Start a new game' })] }));
361
- const controller = new AbortController();
362
- attachInput(ui, document.querySelector('canvas')!, { signal: controller.signal });
363
- // controller.abort() removes every listener again.
364
- ```
365
-
366
- A widget with a `tooltip` shows it after half a second of hovering, or a moment after the keyboard focuses it; Escape
367
- hides it. Tooltips sit below the widget and flip above it at the bottom of the screen.
368
-
369
- ## Accessibility
370
-
371
- The interface is usable without a mouse, without sight and without colour vision, and nothing needs configuring:
372
-
373
- - **Keyboard and gamepad:** every control can be reached and operated, the focus ring is always visible when the keyboard
374
- or gamepad moves focus, and a dialog traps focus. Tab never traps the keyboard: past the last widget it returns to the page.
375
- - **Screen readers:** `UiRenderer` also attaches a hidden DOM mirror (`attachMirror`) next to the canvas (not on a headless canvas, which has no document). It holds real
376
- buttons, switches, range inputs, progress bars, listboxes, dialogs and text, laid over the widgets so touch exploration
377
- works, and it shares focus with the canvas: Tab or a screen reader moving to an element focuses its widget, and moving focus
378
- in the UI moves DOM focus so the reader announces it. Everything behind an open dialog is `inert`.
379
- - **Announcements:** toasts go to polite (assertive for errors) live regions, and `ui.announce(message)` says anything else.
380
- A widget's `tooltip` and `description` become `aria-describedby`.
381
- - **Colour:** the themes keep success, warning and danger apart for protan, deutan and tritan viewers, bars and toasts
382
- carry words and symbols as well as colour, and `themes.highContrast` is black, white, yellow and cyan with 7:1 text.
383
- `themeForPreferences()` picks high contrast for `prefers-contrast: more` and forced colours.
384
- - **Text size:** `ui.textScale` from 0.5 to 3 reflows the whole interface, and `new Ui({ textScale: 'auto' })` follows the font
385
- size the user set in the browser (`browserTextScale()`).
386
- - **Motion:** `prefers-reduced-motion` turns transitions, easing and fades off (`ui.motion`).
387
- - **Targets:** buttons, toggles, sliders and list rows are at least 44 units tall.
388
-
389
- ```ts
390
- import { Ui, UiRenderer, attachMirror, themeForPreferences } from '@margoengine/ui';
391
- import type { EngineKernel } from '@margoengine/core';
392
-
393
- export function accessibleUi(engine: EngineKernel): Ui {
394
- const ui = new Ui({ theme: themeForPreferences(), textScale: 'auto' });
395
- // The renderer attaches input and the mirror itself; to attach them by hand, turn them off and call:
396
- UiRenderer.attach(engine, ui, { input: false, mirror: false });
397
- const detach = attachMirror(ui, engine.canvas, { label: 'Menu and heads-up display' });
398
- ui.announce('Level 3. Your health is full.');
399
- void detach; // call it to remove the mirror; it is also disposable: using detach = attachMirror(...)
400
- return ui;
401
- }
402
- ```
403
-
404
- Keep these working in your own widgets: give a `Widget` a `label` (its accessible name; text widgets use their text), a `description`,
405
- and `focusable = true` with an `activate()` method for anything that reacts to accept.
406
-
407
- ## Real HTML: the DOM host
408
-
409
- The same widgets can also live as real, visible HTML instead of being drawn on the canvas, for pages that are mostly
410
- text, forms and lists. `mountDom` from `@margoengine/ui/dom` shows a `Ui` (or one widget of it) in an element, so the
411
- browser's own keyboard handling, screen readers, IME, autofill, spellcheck, zoom and touch work on them, and app code is
412
- the same as on the canvas: a click on the `<button>` fires the widget's `'click'`, typing fires the text input's
413
- `'change'`, and setting `label.text` patches only that label's element.
414
-
415
- ```ts
416
- import { Button, Label, List, Panel, Ui } from '@margoengine/ui';
417
- import { TextArea } from '@margoengine/ui/input';
418
- import { mountDom, type DomHost } from '@margoengine/ui/dom';
419
-
420
- export function reviewPage(container: HTMLElement): DomHost {
421
- const ui = new Ui();
422
- const answer = new TextArea({ label: 'Change this', placeholder: 'Say what to change' });
423
- const send = new Button({ text: 'Send', variant: 'primary' });
424
- const changes = new List({ label: 'What changed', items: [] });
425
- send.on('click', () => {
426
- changes.items = [...changes.items, answer.value];
427
- ui.toast('Sent');
428
- });
429
- ui.add(
430
- new Panel({ gap: 12, padding: 16, children: [new Label({ text: 'Review', size: 'title' }), answer, send, changes] }),
431
- );
432
- return mountDom(ui, container, { label: 'Review' }); // dispose it (or `using`) to remove every element and listener
433
- }
434
- ```
435
-
436
- - **Elements:** native first, ARIA only where HTML has none. Buttons are `<button>`, toggles and checkboxes
437
- `<input type="checkbox">` (toggles with `role="switch"`), sliders range inputs, `Select` a `<select>`, `RadioGroup` a
438
- `<fieldset>` of radios, `TextInput` and `TextArea` `<input>` and `<textarea>`, meters `<progress>`, and dialogs a modal
439
- `<dialog>` (`showModal`: focus moves in, the page behind is inert, Escape asks the widget). `Tabs`, `List`,
440
- `VirtualList` (with `aria-setsize` and `aria-posinset`) and inventories follow the WAI-ARIA Authoring Practices
441
- patterns with one tab stop each. Roles and states come from the same module as the canvas's screen reader mirror, so
442
- the two cannot drift. A `Menu` is a group of buttons, not `role="menu"`: the Authoring Practices keep the menu role for
443
- application menus, and a game or page menu is navigation.
444
- - **Two-way, keyed patching:** each widget keeps its element. A change touches only the attributes, text and CSS
445
- properties that differ, and children that move are reordered with the fewest moves (the longest run already in order
446
- stays), so focus, the caret, an IME composition and scroll positions survive.
447
- - **Layout:** each widget's layout style becomes CSS flexbox and grid (row, column, stack, grid, gap, align, justify,
448
- padding, margin, sizes, grow, wrap, anchors, scroll), so the page reflows at any zoom.
449
- - **Look:** the theme becomes CSS custom properties on the container (`--mg-primary`, `--mg-surface`, `--mg-radius`,
450
- `--mg-target` and the rest) read by one shared constructable stylesheet. No style attribute is written, so a strict
451
- `style-src 'self'` Content Security Policy passes (where constructable stylesheets are missing, pass `nonce` for the
452
- fallback `<style>`). Focus rings use `:focus-visible`, `prefers-reduced-motion` turns transitions off and forced
453
- colours use the system colours. Controls are at least `targetSize` CSS pixels (default 44; 24 is the WCAG 2.2 minimum).
454
- - **Toasts and announcements** go to the host's live regions, and `update` (on by default) steps `ui.update` on
455
- animation frames so toasts time out. Pass `update: false` and `announce: false` when a `UiRenderer` drives the same `Ui`.
456
-
457
- | Option | Default | Meaning |
458
- | --- | --- | --- |
459
- | `theme` | the UI's theme | The look; followed when `ui.theme` changes. |
460
- | `label` | none | Accessible name of the mounted region. |
461
- | `targetSize` | `44` | Smallest control size in CSS pixels, 24 or more. |
462
- | `update` | `true` | Step `ui.update` on animation frames. |
463
- | `announce` | `true` | Send announcements and toasts to live regions. |
464
- | `nonce` | none | Nonce of the fallback `<style>` element. |
465
- | `idPrefix` | `'margo-dom-'` | Start of every element id. |
466
- | `signal` | none | Unmount when it aborts. |
467
-
468
- The handle also has `elementOf(widget)`, `widgetOf(node)` and `flush()`. To place HTML in the 3D scene (like CSS2D and
469
- CSS3D labels), use `@margoengine/labels` and `@margoengine/html`.
470
-
471
- Sources: W3C, [WAI-ARIA 1.2](https://www.w3.org/TR/wai-aria-1.2/), 2023, and the
472
- [ARIA Authoring Practices Guide](https://www.w3.org/WAI/ARIA/apg/patterns/) (tabs, listbox, menu and dialog patterns);
473
- WHATWG, [HTML Living Standard](https://html.spec.whatwg.org/multipage/) (forms, the `dialog` element, `inert`); W3C,
474
- [WCAG 2.2](https://www.w3.org/TR/WCAG22/), 2023 (2.1.1 keyboard, 2.4.7 focus visible, 2.5.8 target size, 4.1.2 name,
475
- role, value); W3C, [CSS Flexible Box Layout Level 1](https://www.w3.org/TR/css-flexbox-1/); Michael L. Fredman,
476
- [On computing the length of longest increasing subsequences](https://doi.org/10.1016/0012-365X(75)90103-X), 1975 (the
477
- fewest moves of a keyed reorder); Nick ten Veen, Daco Harkes and Eelco Visser,
478
- [PixieDust: Declarative Incremental User Interface Rendering Through Static Dependency Tracking](https://doi.org/10.1145/3184558.3185978),
479
- 2018 (patching from known dependencies instead of diffing whole trees); Aiden Bai and others,
480
- [Million.js: A Fast Compiler-Augmented Virtual DOM for the Web](https://arxiv.org/abs/2202.08409), 2022 (the costs of
481
- diffing and patching in keyed virtual DOM reconciliation).
482
-
483
- ## React
484
-
485
- `@margoengine/ui/react` has thin components for the same widgets. They render no DOM: nest them inside `UiRoot` and they
486
- become widgets of one `Ui`, drawn on the engine's canvas. Props update the widgets in place, `onClick`, `onChange`,
487
- `onSelect`, `onMove` and `onUse` are the widgets' events, and `checked`, `value`, `items` and `selected` are controlled, so
488
- state lives in React. `react` is an optional peer dependency of this package.
489
-
490
- ```tsx
491
- import { useState } from 'react';
492
- import type { EngineKernel } from '@margoengine/core';
493
- import { themes, type InventoryItem } from '@margoengine/ui';
494
- import { UiRoot, Panel, Label, HealthBar, Inventory, Toggle, Button, useUi } from '@margoengine/ui/react';
495
-
496
- export function Hud({ engine, hp }: { engine: EngineKernel; hp: number }) {
497
- const [contrast, setContrast] = useState(false);
498
- const [bag, setBag] = useState<(InventoryItem | null)[]>([{ id: 'potion', name: 'Potion', icon: '🧪', count: 2 }, null, null, null]);
499
- return (
500
- <UiRoot engine={engine} theme={contrast ? themes.highContrast : themes.dark}>
501
- <Panel background="scrim" padding={12} gap={8} anchor="top-left" margin={16}>
502
- <Label text="Camp" size="large" />
503
- <HealthBar value={hp} max={100} width={240} />
504
- <Toggle text="High contrast" checked={contrast} onChange={(e) => setContrast(e.value as boolean)} />
505
- </Panel>
506
- <Panel anchor="bottom-right" margin={16}>
507
- <Inventory columns={2} slots={4} items={bag} onMove={() => setBag([...bag])} />
508
- </Panel>
509
- <Respawn />
510
- </UiRoot>
511
- );
512
- }
513
-
514
- function Respawn() {
515
- const ui = useUi(); // toast(), dialog(), confirm(), announce() for event handlers
516
- return <Button text="Respawn" anchor="bottom" margin={16} onClick={() => ui.toast('Respawned', { kind: 'success' })} />;
517
- }
518
- ```
519
-
520
- Create `UiRoot` where the engine is known (in a child of `@margoengine/react`'s `<Canvas>`, call `useEngine()` and pass it as
521
- `engine`). Pass `ui={yourUi}` to share one `Ui` with plain code. Widgets join their parent in mount order, so show and hide a
522
- widget with `visible` rather than by mounting it conditionally if its place in the order matters. A Next.js server component may import these components: the `react-server` export condition maps
523
- `@margoengine/ui/react` to a `'use client'` boundary, while every other bundler loads a plain module with no directive (so
524
- Vite and Rollup print no warning for it). Props only a constructor
525
- reads (a slider's `min` and `max`, an inventory's `columns` and `slots`) recreate the widget when they change.
526
-
527
- ## World-space and XR panels
528
-
529
- `@margoengine/ui/world` puts a `Ui` on a flat panel in the 3D scene: a diegetic screen on a terminal, a VR menu, a wrist
530
- panel. The panel's `Ui` keeps its own size in CSS pixels; `WorldPanels` draws it into a texture (redrawn only when the UI
531
- changes, with mipmaps so a distant panel does not shimmer) and puts that texture on a quad in the scene, depth-tested
532
- against it, in every view and XR eye. A mouse, pen or touch on the canvas reaches the nearest panel under it by a ray from
533
- the camera, and a press a panel used never reaches the game.
534
-
535
- ```ts
536
- import { Engine } from '@margoengine/core';
537
- import { Ui, Panel, Label, Button } from '@margoengine/ui';
538
- import { WorldPanel, WorldPanels } from '@margoengine/ui/world';
539
-
540
- const engine = await Engine.create(document.querySelector('canvas')!);
541
- const menu = new Ui({ width: 480, height: 300 }); // its own Ui, in CSS pixels of the panel
542
- menu.add(
543
- new Panel({
544
- background: 'surface',
545
- anchor: 'stretch',
546
- padding: 24,
547
- gap: 12,
548
- children: [
549
- new Label({ text: 'Workshop', size: 'title' }),
550
- new Button({ text: 'Craft', variant: 'primary', onClick: () => menu.toast('Crafted') }),
551
- ],
552
- }),
553
- );
554
- const panels = WorldPanels.attach(engine); // draws every panel in the scene and routes canvas pointers to them
555
- panels.add(new WorldPanel(menu, { width: 1.2, position: [0, 1.4, -1.5], pixelRatio: 2 }));
556
- ```
557
-
558
- | `new WorldPanel(ui, {...})` option | Default |
559
- | --- | --- |
560
- | `width` | `1` world unit (metres in glTF scenes) |
561
- | `height` | the width times the UI's height over its width, so the UI keeps its shape |
562
- | `position`, `rotation` | `[0, 0, 0]` and the quaternion `[0, 0, 0, 1]`: the UI faces +Z with +Y up |
563
- | `pixelRatio` | `1` texture pixel per CSS pixel; 2 reads sharper up close in VR |
564
- | `doubleSided` | `false`: the back is invisible and takes no input; `true` shows the UI from behind too, mirrored so it reads |
565
-
566
- `panel.matrix` is the pose (column-major, rotation and translation only): copy a controller's grip pose into it for a wrist
567
- menu, or call `panel.setPose(position, rotation)`. `WorldPanels.attach(engine, { order, input })` takes the frame graph order
568
- (default 25: in the scene, before post-processing) and `input: false` to leave the canvas alone.
569
-
570
- Rays from anything else go through `panels.pointer(ray, pressed, { id })`: the ray hovers the nearest visible panel, a change
571
- of `pressed` presses or releases, and a pressed pointer keeps its panel until it is released (a slider dragged off the
572
- edge). For XR, hand each controller to `panels.controller(controller, id)` every frame: `@margoengine/xr`'s `XRController`
573
- has the shape it reads (`targetRayMatrix` and `buttons`), its ray hovers and button 0, the trigger, presses.
574
-
575
- ```ts
576
- import type { RayController, WorldPanels } from '@margoengine/ui/world';
577
-
578
- // Call once a frame during an XR session; ids keep the two hands apart.
579
- export function pointAtPanels(panels: WorldPanels, controllers: readonly RayController[]): void {
580
- controllers.forEach((controller, hand) => panels.controller(controller, hand + 1));
581
- }
582
- ```
583
-
584
- `panel.intersect(ray)` returns the hit (distance, world point, UI pixel, inside or not), `pickPanel(panels, ray)` the nearest
585
- panel under a ray, `screenRay(camera, x, y, width, height)` the ray under a canvas point and `rayFromMatrix(pose)` an XR
586
- pointing ray. Give a panel's `Ui` to `WorldPanels` only, never also to `UiRenderer`: the renderer would resize it to the
587
- canvas. Keyboard and gamepad focus work as on the screen through the panel's own `ui` (`ui.bindInput`, `ui.navigate`).
588
-
589
- ## Markup and style sheets
590
-
591
- ```ts
592
- import { Ui } from '@margoengine/ui';
593
- import { buildScreen } from '@margoengine/ui/markup';
594
-
595
- const markup = `
596
- <panel id="pause" class="menu">
597
- <label class="title">Paused</label>
598
- <row class="buttons">
599
- <button variant="primary" on-click="resume">Resume</button>
600
- <button on-click="quit">Quit</button>
601
- </row>
602
- <toggle id="music" checked="true">Music</toggle>
603
- <list id="saves" height="120"><item detail="2 h">Slot 1</item><item>Slot 2</item></list>
604
- </panel>`;
605
- const styles = `
606
- .menu { anchor: center; width: 320; padding: 16; gap: 12 }
607
- .menu .title { size: large }
608
- .buttons > button { grow: 1 }`;
609
-
610
- const ui = new Ui();
611
- const screen = buildScreen(markup, {
612
- styles,
613
- actions: { resume: () => console.log('resume'), quit: () => console.log('quit') },
614
- });
615
- ui.add(...screen.widgets);
616
- console.log(screen.get('music')); // the Toggle with id="music"
617
- ```
618
-
619
- `@margoengine/ui/markup` builds a screen from a markup file and style sheets that a designer can edit without code.
620
- Elements are the widgets in lower case: `panel`, `row` and `column` hold other elements; `label`, `button`,
621
- `toggle`, `slider`, `progress` and `health` take their text from their content; `list` and `menu` take `<item>`
622
- children. Attributes and style declarations are the widgets' options in kebab-case (`min-width`, `show-value`), with
623
- spaces between numbers (`padding: 8 16`). Rules select by type, `#id` and `.class`, joined by a space (any
624
- descendant) or `>` (a child); the more specific rule wins, then the later one, and an element's own attributes win over
625
- every sheet. `on-click`, `on-change` and `on-select` name a function in `actions`. Every error names its line and
626
- column. `loadScreen(url, { styles: [cssUrl], actions, signal })` fetches the files first, with an `AbortSignal`;
627
- `parseMarkup` and `parseStyleSheet` return the parsed trees for tools.
628
-
629
- ## Options
630
-
631
- | `new Ui({...})` option | Default |
632
- | --- | --- |
633
- | `width`, `height` | `1280`, `720` (CSS pixels; `UiRenderer` keeps them in step with the canvas) |
634
- | `pixelRatio` | `1` |
635
- | `scale` | `1`, or `{ reference: [w, h], match, min, max }` |
636
- | `theme` | `themeForPreferences()` |
637
- | `font` | `system-ui, sans-serif` at weight 500; a `Font` or options from `@margoengine/text` |
638
- | `textScale` | `1` |
639
- | `safeArea` | `'auto'` |
640
- | `reducedMotion` | the user's `prefers-reduced-motion` |
641
- | `ligatures` | `false` (Arabic and Indic words are always shaped; `true` shapes Latin words too) |
642
- | `direction` | `'auto'` (each text's first strong letter); `'ltr'` or `'rtl'` for all UI text |
643
- | `measurer` | the font; pass your own for tests or servers |
644
-
645
- Errors follow the repository convention: bad arguments throw `TypeError` or `RangeError` whose message names the fix and
646
- ends with a link to [margoengine.com/errors#ui](https://margoengine.com/errors#ui); using a disposed `Ui` throws a
647
- `MargoError` with `code: 'disposed'`. `Ui`, `UiRenderer` and every widget have `dispose()` and `Symbol.dispose`.
648
-
649
- ## How it works
650
-
651
- - **A draw list, not a scene.** `ui.draw()` returns rounded rectangles, text blocks and clip regions in device pixels,
652
- back to front. It is rebuilt only when something changed, and `UiRenderer` uploads it only when it was rebuilt.
653
- A `DrawList` checks each command before adding it: a non-finite position, size, border, radius or blur, a scale
654
- that is not finite and above 0, and a `popClip` with no clip open throw a `RangeError` and leave the list as it was.
655
- - **Two instanced draws.** Rectangles are signed distance rounded boxes (crisp edges, outlines, soft shadows); glyphs are
656
- quads sampling the text package's atlases. Both read storage buffers by instance index, in the engine's own render pass
657
- after post-processing, with premultiplied alpha blending and one scissor per clip region. Images share the colour
658
- atlas; an image no longer drawn (removed, or its `texture` replaced) gives its slots back, so a page it leaves empty
659
- is reused.
660
- - **Layout.** A small flexbox: base sizes, then free space by `grow` and a shortage by `shrink` (resolved as CSS Flexbox
661
- section 9.7 does: a child held by its min or max size is frozen and the rest goes to the others), then `justify` and
662
- `align`. A wrapping row first breaks its children into lines by their base sizes, then does the same per line. Stacks anchor their children; grids fill cells row by row.
663
- - **No globals.** Nothing runs on import; the only DOM access is reading the safe area, and only when you ask for it.
664
-
665
- ## WebGL2 preview backend
666
-
667
- ```ts
668
- import { Engine } from '@margoengine/core';
669
- import { webglRenderer } from '@margoengine/webgl2-compat/preview';
670
- import { Button, Ui, UiRenderer } from '@margoengine/ui';
671
-
672
- const canvas = document.querySelector('canvas')!;
673
- const engine = await Engine.create(canvas, { backend: 'webgl2', fallback: webglRenderer });
674
- const ui = new Ui();
675
- ui.add(new Button({ text: 'Play', anchor: 'center' }));
676
- UiRenderer.attach(engine, ui); // the same rectangles and text as on WebGPU
677
- engine.start();
678
- ```
679
-
680
- On WebGL2 the renderer draws the same instances with two small GLSL ES 3.00 programs into the default framebuffer, over
681
- the finished frame. Its code loads on first use, so WebGPU pages never fetch it and the UI shows from the first frame
682
- after that load. An unchanged UI uploads nothing; it is drawn again each frame because WebGL2 clears its canvas.
683
-
684
- ## Limits
685
-
686
- - World panels require native WebGPU or the full compatibility layer and refuse the small preview during setup. Screen UI has a real preview route.
687
- - A world panel is drawn with depth test and no depth write, so it does not hide transparent effects drawn after it; one texture and one pair of glyph atlases per panel. A `CurvedPanel` (`@margoengine/ui/curved`) is a tessellated cylinder or sphere patch; its rays hit the analytic surface.
688
- - Shaping is the browser's, one word at a time: a run never crosses a space, so no join or ligature forms across
689
- words. Only labels and wrapped text follow the text direction: toggles, slider values, list details and rows of
690
- widgets keep left-to-right placement (no mirrored layout).
691
- - Markup is a subset of XML: no DOCTYPE, CDATA or namespaces, and only the five named character references. Style
692
- sheets have no pseudo-classes, attribute selectors, `+` or `~`, `@` rules or `!important`, and do not restyle a
693
- screen after it is built.
694
- - A `VirtualList` has one row height; rows of different heights need a `List`.
695
- - A wrapping row breaks lines by its children's base sizes, so a child that would grow
696
- never pulls the next one up; columns do not wrap, and lines always stack down from the top (no `align-content`).
697
-
698
- ## Preview tier contract
699
-
700
- The small `@margoengine/webgl2-compat/preview` renderer reports `backend: 'webgl2'` and has no GPU device. GPU-only attachments throw a linked `MargoError` with code `unsupported` before allocating resources. Native WebGPU and the full WebGL2 compatibility layer both report `backend: 'webgpu'`. Use [`autoEngine` with `loadCompat`](../webgl2-compat/README.md#automatic-escalation) during scene setup to select a complete tier automatically.
701
-
702
- Screen `UiRenderer` keeps its real preview renderer. `WorldPanels` requires a complete tier.
703
-
704
- `GlWorldPanels` (`@margoengine/ui/world-gl`) is a reviewed preview route in `scripts/check-preview-contract.mjs` (2026-11-10, 2 `backend` tests): on the small WebGL2 preview it draws world panels with raw WebGL2, on WebGPU it defers to `WorldPanels`. Pixel evidence: `tests/world-gl-browser.js`, run by `npm run test:browser:world-gl` (8 checks each for plane, cylinder and sphere on the preview, 7 each on WebGPU, also under `MARGO_COMPAT=1`). Unit evidence: `tests/world-gl.test.js`. No behaviour changed; the missing row kept `npm run verify` red.
705
-
706
- ## Film time
707
-
708
- `UiRenderer.advanceTime(delta)` runs `ui.update(delta)` (transitions, toasts, tooltips, the caret blink) without drawing; the frame update runs it, so `seek` from `@margoengine/cutscene/seek` replays the overlay's timing.
1
+ # @margoengine/ui
2
+
3
+ Import `margoengine/ui` from the `margoengine` package, or `@margoengine/ui` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
4
+
5
+ Game UI that is drawn inside the engine, so it works in fullscreen and in exported games, with no DOM on top of the
6
+ canvas:
7
+
8
+ - **Widgets:** panels, labels, buttons, toggles, sliders, progress and health bars, lists, inventory grids, menus,
9
+ dialogs, toasts and tooltips.
10
+ - **Layout:** anchors, flex-style rows and columns, grids, scrolling, safe areas.
11
+ - **Scaling:** a reference resolution, the device pixel ratio and the user's text size, with text that stays sharp
12
+ because it is drawn by `@margoengine/text` as signed distance fields.
13
+ - **Themes:** a good-looking dark theme by default, a light theme, a high contrast theme, and `createTheme` for your own.
14
+ All status colours come from the colour-blind-safe Okabe-Ito palette and meaning never rests on colour alone.
15
+
16
+ The package is optional and tree-shakable and adds nothing to core. `Ui` holds the widgets and produces a list of
17
+ rectangles and text in pixels; it touches neither the GPU nor the DOM, so it runs in Node and in tests.
18
+ `UiRenderer` is the engine plugin that draws that list, on WebGPU and on core's WebGL2 preview backend alike.
19
+
20
+ ```ts
21
+ import { Engine } from '@margoengine/core';
22
+ import { Ui, UiRenderer, Menu } from '@margoengine/ui';
23
+
24
+ const engine = await Engine.create(document.querySelector('canvas')!);
25
+ const ui = new Ui(); // dark theme, 1 UI unit = 1 CSS pixel, system font
26
+ UiRenderer.attach(engine, ui); // steps the UI every frame and draws it over the finished frame
27
+
28
+ ui.add(
29
+ new Menu({
30
+ title: 'Paused',
31
+ items: [
32
+ { label: 'Resume', onSelect: () => ui.toast('Back in the game') },
33
+ { label: 'Quit', onSelect: async () => (await ui.confirm('Quit to the title screen?')) && location.reload() },
34
+ ],
35
+ }),
36
+ );
37
+ ```
38
+
39
+ ### The UI as its own layer
40
+
41
+ A tool that renders the frame larger and then takes it down to its output size (supersampling, an upscaler) should lay
42
+ the UI over the finished picture at the output size, so text and panels never go through its filter. `layer: true`
43
+ draws nothing over the frame, and `renderLayer(width, height)` gives the UI as premultiplied, sRGB-coded RGBA bytes
44
+ (row 0 at the top), laid out as the last frame was; over a frame `f` the picture is `rgb + (1 - a) * f`. The shot
45
+ tool's `page.overlay` uses it (docs/shots.md).
46
+
47
+ ```ts
48
+ import { Engine } from '@margoengine/core';
49
+ import { Label, Ui, UiRenderer } from '@margoengine/ui';
50
+
51
+ const engine = await Engine.create(document.querySelector('canvas')!);
52
+ const ui = new Ui();
53
+ ui.add(new Label({ text: 'Caption', anchor: 'bottom-left', margin: 24 }));
54
+ const renderer = UiRenderer.attach(engine, ui, { layer: true });
55
+ engine.render(1 / 60);
56
+ const { width, height, rgba } = await renderer.renderLayer(1920, 1080);
57
+ console.log(width, height, rgba.length); // 1920 1080 8294400
58
+ ```
59
+
60
+ ## Building a screen
61
+
62
+ Every widget is a class you construct with an options object. Put them in a `Panel` (a column by default) and add the
63
+ panel to `ui`. Layout options are on every widget.
64
+
65
+ ```ts
66
+ import { Ui, Panel, Label, Button, Toggle, Slider } from '@margoengine/ui';
67
+
68
+ const ui = new Ui();
69
+ const settings = new Panel({
70
+ background: 'surface',
71
+ border: true,
72
+ shadow: true,
73
+ padding: 24,
74
+ gap: 12,
75
+ width: 360,
76
+ anchor: 'center',
77
+ children: [
78
+ new Label({ text: 'Settings', size: 'title' }),
79
+ new Slider({ text: 'Volume', value: 0.8, onChange: (e) => console.log('volume', e.value) }),
80
+ new Toggle({ text: 'Subtitles', checked: true, onChange: (e) => console.log('subtitles', e.value) }),
81
+ new Button({ text: 'Done', variant: 'primary', onClick: () => settings.removeFromParent() }),
82
+ ],
83
+ });
84
+ ui.add(settings);
85
+ ```
86
+
87
+ `on(type, handler)` works on every widget and returns a function that unsubscribes; it is also disposable, so
88
+ `using off = button.on('click', fn)` ends the subscription at the end of the block. Option callbacks (`onClick`,
89
+ `onChange`, `onSelect`) are shortcuts for `on('click' | 'change' | 'select', ...)`.
90
+
91
+ ## Layout
92
+
93
+ Sizes are UI units. By default one unit is one CSS pixel; see Scaling.
94
+
95
+ `arrange` shares measurements of the same node and available width within one call. A custom
96
+ `LayoutNode.measure` returns a stable content size for that width during the call. The next call
97
+ measures again, so direct edits to styles, children or content take effect without an invalidation API.
98
+ The cache belongs to that call, including when a measurer starts a separate layout.
99
+
100
+ ```ts
101
+ import { arrange, type LayoutNode } from '@margoengine/ui';
102
+
103
+ const label: LayoutNode = {
104
+ style: {}, children: [], rect: { x: 0, y: 0, width: 0, height: 0 },
105
+ measure: (width) => ({ width: Math.min(80, width), height: 20 }),
106
+ };
107
+ const row: LayoutNode = {
108
+ style: { direction: 'row', align: 'center' }, children: [label],
109
+ rect: { x: 0, y: 0, width: 0, height: 0 },
110
+ };
111
+ arrange(row, { x: 0, y: 0, width: 200, height: 100 });
112
+ console.log(label.rect); // { x: 0, y: 40, width: 80, height: 20 }
113
+ ```
114
+
115
+
116
+ | Option | Default | Meaning |
117
+ | --- | --- | --- |
118
+ | `direction` | `'column'` | `'row'`, `'column'`, `'stack'` (children anchored over each other) or `'grid'` |
119
+ | `gap` | `0` | space between children; a number or `[column gap, row gap]` |
120
+ | `align` | stretch (column), center (row) | cross-axis placement: `'start'`, `'center'`, `'end'`, `'stretch'` |
121
+ | `justify` | `'start'` | main-axis placement: `'start'`, `'center'`, `'end'`, `'space-between'`, `'space-around'`, `'space-evenly'` |
122
+ | `padding`, `margin` | `0` | a number, `[vertical, horizontal]` or `[top, right, bottom, left]` |
123
+ | `width`, `height` | `'auto'` | a number, `'auto'` (fit content), `'fill'` or a percentage such as `'50%'` |
124
+ | `minWidth`, `maxWidth`, `minHeight`, `maxHeight` | none | bounds in UI units |
125
+ | `grow`, `shrink` | `0`, `1` | shares of the free or missing main-axis space |
126
+ | `alignSelf` | the parent's `align` | cross-axis placement of this child |
127
+ | `anchor` | `'stretch'` in a stack | `'top-left'`, `'top'`, `'top-right'`, `'left'`, `'center'`, `'right'`, `'bottom-left'`, `'bottom'`, `'bottom-right'` or `'stretch'`; `margin` is the distance from the edges |
128
+ | `position` | `'flow'` | `'absolute'` takes the child out of a row or column and anchors it |
129
+ | `offset` | `[0, 0]` | shift after layout, for animation |
130
+ | `bleed` | `false` | in a stack, ignore the parent's padding and the safe area |
131
+ | `columns`, `cellWidth`, `cellHeight` | `1`, widest, tallest | for `direction: 'grid'` |
132
+ | `overflow` | `'visible'` | `'hidden'` clips; `'scroll'` clips and scrolls on the main axis (a wrapping row scrolls its lines vertically) |
133
+ | `wrap` | `false` | in a `'row'`, children that do not fit move onto new lines below |
134
+
135
+ The screen layer is a stack, so a widget with an `anchor` sits at that corner or edge of the screen, inside the safe area:
136
+
137
+ ```ts
138
+ import { Ui, Panel, Label } from '@margoengine/ui';
139
+
140
+ const ui = new Ui();
141
+ ui.add(
142
+ new Panel({ background: 'scrim', direction: 'row', gap: 12, padding: [8, 16], anchor: 'top-left', margin: 16,
143
+ children: [new Label({ text: 'Gold' }), new Label({ text: '1,250', color: 'warning' })] }),
144
+ new Label({ text: 'Press E to open', anchor: 'bottom', margin: 48, outline: true }),
145
+ );
146
+ ui.update(1 / 60); // lays out the tree
147
+ const [hud] = ui.root.children;
148
+ console.log(hud.rect); // { x, y, width, height } in UI units
149
+ ```
150
+
151
+ Safe areas keep the HUD out of notches, rounded corners and the TV overscan. `new Ui({ safeArea: 'auto' })` (the default)
152
+ reads the device's `env(safe-area-inset-*)`; `ui.setSafeArea([top, right, bottom, left])` sets it in CSS pixels. A widget
153
+ with `bleed: true` (a full-screen backdrop, say) ignores it.
154
+
155
+ ### Wrapping rows
156
+
157
+ A row with `wrap: true` moves the children that do not fit onto new lines, so tag lists and toolbars reflow when the
158
+ panel narrows or the text grows. Each line shares its own free space (`grow`, `shrink`, `justify`) and is as tall as
159
+ its tallest child, which `align` places children within; the second number of `gap` separates the lines. A child
160
+ wider than the row gets a line to itself and shrinks to fit.
161
+
162
+ ```ts
163
+ import { Ui, Panel, Label } from '@margoengine/ui';
164
+
165
+ const ui = new Ui();
166
+ const tags = ['fire', 'ice', 'poison', 'holy', 'shadow', 'storm'].map((text) => new Label({ text }));
167
+ const bar = new Panel({ direction: 'row', wrap: true, gap: [8, 4], width: 200, anchor: 'top-left', children: tags });
168
+ ui.add(bar);
169
+ ui.update(1 / 60);
170
+ console.log(new Set(tags.map((tag) => tag.rect.y)).size); // the number of lines
171
+ bar.setStyle({ width: 600 });
172
+ ui.update(1 / 60); // wide enough now: one line
173
+ ```
174
+
175
+ ## Widgets
176
+
177
+ | Widget | Use | Key options |
178
+ | --- | --- | --- |
179
+ | `Panel` | container with an optional background, outline and shadow | `background`, `border`, `shadow`, `radius` |
180
+ | `Label` | text that wraps and scales | `text`, `size`, `color`, `align`, `wrap`, `outline` |
181
+ | `Button` | push button, 44 units tall at least | `text`, `icon`, `variant`, `onClick` |
182
+ | `Toggle` | switch or checkbox | `text`, `checked`, `variant`, `onChange` |
183
+ | `Slider` | horizontal slider | `min`, `max`, `step`, `value`, `text`, `format`, `onChange` |
184
+ | `ProgressBar` | meter with its value written in it | `value`, `max`, `text`, `variant`, `display` |
185
+ | `HealthBar` | progress bar for hit points, with a damage trail | `value`, `max` |
186
+ | `List` | scrolling list of selectable rows | `items`, `selected`, `onSelect` |
187
+ | `VirtualList` | list that builds only the rows in view, for thousands of entries | `count`, `row`, `rowHeight`, `onSelect` |
188
+ | `Inventory` | grid of item slots; drag, or pick up and put down | `columns`, `slots`, `items`, `onMove`, `onUse` |
189
+ | `Menu` | titled column of buttons | `title`, `items` |
190
+
191
+ `ui.dialog()`, `ui.confirm()` and `ui.alert()` show modal dialogs that return promises, and `ui.toast()` shows a
192
+ message that fades. `AbortSignal` closes a dialog from code.
193
+
194
+ ```ts
195
+ import { Ui, HealthBar, Inventory, Button } from '@margoengine/ui';
196
+
197
+ const ui = new Ui();
198
+ const health = new HealthBar({ max: 100, width: 260, anchor: 'top-left', margin: 16 });
199
+ const bag = new Inventory({
200
+ columns: 4,
201
+ slots: 12,
202
+ anchor: 'bottom-right',
203
+ margin: 16,
204
+ items: [{ id: 'potion', name: 'Potion', icon: '🧪', count: 3, description: 'Restores 25 health' }],
205
+ });
206
+ bag.on('use', (e) => {
207
+ health.value += 25;
208
+ ui.toast(`Used ${(e.item as { name: string }).name}`, { kind: 'success' });
209
+ });
210
+ ui.add(health, bag);
211
+
212
+ health.value = 40; // eases down; the old value lingers as a pale chip
213
+ const respawn = new Button({ text: 'Respawn options' });
214
+ respawn.on('press', async () => {
215
+ const controller = new AbortController();
216
+ const answer = await ui.dialog({
217
+ title: 'Respawn?',
218
+ message: 'You fell off the map.',
219
+ buttons: [{ label: 'Respawn', value: 'respawn' }, { label: 'Quit', value: 'quit' }],
220
+ signal: controller.signal, // controller.abort() closes it and rejects
221
+ });
222
+ console.log(answer);
223
+ });
224
+ ui.add(respawn);
225
+ ```
226
+
227
+ Status never relies on colour alone: bars write their value inside, toasts carry a symbol and a word for screen readers,
228
+ and a switch moves its knob.
229
+
230
+ ### Virtual lists
231
+
232
+ ```ts
233
+ import { Ui, VirtualList } from '@margoengine/ui';
234
+
235
+ const ui = new Ui();
236
+ const entries = Array.from({ length: 50_000 }, (_, i) => ({ time: i * 0.25, text: `Event ${i}` }));
237
+ const log = new VirtualList({
238
+ count: entries.length,
239
+ row: (i) => ({ label: entries[i].text, detail: `${entries[i].time.toFixed(2)} s` }),
240
+ height: 240,
241
+ width: 360,
242
+ anchor: 'top-left',
243
+ margin: 16,
244
+ onSelect: (e) => console.log('picked', e.index),
245
+ });
246
+ ui.add(log);
247
+ ui.update(0);
248
+ console.log(log.range); // [0, 10]: the 6 rows in view and 4 more, the only widgets built
249
+ log.scrollToIndex(40_000); // jump; the rows around it are built on the next update
250
+ ```
251
+
252
+ A `VirtualList` asks `row(index)` only for the rows in view plus `overscan` (default 4) on each side, and stands two
253
+ spacers in for the rest, so scrolling, the scroll bar range and the wheel behave as in a full list while a
254
+ hundred-thousand-row log costs what a screenful does. Every row has the same `rowHeight` (default 44). Arrow keys and
255
+ the d-pad move through all rows, scrolling and building as they go. Set `count` when rows are added or removed, and
256
+ call `refresh()` when their data changes. A focused row that scrolls out of the built range gives up the focus.
257
+ The screen reader mirror reads it as a listbox of the built rows, each telling its place in the whole list.
258
+
259
+ ## Forms, text fields, images, keyboard, languages and a layout editor
260
+
261
+ Six more entries are separate imports, so a screen that does not use them does not load them.
262
+
263
+ - `@margoengine/ui/input` has `TextInput` (single line, or a password that draws one bullet per grapheme) and `TextArea` (several lines). Options: `value`, `placeholder`, `type` (`'text'` or `'password'`), `readOnly`, `maxLength`, `autocomplete` (default `'off'`), `spellcheck`, `required`, `invalid`, `onChange` and `onSubmit`. The canvas paints the text and caret, while a real DOM control that `attachTextInputs(ui, target)` mounts gives you the browser's selection, undo, mobile keyboards and IME. Call `attachTextInputs` after the `UiRenderer`; it returns a function that detaches it.
264
+ - `@margoengine/ui/forms` has `Select`, `Checkbox` (a `Toggle` drawn as a checkbox), `RadioGroup`, `Tabs` and `ColorPicker`. `Select`, `RadioGroup` and `Tabs` take `options`, a list of `{label, value, disabled}` with unique string values, plus `value` and `onChange`; `Tabs` options also carry the `panel` widget that shows while its tab is chosen. `ColorPicker` has HSV, RGB and alpha sliders and a hex field, takes `value` as `#rrggbb` or `#rrggbbaa` (default `#ffffff`) and calls `onChange`. `attachFormsMirror(ui, target)` adds the radio, tab and select ARIA states to the accessibility mirror; attach it after the `UiRenderer`.
265
+ - `@margoengine/ui/image` has `ImageTexture` (decode a URL with cancellation, or copy a decoded image, video frame or canvas) and the `Image` widget. `Image` options: `texture`, `source` (a pixel rectangle), `fit` (`contain` by default, `cover` crops, `fill` stretches), `slice` and `borderScale` for nine-slice borders, and `tint`.
266
+ - `@margoengine/ui/keyboard` has `VirtualKeyboard`, a panel for headsets and touch screens that types into the focused `TextInput` of the same `Ui`. Options: `target`, `rows` (a QWERTY layout with numbers, punctuation and editing keys by default) and `keyWidth`, the minimum width of a normal key (44 UI pixels by default).
267
+ - `@margoengine/ui/i18n` has `Localization`: message tables per locale with `{name}` substitutions and plural forms, a fallback chain, text direction taken from the locale's script (or set with `directions`), and `missing: 'error'` to throw on a missing key instead of showing the key. `bind` ties a translation to a widget, so a locale change reflows the layout on the next frame.
268
+ - `@margoengine/ui/editor` has `LayoutDocument` (a markup layout with undo and redo, validated before each edit commits, saved as a project string) and `LayoutEditor`, a browser editor over it (options `ui`, `canvas`, `actions` and `signal`). Action handlers named in the markup come only from the options you pass, never from the saved project.
269
+
270
+ ### Text fields (`@margoengine/ui/input`)
271
+
272
+ `TextInput` and `TextArea` are painted by the canvas, but the editing is the browser's: `attachTextInputs(ui, canvas)`
273
+ keeps one invisible `<input>` or `<textarea>` over each field, so selection with the keyboard, the clipboard (cut, copy
274
+ and paste, with the system shortcuts and context menu), undo, spellcheck, autofill, mobile keyboards and IME
275
+ composition all behave as in any web form. The canvas reads the value and selection back after every native `input`,
276
+ `select` and `keyup`, and while an IME composes (`field.composing` is `true`), it draws the composition and never resets
277
+ the native value or selection, which would end it.
278
+
279
+ ```ts
280
+ import { Button, Panel, Ui, UiRenderer } from '@margoengine/ui';
281
+ import { Engine } from '@margoengine/core';
282
+ import { TextArea, TextInput, attachTextInputs } from '@margoengine/ui/input';
283
+
284
+ const canvas = document.querySelector('canvas')!;
285
+ const engine = await Engine.create(canvas);
286
+ const ui = new Ui();
287
+ const name = new TextInput({ label: 'Name', placeholder: 'Your name', maxLength: 24, required: true });
288
+ const password = new TextInput({ label: 'Password', type: 'password', autocomplete: 'current-password' });
289
+ const notes = new TextArea({ label: 'Notes', value: 'First line\r\nSecond line' });
290
+ ui.add(new Panel({ anchor: 'center', gap: 12, children: [name, password, notes, new Button({ text: 'Sign in' })] }));
291
+ UiRenderer.attach(engine, ui); // first the renderer, then the native fields
292
+ const detach = attachTextInputs(ui, canvas);
293
+
294
+ name.on('change', () => console.log('typed', name.value));
295
+ name.on('submit', () => ui.focus(password)); // Enter in a single-line field, never while composing
296
+ name.value = 'Ada'; // set from code: no change event
297
+ name.setSelectionRange(3);
298
+ name.insertText(' Lovelace'); // as a virtual keyboard types: replaces the selection, keeps maxLength, emits change
299
+ console.log(name.value, name.selectionStart, notes.value.split('\n').length); // 'Ada Lovelace' 12 2
300
+ engine.start();
301
+ // Later: detach() (or `using`) removes the native fields and their listeners.
302
+ detach();
303
+ ```
304
+
305
+ | Option | Default |
306
+ | --- | --- |
307
+ | `value` | `''`; a `TextInput` drops line breaks, a `TextArea` turns `\r\n` and `\r` into `\n` |
308
+ | `placeholder` | `''`, shown while the field is empty; also the accessible name when there is no `label` |
309
+ | `type` | `'text'`; `'password'` draws one bullet per grapheme over a native password input (`TextInput` only) |
310
+ | `readOnly` | `false`; read-only text can still be selected and copied |
311
+ | `maxLength` | `-1` (no limit), in UTF-16 units as in HTML; `insertText` stops at a whole grapheme within it |
312
+ | `autocomplete` | `'off'`, passed to the native control (`'username'`, `'current-password'`, ...) |
313
+ | `spellcheck` | `true`, `false` for passwords |
314
+ | `required`, `invalid` | `false`, mirrored as `aria-required` and `aria-invalid` |
315
+ | `onChange`, `onSubmit` | `change` after every user edit, IME updates included; `submit` on Enter in a `TextInput` |
316
+
317
+ Selection follows HTML: `selectionStart`, `selectionEnd` and `selectionDirection` in UTF-16 units, and
318
+ `setSelectionRange(start, end, direction)` and `select()` as on an `<input>` (bounds given backwards collapse at the end).
319
+ On the canvas a press places the caret, a drag selects, a double press selects a word (by `Intl.Segmenter`) and a triple
320
+ press selects everything. A gamepad's accept button, or `activate()`, moves the native focus into the field to start
321
+ editing; Escape hands focus back to the canvas. `insertText(text)` is for virtual keyboards and app code: it goes through
322
+ the same edit path as native typing but not through the browser's undo history.
323
+
324
+ Accessibility: each native control carries the field's `label` (or its placeholder) as `aria-label`, its `description`,
325
+ `aria-required` and `aria-invalid`, and stays in the accessibility tree where the canvas cannot be. The controls have
326
+ `tabindex="-1"`: Tab and Shift+Tab move through the `Ui`'s own focus order, and at either end leave the `Ui` for the
327
+ next focusable element of the page. A hidden or disabled field (or one under a disabled panel, or behind a modal) has its
328
+ native control hidden or disabled too.
329
+
330
+ Lifetime: `attachTextInputs` returns a `Detach`; call it, `using` it, or abort `options.signal` to remove every native
331
+ control and listener. `options.container` sets where the controls are placed (default the canvas's parent). A field taken
332
+ out of the `Ui` loses its control at the next change of the `Ui`. Attach once per `Ui`, after its `UiRenderer`.
333
+
334
+ ### Images and nine-slice borders (`@margoengine/ui/image`)
335
+
336
+ An `ImageTexture` is a snapshot: it copies straight-alpha sRGB RGBA bytes when it is made and never changes after, so
337
+ the source can be closed, reused or redrawn at once. Make one from bytes, from anything `drawImage` takes
338
+ (`ImageTexture.from(image | video | canvas | bitmap)`, at its natural size; a video gives its current frame), or from a
339
+ URL (`await ImageTexture.load(url, { signal })`, which fetches, decodes and closes its own bitmap; an aborted signal
340
+ rejects with the signal's reason, and a failed fetch or decode rejects with a `MargoError`).
341
+
342
+ ```ts
343
+ import { Panel, Ui } from '@margoengine/ui';
344
+ import { Image, ImageTexture } from '@margoengine/ui/image';
345
+
346
+ // A 4 by 2 atlas: a red cell on the left, a blue cell on the right.
347
+ const pixels = new Uint8Array(4 * 2 * 4);
348
+ for (let i = 0; i < 8; i++) pixels.set(i % 4 < 2 ? [220, 40, 40, 255] : [40, 80, 220, 255], i * 4);
349
+ const atlas = new ImageTexture(4, 2, pixels);
350
+ pixels.fill(0); // the texture kept its own copy
351
+
352
+ const red = new Image({ texture: atlas, source: { x: 0, y: 0, width: 2, height: 2 }, width: 48, height: 48 });
353
+ const blue = new Image({ texture: atlas, source: { x: 2, y: 0, width: 2, height: 2 }, fit: 'cover', tint: [1, 1, 1, 0.5] });
354
+ const frame = new Image({ texture: atlas, slice: 1, borderScale: 8, width: 200, height: 80 }); // corners stay 8 units
355
+ const ui = new Ui({ width: 320, height: 200 });
356
+ ui.add(new Panel({ anchor: 'center', gap: 8, children: [red, blue, frame] }));
357
+ console.log(atlas.width, atlas.height, red.measure(), blue.measure()); // 4 2 { width: 2, height: 2 } { width: 2, height: 2 }
358
+
359
+ const drawn = new OffscreenCanvas(3, 5);
360
+ drawn.getContext('2d')!.fillRect(0, 0, 3, 5);
361
+ const url = URL.createObjectURL(await drawn.convertToBlob()); // or any same-origin or CORS image URL
362
+ const icon = await ImageTexture.load(url, { signal: AbortSignal.timeout(5000) });
363
+ URL.revokeObjectURL(url);
364
+ red.texture = icon; // swap at any time; the old texture is left for the garbage collector
365
+ red.source = undefined; // the whole new texture
366
+ console.log(icon.width, icon.height); // 3 5
367
+ ```
368
+
369
+ | `new Image({...})` option | Default |
370
+ | --- | --- |
371
+ | `texture` | required, an `ImageTexture` |
372
+ | `source` | the whole texture; an integer pixel rectangle inside it, for one cell of an atlas |
373
+ | `fit` | `'contain'` (letterboxed); `'cover'` fills the box and crops the source's middle; `'fill'` stretches |
374
+ | `slice` | none; top, right, bottom and left border pixels of the source (`Edges`, as `padding`), for nine-slice frames |
375
+ | `borderScale` | `1` UI unit per border pixel; borders shrink when the box is too small for them |
376
+ | `tint` | `[1, 1, 1, 1]`, straight-alpha sRGB 0 to 1, multiplied into every pixel |
377
+
378
+ Without `width` and `height` an `Image` measures as its source rectangle in UI units. With `slice`, `fit` does not apply:
379
+ the corners keep their size, the edges stretch one way and the middle both ways. Every option is also a property; a bad
380
+ value, set from the constructor or later, throws (`TypeError` for a missing texture or unknown fit, `RangeError` for a
381
+ source outside the texture, borders wider than it, or a negative `borderScale`) and leaves the widget as it was.
382
+
383
+ Ownership and GPU residency: an `ImageTexture` holds CPU bytes only, and many `Image`s may share one. The `UiRenderer`
384
+ places what is drawn in its colour atlas (the one emoji use, `colorAtlasSize` 512 by default) as 60 by 60 pixel tiles,
385
+ each with a clamped one-pixel border so filtering never reads a neighbouring cell, and frees the tiles of an image no
386
+ longer drawn at the next upload. There is nothing to dispose on an image: drop the widget and the texture, and
387
+ `renderer.dispose()` frees the atlases. A large image takes many tiles; keep big pictures in an atlas cell no larger
388
+ than they are shown.
389
+
390
+ ### Select, radio buttons, tabs and a colour picker (`@margoengine/ui/forms`)
391
+
392
+ `Select`, `RadioGroup` and `Tabs` take `options`, a list of `{ label, value, disabled }` whose values are unique strings
393
+ (a `TypeError` otherwise), plus `value` (default: the first enabled option) and `onChange`, which receives
394
+ `{ value, index }`. Setting `value` from code checks it names an option (a `RangeError` otherwise) and emits nothing;
395
+ choices made by the user emit `change`. Disabled options cannot be chosen and arrows skip them.
396
+
397
+ ```ts
398
+ import { Label, Panel, Ui } from '@margoengine/ui';
399
+ import { Checkbox, ColorPicker, RadioGroup, Select, Tabs } from '@margoengine/ui/forms';
400
+
401
+ const quality = new Select({
402
+ label: 'Quality',
403
+ options: [
404
+ { label: 'Low', value: 'low' },
405
+ { label: 'High', value: 'high' },
406
+ { label: 'Ultra', value: 'ultra', disabled: true },
407
+ ],
408
+ value: 'high',
409
+ onChange: (e) => console.log('quality', e.value, e.index),
410
+ });
411
+ quality.select('ultra', true); // ignored: disabled
412
+ quality.command('down'); // as the down arrow or d-pad: the next enabled option, wrapping
413
+ console.log(quality.value, quality.expanded); // 'low' false (logged 'quality low 0' first)
414
+
415
+ const hand = new RadioGroup({ label: 'Hand', orientation: 'horizontal', options: [{ label: 'Left', value: 'l' }, { label: 'Right', value: 'r' }] });
416
+ const tabs = new Tabs({
417
+ label: 'Settings',
418
+ options: [
419
+ { label: 'Video', value: 'video', panel: new Panel({ children: [quality] }) },
420
+ { label: 'Controls', value: 'controls', panel: new Panel({ children: [hand, new Checkbox({ text: 'Invert Y' })] }) },
421
+ ],
422
+ });
423
+ tabs.value = 'controls';
424
+ console.log(hand.value, tabs.panels.map((p) => p.visible)); // 'l' [false, true]
425
+
426
+ const tint = new ColorPicker({ value: '#FF8000' });
427
+ console.log(tint.value, tint.hue.toFixed(3), tint.saturation); // '#ff8000ff' '0.084' 1
428
+ tint.value = '#000000';
429
+ console.log(tint.value, tint.hue.toFixed(3), tint.saturation); // '#000000ff' '0.084' 1: black keeps its hue and saturation
430
+ tint.setHSV(0, 0, 1); // from your own control; emits change
431
+ console.log(tint.value, tint.hexInput.value); // '#ffffffff' '#ffffffff'
432
+
433
+ const ui = new Ui({ width: 640, height: 480 });
434
+ ui.add(new Panel({ anchor: 'center', gap: 12, children: [new Label({ text: 'Options' }), tabs, tint] }));
435
+ tabs.dispose(); // disposes every tab's content, the Select (and an open popup) with it
436
+ ```
437
+
438
+ - `Select` is a button showing the chosen label; activating it (press, Enter, gamepad accept) opens a modal dialog with a
439
+ `List` of the options, focus on the current one. Picking an option, Escape or a press outside closes it. `expanded`
440
+ and `popupId` say whether it is open; the `Select` owns the popup and `dispose()` closes it, so a `Select` removed
441
+ while open leaves no dialog behind. Up, down, left and right step through the enabled options without opening it.
442
+ - `Checkbox` is a `Toggle` drawn as a checkbox, with all of `Toggle`'s options and accessibility.
443
+ - `RadioGroup` has one tab stop, on the chosen option (or the first enabled one); arrows move the choice and focus
444
+ together and wrap. `orientation` is `'vertical'` by default; `buttons` are its controls in option order.
445
+ - `Tabs` is a `RadioGroup` whose options each carry the `panel` widget to show (default orientation `'horizontal'`).
446
+ `Tabs` owns those widgets: each goes in its own panel, only the chosen one is visible, and `tabs.dispose()` disposes all
447
+ of them. Choosing a tab with the arrows shows it at once (automatic activation).
448
+ - `ColorPicker` has a saturation and value square, `Hue`, `Saturation`, `Value`, `Red`, `Green`, `Blue` and `Alpha` sliders
449
+ (0 to 1 in steps of 1/255) and `hexInput`, a `TextInput` that applies a complete `#rrggbb` or `#rrggbbaa` as you type.
450
+ `value` reads back normalised as lowercase `#rrggbbaa` (default `#ffffff`, so `#ffffffff`); it accepts `#rgb`,
451
+ `#rrggbb` or `#rrggbbaa`. `hue` and `saturation` (0 to 1) are kept on their own: a grey keeps its hue and black keeps
452
+ its saturation, so dragging the value back up returns the colour you had. `setHSV(h, s, v)` throws a `RangeError`
453
+ outside 0 to 1 and does nothing while the picker is disabled.
454
+
455
+ The screen-reader mirror (`UiRenderer`'s, see Accessibility) knows buttons and sliders. `attachFormsMirror(ui, canvas)`
456
+ adds what forms need: `role="combobox"` with `aria-expanded` and `aria-controls` on a `Select`, `radiogroup` and `radio`
457
+ with `aria-checked` and `aria-orientation`, and `tablist`, `tab` and `tabpanel` with `aria-selected`, `aria-controls` and
458
+ `aria-labelledby`. It also moves the real DOM focus into a `Select`'s popup and back. Call it once after the
459
+ `UiRenderer`; it returns a `Detach` (call it, `using` it, or pass `{ signal }`).
460
+
461
+ ### On-screen keyboard (`@margoengine/ui/keyboard`)
462
+
463
+ `VirtualKeyboard` is a `Panel` of ordinary `Button`s, so the mouse, touch, gamepad spatial navigation and world-panel
464
+ or XR rays work on it with no extra code. Once it is in a `Ui`, it types into whichever `TextInput` of that `Ui` has
465
+ focus; focus moving onto a key does not disconnect it. `connect(field)` sets the field by hand (or `null` to
466
+ disconnect), which is how a keyboard on its own world panel types into a field on another `Ui`.
467
+
468
+ ```ts
469
+ import { Panel, Ui } from '@margoengine/ui';
470
+ import { TextInput } from '@margoengine/ui/input';
471
+ import { VirtualKeyboard } from '@margoengine/ui/keyboard';
472
+
473
+ const ui = new Ui({ width: 800, height: 600 });
474
+ const name = new TextInput({ label: 'Name', onSubmit: (e) => console.log('submit', e.value) });
475
+ const keyboard = new VirtualKeyboard({ anchor: 'bottom' });
476
+ ui.add(new Panel({ anchor: 'center', children: [name] }));
477
+ ui.add(keyboard);
478
+ ui.focus(name);
479
+ console.log(keyboard.target === name); // true
480
+
481
+ keyboard.press('Shift'); // one shifted key, then back to lower case
482
+ for (const key of 'ada') keyboard.press(key);
483
+ console.log(name.value); // 'Ada'
484
+ keyboard.press('CapsLock'); // letters only: digits and punctuation stay unshifted
485
+ keyboard.press('m');
486
+ keyboard.press('1');
487
+ keyboard.press('CapsLock');
488
+ console.log(name.value); // 'AdaM1'
489
+ keyboard.press('Backspace'); // deletes one grapheme (an emoji or accented letter as a whole)
490
+ keyboard.press('ArrowLeft');
491
+ keyboard.press('Delete');
492
+ console.log(name.value, name.selectionStart); // 'Ada' 3
493
+ keyboard.press('Enter'); // a single-line field submits: logs 'submit Ada'; a TextArea gets a new line
494
+
495
+ // A PIN pad: your own rows, each key a string or { key, label, shifted, width }.
496
+ const pin = new VirtualKeyboard({
497
+ rows: [
498
+ ['1', '2', '3'],
499
+ ['4', '5', '6'],
500
+ ['7', '8', '9'],
501
+ [{ key: 'Backspace', label: 'Del' }, '0', { key: 'Enter', label: 'OK' }],
502
+ ],
503
+ keyWidth: 64,
504
+ });
505
+ const code = new TextInput({ maxLength: 4 });
506
+ pin.connect(code);
507
+ for (const key of '12345') pin.press(key);
508
+ console.log(code.value); // '1234': maxLength holds
509
+ code.readOnly = true;
510
+ console.log(pin.press('6'), new VirtualKeyboard().press('a')); // false false: a read-only field, no field
511
+ ```
512
+
513
+ - `rows` default to QWERTY with a number row (shifted to `!@#$%^&*()`), Backspace, Enter, Shift, `,` `.` `?`,
514
+ CapsLock, a wide Space, ArrowLeft, ArrowRight and Delete. Named keys are the W3C key names `Shift`, `CapsLock`,
515
+ `Backspace`, `Delete`, `Enter`, `Space`, `ArrowLeft`, `ArrowRight`, `Home` and `End`; any other key inserts its text.
516
+ - `shifted` is the text a key types with Shift (default: its locale upper case). Shift lasts one key; CapsLock stays on
517
+ and shifts letters only. Shift and CapsLock show as `primary` buttons while on, and letter captions follow them.
518
+ - `width` is relative (default 1) and `keyWidth` is the pixel width of a width-1 key (default 44, the WCAG 2.5.5
519
+ target size); keys are 44 pixels tall. Empty rows, a non-positive `keyWidth` or `width`, or an empty key throw.
520
+ - `press(key)` is what each button runs, so app code and tests can type too. It returns `false` and types nothing
521
+ when the keyboard is disabled, no field is connected, the field is disabled or read-only, or an IME composition is in
522
+ progress in its DOM control. Every handled key emits `'keypress'` with `{ value: key }`.
523
+ - Edits go through `TextInput.insertText` and `setSelectionRange`, so they replace the selection, respect `maxLength`
524
+ and emit `'change'` as typing does. The panel's role is `group`, labelled `'On-screen keyboard'` unless you pass
525
+ `label`.
526
+
527
+ ### Languages (`@margoengine/ui/i18n`)
528
+
529
+ `Localization` holds one message table per locale. `t(key, parameters)` looks the key up in the current locale, then
530
+ its parents (`en-GB`, then `en`), then the `fallback` locale and its parents. Messages substitute `{name}` from
531
+ `parameters`; a plural message is an object of `Intl.PluralRules` forms (`zero`, `one`, `two`, `few`, `many`, `other`)
532
+ and exact counts (`=0`), chosen by the `count` parameter with the plural rules of the locale the message came from.
533
+
534
+ ```ts
535
+ import { Button, Label, Panel, Ui } from '@margoengine/ui';
536
+ import { Localization } from '@margoengine/ui/i18n';
537
+
538
+ const l10n = new Localization(
539
+ {
540
+ en: {
541
+ 'menu.play': 'Play',
542
+ 'menu.quit': 'Quit',
543
+ greeting: 'Hello, {name}',
544
+ coins: { '=0': 'No coins', one: '{count} coin', other: '{count} coins' },
545
+ },
546
+ 'en-GB': { 'menu.quit': 'Exit' },
547
+ ar: { 'menu.play': 'العب', coins: { one: 'عملة واحدة', two: 'عملتان', few: '{count} عملات', other: '{count} عملة' } },
548
+ },
549
+ { locale: 'en-GB' },
550
+ );
551
+ console.log(l10n.locale, l10n.fallback, l10n.direction); // 'en-GB' 'en' 'ltr'
552
+ console.log(l10n.t('menu.play'), l10n.t('menu.quit'), l10n.t('greeting', { name: 'Ada' })); // 'Play' 'Exit' 'Hello, Ada'
553
+ console.log(l10n.t('coins', { count: 0 }), l10n.t('coins', { count: 1 }), l10n.t('coins', { count: 5 })); // 'No coins' '1 coin' '5 coins'
554
+ console.log(l10n.t('menu.options'), l10n.t('greeting')); // 'menu.options' 'Hello, {name}': a missing key or parameter shows
555
+
556
+ const ui = new Ui({ width: 640, height: 360 });
557
+ const play = new Button({});
558
+ const wallet = new Label({});
559
+ let coins = 3;
560
+ ui.add(new Panel({ anchor: 'center', children: [play, wallet] }));
561
+ const unbind = l10n.bind(ui, [
562
+ { target: play, key: 'menu.play' },
563
+ { target: play, key: 'menu.play', property: 'label' }, // the screen-reader name too
564
+ { target: wallet, key: 'coins', parameters: () => ({ count: coins }) },
565
+ ]);
566
+ console.log(play.text, wallet.text, ui.direction); // 'Play' '3 coins' 'ltr'
567
+
568
+ l10n.locale = 'ar-EG'; // uses the ar table; the layout reflows right to left on the next frame
569
+ console.log(l10n.direction, ui.direction, play.text, wallet.text); // 'rtl' 'rtl' 'العب' '3 عملات'
570
+ coins = 11;
571
+ l10n.refresh(); // the parameters changed: apply the bindings again
572
+ console.log(wallet.text); // '11 عملة'
573
+ unbind(); // or `using`, or pass { signal }
574
+ l10n.dispose(); // releases every binding; the widgets keep their text
575
+ ```
576
+
577
+ - `locale` and `fallback` default to the first table's locale (`en` with no tables). Locales are BCP 47 tags,
578
+ canonicalised (`en-gb` becomes `en-GB`); an invalid tag throws a `RangeError`.
579
+ - `direction` is `directions[locale]` (or a parent's) when you pass `directions`, otherwise the browser's
580
+ `Intl.Locale` text info, otherwise the locale's likely script: `he` and `ar` are `'rtl'`, `ar-Latn` is `'ltr'`.
581
+ `bind` sets `ui.direction` from it each time it applies.
582
+ - `missing: 'error'` makes a missing key, or a `{name}` with no parameter, throw a `RangeError` naming it. The default
583
+ `'key'` shows the key (or leaves the token), so a missing string is visible rather than blank. A plural message
584
+ without a finite `count` always throws.
585
+ - `setTable(locale, table)` replaces one locale's table whole (it is copied, so later edits to your object do nothing)
586
+ and reapplies the bindings. A plural message without `other`, or with a form not listed above, throws a `TypeError`.
587
+ - `bind` assigns through each widget's own `text`, `label` or `placeholder` setter, so layout and the accessibility
588
+ mirror update as for any change. `onChange(listener)` runs on every locale or table change and on `refresh()`; it and
589
+ `bind` return a disposable unsubscribe.
590
+
591
+ ### Layout editor (`@margoengine/ui/editor`)
592
+
593
+ `LayoutDocument` holds a markup layout and its style sheet (see Markup and style sheets) with undo and redo. Every edit
594
+ builds the layout before it commits, so an edit that would fail to build throws and leaves the document and its
595
+ history as they were. It needs no DOM or GPU, so tools and tests can edit layouts in Node.
596
+
597
+ ```ts
598
+ import { LayoutDocument } from '@margoengine/ui/editor';
599
+
600
+ const doc = new LayoutDocument(
601
+ { markup: '<panel id="menu"><button id="play" on-click="play">Play</button></panel>', styles: '.big { padding: 16; }' },
602
+ { actions: { play: () => console.log('play') }, historyLimit: 50 },
603
+ );
604
+ doc.onChange(() => console.log(doc.canUndo, doc.canRedo)); // after each commit, undo and redo
605
+ doc.setText('play', 'Start');
606
+ doc.setAttribute('menu', 'class', 'big'); // undefined removes the attribute
607
+ const added = doc.insert('button', 'menu'); // a new <button> at the end of #menu
608
+ console.log(added, doc.tree[0].children.map((c) => c.attributes.id)); // 'element-1' ['play', 'element-1']
609
+ doc.move(added, 'menu', 0); // reorder or reparent; an undefined parent moves it to the top level
610
+ console.log(doc.tree[0].children.map((c) => c.attributes.id)); // ['element-1', 'play']
611
+
612
+ try {
613
+ doc.apply({ markup: '<panel><button on-click="quit">Quit</button></panel>' });
614
+ } catch (e) {
615
+ console.log((e as Error).name); // 'TypeError': quit names no function in actions; nothing changed
616
+ }
617
+ doc.undo(); // back to before the move
618
+ doc.redo();
619
+
620
+ const project = doc.save(); // '{ "version": 1, "markup": ..., "styles": ... }': no functions, no runtime state
621
+ const screen = doc.build(); // fresh widgets you own: add screen.widgets to a Ui, dispose them when done
622
+ console.log(screen.widgets.length, screen.get('play')?.text); // 1 'Start'
623
+
624
+ const other = new LayoutDocument({ markup: '<panel></panel>', styles: '' }, { actions: { play() {} } });
625
+ other.load(project); // one undoable edit; a project of another version throws and changes nothing
626
+ console.log(other.source.markup === doc.source.markup, other.canUndo); // true true
627
+ ```
628
+
629
+ `LayoutEditor` is the browser workspace over a `LayoutDocument`: a widget palette, the element tree (drag to reorder),
630
+ the properties of the selected element, the markup and style sheet as text, undo and redo, and Save and Open. Its
631
+ preview is your own `Ui` drawn by your own `UiRenderer`: the editor moves your canvas into its preview while it lives
632
+ and puts it back where it was (with the accessibility mirror) on `dispose()`. A press on the preview selects the
633
+ element under it, labels and layout boxes included.
634
+
635
+ ```ts
636
+ import { Ui } from '@margoengine/ui';
637
+ import { LayoutEditor } from '@margoengine/ui/editor';
638
+
639
+ const canvas = document.createElement('canvas');
640
+ document.body.append(canvas);
641
+ const ui = new Ui({ width: 640, height: 360 }); // draw it with your UiRenderer as usual
642
+ const controller = new AbortController();
643
+ const editor = new LayoutEditor(document.body, {
644
+ ui,
645
+ canvas,
646
+ markup: '<panel id="hud"><label id="score">Score 0</label></panel>',
647
+ styles: '',
648
+ actions: {}, // the only handlers the markup may name; never read from a project file
649
+ signal: controller.signal, // aborting it disposes the editor
650
+ });
651
+ editor.document.setText('score', 'Score 10');
652
+ await editor.open(new Blob([editor.document.save()])); // a saved project from disk, as one undoable edit
653
+ console.log(editor.element.isConnected, editor.document.canUndo); // true true
654
+ editor.dispose(); // removes the workspace and its listeners; your Ui, canvas and renderer stay
655
+ console.log(editor.element.isConnected, canvas.parentElement === document.body); // false true
656
+ ```
657
+
658
+ - `historyLimit` (default 100, a positive integer) is how many edits undo keeps; the oldest drop first. `dispose()`
659
+ drops the history and listeners and keeps the current source.
660
+ - `insert(tag, parentId)` gives the new element the first free `element-<n>` id; labels, buttons and toggles get their
661
+ tag as text. `setAttribute`, `setText`, `remove` and `move` throw a `RangeError` for an id that does not exist, and
662
+ `move` refuses to put an element inside itself.
663
+ - `open(file, { signal })` reads a `Blob` or `File`; aborting the call's signal or the editor's stops it before the
664
+ document changes. The workspace lives in a shadow root, so its styles do not leak into the page.
665
+
666
+ ## Theming
667
+
668
+ `themes.dark` is the default (`themeForPreferences()` picks high contrast, light or dark from the user's settings).
669
+ `createTheme` makes your own from any base:
670
+
671
+ ```ts
672
+ import { Ui, createTheme, themes } from '@margoengine/ui';
673
+
674
+ const forest = createTheme({ name: 'forest', colors: { primary: '#7bd88f', onPrimary: '#06210d' }, radius: 12 }, themes.dark);
675
+ const ui = new Ui({ theme: forest });
676
+ ui.theme = themes.highContrast; // restyles everything on the next frame
677
+ ```
678
+
679
+ | Theme | Notes |
680
+ | --- | --- |
681
+ | `themes.dark` | default; every text colour is at least 4.5:1 on what it is drawn on |
682
+ | `themes.light` | same contrast rules on light surfaces |
683
+ | `themes.highContrast` | black, white, yellow and cyan; 7:1 text, thick outlines, 4-unit focus ring, no shadows or motion |
684
+
685
+ The colour roles (`primary`, `success`, `warning`, `danger`, `info`, `accent`, `focus`, `surface`, `text`, ...) are
686
+ documented on `ThemeColors`. The tests check text contrast for every built-in theme and that the success, warning and
687
+ danger colours stay apart for protan, deutan and tritan viewers (`simulateColorBlindness`, `contrastRatio` and
688
+ `colorDifference` are exported so you can check your own theme the same way).
689
+
690
+ ## Scaling
691
+
692
+ ```ts
693
+ import { Ui } from '@margoengine/ui';
694
+
695
+ const ui = new Ui({
696
+ scale: { reference: [1280, 720], match: 0.5 }, // design for 720p; the UI scales with the window
697
+ textScale: 1.25, // the user's text size preference, 0.5 to 3
698
+ });
699
+ ui.resize(1920, 1080, window.devicePixelRatio);
700
+ console.log(ui.width, ui.height, ui.scale); // 1280 720 1.5 (with a pixel ratio of 1)
701
+ ```
702
+
703
+ UI units become CSS pixels by the resolution scale and device pixels by the pixel ratio on top; text is laid out in UI
704
+ units and drawn as signed distance fields at the final pixel size, so it stays sharp. `UiRenderer` calls `resize` from
705
+ the canvas every frame. `textScale` multiplies every text size and reflows the layout.
706
+
707
+ ## Arabic, Indic and right-to-left text
708
+
709
+ ```ts
710
+ import { Label, Panel, Ui } from '@margoengine/ui';
711
+
712
+ const ui = new Ui({ ligatures: true }); // Latin words draw as shaped runs too, so fi and fl join
713
+ ui.add(
714
+ new Panel({
715
+ anchor: 'top-left',
716
+ children: [
717
+ new Label({ text: 'مرحبا بالعالم', width: 300 }), // joined Arabic letters, at the right edge of its box
718
+ new Label({ text: 'नमस्ते दुनिया', width: 300 }), // Devanagari conjuncts and vowel signs
719
+ new Label({ text: 'office flow', width: 300 }),
720
+ ],
721
+ }),
722
+ );
723
+ console.log(ui.textDirection('مرحبا')); // 'rtl'
724
+ ```
725
+
726
+ UI text is laid out by `@margoengine/text`, which hands each Arabic and Indic word (Devanagari, Bengali, Tamil and the
727
+ other Indic scripts) to the browser's shaper as one run, so letters join, conjuncts form and vowel signs sit where they
728
+ belong. `ligatures: true` does the same for Latin words. Each text reads in the direction of its first strong letter
729
+ (`ui.textDirection(text)`), and `'start'` alignment is its reading start: the right edge for Arabic and Hebrew.
730
+ `direction: 'rtl'` or `'ltr'` sets one direction for all UI text instead. Both can be changed later (`ui.ligatures`,
731
+ `ui.direction`), which lays the text out again.
732
+
733
+ ## Mouse, touch, keyboard and gamepad
734
+
735
+ `UiRenderer.attach(engine, ui)` connects the engine's canvas for you (`{ input: false }` turns that off; a headless canvas in Node has no pointer events, so it is left out and the UI only draws). Everything works
736
+ with every device:
737
+
738
+ | Input | What it does |
739
+ | --- | --- |
740
+ | Mouse, pen | hover, click, drag sliders and inventory items, wheel scrolls lists |
741
+ | Touch | tap, drag, scroll; touch never hovers |
742
+ | Arrow keys, d-pad, left stick | move focus to the nearest widget in that direction (holding repeats); a focused slider takes left and right |
743
+ | Tab, Shift+Tab, bumpers | step through the widgets; Tab past the last one hands the keyboard back to the page |
744
+ | Enter, Space, gamepad A | press the focused widget |
745
+ | Escape, gamepad B | close the tooltip, then the dialog |
746
+
747
+ The focus ring shows for the keyboard and gamepad and hides for the mouse and touch. A dialog traps focus, puts it on its
748
+ first button and gives it back when it closes. A press that lands on a widget never reaches other listeners on the canvas
749
+ (it will not also orbit the camera) and `ui.wantsPointer(x, y)` tells your own code when the pointer is over the UI. Keys
750
+ go to the UI only while a widget has focus or a dialog is open; set `ui.captureKeys = true` while a full-screen menu shows
751
+ so the arrows work from the first press.
752
+
753
+ ```ts
754
+ import { Input } from '@margoengine/input';
755
+ import { Ui, uiActions } from '@margoengine/ui';
756
+
757
+ const ui = new Ui();
758
+ // Gamepad (and, with { keyboard: true }, keys) as Input actions; merge your own actions in the same object.
759
+ const input = new Input({ ...uiActions(), jump: [{ type: 'key', code: 'Space' }] });
760
+ ui.bindInput(input); // reads the ui.* actions each ui.update(); call input.update() before it
761
+
762
+ ui.captureKeys = true; // a full-screen menu is open
763
+ ui.navigate('down'); // the same thing the arrow keys, the d-pad and the stick do
764
+ ui.accept(); // Enter, Space, gamepad A
765
+ ui.cancel(); // Escape, gamepad B: returns false when there was nothing to close
766
+ console.log(ui.focused?.label, ui.inputMode); // 'keyboard'
767
+ ```
768
+
769
+ To handle the events yourself, call `ui.pointerMove`, `ui.pointerDown`, `ui.pointerUp`, `ui.wheel`, `ui.navigate`,
770
+ `ui.tab`, `ui.accept` and `ui.cancel` (or `ui.execute(command)`) from your own listeners, or attach a different element with
771
+ `attachInput(ui, element, { signal })`, which returns a function that detaches it and is also disposable.
772
+
773
+ ```ts
774
+ import { Ui, Panel, Button, attachInput } from '@margoengine/ui';
775
+
776
+ const ui = new Ui();
777
+ ui.add(new Panel({ children: [new Button({ text: 'Play', tooltip: 'Start a new game' })] }));
778
+ const controller = new AbortController();
779
+ attachInput(ui, document.querySelector('canvas')!, { signal: controller.signal });
780
+ // controller.abort() removes every listener again.
781
+ ```
782
+
783
+ A widget with a `tooltip` shows it after half a second of hovering, or a moment after the keyboard focuses it; Escape
784
+ hides it. Tooltips sit below the widget and flip above it at the bottom of the screen.
785
+
786
+ ## Accessibility
787
+
788
+ The interface is usable without a mouse, without sight and without colour vision, and nothing needs configuring:
789
+
790
+ - **Keyboard and gamepad:** every control can be reached and operated, the focus ring is always visible when the keyboard
791
+ or gamepad moves focus, and a dialog traps focus. Tab never traps the keyboard: past the last widget it returns to the page.
792
+ - **Screen readers:** `UiRenderer` also attaches a hidden DOM mirror (`attachMirror`) next to the canvas (not on a headless canvas, which has no document). It holds real
793
+ buttons, switches, range inputs, progress bars, listboxes, dialogs and text, laid over the widgets so touch exploration
794
+ works, and it shares focus with the canvas: Tab or a screen reader moving to an element focuses its widget, and moving focus
795
+ in the UI moves DOM focus so the reader announces it. Everything behind an open dialog is `inert`.
796
+ - **Announcements:** toasts go to polite (assertive for errors) live regions, and `ui.announce(message)` says anything else.
797
+ A widget's `tooltip` and `description` become `aria-describedby`.
798
+ - **Colour:** the themes keep success, warning and danger apart for protan, deutan and tritan viewers, bars and toasts
799
+ carry words and symbols as well as colour, and `themes.highContrast` is black, white, yellow and cyan with 7:1 text.
800
+ `themeForPreferences()` picks high contrast for `prefers-contrast: more` and forced colours.
801
+ - **Text size:** `ui.textScale` from 0.5 to 3 reflows the whole interface, and `new Ui({ textScale: 'auto' })` follows the font
802
+ size the user set in the browser (`browserTextScale()`).
803
+ - **Motion:** `prefers-reduced-motion` turns transitions, easing and fades off (`ui.motion`).
804
+ - **Targets:** buttons, toggles, sliders and list rows are at least 44 units tall.
805
+
806
+ ```ts
807
+ import { Ui, UiRenderer, attachMirror, themeForPreferences } from '@margoengine/ui';
808
+ import type { EngineKernel } from '@margoengine/core';
809
+
810
+ export function accessibleUi(engine: EngineKernel): Ui {
811
+ const ui = new Ui({ theme: themeForPreferences(), textScale: 'auto' });
812
+ // The renderer attaches input and the mirror itself; to attach them by hand, turn them off and call:
813
+ UiRenderer.attach(engine, ui, { input: false, mirror: false });
814
+ const detach = attachMirror(ui, engine.canvas, { label: 'Menu and heads-up display' });
815
+ ui.announce('Level 3. Your health is full.');
816
+ void detach; // call it to remove the mirror; it is also disposable: using detach = attachMirror(...)
817
+ return ui;
818
+ }
819
+ ```
820
+
821
+ Keep these working in your own widgets: give a `Widget` a `label` (its accessible name; text widgets use their text), a `description`,
822
+ and `focusable = true` with an `activate()` method for anything that reacts to accept.
823
+
824
+ ## Real HTML: the DOM host
825
+
826
+ The same widgets can also live as real, visible HTML instead of being drawn on the canvas, for pages that are mostly
827
+ text, forms and lists. `mountDom` from `@margoengine/ui/dom` shows a `Ui` (or one widget of it) in an element, so the
828
+ browser's own keyboard handling, screen readers, IME, autofill, spellcheck, zoom and touch work on them, and app code is
829
+ the same as on the canvas: a click on the `<button>` fires the widget's `'click'`, typing fires the text input's
830
+ `'change'`, and setting `label.text` patches only that label's element.
831
+
832
+ ```ts
833
+ import { Button, Label, List, Panel, Ui } from '@margoengine/ui';
834
+ import { TextArea } from '@margoengine/ui/input';
835
+ import { mountDom, type DomHost } from '@margoengine/ui/dom';
836
+
837
+ export function reviewPage(container: HTMLElement): DomHost {
838
+ const ui = new Ui();
839
+ const answer = new TextArea({ label: 'Change this', placeholder: 'Say what to change' });
840
+ const send = new Button({ text: 'Send', variant: 'primary' });
841
+ const changes = new List({ label: 'What changed', items: [] });
842
+ send.on('click', () => {
843
+ changes.items = [...changes.items, answer.value];
844
+ ui.toast('Sent');
845
+ });
846
+ ui.add(
847
+ new Panel({ gap: 12, padding: 16, children: [new Label({ text: 'Review', size: 'title' }), answer, send, changes] }),
848
+ );
849
+ return mountDom(ui, container, { label: 'Review' }); // dispose it (or `using`) to remove every element and listener
850
+ }
851
+ ```
852
+
853
+ - **Elements:** native first, ARIA only where HTML has none. Buttons are `<button>`, toggles and checkboxes
854
+ `<input type="checkbox">` (toggles with `role="switch"`), sliders range inputs, `Select` a `<select>`, `RadioGroup` a
855
+ `<fieldset>` of radios, `TextInput` and `TextArea` `<input>` and `<textarea>`, meters `<progress>`, and dialogs a modal
856
+ `<dialog>` (`showModal`: focus moves in, the page behind is inert, Escape asks the widget). `Tabs`, `List`,
857
+ `VirtualList` (with `aria-setsize` and `aria-posinset`) and inventories follow the WAI-ARIA Authoring Practices
858
+ patterns with one tab stop each. Roles and states come from the same module as the canvas's screen reader mirror, so
859
+ the two cannot drift. A `Menu` is a group of buttons, not `role="menu"`: the Authoring Practices keep the menu role for
860
+ application menus, and a game or page menu is navigation.
861
+ - **Two-way, keyed patching:** each widget keeps its element. A change touches only the attributes, text and CSS
862
+ properties that differ, and children that move are reordered with the fewest moves (the longest run already in order
863
+ stays), so focus, the caret, an IME composition and scroll positions survive.
864
+ - **Layout:** each widget's layout style becomes CSS flexbox and grid (row, column, stack, grid, gap, align, justify,
865
+ padding, margin, sizes, grow, wrap, anchors, scroll), so the page reflows at any zoom.
866
+ - **Look:** the theme becomes CSS custom properties on the container (`--mg-primary`, `--mg-surface`, `--mg-radius`,
867
+ `--mg-target` and the rest) read by one shared constructable stylesheet. No style attribute is written, so a strict
868
+ `style-src 'self'` Content Security Policy passes (where constructable stylesheets are missing, pass `nonce` for the
869
+ fallback `<style>`). Focus rings use `:focus-visible`, `prefers-reduced-motion` turns transitions off and forced
870
+ colours use the system colours. Controls are at least `targetSize` CSS pixels (default 44; 24 is the WCAG 2.2 minimum).
871
+ - **Toasts and announcements** go to the host's live regions, and `update` (on by default) steps `ui.update` on
872
+ animation frames so toasts time out. Pass `update: false` and `announce: false` when a `UiRenderer` drives the same `Ui`.
873
+
874
+ | Option | Default | Meaning |
875
+ | --- | --- | --- |
876
+ | `theme` | the UI's theme | The look; followed when `ui.theme` changes. |
877
+ | `label` | none | Accessible name of the mounted region. |
878
+ | `targetSize` | `44` | Smallest control size in CSS pixels, 24 or more. |
879
+ | `update` | `true` | Step `ui.update` on animation frames. |
880
+ | `announce` | `true` | Send announcements and toasts to live regions. |
881
+ | `nonce` | none | Nonce of the fallback `<style>` element. |
882
+ | `idPrefix` | `'margo-dom-'` | Start of every element id. |
883
+ | `signal` | none | Unmount when it aborts. |
884
+
885
+ The handle also has `elementOf(widget)`, `widgetOf(node)` and `flush()`. To place HTML in the 3D scene (like CSS2D and
886
+ CSS3D labels), use `@margoengine/labels` and `@margoengine/html`.
887
+
888
+ Sources: W3C, [WAI-ARIA 1.2](https://www.w3.org/TR/wai-aria-1.2/), 2023, and the
889
+ [ARIA Authoring Practices Guide](https://www.w3.org/WAI/ARIA/apg/patterns/) (tabs, listbox, menu and dialog patterns);
890
+ WHATWG, [HTML Living Standard](https://html.spec.whatwg.org/multipage/) (forms, the `dialog` element, `inert`); W3C,
891
+ [WCAG 2.2](https://www.w3.org/TR/WCAG22/), 2023 (2.1.1 keyboard, 2.4.7 focus visible, 2.5.8 target size, 4.1.2 name,
892
+ role, value); W3C, [CSS Flexible Box Layout Level 1](https://www.w3.org/TR/css-flexbox-1/); Michael L. Fredman,
893
+ [On computing the length of longest increasing subsequences](https://doi.org/10.1016/0012-365X(75)90103-X), 1975 (the
894
+ fewest moves of a keyed reorder); Nick ten Veen, Daco Harkes and Eelco Visser,
895
+ [PixieDust: Declarative Incremental User Interface Rendering Through Static Dependency Tracking](https://doi.org/10.1145/3184558.3185978),
896
+ 2018 (patching from known dependencies instead of diffing whole trees); Aiden Bai and others,
897
+ [Million.js: A Fast Compiler-Augmented Virtual DOM for the Web](https://arxiv.org/abs/2202.08409), 2022 (the costs of
898
+ diffing and patching in keyed virtual DOM reconciliation).
899
+
900
+ ## React
901
+
902
+ `@margoengine/ui/react` has thin components for the same widgets. They render no DOM: nest them inside `UiRoot` and they
903
+ become widgets of one `Ui`, drawn on the engine's canvas. Props update the widgets in place, `onClick`, `onChange`,
904
+ `onSelect`, `onMove` and `onUse` are the widgets' events, and `checked`, `value`, `items` and `selected` are controlled, so
905
+ state lives in React. `react` is an optional peer dependency of this package.
906
+
907
+ ```tsx
908
+ import { useState } from 'react';
909
+ import type { EngineKernel } from '@margoengine/core';
910
+ import { themes, type InventoryItem } from '@margoengine/ui';
911
+ import { UiRoot, Panel, Label, HealthBar, Inventory, Toggle, Button, useUi } from '@margoengine/ui/react';
912
+
913
+ export function Hud({ engine, hp }: { engine: EngineKernel; hp: number }) {
914
+ const [contrast, setContrast] = useState(false);
915
+ const [bag, setBag] = useState<(InventoryItem | null)[]>([{ id: 'potion', name: 'Potion', icon: '🧪', count: 2 }, null, null, null]);
916
+ return (
917
+ <UiRoot engine={engine} theme={contrast ? themes.highContrast : themes.dark}>
918
+ <Panel background="scrim" padding={12} gap={8} anchor="top-left" margin={16}>
919
+ <Label text="Camp" size="large" />
920
+ <HealthBar value={hp} max={100} width={240} />
921
+ <Toggle text="High contrast" checked={contrast} onChange={(e) => setContrast(e.value as boolean)} />
922
+ </Panel>
923
+ <Panel anchor="bottom-right" margin={16}>
924
+ <Inventory columns={2} slots={4} items={bag} onMove={() => setBag([...bag])} />
925
+ </Panel>
926
+ <Respawn />
927
+ </UiRoot>
928
+ );
929
+ }
930
+
931
+ function Respawn() {
932
+ const ui = useUi(); // toast(), dialog(), confirm(), announce() for event handlers
933
+ return <Button text="Respawn" anchor="bottom" margin={16} onClick={() => ui.toast('Respawned', { kind: 'success' })} />;
934
+ }
935
+ ```
936
+
937
+ Create `UiRoot` where the engine is known (in a child of `@margoengine/react`'s `<Canvas>`, call `useEngine()` and pass it as
938
+ `engine`). Pass `ui={yourUi}` to share one `Ui` with plain code. Widgets join their parent in mount order, so show and hide a
939
+ widget with `visible` rather than by mounting it conditionally if its place in the order matters. A Next.js server component may import these components: the `react-server` export condition maps
940
+ `@margoengine/ui/react` to a `'use client'` boundary, while every other bundler loads a plain module with no directive (so
941
+ Vite and Rollup print no warning for it). Props only a constructor
942
+ reads (a slider's `min` and `max`, an inventory's `columns` and `slots`) recreate the widget when they change.
943
+
944
+ ## World-space and XR panels
945
+
946
+ `@margoengine/ui/world` puts a `Ui` on a flat panel in the 3D scene: a diegetic screen on a terminal, a VR menu, a wrist
947
+ panel. The panel's `Ui` keeps its own size in CSS pixels; `WorldPanels` draws it into a texture (redrawn only when the UI
948
+ changes, with mipmaps so a distant panel does not shimmer) and puts that texture on a quad in the scene, depth-tested
949
+ against it, in every view and XR eye. A mouse, pen or touch on the canvas reaches the nearest panel under it by a ray from
950
+ the camera, and a press a panel used never reaches the game.
951
+
952
+ ```ts
953
+ import { Engine } from '@margoengine/core';
954
+ import { Ui, Panel, Label, Button } from '@margoengine/ui';
955
+ import { WorldPanel, WorldPanels } from '@margoengine/ui/world';
956
+
957
+ const engine = await Engine.create(document.querySelector('canvas')!);
958
+ const menu = new Ui({ width: 480, height: 300 }); // its own Ui, in CSS pixels of the panel
959
+ menu.add(
960
+ new Panel({
961
+ background: 'surface',
962
+ anchor: 'stretch',
963
+ padding: 24,
964
+ gap: 12,
965
+ children: [
966
+ new Label({ text: 'Workshop', size: 'title' }),
967
+ new Button({ text: 'Craft', variant: 'primary', onClick: () => menu.toast('Crafted') }),
968
+ ],
969
+ }),
970
+ );
971
+ const panels = WorldPanels.attach(engine); // draws every panel in the scene and routes canvas pointers to them
972
+ panels.add(new WorldPanel(menu, { width: 1.2, position: [0, 1.4, -1.5], pixelRatio: 2 }));
973
+ ```
974
+
975
+ | `new WorldPanel(ui, {...})` option | Default |
976
+ | --- | --- |
977
+ | `width` | `1` world unit (metres in glTF scenes) |
978
+ | `height` | the width times the UI's height over its width, so the UI keeps its shape |
979
+ | `position`, `rotation` | `[0, 0, 0]` and the quaternion `[0, 0, 0, 1]`: the UI faces +Z with +Y up |
980
+ | `pixelRatio` | `1` texture pixel per CSS pixel; 2 reads sharper up close in VR |
981
+ | `doubleSided` | `false`: the back is invisible and takes no input; `true` shows the UI from behind too, mirrored so it reads |
982
+
983
+ `panel.matrix` is the pose (column-major, rotation and translation only): copy a controller's grip pose into it for a wrist
984
+ menu, or call `panel.setPose(position, rotation)`. `WorldPanels.attach(engine, { order, input })` takes the frame graph order
985
+ (default 25: in the scene, before post-processing) and `input: false` to leave the canvas alone.
986
+
987
+ Rays from anything else go through `panels.pointer(ray, pressed, { id })`: the ray hovers the nearest visible panel, a change
988
+ of `pressed` presses or releases, and a pressed pointer keeps its panel until it is released (a slider dragged off the
989
+ edge). For XR, hand each controller to `panels.controller(controller, id)` every frame: `@margoengine/xr`'s `XRController`
990
+ has the shape it reads (`targetRayMatrix` and `buttons`), its ray hovers and button 0, the trigger, presses.
991
+
992
+ ```ts
993
+ import type { RayController, WorldPanels } from '@margoengine/ui/world';
994
+
995
+ // Call once a frame during an XR session; ids keep the two hands apart.
996
+ export function pointAtPanels(panels: WorldPanels, controllers: readonly RayController[]): void {
997
+ controllers.forEach((controller, hand) => panels.controller(controller, hand + 1));
998
+ }
999
+ ```
1000
+
1001
+ `panel.intersect(ray)` returns the hit (distance, world point, UI pixel, inside or not), `pickPanel(panels, ray)` the nearest
1002
+ panel under a ray, `screenRay(camera, x, y, width, height)` the ray under a canvas point and `rayFromMatrix(pose)` an XR
1003
+ pointing ray. Give a panel's `Ui` to `WorldPanels` only, never also to `UiRenderer`: the renderer would resize it to the
1004
+ canvas. Keyboard and gamepad focus work as on the screen through the panel's own `ui` (`ui.bindInput`, `ui.navigate`).
1005
+
1006
+ ### Curved panels and panel layouts (`@margoengine/ui/curved`)
1007
+
1008
+ `CurvedPanel` is a `WorldPanel` bent onto a cylinder or a sphere, for a menu that wraps around the player. It takes every
1009
+ `WorldPanel` option; `width` and `height` are arc lengths in metres along the surface, and the panel's origin is the
1010
+ middle of the patch, where the surface touches the panel's local `z = 0` plane, with the centre of curvature at
1011
+ `[0, 0, -radius]` (the UI faces +Z, so the curve bows away from a viewer in front of it).
1012
+
1013
+ | `new CurvedPanel(ui, {...})` option | Default |
1014
+ | --- | --- |
1015
+ | `shape` | `'cylinder'`: curved left to right only; `'sphere'` curves top to bottom too |
1016
+ | `radius` | `2` metres; must be positive and finite |
1017
+ | `segments` | `64` quads per curved axis, an integer from 4 to 512; only the drawing is tessellated |
1018
+ | every `WorldPanel` option | as above (`width`, `height`, `position`, `rotation`, `pixelRatio`, `doubleSided`) |
1019
+
1020
+ The constructor throws a `RangeError` for an unknown shape, a radius that is not positive, segments outside 4 to 512, a
1021
+ width of one full circumference or more, or (for a sphere) a height of half a circumference or more.
1022
+
1023
+ A ray hits the exact cylinder or sphere, not the drawn triangles, so a press lands on the same UI pixel whatever
1024
+ `segments` is. `panel.pointAt(u, v)` is the local position of a UI point given as 0 to 1 across and down (`[0, 0, 0]` at
1025
+ the middle, `pointAt(0, 0)` the top left corner); the shader draws with the same mapping. `intersect` reports `back: true`
1026
+ for a hit from behind, mirrored so the UI reads, and skips it unless the panel is `doubleSided`.
1027
+
1028
+ `layoutPanels(panels, options)` sets the pose of each panel, row by row, on a plane, cylinder or sphere; it works for
1029
+ flat `WorldPanel`s and `CurvedPanel`s alike and keeps their sizes. Each panel faces out from the centre of curvature,
1030
+ or toward it with `inward: true`, tangent to the surface. The last row, when shorter, is centred.
1031
+
1032
+ | `layoutPanels(panels, {...})` option | Default |
1033
+ | --- | --- |
1034
+ | `shape` | `'plane'`; `'cylinder'` or `'sphere'` put the panels round an arc |
1035
+ | `columns` | `ceil(sqrt(panels.length))` |
1036
+ | `spacing` | `[1.2, 0.8]` metres between panel centres across and down, measured along the arc |
1037
+ | `radius` | `2` metres |
1038
+ | `position` | `[0, 0, 0]`: the middle of the arrangement, where it touches its tangent plane |
1039
+ | `inward` | `false`: panels face away from the centre of curvature |
1040
+
1041
+ It throws a `RangeError` for an unknown shape, columns that are not a positive integer, a spacing or radius that is not
1042
+ positive, a position that is not finite, or an arrangement that would wrap onto itself (a row as long as the
1043
+ circumference, or for a sphere, a column as tall as half of it).
1044
+
1045
+ ```ts
1046
+ import { Button, Label, Panel, Ui } from '@margoengine/ui';
1047
+ import { CurvedPanel, layoutPanels } from '@margoengine/ui/curved';
1048
+
1049
+ const screen = (title: string) => {
1050
+ const ui = new Ui({ width: 400, height: 240 });
1051
+ ui.add(
1052
+ new Panel({
1053
+ background: 'surface',
1054
+ anchor: 'stretch',
1055
+ padding: 16,
1056
+ children: [new Label({ text: title, size: 'title' }), new Button({ text: 'Open' })],
1057
+ }),
1058
+ );
1059
+ return ui;
1060
+ };
1061
+ const wall = new CurvedPanel(screen('Inventory'), { width: 2, radius: 1.5, position: [0, 1.5, -1.5] });
1062
+ console.log(wall.surface, wall.pointAt(0.5, 0.5)); // [1.5, 1, 64, 1] [0, 0, 0]
1063
+ const hit = wall.intersect({ origin: [0, 1.5, 0], direction: [0, 0, -1] });
1064
+ console.log(hit?.inside, hit?.x, hit?.y); // true 200 120: the middle of the 400 by 240 UI
1065
+
1066
+ const menus = ['Map', 'Quests', 'Crafting', 'Settings'].map((title) => new CurvedPanel(screen(title), { width: 1, radius: 2 }));
1067
+ layoutPanels(menus, { shape: 'cylinder', columns: 4, spacing: [1.1, 0.8], radius: 2, position: [0, 1.5, -2], inward: true });
1068
+ console.log(menus.map((panel) => panel.matrix[13].toFixed(2))); // ['1.50', '1.50', '1.50', '1.50']
1069
+ ```
1070
+
1071
+ Add the panels to a `WorldPanels` (or the `@margoengine/ui/world-gl` one below) as any other panel.
1072
+
1073
+ ### World panels on every backend (`@margoengine/ui/world-gl`)
1074
+
1075
+ `@margoengine/ui/world` draws with WebGPU only: native WebGPU and the full WebGL2 compatibility layer, which both
1076
+ report `backend: 'webgpu'`. `@margoengine/ui/world-gl` exports everything `@margoengine/ui/world` does, with a
1077
+ `WorldPanels` that also draws on the small `@margoengine/webgl2-compat/preview` renderer. Swap the import and nothing
1078
+ else changes:
1079
+
1080
+ ```ts
1081
+ import { Engine } from '@margoengine/core';
1082
+ import { webglRenderer } from '@margoengine/webgl2-compat/preview';
1083
+ import { Button, Panel, Ui } from '@margoengine/ui';
1084
+ import { WorldPanel, WorldPanels } from '@margoengine/ui/world-gl';
1085
+
1086
+ const engine = await Engine.create(document.querySelector('canvas')!, { fallback: webglRenderer });
1087
+ const menu = new Ui({ width: 320, height: 200 });
1088
+ menu.add(new Panel({ background: 'surface', anchor: 'stretch', padding: 16, children: [new Button({ text: 'Start' })] }));
1089
+ const panels = WorldPanels.attach(engine); // the WebGPU renderer on 'webgpu', its own WebGL2 program on 'webgl2'
1090
+ panels.add(new WorldPanel(menu, { width: 1, position: [0, 1.5, -1.5] }));
1091
+ console.log(engine.backend, panels.list.length); // 'webgpu' 1, or 'webgl2' 1 where WebGPU is missing
1092
+ engine.start();
1093
+ ```
1094
+
1095
+ On `backend: 'webgpu'` it is the WebGPU `WorldPanels`, unchanged. On the preview it keeps the same options (`order`,
1096
+ `input`, `signal`), the same `WorldPanel` and `CurvedPanel` options, the same canvas pointer routing and the same
1097
+ `pointer` and `controller` rays. What differs on the preview:
1098
+
1099
+ - Each panel draws into a WebGL2 texture with a full mip chain, then onto the scene with depth test, no depth write and
1100
+ premultiplied alpha, after the frame; the WebGL2 state it changes is put back afterwards.
1101
+ - A panel larger than the context's `MAX_TEXTURE_SIZE` (its UI size times `pixelRatio`) throws a `RangeError` at its
1102
+ first draw; lower its size or `pixelRatio`.
1103
+ - When the engine restores a lost context, the panel textures and the program are made again.
1104
+ - `dispose()` (or `using`) deletes every panel's texture, framebuffer and painter, the program, and the canvas listeners.
1105
+
1106
+ ## Markup and style sheets
1107
+
1108
+ ```ts
1109
+ import { Ui } from '@margoengine/ui';
1110
+ import { buildScreen } from '@margoengine/ui/markup';
1111
+
1112
+ const markup = `
1113
+ <panel id="pause" class="menu">
1114
+ <label class="title">Paused</label>
1115
+ <row class="buttons">
1116
+ <button variant="primary" on-click="resume">Resume</button>
1117
+ <button on-click="quit">Quit</button>
1118
+ </row>
1119
+ <toggle id="music" checked="true">Music</toggle>
1120
+ <list id="saves" height="120"><item detail="2 h">Slot 1</item><item>Slot 2</item></list>
1121
+ </panel>`;
1122
+ const styles = `
1123
+ .menu { anchor: center; width: 320; padding: 16; gap: 12 }
1124
+ .menu .title { size: large }
1125
+ .buttons > button { grow: 1 }`;
1126
+
1127
+ const ui = new Ui();
1128
+ const screen = buildScreen(markup, {
1129
+ styles,
1130
+ actions: { resume: () => console.log('resume'), quit: () => console.log('quit') },
1131
+ });
1132
+ ui.add(...screen.widgets);
1133
+ console.log(screen.get('music')); // the Toggle with id="music"
1134
+ ```
1135
+
1136
+ `@margoengine/ui/markup` builds a screen from a markup file and style sheets that a designer can edit without code.
1137
+ Elements are the widgets in lower case: `panel`, `row` and `column` hold other elements; `label`, `button`,
1138
+ `toggle`, `slider`, `progress` and `health` take their text from their content; `list` and `menu` take `<item>`
1139
+ children. Attributes and style declarations are the widgets' options in kebab-case (`min-width`, `show-value`), with
1140
+ spaces between numbers (`padding: 8 16`). Rules select by type, `#id` and `.class`, joined by a space (any
1141
+ descendant) or `>` (a child); the more specific rule wins, then the later one, and an element's own attributes win over
1142
+ every sheet. `on-click`, `on-change` and `on-select` name a function in `actions`. Every error names its line and
1143
+ column. `loadScreen(url, { styles: [cssUrl], actions, signal })` fetches the files first, with an `AbortSignal`;
1144
+ `parseMarkup` and `parseStyleSheet` return the parsed trees for tools.
1145
+
1146
+ ## Options
1147
+
1148
+ | `new Ui({...})` option | Default |
1149
+ | --- | --- |
1150
+ | `width`, `height` | `1280`, `720` (CSS pixels; `UiRenderer` keeps them in step with the canvas) |
1151
+ | `pixelRatio` | `1` |
1152
+ | `scale` | `1`, or `{ reference: [w, h], match, min, max }` |
1153
+ | `theme` | `themeForPreferences()` |
1154
+ | `font` | `system-ui, sans-serif` at weight 500; a `Font` or options from `@margoengine/text` |
1155
+ | `textScale` | `1` |
1156
+ | `safeArea` | `'auto'` |
1157
+ | `reducedMotion` | the user's `prefers-reduced-motion` |
1158
+ | `ligatures` | `false` (Arabic and Indic words are always shaped; `true` shapes Latin words too) |
1159
+ | `direction` | `'auto'` (each text's first strong letter); `'ltr'` or `'rtl'` for all UI text |
1160
+ | `measurer` | the font; pass your own for tests or servers |
1161
+
1162
+ Errors follow the repository convention: bad arguments throw `TypeError` or `RangeError` whose message names the fix and
1163
+ ends with a link to [margoengine.com/errors#ui](https://margoengine.com/errors#ui); using a disposed `Ui` throws a
1164
+ `MargoError` with `code: 'disposed'`. `Ui`, `UiRenderer` and every widget have `dispose()` and `Symbol.dispose`.
1165
+
1166
+ ## How it works
1167
+
1168
+ - **A draw list, not a scene.** `ui.draw()` returns rounded rectangles, text blocks and clip regions in device pixels,
1169
+ back to front. It is rebuilt only when something changed, and `UiRenderer` uploads it only when it was rebuilt.
1170
+ A `DrawList` checks each command before adding it: a non-finite position, size, border, radius or blur, a scale
1171
+ that is not finite and above 0, and a `popClip` with no clip open throw a `RangeError` and leave the list as it was.
1172
+ - **Two instanced draws.** Rectangles are signed distance rounded boxes (crisp edges, outlines, soft shadows); glyphs are
1173
+ quads sampling the text package's atlases. Both read storage buffers by instance index, in the engine's own render pass
1174
+ after post-processing, with premultiplied alpha blending and one scissor per clip region. Images share the colour
1175
+ atlas; an image no longer drawn (removed, or its `texture` replaced) gives its slots back, so a page it leaves empty
1176
+ is reused.
1177
+ - **Layout.** A small flexbox: base sizes, then free space by `grow` and a shortage by `shrink` (resolved as CSS Flexbox
1178
+ section 9.7 does: a child held by its min or max size is frozen and the rest goes to the others), then `justify` and
1179
+ `align`. A wrapping row first breaks its children into lines by their base sizes, then does the same per line. Stacks anchor their children; grids fill cells row by row.
1180
+ - **No globals.** Nothing runs on import; the only DOM access is reading the safe area, and only when you ask for it.
1181
+
1182
+ ## WebGL2 preview backend
1183
+
1184
+ ```ts
1185
+ import { Engine } from '@margoengine/core';
1186
+ import { webglRenderer } from '@margoengine/webgl2-compat/preview';
1187
+ import { Button, Ui, UiRenderer } from '@margoengine/ui';
1188
+
1189
+ const canvas = document.querySelector('canvas')!;
1190
+ const engine = await Engine.create(canvas, { backend: 'webgl2', fallback: webglRenderer });
1191
+ const ui = new Ui();
1192
+ ui.add(new Button({ text: 'Play', anchor: 'center' }));
1193
+ UiRenderer.attach(engine, ui); // the same rectangles and text as on WebGPU
1194
+ engine.start();
1195
+ ```
1196
+
1197
+ On WebGL2 the renderer draws the same instances with two small GLSL ES 3.00 programs into the default framebuffer, over
1198
+ the finished frame. Its code loads on first use, so WebGPU pages never fetch it and the UI shows from the first frame
1199
+ after that load. An unchanged UI uploads nothing; it is drawn again each frame because WebGL2 clears its canvas.
1200
+
1201
+ ## Limits
1202
+
1203
+ - `@margoengine/ui/world` panels require native WebGPU or the full compatibility layer and refuse the small preview during setup; `@margoengine/ui/world-gl` draws them on the preview too. Screen UI has a real preview route.
1204
+ - A world panel is drawn with depth test and no depth write, so it does not hide transparent effects drawn after it; one texture and one pair of glyph atlases per panel. A `CurvedPanel` (`@margoengine/ui/curved`) is a tessellated cylinder or sphere patch; its rays hit the analytic surface.
1205
+ - Shaping is the browser's, one word at a time: a run never crosses a space, so no join or ligature forms across
1206
+ words. Only labels and wrapped text follow the text direction: toggles, slider values, list details and rows of
1207
+ widgets keep left-to-right placement (no mirrored layout).
1208
+ - Markup is a subset of XML: no DOCTYPE, CDATA or namespaces, and only the five named character references. Style
1209
+ sheets have no pseudo-classes, attribute selectors, `+` or `~`, `@` rules or `!important`, and do not restyle a
1210
+ screen after it is built.
1211
+ - A `VirtualList` has one row height; rows of different heights need a `List`.
1212
+ - A wrapping row breaks lines by its children's base sizes, so a child that would grow
1213
+ never pulls the next one up; columns do not wrap, and lines always stack down from the top (no `align-content`).
1214
+
1215
+ ## Preview tier contract
1216
+
1217
+ The small `@margoengine/webgl2-compat/preview` renderer reports `backend: 'webgl2'` and has no GPU device. GPU-only attachments throw a linked `MargoError` with code `unsupported` before allocating resources. Native WebGPU and the full WebGL2 compatibility layer both report `backend: 'webgpu'`. Use [`autoEngine` with `loadCompat`](../webgl2-compat/README.md#automatic-escalation) during scene setup to select a complete tier automatically.
1218
+
1219
+ Screen `UiRenderer` keeps its real preview renderer. `WorldPanels` requires a complete tier.
1220
+
1221
+ `GlWorldPanels` (`@margoengine/ui/world-gl`) is a reviewed preview route in `scripts/check-preview-contract.mjs` (2026-11-10, 2 `backend` tests): on the small WebGL2 preview it draws world panels with raw WebGL2, on WebGPU it defers to `WorldPanels`. Pixel evidence: `tests/world-gl-browser.js`, run by `npm run test:browser:world-gl` (8 checks each for plane, cylinder and sphere on the preview, 7 each on WebGPU, also under `MARGO_COMPAT=1`). Unit evidence: `tests/world-gl.test.js`. No behaviour changed; the missing row kept `npm run verify` red.
1222
+
1223
+ ## Film time
1224
+
1225
+ `UiRenderer.advanceTime(delta)` runs `ui.update(delta)` (transitions, toasts, tooltips, the caret blink) without drawing; the frame update runs it, so `seek` from `@margoengine/cutscene/seek` replays the overlay's timing.