@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.
Files changed (61) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +708 -3
  4. package/dist/basic.d.ts +87 -0
  5. package/dist/collections.d.ts +180 -0
  6. package/dist/color.d.ts +24 -0
  7. package/dist/controls.d.ts +130 -0
  8. package/dist/curved.d.ts +41 -0
  9. package/dist/curved.js +105 -0
  10. package/dist/dom-CWJhpotq.js +340 -0
  11. package/dist/dom-host.d.ts +67 -0
  12. package/dist/dom-host.js +563 -0
  13. package/dist/dom-spec.d.ts +21 -0
  14. package/dist/dom.d.ts +63 -0
  15. package/dist/draw.d.ts +107 -0
  16. package/dist/editor.d.ts +83 -0
  17. package/dist/editor.js +323 -0
  18. package/dist/errors-CDgOgzCd.js +7 -0
  19. package/dist/focus.d.ts +12 -0
  20. package/dist/forms.d.ts +114 -0
  21. package/dist/forms.js +354 -0
  22. package/dist/gl-bb768Mje.js +165 -0
  23. package/dist/gl-load-wwKmojhb.js +5 -0
  24. package/dist/gl-load.d.ts +3 -0
  25. package/dist/gl.d.ts +30 -0
  26. package/dist/i18n.d.ts +69 -0
  27. package/dist/i18n.js +117 -0
  28. package/dist/image.d.ts +74 -0
  29. package/dist/image.js +295 -0
  30. package/dist/index.d.ts +36 -0
  31. package/dist/index.js +4 -0
  32. package/dist/input-dom.d.ts +14 -0
  33. package/dist/input.d.ts +92 -0
  34. package/dist/input.js +315 -0
  35. package/dist/interaction.d.ts +106 -0
  36. package/dist/keyboard.d.ts +40 -0
  37. package/dist/keyboard.js +132 -0
  38. package/dist/layout.d.ts +116 -0
  39. package/dist/markup.d.ts +89 -0
  40. package/dist/markup.js +369 -0
  41. package/dist/meters-yaZRtwsX.js +1401 -0
  42. package/dist/meters.d.ts +72 -0
  43. package/dist/mirror.d.ts +30 -0
  44. package/dist/overlays.d.ts +89 -0
  45. package/dist/painter.d.ts +115 -0
  46. package/dist/pass-CAn29pqc.js +15 -0
  47. package/dist/react.d.ts +99 -0
  48. package/dist/react.js +246 -0
  49. package/dist/renderer-Bdhc_0Cu.js +1653 -0
  50. package/dist/renderer.d.ts +92 -0
  51. package/dist/rsc/react.js +3 -0
  52. package/dist/shader.d.ts +6 -0
  53. package/dist/theme.d.ts +104 -0
  54. package/dist/ui.d.ts +328 -0
  55. package/dist/virtual.d.ts +81 -0
  56. package/dist/widget.d.ts +196 -0
  57. package/dist/world-gl.d.ts +32 -0
  58. package/dist/world-gl.js +195 -0
  59. package/dist/world.d.ts +216 -0
  60. package/dist/world.js +561 -0
  61. package/package.json +119 -6
