@margoengine/ui 0.0.0-stage → 0.1.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/LICENSE +201 -0
- package/NOTICE +4 -0
- package/README.md +708 -3
- package/dist/basic.d.ts +87 -0
- package/dist/collections.d.ts +180 -0
- package/dist/color.d.ts +24 -0
- package/dist/controls.d.ts +130 -0
- package/dist/curved.d.ts +41 -0
- package/dist/curved.js +105 -0
- package/dist/dom-CWJhpotq.js +340 -0
- package/dist/dom-host.d.ts +67 -0
- package/dist/dom-host.js +563 -0
- package/dist/dom-spec.d.ts +21 -0
- package/dist/dom.d.ts +63 -0
- package/dist/draw.d.ts +107 -0
- package/dist/editor.d.ts +83 -0
- package/dist/editor.js +323 -0
- package/dist/errors-CDgOgzCd.js +7 -0
- package/dist/focus.d.ts +12 -0
- package/dist/forms.d.ts +114 -0
- package/dist/forms.js +354 -0
- package/dist/gl-bb768Mje.js +165 -0
- package/dist/gl-load-wwKmojhb.js +5 -0
- package/dist/gl-load.d.ts +3 -0
- package/dist/gl.d.ts +30 -0
- package/dist/i18n.d.ts +69 -0
- package/dist/i18n.js +117 -0
- package/dist/image.d.ts +74 -0
- package/dist/image.js +295 -0
- package/dist/index.d.ts +36 -0
- package/dist/index.js +4 -0
- package/dist/input-dom.d.ts +14 -0
- package/dist/input.d.ts +92 -0
- package/dist/input.js +315 -0
- package/dist/interaction.d.ts +106 -0
- package/dist/keyboard.d.ts +40 -0
- package/dist/keyboard.js +132 -0
- package/dist/layout.d.ts +116 -0
- package/dist/markup.d.ts +89 -0
- package/dist/markup.js +369 -0
- package/dist/meters-yaZRtwsX.js +1401 -0
- package/dist/meters.d.ts +72 -0
- package/dist/mirror.d.ts +30 -0
- package/dist/overlays.d.ts +89 -0
- package/dist/painter.d.ts +115 -0
- package/dist/pass-CAn29pqc.js +15 -0
- package/dist/react.d.ts +99 -0
- package/dist/react.js +246 -0
- package/dist/renderer-Bdhc_0Cu.js +1653 -0
- package/dist/renderer.d.ts +92 -0
- package/dist/rsc/react.js +3 -0
- package/dist/shader.d.ts +6 -0
- package/dist/theme.d.ts +104 -0
- package/dist/ui.d.ts +328 -0
- package/dist/virtual.d.ts +81 -0
- package/dist/widget.d.ts +196 -0
- package/dist/world-gl.d.ts +32 -0
- package/dist/world-gl.js +195 -0
- package/dist/world.d.ts +216 -0
- package/dist/world.js +561 -0
- package/package.json +119 -6
package/README.md
CHANGED
|
@@ -1,3 +1,708 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
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.
|