@@ -0,0 +1,92 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { EngineKernel } from '@margoengine/core';
3
+ import type { Engine, EnginePlugin, FrameGraph } from '@margoengine/core/extension';
4
+ import { type AttachOptions } from './dom.js';
5
+ import { type MirrorOptions } from './mirror.js';
6
+ import type { Ui } from './ui.js';
7
+ /** Options for {@link UiRenderer}. */
8
+ export interface UiRendererOptions {
9
+ /** Plugin name, unique per engine. Default `'ui'`. */
10
+ name?: string;
11
+ /** Frame graph order. Default 1000: after the scene and post-processing, so the UI is never tone mapped or blurred. */
12
+ order?: number;
13
+ /** SDF atlas page size in texels. Default 1024. */
14
+ atlasSize?: number;
15
+ /** Colour (emoji) atlas page size in texels. Default 512. */
16
+ colorAtlasSize?: number;
17
+ /** Page limit per atlas. Default 16. */
18
+ maxPages?: number;
19
+ /**
20
+ * Connect the engine's canvas to the UI (pointer, touch, wheel and keyboard; see {@link attachInput}). Pass false to
21
+ * do it yourself, or options for `attachInput`. Default true.
22
+ */
23
+ input?: boolean | AttachOptions;
24
+ /**
25
+ * Mirror the UI into the DOM for screen readers (see {@link attachMirror}). Pass false to leave it out, or options. Default
26
+ * true: the interface is accessible with no setup.
27
+ */
28
+ mirror?: boolean | MirrorOptions;
29
+ }
30
+ /**
31
+ * Engine plugin that draws a {@link Ui} over the finished frame, in the engine's own render pass: rounded rectangles
32
+ * and signed distance field text from the text package, in device pixels, so it works in fullscreen and in exported
33
+ * games with no DOM involved. It also steps the UI each frame (`ui.update`) and keeps its size in step with the canvas.
34
+ * On core's WebGL2 preview backend it draws the same rectangles and text with WebGL2 (its code loads on first use, so
35
+ * the UI shows from the first frame after that load).
36
+ *
37
+ * @example
38
+ * const ui = new Ui();
39
+ * UiRenderer.attach(engine, ui);
40
+ */
41
+ export declare class UiRenderer implements EnginePlugin {
42
+ readonly ui: Ui;
43
+ readonly name: string;
44
+ readonly order: number;
45
+ /** Counts for the latest frame. */
46
+ readonly stats: {
47
+ rects: number;
48
+ glyphs: number;
49
+ drawCalls: number;
50
+ uploads: number;
51
+ };
52
+ private engine?;
53
+ private device?;
54
+ private readonly painter;
55
+ private readonly descriptor;
56
+ private readonly options;
57
+ private readonly inputOptions;
58
+ private readonly mirrorOptions;
59
+ private gl?;
60
+ private glPainter?;
61
+ private detach?;
62
+ private detachMirror?;
63
+ private disposed;
64
+ /** Same as `engine.use(new UiRenderer(ui, options))`; returns the renderer. */
65
+ static attach(engine: EngineKernel, ui: Ui, options?: UiRendererOptions): UiRenderer;
66
+ /**
67
+ * @throws TypeError for a missing `ui`, an empty name or a non-finite order.
68
+ * @throws RangeError for an atlas size under 64 texels or a page limit that is not a positive integer.
69
+ */
70
+ constructor(ui: Ui, options?: UiRendererOptions);
71
+ setup(engine: Engine): void;
72
+ registerPasses(graph: FrameGraph): void;
73
+ /** Seconds of frame updates the renderer has run. */
74
+ get time(): number;
75
+ /**
76
+ * Runs `ui.update(delta)` (transitions, toasts, tooltips, the caret blink), all CPU, without drawing. Each frame
77
+ * update runs it, so `seek` from `@margoengine/cutscene/seek` replays it exactly.
78
+ */
79
+ advanceTime(delta: number): void;
80
+ onPreUpdate(delta: number): void;
81
+ private elapsed;
82
+ private readonly execute;
83
+ private draw;
84
+ /** The WebGL2 path: the same draw list over the finished frame in the default framebuffer. */
85
+ private drawGl;
86
+ /** Device pixels per CSS pixel: the drawing buffer's width over the canvas's CSS width. */
87
+ private pixelRatio;
88
+ onDeviceRestored(engine: Engine): void;
89
+ /** Release every GPU resource, atlases included. The `Ui` is not disposed. */
90
+ dispose(): void;
91
+ [Symbol.dispose]: () => void;
92
+ }
@@ -0,0 +1,3 @@
1
+ 'use client';
2
+ // Generated by scripts/react-server-entries.js: the "react-server" entry, ../react.js behind a client boundary.
3
+ export { Button, HealthBar, Inventory, Label, List, Menu, Panel, ProgressBar, Slider, Toggle, UiRoot, useUi } from '../react.js';
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Shader of the UI renderer. Rectangles are signed-distance rounded boxes with an optional outline and soft edge;
3
+ * glyphs are quads sampling the text package's signed distance atlases. Both are instanced draws that read their
4
+ * data from storage buffers by `instance_index` (the draw's first instance selects the run), in device pixels.
5
+ */
6
+ export declare const uiShader: string;
@@ -0,0 +1,104 @@
1
+ /** The colour roles of a theme: `#rrggbb` or `#rrggbbaa` strings. A `on*` colour is the text drawn on its fill. */
2
+ export interface ThemeColors {
3
+ /** Behind everything, for example a full-screen menu backdrop. */
4
+ background: string;
5
+ /** Panels, dialogs, list rows. */
6
+ surface: string;
7
+ /** Controls on a surface: buttons, sliders, slots. */
8
+ surfaceRaised: string;
9
+ /** Wells: progress tracks, text fields, empty slots. */
10
+ surfaceSunken: string;
11
+ /** Outlines of controls. Meets 3:1 against `surface`. */
12
+ border: string;
13
+ /** Body text. Meets 4.5:1 (7:1 in high contrast) against `surface` and `surfaceRaised`. */
14
+ text: string;
15
+ /** Secondary text. Meets 4.5:1 against `surface`. */
16
+ textMuted: string;
17
+ /** Main action and selection. */
18
+ primary: string;
19
+ onPrimary: string;
20
+ /** Second accent, for highlights and the second series of a bar. */
21
+ accent: string;
22
+ onAccent: string;
23
+ /** Good, full, done. */
24
+ success: string;
25
+ onSuccess: string;
26
+ /** Careful, low. */
27
+ warning: string;
28
+ onWarning: string;
29
+ /** Bad, critical, destructive. */
30
+ danger: string;
31
+ onDanger: string;
32
+ /** Neutral information. */
33
+ info: string;
34
+ onInfo: string;
35
+ /** The keyboard and gamepad focus ring. Meets 3:1 against `surface`, `surfaceRaised` and `primary`. */
36
+ focus: string;
37
+ /** Fill of a disabled control. */
38
+ disabled: string;
39
+ /** Text of a disabled control. */
40
+ onDisabled: string;
41
+ /** Dims the game behind a modal dialog. */
42
+ scrim: string;
43
+ /** Drop shadow under panels. */
44
+ shadow: string;
45
+ }
46
+ /** Look of every widget. Create one with {@link createTheme}; the built-ins are in {@link themes}. */
47
+ export interface Theme {
48
+ /** Shown in the screen reader mirror and in tests. */
49
+ name: string;
50
+ colors: ThemeColors;
51
+ /** Corner radius of controls in UI units. */
52
+ radius: number;
53
+ /** Outline width of controls in UI units. */
54
+ borderWidth: number;
55
+ /** Focus ring width in UI units. */
56
+ focusWidth: number;
57
+ /** Base spacing unit in UI units; paddings and gaps are multiples of it. */
58
+ spacing: number;
59
+ /** Text sizes in UI units, before the user's text scale. */
60
+ fontSize: {
61
+ small: number;
62
+ body: number;
63
+ large: number;
64
+ title: number;
65
+ display: number;
66
+ };
67
+ /** Blur of the drop shadow in UI units; 0 turns shadows off. */
68
+ shadowBlur: number;
69
+ /** Seconds of the hover, press and toggle transitions; 0 turns them off. */
70
+ transition: number;
71
+ }
72
+ /** A theme with any field replaced; colours and sizes are merged one level down. */
73
+ export interface ThemeOverrides {
74
+ name?: string;
75
+ colors?: Partial<ThemeColors>;
76
+ radius?: number;
77
+ borderWidth?: number;
78
+ focusWidth?: number;
79
+ spacing?: number;
80
+ fontSize?: Partial<Theme['fontSize']>;
81
+ shadowBlur?: number;
82
+ transition?: number;
83
+ }
84
+ /**
85
+ * The built-in themes. `dark` is the default. All three use colour-blind-safe status colours (Okabe-Ito); `highContrast`
86
+ * is black, white, yellow and cyan with thick outlines, 7:1 text, and no shadows or transitions.
87
+ */
88
+ export declare const themes: Readonly<{
89
+ dark: Theme;
90
+ light: Theme;
91
+ highContrast: Theme;
92
+ }>;
93
+ /**
94
+ * A theme made from `base` (default {@link themes}.dark) with `overrides` applied. Colours must be hex strings and sizes
95
+ * finite numbers of at least 0 (font sizes above 0). The result is frozen.
96
+ * @throws TypeError for an unknown field or a colour that does not parse.
97
+ * @throws RangeError for a size outside its range.
98
+ */
99
+ export declare function createTheme(overrides?: ThemeOverrides, base?: Theme): Theme;
100
+ /**
101
+ * The built-in theme that matches the user's settings: high contrast for `prefers-contrast: more` or forced colours, light
102
+ * for `prefers-color-scheme: light`, otherwise dark. Returns dark where `matchMedia` does not exist (Node, workers).
103
+ */
104
+ export declare function themeForPreferences(): Theme;
package/dist/ui.d.ts ADDED
@@ -0,0 +1,328 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import { Font, type FontOptions, type TextLayout, type TextMeasurer } from '@margoengine/text';
3
+ import { Panel, type TextSize } from './basic.js';
4
+ import { type Rgba } from './color.js';
5
+ import { DrawList } from './draw.js';
6
+ import type { Direction } from './focus.js';
7
+ import { type InputSource, type PointerInfo } from './interaction.js';
8
+ import { Dialog, Toast, Tooltip, type DialogOptions, type ToastOptions } from './overlays.js';
9
+ import { type Theme } from './theme.js';
10
+ import type { ColorRef, UiCommand, Widget } from './widget.js';
11
+ import type { Input } from '@margoengine/input';
12
+ /** Scale the UI with the window so a layout made for one resolution fills any other. */
13
+ export interface ScaleOptions {
14
+ /** The window size, in CSS pixels, the layout was designed for, for example `[1280, 720]`. */
15
+ reference: readonly [number, number];
16
+ /** How much the height decides (1) rather than the width (0) when the aspect ratio differs. Default 0.5. */
17
+ match?: number;
18
+ /** Smallest scale. Default 0.5. */
19
+ min?: number;
20
+ /** Largest scale. Default 4. */
21
+ max?: number;
22
+ }
23
+ /**
24
+ * How many CSS pixels one UI unit is for a window of `width` by `height`: 1 by default (UI units are CSS pixels), the
25
+ * number itself for a number scale, or for a reference size `(w / rw) ** (1 - match) * (h / rh) ** match` between `min`
26
+ * and `max` (a window 1.5 times the reference gives 1.5: the UI fills it at 1.5 times the size).
27
+ * @throws RangeError for a non-positive size or an invalid reference.
28
+ */
29
+ export declare function resolutionScale(width: number, height: number, scale?: number | ScaleOptions): number;
30
+ /**
31
+ * The user's text size preference as a multiplier: the browser's root font size over the 16 px default (a user who set
32
+ * "large" fonts gets 1.25, say), between 0.5 and 3. 1 where there is no document.
33
+ */
34
+ export declare function browserTextScale(document?: Document | undefined): number;
35
+ /** Insets in CSS pixels: `[top, right, bottom, left]`. */
36
+ export type SafeArea = readonly [number, number, number, number];
37
+ /**
38
+ * The device's safe-area insets (notches, rounded corners, system bars) in CSS pixels, read from the CSS `env()`
39
+ * values. All zero where there is no document or the page has no `viewport-fit=cover`.
40
+ */
41
+ export declare function readSafeArea(document?: Document | undefined): SafeArea;
42
+ /** Options for `new Ui(...)`. Every field is optional. */
43
+ export interface UiOptions {
44
+ /** Width of the window or canvas in CSS pixels. Default 1280. Change it later with `ui.resize()`. */
45
+ width?: number;
46
+ /** Height in CSS pixels. Default 720. */
47
+ height?: number;
48
+ /** Device pixels per CSS pixel. Default 1. */
49
+ pixelRatio?: number;
50
+ /** Resolution scaling: CSS pixels per UI unit, or a reference size. Default 1 (UI units are CSS pixels). */
51
+ scale?: number | ScaleOptions;
52
+ /** The look. Default {@link themeForPreferences}: dark, or light / high contrast when the user asks for them. */
53
+ theme?: Theme;
54
+ /** The text package font, or options for one. Default `system-ui, sans-serif` at weight 500. */
55
+ font?: Font | FontOptions;
56
+ /** Measures text instead of the font; for tests and server rendering. */
57
+ measurer?: TextMeasurer;
58
+ /**
59
+ * The user's text size preference, 0.5 to 3, or `'auto'` to follow the browser's default font size (a user who raised
60
+ * it in the browser settings gets bigger text). Default 1.
61
+ */
62
+ textScale?: number | 'auto';
63
+ /** Safe area in CSS pixels (`[top, right, bottom, left]`), or `'auto'` to read the device's. Default `'auto'`. */
64
+ safeArea?: SafeArea | 'auto';
65
+ /** Turn transitions off. Default the user's `prefers-reduced-motion`. */
66
+ reducedMotion?: boolean;
67
+ /**
68
+ * Latin ligatures: each Latin word is drawn as one shaped run, so fi, fl and the font's other ligatures form. Arabic
69
+ * and Indic words are always drawn as shaped runs (joined letters, conjuncts, vowel signs). Default false.
70
+ */
71
+ ligatures?: boolean;
72
+ /**
73
+ * Direction of UI text. `'auto'` takes it from each text's first strong letter (Arabic and Hebrew read right to left,
74
+ * text with no strong letter left to right); `'ltr'` or `'rtl'` sets it for every text. A text's `'start'`
75
+ * alignment is its reading start: the right edge for right-to-left text. Default `'auto'`.
76
+ */
77
+ direction?: UiDirection;
78
+ }
79
+ /** Direction of UI text: from each text, or set for all. */
80
+ export type UiDirection = 'auto' | 'ltr' | 'rtl';
81
+ /**
82
+ * A game user interface: a tree of widgets in layers (screen, dialogs, toasts, tooltips), a theme, resolution and text
83
+ * scaling, and a draw list for the engine to render. It owns no GPU resources and touches no DOM, so it runs
84
+ * anywhere; {@link UiRenderer} draws it and {@link UiInput} connects a canvas.
85
+ *
86
+ * @example
87
+ * const ui = new Ui();
88
+ * ui.add(new Menu({ title: 'Paused', items: [{ label: 'Resume', onSelect: () => ui.toast('Resumed') }] }));
89
+ * ui.update(1 / 60);
90
+ * const commands = ui.draw().commands; // rectangles and text, in pixels
91
+ */
92
+ export declare class Ui {
93
+ /** The screen layer: add HUD and menu widgets here (or with {@link Ui.add}). */
94
+ readonly root: Panel;
95
+ /** Dialogs, above the screen, dimming it. */
96
+ readonly modalLayer: Panel;
97
+ /** Toasts, above dialogs. */
98
+ readonly toastLayer: Panel;
99
+ /** The tooltip bubble, above everything. */
100
+ readonly tooltipLayer: Panel;
101
+ readonly font: Font;
102
+ /** Resolves when the font is ready to draw with. */
103
+ readonly ready: Promise<void>;
104
+ private readonly measurer;
105
+ private readonly toastStack;
106
+ private readonly tooltip;
107
+ private readonly layers;
108
+ private readonly list;
109
+ private readonly context;
110
+ private readonly cache;
111
+ private readonly colors;
112
+ private _theme;
113
+ private _textScale;
114
+ private _scale;
115
+ private _width;
116
+ private _height;
117
+ private _pixelRatio;
118
+ private _safeArea;
119
+ private _motion;
120
+ private _ligatures;
121
+ private _direction;
122
+ private resolved;
123
+ private layoutDirty;
124
+ private drawDirty;
125
+ private fontRevision;
126
+ private disposed;
127
+ private readonly interaction;
128
+ private readonly changeListeners;
129
+ private readonly focusListeners;
130
+ private readonly announcers;
131
+ /** Increases whenever any widget's text, state or position changed; the accessibility mirror syncs on it. */
132
+ mirrorRevision: number;
133
+ /**
134
+ * @throws RangeError for a size, ratio, scale or text scale outside its range.
135
+ * @throws TypeError for a theme, font or measurer of the wrong type.
136
+ */
137
+ constructor(options?: UiOptions);
138
+ private checkSize;
139
+ /** The theme. Set another one to restyle the whole UI at once. */
140
+ get theme(): Theme;
141
+ set theme(theme: Theme);
142
+ /** The user's text size multiplier. */
143
+ get textScale(): number;
144
+ set textScale(value: number);
145
+ private setTextScale;
146
+ /** Whether Latin words draw as shaped runs with the font's ligatures. Setting it lays the text out again. */
147
+ get ligatures(): boolean;
148
+ set ligatures(value: boolean);
149
+ /** Direction of UI text: `'auto'` from each text, or `'ltr'` or `'rtl'` for all. Setting it lays the text out again. */
150
+ get direction(): UiDirection;
151
+ set direction(value: UiDirection);
152
+ private setShaping;
153
+ /**
154
+ * The direction `text` reads in: the UI's `direction` when set, otherwise that of the first strong letter (`'rtl'`
155
+ * for Arabic, Hebrew and their neighbours), and `'ltr'` for text without one.
156
+ */
157
+ textDirection(text: string): 'ltr' | 'rtl';
158
+ /** False when transitions are off (reduced motion). */
159
+ get motion(): boolean;
160
+ set motion(value: boolean);
161
+ /** Width of the screen in UI units. */
162
+ get width(): number;
163
+ /** Height of the screen in UI units. */
164
+ get height(): number;
165
+ /** Device pixels per UI unit: the pixel ratio times the resolution scaling. */
166
+ get scale(): number;
167
+ /** CSS pixels per UI unit; pointer coordinates in CSS pixels are divided by it. */
168
+ get cssScale(): number;
169
+ get pixelRatio(): number;
170
+ /** Safe-area insets in UI units, `[top, right, bottom, left]`. */
171
+ get safeArea(): readonly [number, number, number, number];
172
+ /** Set the safe area in CSS pixels, or `'auto'` to read the device's on each resize. */
173
+ setSafeArea(inset: SafeArea | 'auto'): void;
174
+ /**
175
+ * Set the window size in CSS pixels and the device pixel ratio. {@link UiRenderer} calls this each frame from the
176
+ * canvas; call it yourself when drawing the list elsewhere.
177
+ * @throws RangeError for a size or ratio outside its range.
178
+ */
179
+ resize(width: number, height: number, pixelRatio?: number): void;
180
+ /** Change the resolution scaling. */
181
+ setScale(scale: number | ScaleOptions): void;
182
+ /** Add widgets to the screen layer. */
183
+ add(...widgets: Widget[]): this;
184
+ /** Remove a widget from the screen layer. */
185
+ remove(widget: Widget): this;
186
+ /** The first widget with this id in any layer, or undefined. */
187
+ find(id: string): Widget | undefined;
188
+ /** Visit every widget in every layer, back to front. */
189
+ walk(visit: (widget: Widget) => void): void;
190
+ /** The widget with input focus, or null. */
191
+ get focused(): Widget | null;
192
+ /** Where the latest input came from; the focus ring shows for `'keyboard'` and `'gamepad'`. */
193
+ get inputMode(): InputSource;
194
+ /**
195
+ * When true, arrow keys, Enter, Space and Escape always go to the UI: set it while a full-screen menu shows. When
196
+ * false (default) they go to the UI only once a widget has focus or while a dialog is open, so the game keeps its keys.
197
+ */
198
+ get captureKeys(): boolean;
199
+ set captureKeys(value: boolean);
200
+ /** Whether moving past the first or last widget in a direction wraps to the other end. Default true. */
201
+ get wrapFocus(): boolean;
202
+ set wrapFocus(value: boolean);
203
+ /** The widgets keyboard and gamepad navigation can reach now: inside the top dialog, or on the screen and in toasts. */
204
+ focusables(): Widget[];
205
+ /** Give `widget` (or nothing, with null) input focus. Returns false if it cannot take focus. */
206
+ focus(widget: Widget | null, source?: InputSource): boolean;
207
+ /** Move focus to the nearest focusable widget in a direction; a focused slider takes left and right itself. */
208
+ navigate(direction: Direction, source?: InputSource): boolean;
209
+ /** Tab order: the next (or with `false`, the previous) widget. Returns false when focus leaves the UI. */
210
+ tab(forward?: boolean, source?: InputSource): boolean;
211
+ /** Activate the focused widget; with no focus, focus the first one. */
212
+ accept(source?: InputSource): boolean;
213
+ /** Close a tooltip, then let the focused widget, then the open dialog take Escape. Returns false when none did. */
214
+ cancel(source?: InputSource): boolean;
215
+ /** Run a command from any source: `'up'`, `'down'`, `'left'`, `'right'`, `'accept'`, `'cancel'`, `'next'`, `'previous'`. */
216
+ execute(command: UiCommand, source?: InputSource): boolean;
217
+ /** True when a key press belongs to the UI (see {@link Ui.captureKeys}). */
218
+ wantsKeys(): boolean;
219
+ /** A pointer moved to (x, y) CSS pixels from the canvas's top left. Returns true over a widget that takes the pointer. */
220
+ pointerMove(x: number, y: number, info?: PointerInfo): boolean;
221
+ /** A pointer pressed at (x, y) CSS pixels. Returns true when the UI used it; otherwise the game should. */
222
+ pointerDown(x: number, y: number, info?: PointerInfo): boolean;
223
+ /** A pointer was released at (x, y) CSS pixels. Returns true when it ends a press that began on the UI. */
224
+ pointerUp(x: number, y: number, info?: PointerInfo): boolean;
225
+ /** The system cancelled the pointer (a touch became a scroll, the window lost focus). */
226
+ pointerCancel(): void;
227
+ /** The pointer left the canvas. */
228
+ pointerLeave(): void;
229
+ /** The wheel turned at (x, y) CSS pixels by `dy` CSS pixels (positive scrolls down). Returns true when a widget scrolled. */
230
+ wheel(x: number, y: number, dy: number): boolean;
231
+ /** True when a pointer at (x, y) CSS pixels is over the UI, so the game should ignore it. */
232
+ wantsPointer(x: number, y: number): boolean;
233
+ /** The widget under (x, y) CSS pixels that takes pointer events, or null. */
234
+ hitTest(x: number, y: number): Widget | null;
235
+ /**
236
+ * Drive the UI from an `Input` of `@margoengine/input` created with {@link uiActions}: d-pad and left stick move
237
+ * focus (holding repeats), A accepts, B cancels, the bumpers tab. `input.update()` must run before `ui.update()` each
238
+ * frame, as it does when your game loop calls it before `engine.render()`.
239
+ * @throws TypeError when the Input lacks the `ui.*` actions.
240
+ */
241
+ bindInput(input: Pick<Input, 'state'>): this;
242
+ /** Stop reading the bound Input. */
243
+ unbindInput(): this;
244
+ /** The colour of a theme role or `#rrggbb[aa]` string as straight sRGB. */
245
+ color(ref: ColorRef): Rgba;
246
+ /** A text size in UI units, with the user's text scale applied. */
247
+ fontSize(size: TextSize): number;
248
+ /**
249
+ * Lay out text with the font: wrapped to `maxWidth` UI units, `align`ed within its widest line (`'start'` is the
250
+ * right edge of right-to-left text, see {@link Ui.textDirection}). Arabic and Indic words are shaped runs, and Latin
251
+ * words too with {@link UiOptions.ligatures}. Results are cached.
252
+ * @throws TypeError or RangeError for a bad size or width.
253
+ */
254
+ textLayout(text: string, size: TextSize, maxWidth?: number, lineHeight?: number, align?: 'start' | 'center' | 'end'): TextLayout;
255
+ /** Size of `text` wrapped to `maxWidth`, in UI units. */
256
+ measureText(text: string, size: TextSize, maxWidth?: number, lineHeight?: number): {
257
+ width: number;
258
+ height: number;
259
+ };
260
+ /** Ask for a layout (default) or only a redraw on the next update. */
261
+ invalidate(layout?: boolean): void;
262
+ /** Tell the accessibility mirror that text or state changed. */
263
+ touchMirror(): void;
264
+ /** Run `listener` whenever the UI changed; returns a function that stops it. */
265
+ onChange(listener: () => void): () => void;
266
+ /** Run `listener` whenever input focus moves; returns a function that stops it. */
267
+ onFocus(listener: () => void): () => void;
268
+ /** @internal */
269
+ focusChanged(): void;
270
+ /**
271
+ * Say something to screen reader users (a polite announcement waits for the reader to finish; an assertive one
272
+ * interrupts). Toasts are announced for you. Does nothing without an accessibility mirror
273
+ * (see {@link attachMirror}; {@link UiRenderer} attaches one by default).
274
+ */
275
+ announce(message: string, politeness?: 'polite' | 'assertive'): void;
276
+ /** Receive the messages of {@link Ui.announce}; the accessibility mirror uses it. Returns a function that stops it. */
277
+ onAnnounce(listener: (message: string, politeness: 'polite' | 'assertive') => void): () => void;
278
+ /** @internal */
279
+ widgetAdded(_widget: Widget): void;
280
+ /** @internal */
281
+ widgetRemoved(widget: Widget): void;
282
+ /** @internal */
283
+ widgetHidden(widget: Widget): void;
284
+ /** @internal */
285
+ cancelTooltip(): void;
286
+ /** @internal */
287
+ dialogClosed(_dialog: Dialog): void;
288
+ /** Lay out the layers now, if anything changed. {@link Ui.update} and {@link Ui.draw} do this for you. */
289
+ layout(): void;
290
+ /**
291
+ * Advance transitions, toasts and tooltips by `dt` seconds (clamped to 0.1) and lay out whatever changed.
292
+ * {@link UiRenderer} calls this every frame; call it yourself when you render the draw list elsewhere.
293
+ */
294
+ update(dt?: number): void;
295
+ /** The draw list for the current state: rebuilt only when something changed since the last call. */
296
+ draw(): DrawList;
297
+ private drawWidget;
298
+ /**
299
+ * Show a modal dialog and resolve with the chosen button's value (see {@link DialogOptions}).
300
+ * @throws TypeError or RangeError for invalid options; the promise rejects with the signal's reason when aborted.
301
+ */
302
+ dialog(options?: DialogOptions): Promise<unknown>;
303
+ /** @internal */
304
+ dialogOpened(dialog: Dialog): void;
305
+ /** Ask a yes or no question; resolves true for the confirm button and false otherwise. */
306
+ confirm(message: string, options?: {
307
+ title?: string;
308
+ confirmLabel?: string;
309
+ cancelLabel?: string;
310
+ signal?: AbortSignal;
311
+ }): Promise<boolean>;
312
+ /** Show a message with one OK button. */
313
+ alert(message: string, options?: {
314
+ title?: string;
315
+ signal?: AbortSignal;
316
+ }): Promise<void>;
317
+ /**
318
+ * Show a short message that fades after a few seconds. At most five toasts show at once; the oldest is dismissed
319
+ * first.
320
+ */
321
+ toast(message: string, options?: ToastOptions): Toast;
322
+ /** The tooltip widget, for tests and custom placement. */
323
+ get tooltipWidget(): Tooltip;
324
+ private live;
325
+ /** Remove every widget and stop. Idempotent. */
326
+ dispose(): void;
327
+ [Symbol.dispose]: () => void;
328
+ }
@@ -0,0 +1,81 @@
1
+ import { Panel, type PanelOptions } from './basic.js';
2
+ import { type ListEntry } from './collections.js';
3
+ import type { InputSource } from './interaction.js';
4
+ import { Widget, type UiEvent } from './widget.js';
5
+ /** Options for {@link VirtualList}. */
6
+ export interface VirtualListOptions extends PanelOptions {
7
+ /** Number of rows. Default 0. */
8
+ count?: number;
9
+ /** Height of every row in UI units. Default 44. */
10
+ rowHeight?: number;
11
+ /** The row at `index`: a label or a `{ label, detail, disabled, value }` entry. Called only for rows that are built. */
12
+ row?: (index: number) => string | ListEntry;
13
+ /** Rows built beyond each edge of the view, so a quick scroll shows no gap. Default 4. */
14
+ overscan?: number;
15
+ /** Index of the selected row. Default -1 (none). */
16
+ selected?: number;
17
+ /** Called with `index` and `item` when a row is chosen by click, tap, Enter or the gamepad. */
18
+ onSelect?: (event: UiEvent) => void;
19
+ }
20
+ /**
21
+ * A scrolling list of selectable rows of one height that builds only the rows in view (plus `overscan` on each side),
22
+ * so an inventory or a log of a hundred thousand entries costs as much as a screenful. Rows come from `row(index)`;
23
+ * call {@link VirtualList.refresh} when their data changes. Arrow keys and the d-pad move through every row, scrolling
24
+ * and building as they go.
25
+ *
26
+ * @example
27
+ * const log = new VirtualList({ count: 50_000, row: (i) => `Event ${i}`, height: 240, onSelect: (e) => show(e.index!) });
28
+ */
29
+ export declare class VirtualList extends Panel {
30
+ private _count;
31
+ private readonly _rowHeight;
32
+ private readonly overscan;
33
+ private _selected;
34
+ private readonly source;
35
+ private readonly built;
36
+ private readonly top;
37
+ private readonly bottom;
38
+ private first;
39
+ private last;
40
+ private synced;
41
+ private leaving;
42
+ /** @throws TypeError or RangeError for a bad count, row height, overscan or row function. */
43
+ constructor(options?: VirtualListOptions);
44
+ /** Number of rows. Setting it builds the view again and clears a selection past the end. */
45
+ get count(): number;
46
+ set count(value: number);
47
+ /** Height of every row in UI units. */
48
+ get rowHeight(): number;
49
+ /** The selected row, or -1. */
50
+ get selected(): number;
51
+ /** The rows built now, as `[first, last)`; the others are not widgets at all. */
52
+ get range(): readonly [number, number];
53
+ /** Build the rows in view again from `row(index)`, after their data changed. */
54
+ refresh(): void;
55
+ /**
56
+ * Select a row (-1 clears). With `emit` it also fires `'select'`.
57
+ * @throws RangeError for an index outside -1 to count - 1.
58
+ */
59
+ select(index: number, emit?: boolean): void;
60
+ /**
61
+ * Scroll so row `index` is fully in view, and build it.
62
+ * @throws RangeError for an index outside 0 to count - 1.
63
+ */
64
+ scrollToIndex(index: number): void;
65
+ /** Scroll to row `index`, build it and give it the focus. Returns false when it cannot take the focus. */
66
+ focusIndex(index: number, source?: InputSource): boolean;
67
+ /**
68
+ * An arrow past the first or last row: the UI moves the focus on as it would from the end of a full list. When that
69
+ * wraps back into this list, the focus lands on the far end, scrolled into view, not on whichever row is built.
70
+ * @internal
71
+ */
72
+ leave(row: Widget, command: 'up' | 'down'): boolean;
73
+ tick(dt: number): boolean;
74
+ private step;
75
+ /**
76
+ * Height of the view inside the padding. Before the first layout: a numeric `height` style, else the screen's height.
77
+ */
78
+ private view;
79
+ /** Build the rows the view needs, drop the rest, and size the two spacers that stand for the rows not built. */
80
+ private sync;
81
+ }