@ignifx/ui 0.9.0 → 0.11.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/dist/index.d.ts +7 -7
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -7
- package/dist/index.js.map +1 -1
- package/package.json +5 -5
- package/skills/ui/SKILL.md +2 -2
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/augmentation.ts","../src/dom/focus.ts","../src/settings.ts","../src/dom/styles.ts","../src/dom/layer.ts","../src/dom/scaling.ts","../src/dom/host.ts","../src/errors.ts","../src/dom/dom-target.ts","../src/i18n/locale-file.ts","../src/i18n/message.ts","../src/i18n/i18n-service.ts","../src/i18n/loader.ts","../src/lite/gpu/text-renderer.ts","../src/lite/text.ts","../src/text/hud-layout.ts","../src/text/text-component.ts","../src/text/hud-text.ts","../src/text/text-runtime.ts","../src/text/world-text-2d.ts","../src/text/world-text.ts","../src/version.ts","../src/world/anchor-math.ts","../src/world/world-anchor.ts","../src/world/ui-system.ts","../src/extension.ts","../src/schemas.ts","../src/widgets/dialog.ts","../src/widgets/loading-screen.ts","../src/widgets/menu-row.ts","../src/widgets/menu.ts","../src/widgets/menu-stack.ts","../src/widgets/toast.ts","../src/widgets/virtual-device.ts","../src/widgets/virtual-button.ts","../src/widgets/virtual-joystick.ts"],"sourcesContent":["import type { UiHost } from \"./dom/host.js\";\nimport type { I18nService } from \"./i18n/i18n-service.js\";\nimport type { ExtensionContext } from \"@ignifx/core\";\n\n/**\n * Import core before augmenting it so TypeScript resolves the target module.\n * Keep the barrel's bare augmentation import: declaration bundling otherwise drops these types.\n * The augmentation emits no runtime registration (docs/architecture/03-scripting-and-components.md §7).\n */\n\ndeclare module \"@ignifx/core\" {\n interface App {\n /**\n * The DOM overlay host (`docs/architecture/13-ui.md` §1): the root over the canvas, the named\n * layers, the scaling modes, the safe-area variables, and the focus flag.\n */\n readonly ui: UiHost;\n /**\n * The localization service (`docs/architecture/13-ui.md` §3): `.i18n.json` documents,\n * `{name}` interpolation, ICU-style plurals, and the active locale.\n */\n readonly i18n: I18nService;\n }\n}\n\n/**\n * Defines `app.ui`, pairing with the augmentation above.\n *\n * @param ctx - The extension registration surface.\n * @param host - The host the property returns.\n * @throws IgnifxError with code `IGX-0401` when something already defined `app.ui`.\n *\n * @internal\n */\nexport function defineUiAppProperty(ctx: ExtensionContext, host: UiHost): void {\n ctx.defineAppProperty(\"ui\", (): unknown => host);\n}\n\n/**\n * Defines `app.i18n`, pairing with the augmentation above.\n *\n * @param ctx - The extension registration surface.\n * @param service - The service the property returns.\n * @throws IgnifxError with code `IGX-0401` when something already defined `app.i18n`.\n *\n * @internal\n */\nexport function defineI18nAppProperty(ctx: ExtensionContext, service: I18nService): void {\n ctx.defineAppProperty(\"i18n\", (): unknown => service);\n}\n","/**\n * Focus routing (`docs/architecture/13-ui.md` §1, `08-input.md` §5).\n *\n * ## What `@ignifx/input` does and does not do\n *\n * `InputService.uiHasFocus` is a **plain settable property**; its own documentation says so —\n * \"`@ignifx/ui` assigns it\"* (`packages/input/src/service/input-service.ts` 340-349). Nothing in\n * `@ignifx/input` watches the DOM for it: `FocusSource` subscribes only to `blur` and\n * `visibilitychange`, and translates both into one `releaseAll`. So the policy for *what counts as\n * a focused text field* is defined here, by this module, and this module is the only thing that\n * ever writes the flag. While it is `true`, `Binding.readRef` reports every keyboard control as\n * released (`packages/input/src/bindings/binding.ts` 330 and 350), which is what makes typing in a\n * field stop firing actions; pointer and gamepad controls are untouched.\n *\n * ## The policy\n *\n * An element takes the keyboard when it is a text-entry element: a `<textarea>`, a `<select>`, a\n * `contenteditable` element, or an `<input>` whose type is not one of the button-like or\n * slider-like types (which games legitimately want to drive with the keyboard *and* have the\n * player use). Two data attributes override the guess in either direction, for the widgets a\n * framework builds out of `<div role=\"textbox\">` and for the search box a game wants to keep\n * transparent to gameplay:\n *\n * - `data-ignifx-focus=\"capture\"` — always takes the keyboard.\n * - `data-ignifx-focus=\"ignore\"` — never takes it.\n */\n\n/**\n * The attribute that overrides the editability guess in either direction.\n *\n * @public\n */\nexport const UI_FOCUS_ATTRIBUTE = \"data-ignifx-focus\";\n\n/**\n * The `<input>` types that are **not** text entry: a player may want to drive them with the\n * keyboard, so focusing one must not stop gameplay actions.\n */\nconst NON_TEXT_INPUT_TYPES: readonly string[] = Object.freeze([\n \"button\",\n \"checkbox\",\n \"color\",\n \"file\",\n \"hidden\",\n \"image\",\n \"radio\",\n \"range\",\n \"reset\",\n \"submit\",\n]);\n\n/** The element members this module reads, so a fake in a node test only has to provide these. */\ninterface FocusCandidate {\n readonly tagName?: unknown;\n readonly type?: unknown;\n readonly isContentEditable?: unknown;\n readonly getAttribute?: unknown;\n}\n\n/**\n * Reads one attribute off a candidate without assuming it is a real `Element`.\n *\n * @param candidate - The focused node.\n * @param name - The attribute name.\n * @returns The attribute's value, or `null` when there is none or the node cannot answer.\n */\nfunction attribute(candidate: FocusCandidate, name: string): string | null {\n const getter = candidate.getAttribute;\n if (typeof getter !== \"function\") {\n return null;\n }\n const value: unknown = Reflect.apply(getter, candidate, [name]);\n return typeof value === \"string\" ? value : null;\n}\n\n/**\n * Reports whether a focused node is a text-entry element, and therefore owns the keyboard.\n *\n * @remarks\n * Deliberately structural rather than `instanceof HTMLInputElement`: the same function then answers\n * for a real element in Chromium and for the fake DOM the node suite builds, and two documents in\n * one page (an `<iframe>`) do not need their constructors to match.\n *\n * @param node - The node that just received focus, or `null`.\n * @returns `true` when typing into it must stop keyboard actions from firing.\n *\n * @example\n * ```ts\n * const field = document.createElement(\"input\");\n * isEditableElement(field); // true — an <input> with no type is a text field\n * ```\n *\n * @public\n */\nexport function isEditableElement(node: unknown): boolean {\n if (node === null || typeof node !== \"object\") {\n return false;\n }\n const candidate: FocusCandidate = node;\n const override = attribute(candidate, UI_FOCUS_ATTRIBUTE);\n if (override === \"capture\") {\n return true;\n }\n if (override === \"ignore\") {\n return false;\n }\n if (candidate.isContentEditable === true) {\n return true;\n }\n const tagName = typeof candidate.tagName === \"string\" ? candidate.tagName.toUpperCase() : \"\";\n if (tagName === \"TEXTAREA\" || tagName === \"SELECT\") {\n return true;\n }\n if (tagName !== \"INPUT\") {\n return false;\n }\n const type = typeof candidate.type === \"string\" ? candidate.type.toLowerCase() : \"text\";\n return !NON_TEXT_INPUT_TYPES.includes(type);\n}\n\n/**\n * What {@link UiFocusWatcher} needs.\n *\n * @internal\n */\nexport interface UiFocusWatcherOptions {\n /** The document `focusin` and `focusout` are read from. */\n readonly document: Document;\n /** Called whenever the answer changes; the host forwards it to `app.input.uiHasFocus`. */\n readonly onChanged: (hasFocus: boolean) => void;\n}\n\n/**\n * Watches the document's focus and reports whether a text field owns the keyboard.\n *\n * @remarks\n * Scoped to the whole document rather than to `app.ui.root`, because a game may portal a menu\n * anywhere — a React portal on `document.body`, a `<dialog>` in the top layer — and a field that\n * fires gameplay actions is a bug wherever it lives. `focusout` re-reads `document.activeElement`\n * rather than trusting `relatedTarget`, which is `null` for a blur that leaves the page entirely.\n *\n * @internal\n */\nexport class UiFocusWatcher {\n readonly #document: Document;\n\n readonly #onChanged: (hasFocus: boolean) => void;\n\n #hasFocus = false;\n\n #attached = false;\n\n readonly #onFocusIn = (event: Event): void => {\n this.#set(isEditableElement(event.target));\n };\n\n readonly #onFocusOut = (): void => {\n // `focusout` fires *before* the new element is focused, so the answer is read on the next\n // microtask — by which time `activeElement` is the element that actually took focus, or the\n // body when nothing did.\n void Promise.resolve().then((): void => {\n if (this.#attached) {\n this.#set(isEditableElement(this.#document.activeElement));\n }\n });\n };\n\n /**\n * Builds the watcher. It subscribes nothing until {@link UiFocusWatcher.attach} is called.\n *\n * @param options - The document to watch and the callback to report through.\n */\n constructor(options: UiFocusWatcherOptions) {\n this.#document = options.document;\n this.#onChanged = options.onChanged;\n }\n\n /**\n * Whether a text field currently owns the keyboard.\n *\n * @returns The last reported answer.\n */\n get hasFocus(): boolean {\n return this.#hasFocus;\n }\n\n /** Subscribes to the document, and reports the element that is already focused. */\n attach(): void {\n if (this.#attached) {\n return;\n }\n this.#attached = true;\n this.#document.addEventListener(\"focusin\", this.#onFocusIn);\n this.#document.addEventListener(\"focusout\", this.#onFocusOut);\n this.#set(isEditableElement(this.#document.activeElement));\n }\n\n /** Unsubscribes and reports `false`, so a disposed overlay never leaves the keyboard captured. */\n detach(): void {\n if (!this.#attached) {\n return;\n }\n this.#attached = false;\n this.#document.removeEventListener(\"focusin\", this.#onFocusIn);\n this.#document.removeEventListener(\"focusout\", this.#onFocusOut);\n this.#set(false);\n }\n\n /**\n * Reports a new answer, if it changed.\n *\n * @param value - The new answer.\n */\n #set(value: boolean): void {\n if (this.#hasFocus === value) {\n return;\n }\n this.#hasFocus = value;\n this.#onChanged(value);\n }\n}\n","import { array, bool, defineSchema, enumOf, str, u32 } from \"@ignifx/core\";\nimport type { Schema } from \"@ignifx/core\";\n\n/**\n * The `ui` project settings section (`docs/architecture/04-extensions.md` §5, `13-ui.md` §1).\n * Everything here is what a game writes in `ignifx.config.ts`; the knobs a game changes per frame\n * live on `app.ui` and on the individual layers instead.\n */\n\n/**\n * The section name as it appears in `ignifx.config.ts`.\n *\n * @public\n */\nexport const UI_SETTINGS_SECTION = \"ui\";\n\n/**\n * Every scaling mode the overlay host supports, in the order an inspector should list them\n * (`docs/architecture/13-ui.md` §1).\n *\n * @public\n */\nexport const UI_SCALING_MODES = [\"css\", \"fit\", \"dpi\"] as const;\n\n/**\n * How the overlay's coordinate system relates to the canvas.\n *\n * @remarks\n * - `\"css\"` — one UI unit is one CSS pixel and nothing is scaled. The browser default, and what a\n * responsive HTML menu wants.\n * - `\"fit\"` — the root is exactly {@link UiSettings.referenceResolution} CSS pixels and is scaled\n * uniformly to fit inside the canvas, keeping aspect and centring the letterbox. A HUD authored\n * once at 1920x1080 then looks the same on every window size.\n * - `\"dpi\"` — one UI unit is one **render-target** pixel: the root is sized to the canvas's\n * backing store and scaled by `1 / devicePixelRatio` so it still covers the same area. This is\n * the space `Camera.worldToScreen`, `HudText`, and `app.renderer.captureScreenshot()` all work\n * in, so an element placed at `left: 100px` lands on render-target column 100 exactly.\n *\n * @public\n */\nexport type UiScalingMode = (typeof UI_SCALING_MODES)[number];\n\n/**\n * The resolved `ui` settings section.\n *\n * @example\n * ```ts\n * // ignifx.config.ts\n * export default defineConfig({\n * ui: { scaling: \"fit\", referenceResolution: [640, 360], layers: [\"hud\", \"menu\"] },\n * });\n * ```\n *\n * @public\n */\nexport interface UiSettings {\n /** How the overlay's coordinate system relates to the canvas. Defaults to `\"css\"`. */\n readonly scaling: UiScalingMode;\n /**\n * The `[width, height]`, in UI units, that `\"fit\"` scales to. Ignored by the other two modes.\n * Defaults to `[1920, 1080]`.\n */\n readonly referenceResolution: readonly number[];\n /**\n * The layers created eagerly, back to front. Declaring them here is what makes their stacking\n * order independent of the order the game happens to call {@link UiHost.layer} in.\n */\n readonly layers: readonly string[];\n /** Whether the overlay is shown at all. Defaults to `true`. */\n readonly visible: boolean;\n}\n\n/**\n * The z-index step between two consecutive layers. The first declared layer sits at\n * `UI_LAYER_Z_STEP`, the second at twice that, and so on, which leaves nine free slots between any\n * two layers for a game that wants to interleave its own elements.\n *\n * @public\n */\nexport const UI_LAYER_Z_STEP = 10;\n\n/**\n * The values used for everything a project omits.\n *\n * @returns The default `ui` section.\n *\n * @public\n */\nexport function defaultUiSettings(): UiSettings {\n return { scaling: \"css\", referenceResolution: [1920, 1080], layers: [\"hud\", \"menu\", \"overlay\"], visible: true };\n}\n\n/**\n * The schema the `ui` section is validated against.\n *\n * @returns The schema, built fresh so no module holds state (`CONSTITUTION.md` §3.5).\n *\n * @public\n */\nexport function uiSettingsSchema(): Schema {\n return defineSchema({\n scaling: enumOf(UI_SCALING_MODES, \"css\", { tooltip: \"How the overlay's units map onto the canvas.\" }),\n referenceResolution: array(u32(1), [1920, 1080], {\n tooltip: 'The [width, height] the \"fit\" mode scales to.',\n }),\n layers: array(str(), [\"hud\", \"menu\", \"overlay\"], {\n tooltip: \"The layers created up front, back to front.\",\n }),\n visible: bool(true, { tooltip: \"Whether the overlay is shown.\" }),\n });\n}\n","/**\n * The one stylesheet `@ignifx/ui` injects, and the class names it defines\n * (`docs/architecture/13-ui.md` §3: *\"plain DOM helper classes with no styling opinions beyond a\n * minimal stylesheet; templates ship their own CSS\"*).\n *\n * The rules do only what a game cannot reasonably be asked to repeat: position the root over the\n * canvas, make it click-through, and give the helper widgets a shape that is visible before any\n * game CSS loads. No rule uses `!important`, and every rule is a single class selector — except the\n * two that carry a state a game must not be able to defeat by accident: `.ignifx-ui-menu[hidden]`,\n * which is what actually hides a menu, and the `[data-focused]` / `[data-disabled]` row states,\n * which a game restyles by writing the same selector.\n */\n\n/**\n * The `id` of the injected `<style>` element, so a second app in one document reuses it.\n *\n * @public\n */\nexport const UI_STYLE_ELEMENT_ID = \"ignifx-ui-styles\";\n\n/**\n * The `z-index` a `Dialog` is drawn at inside its layer.\n *\n * @remarks\n * A dialog is modal, and a modal that paints under the panel that opened it swallows every click\n * on that panel. Siblings with no `z-index` paint in DOM order, so a `Dialog` created before a\n * `Menu` in the same layer would lose; giving every dialog one number puts it above every other\n * root of its layer whatever order they were built in. Two dialogs in one layer still stack in DOM\n * order, and `DialogOptions.zIndex` overrides the number for a dialog that must sit elsewhere.\n *\n * @public\n */\nexport const UI_DIALOG_Z_INDEX = 1000;\n\n/**\n * The class names the host and the helper widgets set, so a template's CSS can target them without\n * guessing (`docs/architecture/13-ui.md` §3).\n *\n * @public\n */\nexport const UI_CLASS_NAMES = {\n /** The overlay root. */\n root: \"ignifx-ui-root\",\n /** A named layer inside the root. */\n layer: \"ignifx-ui-layer\",\n /** Anything that should receive pointer events; the root does not. */\n interactive: \"ignifx-ui-interactive\",\n /** A `Dialog`'s outermost element. */\n dialog: \"ignifx-ui-dialog\",\n /** A `Dialog`'s backdrop. */\n dialogBackdrop: \"ignifx-ui-dialog-backdrop\",\n /** A `Dialog`'s panel. */\n dialogPanel: \"ignifx-ui-dialog-panel\",\n /** A `Dialog`'s title. */\n dialogTitle: \"ignifx-ui-dialog-title\",\n /** A `Dialog`'s message. */\n dialogMessage: \"ignifx-ui-dialog-message\",\n /** A `Dialog`'s button row. */\n dialogButtons: \"ignifx-ui-dialog-buttons\",\n /** One `Dialog` button. */\n dialogButton: \"ignifx-ui-dialog-button\",\n /** A `Menu`'s outermost panel. */\n menu: \"ignifx-ui-menu\",\n /** A `Menu`'s heading. */\n menuTitle: \"ignifx-ui-menu-title\",\n /** A `Menu`'s subtitle. */\n menuSubtitle: \"ignifx-ui-menu-subtitle\",\n /** The list a `Menu`'s rows are appended to. */\n menuRows: \"ignifx-ui-menu-rows\",\n /** One selectable `Menu` row. */\n menuRow: \"ignifx-ui-menu-row\",\n /** A `Menu` row's left-hand text. */\n menuRowLabel: \"ignifx-ui-menu-row-label\",\n /** A `Menu` row's right-hand text. */\n menuRowValue: \"ignifx-ui-menu-row-value\",\n /** A `Menu` slider row's range input. */\n menuRowSlider: \"ignifx-ui-menu-row-slider\",\n /** A `Menu`'s `\"heading\"` row. */\n menuHeading: \"ignifx-ui-menu-heading\",\n /** A `Menu`'s `\"separator\"` row. */\n menuSeparator: \"ignifx-ui-menu-separator\",\n /** A `Toast`'s stack container. */\n toastStack: \"ignifx-ui-toasts\",\n /** One toast. */\n toast: \"ignifx-ui-toast\",\n /** A `LoadingScreen`'s outermost element. */\n loading: \"ignifx-ui-loading\",\n /** A `LoadingScreen`'s label. */\n loadingLabel: \"ignifx-ui-loading-label\",\n /** A `LoadingScreen`'s progress track. */\n loadingTrack: \"ignifx-ui-loading-track\",\n /** A `LoadingScreen`'s progress bar. */\n loadingBar: \"ignifx-ui-loading-bar\",\n /** A `VirtualJoystick`'s outer pad. */\n joystick: \"ignifx-ui-joystick\",\n /** A `VirtualJoystick`'s knob. */\n joystickKnob: \"ignifx-ui-joystick-knob\",\n /** A `VirtualButton`. */\n button: \"ignifx-ui-button\",\n} as const;\n\n/**\n * The CSS custom properties the root carries, so game CSS can read the safe area and the current\n * scale without measuring anything (`docs/architecture/13-ui.md` §1).\n *\n * @public\n */\nexport const UI_CSS_VARIABLES = {\n /** The top safe-area inset, from `env(safe-area-inset-top)`. */\n safeTop: \"--ignifx-safe-top\",\n /** The right safe-area inset. */\n safeRight: \"--ignifx-safe-right\",\n /** The bottom safe-area inset. */\n safeBottom: \"--ignifx-safe-bottom\",\n /** The left safe-area inset. */\n safeLeft: \"--ignifx-safe-left\",\n /** The uniform scale the root is drawn at, as a bare number. */\n scale: \"--ignifx-ui-scale\",\n} as const;\n\n/**\n * The stylesheet text.\n *\n * @remarks\n * A function rather than a module constant so nothing but a declaration lives at module scope\n * (`CONSTITUTION.md` §3.5, and the `ignifx/no-module-side-effects` rule).\n *\n * @returns The CSS the host injects once per document.\n *\n * @internal\n */\nexport function uiStyleSheet(): string {\n const c = UI_CLASS_NAMES;\n return [\n `.${c.root}{position:absolute;top:0;left:0;pointer-events:none;overflow:hidden;transform-origin:0 0;}`,\n `.${c.layer}{position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none;}`,\n `.${c.interactive}{pointer-events:auto;}`,\n `.${c.dialog}{position:absolute;top:0;left:0;width:100%;height:100%;display:flex;` +\n `align-items:center;justify-content:center;pointer-events:auto;z-index:${String(UI_DIALOG_Z_INDEX)};}`,\n `.${c.dialogBackdrop}{position:absolute;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);}`,\n `.${c.dialogPanel}{position:relative;min-width:12rem;padding:1rem;border-radius:0.5rem;` +\n `background:#1b1d22;color:#f5f5f5;font:inherit;}`,\n `.${c.dialogTitle}{margin:0 0 0.5rem;font-size:1.1em;}`,\n `.${c.dialogMessage}{margin:0 0 1rem;}`,\n `.${c.dialogButtons}{display:flex;gap:0.5rem;justify-content:flex-end;}`,\n `.${c.dialogButton}{padding:0.4rem 0.9rem;border:0;border-radius:0.25rem;background:#3a6df0;` +\n `color:#fff;font:inherit;cursor:pointer;}`,\n `.${c.menu}{position:absolute;top:0;left:0;width:100%;height:100%;display:flex;` +\n `flex-direction:column;align-items:center;justify-content:center;gap:0.5rem;pointer-events:auto;}`,\n // The UA rule for `[hidden]` is a type selector, so a game's own `.ignifx-ui-menu { display: … }`\n // would beat it; this class-plus-attribute selector stays ahead of a single-class rule without\n // an `!important`.\n `.${c.menu}[hidden]{display:none;}`,\n `.${c.menuRows}{display:flex;flex-direction:column;min-width:12rem;max-height:100%;overflow:auto;}`,\n `.${c.menuRow}{display:flex;align-items:center;justify-content:space-between;gap:0.75rem;` +\n `padding:0.4rem 0.75rem;border:1px solid transparent;border-radius:0.25rem;background:transparent;` +\n `color:inherit;font:inherit;text-align:left;cursor:pointer;}`,\n `.${c.menuRow}[data-focused]{border-color:currentColor;background:rgba(255,255,255,0.1);}`,\n `.${c.menuRow}[data-disabled]{opacity:0.4;cursor:default;}`,\n `.${c.menuHeading}{padding:0.6rem 0.75rem 0.2rem;opacity:0.6;}`,\n `.${c.menuSeparator}{margin:0.4rem 0.75rem;border-top:1px solid currentColor;opacity:0.25;}`,\n `.${c.toastStack}{position:absolute;right:1rem;bottom:1rem;display:flex;flex-direction:column;` +\n `gap:0.5rem;align-items:flex-end;}`,\n `.${c.toast}{padding:0.5rem 0.9rem;border-radius:0.25rem;background:#1b1d22;color:#f5f5f5;}`,\n `.${c.loading}{position:absolute;top:0;left:0;width:100%;height:100%;display:flex;` +\n `flex-direction:column;align-items:center;justify-content:center;gap:0.75rem;` +\n `background:#0d0f12;color:#f5f5f5;pointer-events:auto;}`,\n `.${c.loadingTrack}{width:60%;max-width:24rem;height:0.5rem;border-radius:0.25rem;background:#2a2e36;}`,\n `.${c.loadingBar}{height:100%;width:0;border-radius:0.25rem;background:#3a6df0;}`,\n `.${c.joystick}{position:absolute;width:7rem;height:7rem;border-radius:50%;` +\n `background:rgba(255,255,255,0.12);touch-action:none;pointer-events:auto;}`,\n `.${c.joystickKnob}{position:absolute;top:50%;left:50%;width:3rem;height:3rem;margin:-1.5rem 0 0 -1.5rem;` +\n `border-radius:50%;background:rgba(255,255,255,0.35);}`,\n `.${c.button}{position:absolute;width:4rem;height:4rem;border:0;border-radius:50%;` +\n `background:rgba(255,255,255,0.2);color:#fff;font:inherit;touch-action:none;pointer-events:auto;}`,\n ].join(\"\\n\");\n}\n\n/**\n * Injects the stylesheet into a document, once.\n *\n * @remarks\n * Keyed by {@link UI_STYLE_ELEMENT_ID}, so two apps sharing a document share one `<style>` element\n * and neither removes the other's (`CONSTITUTION.md` §3.6). Nothing removes it: a stylesheet with\n * no matching elements costs nothing, and unmounting it would break the app that is still running.\n *\n * It is **prepended** to the head rather than appended, which is what actually makes this file's\n * promise true. The overlay is built inside `createApp`, long after the page's own `<style>` and\n * `<link>` elements have been parsed; appending would put every package rule *after* the game's,\n * and a game rule of equal specificity would silently lose. Prepending puts the defaults where\n * defaults belong — first — so a single-class rule in the game's stylesheet wins on order.\n *\n * @param document - The document to inject into.\n *\n * @internal\n */\nexport function ensureUiStyles(document: Document): void {\n // `getElementById` rather than `querySelector`: the id is the whole query, and the node test's\n // fake document then needs one method instead of a selector parser.\n // oxlint-disable-next-line unicorn/prefer-query-selector\n if (document.getElementById(UI_STYLE_ELEMENT_ID) !== null) {\n return;\n }\n const style = document.createElement(\"style\");\n style.id = UI_STYLE_ELEMENT_ID;\n style.textContent = uiStyleSheet();\n document.head.prepend(style);\n}\n","import { UI_CLASS_NAMES } from \"./styles.js\";\n\n/**\n * One named stacking layer inside the overlay root (`docs/architecture/13-ui.md` §1:\n * \"games mount React/Preact/Svelte/Vue/vanilla trees into it, or into named layers\"*).\n *\n * A layer is a plain absolutely-positioned `<div>` that fills the root, carries a `z-index`, and is\n * `pointer-events: none` like the root — children opt in with the\n * {@link UI_CLASS_NAMES.interactive} class or their own CSS. Under a headless app the layer still\n * exists as an object, with `element` `null` and every mutation a no-op, so game code never has to\n * branch on the environment.\n */\n\n/**\n * Options accepted by `app.ui.layer`.\n *\n * @public\n */\nexport interface UiLayerOptions {\n /** The stacking order. Defaults to the layer's declaration index times `UI_LAYER_Z_STEP`. */\n readonly zIndex?: number;\n /** Whether the layer starts visible. Defaults to `true`. */\n readonly visible?: boolean;\n}\n\n/**\n * A named layer of the overlay.\n *\n * @example\n * ```ts\n * const hud = app.ui.layer(\"hud\");\n * hud.element?.append(document.createElement(\"div\"));\n * hud.visible = false;\n * ```\n *\n * @public\n */\nexport class UiLayer {\n /** The name the layer is addressed by. */\n readonly name: string;\n\n #element: HTMLDivElement | null;\n\n #zIndex: number;\n\n #visible: boolean;\n\n /**\n * Builds a layer. `app.ui.layer` does this; a game never constructs one.\n *\n * @param name - The layer name.\n * @param element - The layer's element, or `null` under a headless app.\n * @param zIndex - The initial stacking order.\n * @param visible - Whether the layer starts visible.\n *\n * @internal\n */\n constructor(name: string, element: HTMLDivElement | null, zIndex: number, visible: boolean) {\n this.name = name;\n this.#element = element;\n this.#zIndex = zIndex;\n this.#visible = visible;\n if (element !== null) {\n this.#dress(element);\n }\n }\n\n /**\n * Gives a layer that was created before the overlay mounted its element.\n *\n * @remarks\n * The host builds its root when the world is created, which is after every extension registered;\n * a layer declared in the `ui` settings section therefore exists as an object first and gets its\n * element a moment later. Nothing observable changes: an unmounted layer is exactly a headless\n * one.\n *\n * @param element - The layer's element.\n *\n * @internal\n */\n attach(element: HTMLDivElement): void {\n this.#element = element;\n this.#dress(element);\n }\n\n /**\n * The layer's element, or `null` when the app has no DOM overlay.\n *\n * @returns The `<div>` a game mounts its tree into.\n */\n get element(): HTMLDivElement | null {\n return this.#element;\n }\n\n /**\n * The layer's stacking order within the root.\n *\n * @returns The `z-index`.\n */\n get zIndex(): number {\n return this.#zIndex;\n }\n\n // eslint-disable-next-line jsdoc/require-jsdoc -- the accessor pair is documented on the getter.\n set zIndex(value: number) {\n if (this.#zIndex === value) {\n return;\n }\n this.#zIndex = value;\n this.#applyZIndex();\n }\n\n /**\n * Whether the layer is shown. Hiding a layer hides everything mounted in it without unmounting\n * anything, which is what a pause menu wants.\n *\n * @returns `true` while the layer is shown.\n */\n get visible(): boolean {\n return this.#visible;\n }\n\n // eslint-disable-next-line jsdoc/require-jsdoc -- the accessor pair is documented on the getter.\n set visible(value: boolean) {\n if (this.#visible === value) {\n return;\n }\n this.#visible = value;\n this.#applyVisibility();\n }\n\n /**\n * Removes every child of the layer without removing the layer itself.\n *\n * @remarks\n * A no-op under a headless app.\n */\n clear(): void {\n const element = this.#element;\n if (element !== null) {\n element.replaceChildren();\n }\n }\n\n /**\n * Writes the layer's name, class, order, and visibility onto a fresh element.\n *\n * @param element - The element to dress.\n */\n #dress(element: HTMLDivElement): void {\n element.className = UI_CLASS_NAMES.layer;\n element.dataset[\"ignifxLayer\"] = this.name;\n this.#applyZIndex();\n this.#applyVisibility();\n }\n\n /** Writes the current `z-index` onto the element. */\n #applyZIndex(): void {\n this.#element?.style.setProperty(\"z-index\", String(this.#zIndex));\n }\n\n /** Writes the current visibility onto the element. */\n #applyVisibility(): void {\n this.#element?.style.setProperty(\"display\", this.#visible ? \"block\" : \"none\");\n }\n}\n","import type { UiScalingMode } from \"../settings.js\";\n\n/**\n * The scaling arithmetic behind `app.ui.scaling` (`docs/architecture/13-ui.md` §1). Every function\n * here is pure: it takes measurements and returns numbers, so the three modes are unit-testable\n * under Node with no DOM at all, and the host is left with nothing but the DOM writes.\n *\n * ## The three coordinate systems\n *\n * A canvas has two sizes: its **CSS** size, which is what layout and pointer coordinates use, and\n * its **backing-store** size (`canvas.width`/`canvas.height`), which is what WebGPU renders into.\n * Their ratio is the effective device pixel ratio. `Camera.worldToScreen`, Lite's text renderer,\n * and `app.renderer.captureScreenshot()` all work in backing-store pixels; a DOM element is placed\n * in CSS pixels. A \"UI unit\" is whichever of the two — or neither — the scaling mode picks:\n *\n * | Mode | One UI unit is | Root size | Scale |\n * | ------- | -------------------- | ------------------------ | ---------------------------- |\n * | `\"css\"` | one CSS pixel | the canvas's CSS size | `1` |\n * | `\"fit\"` | one reference pixel | `referenceResolution` | `min(cssW/refW, cssH/refH)` |\n * | `\"dpi\"` | one backing pixel | the canvas's pixel size | `cssW / backingW` |\n */\n\n/**\n * The two sizes of the canvas the overlay covers, both measured by the host.\n *\n * @public\n */\nexport interface UiSurfaceMetrics {\n /** The canvas's laid-out width, in CSS pixels. */\n readonly cssWidth: number;\n /** The canvas's laid-out height, in CSS pixels. */\n readonly cssHeight: number;\n /** The canvas's backing-store width, in device pixels — `canvas.width`. */\n readonly deviceWidth: number;\n /** The canvas's backing-store height, in device pixels — `canvas.height`. */\n readonly deviceHeight: number;\n}\n\n/**\n * Where the overlay root sits and how big it is, in the units the mode chose.\n *\n * @public\n */\nexport interface UiLayout {\n /** The mode this layout was computed for. */\n readonly mode: UiScalingMode;\n /** The root's width, in UI units. */\n readonly width: number;\n /** The root's height, in UI units. */\n readonly height: number;\n /** The uniform CSS scale applied to the root. */\n readonly scale: number;\n /** The root's left edge, in CSS pixels from the canvas's left edge. */\n readonly offsetX: number;\n /** The root's top edge, in CSS pixels from the canvas's top edge. */\n readonly offsetY: number;\n}\n\n/** The smallest size any measurement is treated as, so no ratio divides by zero. */\nconst MIN_EXTENT = 1;\n\n/**\n * Clamps a measurement to something a ratio can safely divide by.\n *\n * @param value - The measured extent.\n * @returns The extent, or {@link MIN_EXTENT} when it is absent, zero, or not a finite number.\n */\nfunction extent(value: number): number {\n return Number.isFinite(value) && value > 0 ? value : MIN_EXTENT;\n}\n\n/**\n * The `[width, height]` a `\"fit\"` layout scales to, with both entries made safe.\n *\n * @param reference - The `ui.referenceResolution` setting.\n * @returns The width and height, each at least {@link MIN_EXTENT}.\n *\n * @internal\n */\nexport function resolveReferenceResolution(reference: readonly number[]): { width: number; height: number } {\n return { width: extent(reference[0] ?? 0), height: extent(reference[1] ?? 0) };\n}\n\n/**\n * Computes the overlay root's size, scale, and offset for one mode and one measured canvas.\n *\n * @param mode - The scaling mode.\n * @param metrics - The canvas's CSS and backing-store sizes.\n * @param reference - The `[width, height]` a `\"fit\"` layout scales to; ignored by the other modes.\n * @returns The layout to write onto the root.\n *\n * @example\n * ```ts\n * computeUiLayout(\"fit\", { cssWidth: 800, cssHeight: 600, deviceWidth: 800, deviceHeight: 600 }, [\n * 400, 300,\n * ]).scale; // 2\n * ```\n *\n * @public\n */\nexport function computeUiLayout(\n mode: UiScalingMode,\n metrics: UiSurfaceMetrics,\n reference: readonly number[],\n): UiLayout {\n const cssWidth = extent(metrics.cssWidth);\n const cssHeight = extent(metrics.cssHeight);\n if (mode === \"fit\") {\n const { width, height } = resolveReferenceResolution(reference);\n const scale = Math.min(cssWidth / width, cssHeight / height);\n return {\n mode,\n width,\n height,\n scale,\n offsetX: (cssWidth - width * scale) / 2,\n offsetY: (cssHeight - height * scale) / 2,\n };\n }\n if (mode === \"dpi\") {\n const deviceWidth = extent(metrics.deviceWidth);\n const deviceHeight = extent(metrics.deviceHeight);\n const scale = cssWidth / deviceWidth;\n return { mode, width: deviceWidth, height: deviceHeight, scale, offsetX: 0, offsetY: 0 };\n }\n return { mode: \"css\", width: cssWidth, height: cssHeight, scale: 1, offsetX: 0, offsetY: 0 };\n}\n\n/**\n * Whether two layouts are the same, so the host can skip the DOM writes when a resize changed\n * nothing (coding standards §7).\n *\n * @param left - One layout.\n * @param right - The other.\n * @returns `true` when every field matches.\n *\n * @internal\n */\nexport function layoutsEqual(left: UiLayout, right: UiLayout): boolean {\n return (\n left.mode === right.mode &&\n left.width === right.width &&\n left.height === right.height &&\n left.scale === right.scale &&\n left.offsetX === right.offsetX &&\n left.offsetY === right.offsetY\n );\n}\n\n/**\n * How a render-target pixel maps onto a UI unit under one layout.\n *\n * @remarks\n * `Camera.worldToScreen` answers in **backing-store** pixels (it divides by\n * `RendererImpl.readTargetSize`, which reads `canvas.width`/`canvas.height`), and a DOM element is\n * placed in UI units inside a root that is itself translated by `offsetX`/`offsetY` CSS pixels and\n * scaled by `scale`. This is the conversion between the two, expressed so a per-frame loop needs\n * two multiplies and a subtract and allocates nothing.\n *\n * @public\n */\nexport interface UiPixelMapping {\n /** Multiply a backing-store x by this. */\n readonly scaleX: number;\n /** Then subtract this. */\n readonly originX: number;\n /** Multiply a backing-store y by this. */\n readonly scaleY: number;\n /** Then subtract this. */\n readonly originY: number;\n}\n\n/**\n * Builds the backing-store-pixel to UI-unit conversion for one layout and one canvas.\n *\n * @param layout - The current layout.\n * @param metrics - The canvas's CSS and backing-store sizes.\n * @returns The mapping.\n *\n * @example\n * ```ts\n * const metrics = { cssWidth: 400, cssHeight: 300, deviceWidth: 800, deviceHeight: 600 };\n * const layout = computeUiLayout(\"css\", metrics, [400, 300]);\n * const map = pixelMapping(layout, metrics);\n * map.scaleX * 800 - map.originX; // 400 — the canvas's right edge, in CSS pixels\n * ```\n *\n * @public\n */\nexport function pixelMapping(layout: UiLayout, metrics: UiSurfaceMetrics): UiPixelMapping {\n const cssPerDeviceX = extent(metrics.cssWidth) / extent(metrics.deviceWidth);\n const cssPerDeviceY = extent(metrics.cssHeight) / extent(metrics.deviceHeight);\n const scale = layout.scale === 0 ? 1 : layout.scale;\n return {\n scaleX: cssPerDeviceX / scale,\n originX: layout.offsetX / scale,\n scaleY: cssPerDeviceY / scale,\n originY: layout.offsetY / scale,\n };\n}\n","import { Signal } from \"@ignifx/core\";\nimport { UI_LAYER_Z_STEP } from \"../settings.js\";\nimport { UiFocusWatcher } from \"./focus.js\";\nimport { UiLayer } from \"./layer.js\";\nimport { computeUiLayout, layoutsEqual, pixelMapping } from \"./scaling.js\";\nimport { ensureUiStyles, UI_CLASS_NAMES, UI_CSS_VARIABLES } from \"./styles.js\";\nimport type { UiDomTarget } from \"./dom-target.js\";\nimport type { UiLayerOptions } from \"./layer.js\";\nimport type { UiLayout, UiPixelMapping, UiSurfaceMetrics } from \"./scaling.js\";\nimport type { UiScalingMode, UiSettings } from \"../settings.js\";\nimport type { Logger, SignalLike } from \"@ignifx/core\";\n\n/**\n * The overlay host behind `app.ui` (`docs/architecture/13-ui.md` §1).\n *\n * ## What it is\n *\n * One absolutely-positioned `<div>` laid over the canvas, `pointer-events: none`, holding one\n * `<div>` per named layer. Everything a game mounts goes inside a layer. The host owns four things\n * and nothing else: the root's geometry (the three scaling modes), the safe-area custom properties,\n * the layer stack, and the focus flag it writes into `@ignifx/input`.\n *\n * ## Headless\n *\n * `07-rendering.md` §6 says a headless app's render objects are inert rather than absent. The host\n * follows the same rule: with no DOM canvas — a headless app, an `OffscreenCanvas`, a canvas that\n * is not in a document — {@link UiHost.root} is `null`, every layer's `element` is `null`, every\n * mutation is a no-op, and one debug line is logged at construction. Nothing throws, so a script\n * that puts a name tag on a monster is the same script in a test and in a browser.\n *\n * ## When the root is built\n *\n * Not in the extension's `register`: `AppImpl.initialize` registers every extension **before** it\n * creates the Lite engine, so `app.renderer.surface` throws `IGX-0107` there\n * (`packages/core/src/app/app.ts` 416-424). The host is therefore constructed inert and\n * {@link UiHost.mount}ed from `UiSystem.onWorldCreated`, which fires later inside the same\n * `createApp` call — the same hook `@ignifx/2d` uses for the same reason. By the time\n * `await createApp(...)` resolves, `app.ui.root` is an element.\n *\n * ## Where the root is attached\n *\n * As the canvas's next sibling, inside the canvas's own parent, rather than on `document.body`. A\n * game that puts its canvas inside a positioned wrapper — every template does — then gets an\n * overlay that moves with the canvas, and two apps in one document get one overlay each\n * (`CONSTITUTION.md` §3.6). When the canvas has no parent element the root is appended to the\n * document body instead, which is what a bare test page looks like.\n */\n\n/** The `ResizeObserver` shape the host uses, duck-typed so a node test can inject a fake. */\ninterface ResizeObserverLike {\n /** Starts observing an element. */\n observe(target: Element): void;\n /** Stops observing everything. */\n disconnect(): void;\n}\n\n/** The constructor of {@link ResizeObserverLike}, as it appears on a window. */\ntype ResizeObserverConstructor = new (callback: () => void) => ResizeObserverLike;\n\n/**\n * Reads a `ResizeObserver` constructor off a window, if it has one.\n *\n * @param view - The window.\n * @returns The constructor, or `null` on a platform without one.\n */\nfunction resizeObserverOf(view: Window): ResizeObserverConstructor | null {\n const candidate: unknown = Reflect.get(view, \"ResizeObserver\");\n if (typeof candidate !== \"function\") {\n return null;\n }\n // The platform either has the constructor the spec\n // defines or it has nothing, and a fake injected by a test declares the same two methods.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return candidate as ResizeObserverConstructor;\n}\n\n/**\n * What {@link UiHost} is constructed with.\n *\n * @internal\n */\nexport interface UiHostOptions {\n /**\n * Finds the DOM to build the overlay in, or answers `null` for a headless app. Called once, from\n * {@link UiHost.mount}, because the render surface does not exist while extensions register.\n */\n readonly resolveTarget: () => UiDomTarget | null;\n /** The resolved `ui` settings section, already merged with the extension's options. */\n readonly settings: UiSettings;\n /** The extension's logger. */\n readonly log: Logger;\n /**\n * Writes `app.input.uiHasFocus`. The extension supplies a setter that duck-types the input\n * service, so `@ignifx/ui` never imports `@ignifx/input` and the peer stays genuinely optional.\n */\n readonly setInputFocus: (value: boolean) => void;\n /**\n * Writes `app.input.uiHasPointer`: `true` while at least one pointer is pressed on the overlay,\n * so pointing-device actions read as released during a drag that began on UI. Same duck-typing\n * as {@link UiHostOptions.setInputFocus}.\n */\n readonly setInputPointer: (value: boolean) => void;\n}\n\n/** The metrics a headless host reports, so every conversion degenerates predictably. */\nconst HEADLESS_METRICS: UiSurfaceMetrics = Object.freeze({\n cssWidth: 1,\n cssHeight: 1,\n deviceWidth: 1,\n deviceHeight: 1,\n});\n\n/**\n * The DOM overlay host, reached as `app.ui`.\n *\n * @example\n * ```ts\n * const hud = app.ui.layer(\"hud\");\n * app.ui.scaling = \"fit\";\n * app.ui.referenceResolution = [640, 360];\n * ```\n *\n * @public\n */\nexport class UiHost {\n readonly #resolveTarget: () => UiDomTarget | null;\n\n readonly #log: Logger;\n\n readonly #setInputFocus: (value: boolean) => void;\n readonly #setInputPointer: (value: boolean) => void;\n\n #target: UiDomTarget | null = null;\n\n #root: HTMLDivElement | null = null;\n\n readonly #layers = new Map<string, UiLayer>();\n\n readonly #layerOrder: UiLayer[] = [];\n\n #focus: UiFocusWatcher | null = null;\n\n readonly #layoutChanged = new Signal<UiLayout>();\n\n readonly #metrics: { cssWidth: number; cssHeight: number; deviceWidth: number; deviceHeight: number } = {\n cssWidth: 1,\n cssHeight: 1,\n deviceWidth: 1,\n deviceHeight: 1,\n };\n\n #observer: ResizeObserverLike | null = null;\n\n #scaling: UiScalingMode;\n\n #reference: readonly number[];\n\n #visible: boolean;\n\n #layout: UiLayout;\n\n #mapping: UiPixelMapping;\n\n #pointerCount = 0;\n\n #mounted = false;\n\n #disposed = false;\n\n readonly #onResize = (): void => {\n this.refresh();\n };\n\n readonly #onPointerDown = (): void => {\n this.#pointerCount += 1;\n if (this.#pointerCount === 1) {\n this.#setInputPointer(true);\n }\n };\n\n readonly #onPointerUp = (): void => {\n if (this.#pointerCount === 0) {\n return;\n }\n this.#pointerCount -= 1;\n if (this.#pointerCount === 0) {\n this.#setInputPointer(false);\n }\n };\n\n /**\n * Builds the host and, when there is a DOM, the root and the declared layers.\n *\n * @param options - The DOM target, the settings, the logger, and the focus setter.\n *\n * @internal\n */\n constructor(options: UiHostOptions) {\n const { settings, log } = options;\n this.#resolveTarget = options.resolveTarget;\n this.#log = log;\n this.#setInputFocus = options.setInputFocus;\n this.#setInputPointer = options.setInputPointer;\n this.#scaling = settings.scaling;\n this.#reference = [...settings.referenceResolution];\n this.#visible = settings.visible;\n this.#layout = computeUiLayout(this.#scaling, HEADLESS_METRICS, this.#reference);\n this.#mapping = pixelMapping(this.#layout, HEADLESS_METRICS);\n for (const name of settings.layers) {\n this.#createLayer(name, {});\n }\n }\n\n /**\n * Builds the root, the layer elements, the focus watcher, and the resize subscriptions. Called\n * once, from `UiSystem.onWorldCreated`; calling it again does nothing.\n *\n * @internal\n */\n mount(): void {\n if (this.#mounted || this.#disposed) {\n return;\n }\n this.#mounted = true;\n const target = this.#resolveTarget();\n if (target === null) {\n this.#log.debug(\"No DOM canvas: app.ui.root is null and every overlay member is a no-op.\");\n return;\n }\n this.#target = target;\n ensureUiStyles(target.document);\n const root = this.#createRoot(target);\n this.#root = root;\n this.#focus = new UiFocusWatcher({ document: target.document, onChanged: this.#setInputFocus });\n this.#focus.attach();\n for (const layer of this.#layerOrder) {\n const element = target.document.createElement(\"div\");\n layer.attach(element);\n root.append(element);\n }\n this.#observe(target);\n this.refresh();\n }\n\n /**\n * The overlay root: an absolutely positioned `<div>` covering the canvas, `pointer-events: none`.\n *\n * @returns The root, or `null` when the app has no DOM overlay.\n */\n get root(): HTMLDivElement | null {\n return this.#root;\n }\n\n /**\n * Whether there is a DOM overlay at all. `false` under a headless app, an `OffscreenCanvas`, or a\n * detached canvas — the three cases in which every other member is a no-op.\n *\n * @returns `true` when {@link UiHost.root} is an element.\n */\n get isActive(): boolean {\n return this.#root !== null;\n }\n\n /**\n * How the overlay's coordinate system relates to the canvas. Writing it recomputes the layout\n * immediately.\n *\n * @returns The current mode.\n */\n get scaling(): UiScalingMode {\n return this.#scaling;\n }\n\n // eslint-disable-next-line jsdoc/require-jsdoc -- the accessor pair is documented on the getter.\n set scaling(value: UiScalingMode) {\n if (this.#scaling === value) {\n return;\n }\n this.#scaling = value;\n this.refresh();\n }\n\n /**\n * The `[width, height]` the `\"fit\"` mode scales to. Writing it recomputes the layout.\n *\n * @returns A copy of the current reference resolution.\n */\n get referenceResolution(): readonly number[] {\n return this.#reference;\n }\n\n // eslint-disable-next-line jsdoc/require-jsdoc -- the accessor pair is documented on the getter.\n set referenceResolution(value: readonly number[]) {\n this.#reference = [...value];\n this.refresh();\n }\n\n /**\n * Whether the whole overlay is shown. Per-layer visibility is `app.ui.layer(name).visible`.\n *\n * @returns `true` while the overlay is shown.\n */\n get visible(): boolean {\n return this.#visible;\n }\n\n // eslint-disable-next-line jsdoc/require-jsdoc -- the accessor pair is documented on the getter.\n set visible(value: boolean) {\n if (this.#visible === value) {\n return;\n }\n this.#visible = value;\n this.#root?.style.setProperty(\"display\", value ? \"block\" : \"none\");\n }\n\n /**\n * The root's current size, scale, and offset, in the units the scaling mode chose.\n *\n * @returns The layout last computed.\n */\n get layout(): UiLayout {\n return this.#layout;\n }\n\n /**\n * The conversion from render-target pixels — the space `Camera.worldToScreen`, `HudText`, and\n * `app.renderer.captureScreenshot()` work in — to UI units.\n *\n * @returns The mapping last computed.\n */\n get pixelMapping(): UiPixelMapping {\n return this.#mapping;\n }\n\n /**\n * Every layer, back to front.\n *\n * @returns The layers, ordered by `zIndex`.\n */\n get layers(): readonly UiLayer[] {\n return this.#layerOrder;\n }\n\n /**\n * Whether a pointer is currently pressed on an interactive element of the overlay.\n *\n * @remarks\n * A click on a UI element never reaches gameplay in the first place: `@ignifx/input` reads\n * `pointerdown` and `wheel` from the **canvas** (`packages/input/src/dom/pointer-source.ts`), and\n * the overlay root is the canvas's sibling rather than its child, so a press that lands on a\n * `pointer-events: auto` element is not on the canvas and is never queued. This flag covers the\n * remaining case: `pointermove` and `pointerup` are read from the **window**, so a drag that\n * started on a slider still moves `<Pointer>/delta`. A camera script that must ignore that reads\n * this flag.\n *\n * @returns `true` while at least one pointer is down on the overlay.\n */\n get pointerOverUi(): boolean {\n return this.#pointerCount > 0;\n }\n\n /**\n * Whether a text field currently owns the keyboard — the same value the host writes into\n * `app.input.uiHasFocus`.\n *\n * @returns `true` while typing must not fire keyboard actions.\n */\n get keyboardHasFocus(): boolean {\n return this.#focus?.hasFocus ?? false;\n }\n\n /**\n * Emitted after every recomputation that changed the layout: a canvas resize, a device-pixel-ratio\n * change, or a write to {@link UiHost.scaling} or {@link UiHost.referenceResolution}.\n *\n * @returns The signal.\n */\n get onLayoutChanged(): SignalLike<UiLayout> {\n return this.#layoutChanged;\n }\n\n /**\n * Returns the named layer, creating it the first time it is asked for.\n *\n * @param name - The layer name.\n * @param options - The stacking order and the initial visibility, used only on creation.\n * @returns The layer.\n *\n * @example\n * ```ts\n * const menu = app.ui.layer(\"menu\", { zIndex: 100 });\n * ```\n */\n layer(name: string, options?: UiLayerOptions): UiLayer {\n const existing = this.#layers.get(name);\n if (existing !== undefined) {\n if (options?.zIndex !== undefined) {\n existing.zIndex = options.zIndex;\n this.#sortLayers();\n }\n return existing;\n }\n return this.#createLayer(name, options ?? {});\n }\n\n /**\n * Re-measures the canvas and rewrites the root's geometry.\n *\n * @remarks\n * Called by the `ResizeObserver`, by the window's `resize` event — which is what a\n * device-pixel-ratio change fires — and by every write to a scaling property. Games call it after\n * changing the canvas's size by hand. A recomputation that produces the same layout writes\n * nothing and emits nothing.\n */\n refresh(): void {\n const target = this.#target;\n const root = this.#root;\n if (target === null || root === null || this.#disposed) {\n return;\n }\n const rect = target.canvas.getBoundingClientRect();\n this.#metrics.cssWidth = rect.width;\n this.#metrics.cssHeight = rect.height;\n this.#metrics.deviceWidth = target.canvas.width;\n this.#metrics.deviceHeight = target.canvas.height;\n const layout = computeUiLayout(this.#scaling, this.#metrics, this.#reference);\n this.#mapping = pixelMapping(layout, this.#metrics);\n if (layoutsEqual(this.#layout, layout)) {\n return;\n }\n this.#layout = layout;\n const style = root.style;\n style.setProperty(\"width\", `${String(layout.width)}px`);\n style.setProperty(\"height\", `${String(layout.height)}px`);\n style.setProperty(\n \"transform\",\n `translate(${String(layout.offsetX)}px, ${String(layout.offsetY)}px) scale(${String(layout.scale)})`,\n );\n style.setProperty(UI_CSS_VARIABLES.scale, String(layout.scale));\n this.#layoutChanged.emit(layout);\n }\n\n /**\n * Removes the overlay from the document and unsubscribes from everything.\n *\n * @internal\n */\n dispose(): void {\n if (this.#disposed) {\n return;\n }\n this.#disposed = true;\n this.#mounted = true;\n this.#observer?.disconnect();\n this.#observer = null;\n this.#focus?.detach();\n const target = this.#target;\n const root = this.#root;\n if (target !== null && root !== null) {\n target.window.removeEventListener(\"resize\", this.#onResize);\n root.removeEventListener(\"pointerdown\", this.#onPointerDown);\n target.window.removeEventListener(\"pointerup\", this.#onPointerUp);\n target.window.removeEventListener(\"pointercancel\", this.#onPointerUp);\n root.remove();\n }\n this.#layers.clear();\n this.#layerOrder.length = 0;\n this.#layoutChanged.clear();\n }\n\n /**\n * Builds the root element, sets the safe-area variables, and puts it over the canvas.\n *\n * @param target - The DOM target.\n * @returns The root.\n */\n #createRoot(target: UiDomTarget): HTMLDivElement {\n const root = target.document.createElement(\"div\");\n root.className = UI_CLASS_NAMES.root;\n const style = root.style;\n style.setProperty(\"display\", this.#visible ? \"block\" : \"none\");\n // `env()` is resolved by the browser against the actual display, so the four variables are set\n // once and never recomputed; a game reads them with `var(--ignifx-safe-top)`. The `0px`\n // fallback is what a desktop browser and the node fake both report.\n style.setProperty(UI_CSS_VARIABLES.safeTop, \"env(safe-area-inset-top, 0px)\");\n style.setProperty(UI_CSS_VARIABLES.safeRight, \"env(safe-area-inset-right, 0px)\");\n style.setProperty(UI_CSS_VARIABLES.safeBottom, \"env(safe-area-inset-bottom, 0px)\");\n style.setProperty(UI_CSS_VARIABLES.safeLeft, \"env(safe-area-inset-left, 0px)\");\n const parent = target.canvas.parentElement;\n if (parent === null) {\n target.document.body.append(root);\n } else {\n target.canvas.after(root);\n }\n return root;\n }\n\n /**\n * Subscribes to the canvas's size and the window's resize event.\n *\n * @param target - The DOM target.\n */\n #observe(target: UiDomTarget): void {\n const Observer = resizeObserverOf(target.window);\n if (Observer !== null) {\n const observer = new Observer(this.#onResize);\n observer.observe(target.canvas);\n this.#observer = observer;\n }\n // The window's `resize` is the one event a device-pixel-ratio change reliably fires; a\n // `ResizeObserver` on the canvas sees the CSS box, which does not change when the ratio does.\n target.window.addEventListener(\"resize\", this.#onResize);\n this.#root?.addEventListener(\"pointerdown\", this.#onPointerDown);\n target.window.addEventListener(\"pointerup\", this.#onPointerUp);\n target.window.addEventListener(\"pointercancel\", this.#onPointerUp);\n }\n\n /**\n * Creates one layer and inserts it in stacking order.\n *\n * @param name - The layer name.\n * @param options - The stacking order and the initial visibility.\n * @returns The new layer.\n */\n #createLayer(name: string, options: UiLayerOptions): UiLayer {\n const zIndex = options.zIndex ?? (this.#layerOrder.length + 1) * UI_LAYER_Z_STEP;\n const element = this.#target === null ? null : this.#target.document.createElement(\"div\");\n const layer = new UiLayer(name, element, zIndex, options.visible ?? true);\n this.#layers.set(name, layer);\n this.#layerOrder.push(layer);\n if (element !== null) {\n this.#root?.append(element);\n }\n this.#sortLayers();\n return layer;\n }\n\n /** Re-sorts the layer list by `zIndex`; the DOM order follows the `z-index` property itself. */\n #sortLayers(): void {\n this.#layerOrder.sort((left: UiLayer, right: UiLayer): number => left.zIndex - right.zIndex);\n }\n}\n","import { IgnifxError } from \"@ignifx/core\";\nimport type { ErrorContext } from \"@ignifx/core\";\n\n/**\n * The diagnostic codes `@ignifx/ui` owns. The UI subsystem sits in the `13` range of\n * `docs/architecture/15-devtools-and-diagnostics.md` §1 — *\"`13xx` UI\"* — so every code reads\n * `IGX-13##`. `@ignifx/ui` is the only package in the range and owns all of it.\n *\n * The table lives here rather than in `@ignifx/core`'s `CoreErrorCode`: an extension owns its own\n * codes and hands them to the app through `ExtensionContext.registerErrorCodes`\n * (`docs/architecture/04-extensions.md` §3).\n */\n\n/**\n * Every diagnostic code `@ignifx/ui` can throw or log, keyed by an intention-revealing name so call\n * sites read as prose and the compiler catches typos (coding standards §5.2).\n *\n * @example\n * ```ts\n * throw uiError(UiErrorCode.unknownLayer, \"hud is not a declared UI layer.\", {\n * context: { layer: \"hud\" },\n * });\n * ```\n *\n * @public\n */\nexport const UiErrorCode = {\n /** A second `ui()` extension was registered on one app. */\n duplicateExtension: \"IGX-1301\",\n /** A `.i18n.json` file is not an `ignifx.i18n` document this build can read. */\n invalidLocaleFile: \"IGX-1302\",\n /** `app.i18n.locale` was set to a locale the loaded document does not declare. */\n unknownLocale: \"IGX-1303\",\n /** A message pattern could not be parsed: an unbalanced brace or an unknown argument form. */\n invalidMessagePattern: \"IGX-1304\",\n /** A widget that needs `@ignifx/input` was built on an app that did not register it. */\n inputExtensionMissing: \"IGX-1305\",\n /** A `WorldText` or `HudText` was asked to draw before its `font` asset was assigned. */\n missingFont: \"IGX-1306\",\n /** A DOM-only member was reached on a host with no document, and did nothing. */\n headlessNoOp: \"IGX-1307\",\n /** A `WorldText` needed a scene renderable after the render scene had already been built. */\n sceneAlreadyBuilt: \"IGX-1308\",\n} as const;\n\n/**\n * The union of the codes the `UiErrorCode` table declares.\n *\n * @public\n */\nexport type UiErrorCode = (typeof UiErrorCode)[keyof typeof UiErrorCode];\n\n/**\n * The one-line message template of every code, as `ExtensionContext.registerErrorCodes` wants it.\n * Context keys appear in braces, matching the core table's convention.\n *\n * @public\n */\nexport const UI_ERROR_MESSAGES: Readonly<Record<string, string>> = Object.freeze({\n \"IGX-1301\": \"The ui() extension is already registered on this app.\",\n \"IGX-1302\": \"{file} is not an ignifx.i18n document this build can read.\",\n \"IGX-1303\": \"{locale} is not a locale the loaded translation document declares.\",\n \"IGX-1304\": \"Message {key} could not be parsed: {reason}.\",\n \"IGX-1305\": \"{widget} needs the @ignifx/input extension, which this app did not register.\",\n \"IGX-1306\": \"{component} has no font asset assigned, so it has nothing to draw.\",\n \"IGX-1307\": \"{member} did nothing: this app has no DOM overlay host.\",\n \"IGX-1308\": \"{component} was given its text after app.start(), so Babylon Lite will not draw it.\",\n});\n\n/**\n * Options accepted by {@link uiError}: the same subset of `IgnifxErrorOptions` this package uses.\n *\n * @public\n */\nexport interface UiErrorOptions {\n /** Identifiers that locate the failure. */\n readonly context?: ErrorContext;\n /** One sentence telling the developer what to do about it. */\n readonly hint?: string;\n /** The failure being wrapped, when there is one. */\n readonly cause?: unknown;\n}\n\n/**\n * Builds an `IgnifxError` carrying one of this package's codes.\n *\n * @param code - The code from the `UiErrorCode` table.\n * @param message - The actionable development sentence.\n * @param options - Context identifiers, a remedy hint, and the wrapped cause.\n * @returns The error to throw or to reject with.\n *\n * @example\n * ```ts\n * throw uiError(UiErrorCode.unknownLocale, \"fr is not a locale strings.i18n.json declares.\", {\n * context: { locale: \"fr\" },\n * });\n * ```\n *\n * @public\n */\nexport function uiError(code: UiErrorCode, message: string, options?: UiErrorOptions): IgnifxError {\n return new IgnifxError(code, message, {\n ...(options?.context === undefined ? {} : { context: options.context }),\n ...(options?.hint === undefined ? {} : { hint: options.hint }),\n ...(options?.cause === undefined ? {} : { cause: options.cause }),\n });\n}\n","/**\n * What the overlay host needs from the host page (`docs/architecture/13-ui.md` §1). Passing it\n * explicitly, instead of reaching for `globalThis.document`, is what makes two apps in one document\n * possible (`CONSTITUTION.md` §3.6) and what lets a test hand in a fake.\n *\n * The whole module is written against the real DOM types rather than structural stand-ins, which is\n * the choice `@ignifx/input`'s `DomTarget` already made: games get real elements to mount React or\n * Svelte into, and the node test suite passes a fake through one `as unknown as` in\n * `test/support/fake-dom.ts` rather than every call site paying for an abstraction.\n */\n\n/**\n * The DOM objects one app's overlay is built in.\n *\n * @public\n */\nexport interface UiDomTarget {\n /** The canvas the overlay is positioned over. */\n readonly canvas: HTMLCanvasElement;\n /** The document the overlay's elements and its stylesheet are created in. */\n readonly document: Document;\n /** The window resize and focus events are read from, and the pixel ratio is read from. */\n readonly window: Window;\n}\n\n/**\n * Narrows an unknown render surface to a DOM canvas, so a headless app or an `OffscreenCanvas`\n * simply gets no overlay.\n *\n * @param surface - The renderer's surface, or anything else.\n * @returns The canvas, or `null` when there is no DOM canvas to overlay.\n *\n * @internal\n */\nexport function asDomCanvas(surface: unknown): HTMLCanvasElement | null {\n if (typeof HTMLCanvasElement === \"undefined\") {\n return null;\n }\n return surface instanceof HTMLCanvasElement ? surface : null;\n}\n\n/**\n * Builds the DOM target from a render surface.\n *\n * @remarks\n * Returns `null` — which is what makes every overlay member a documented no-op\n * (`docs/architecture/07-rendering.md` §6) — for a headless app, for an `OffscreenCanvas`, and for\n * a canvas that has been removed from its document, because a detached canvas has no\n * `defaultView` to subscribe to.\n *\n * @param surface - The renderer's surface, or anything else.\n * @returns The target, or `null` when there is no DOM to build an overlay in.\n *\n * @internal\n */\nexport function resolveDomTarget(surface: unknown): UiDomTarget | null {\n const canvas = asDomCanvas(surface);\n if (canvas === null) {\n return null;\n }\n const document = canvas.ownerDocument;\n const view = document.defaultView;\n if (view === null) {\n return null;\n }\n return { canvas, document, window: view };\n}\n","import { defineSchema, describeSchema, map, str, toJsonSchema, u32 } from \"@ignifx/core\";\nimport { uiError, UiErrorCode } from \"../errors.js\";\nimport type { JsonSchemaObject, Schema, SchemaDescription } from \"@ignifx/core\";\n\n/**\n * The `ignifx.i18n` document (`docs/architecture/06-serialization-and-scene-format.md` §6,\n * `13-ui.md` §3: *\"loaded from `.json` assets\"*).\n *\n * One file carries **every** locale, keyed by BCP 47 tag, because a game with two languages should\n * not need two fetches and a `locale` switch should not need a load at all:\n *\n * ```json\n * {\n * \"format\": \"ignifx.i18n\",\n * \"formatVersion\": 1,\n * \"defaultLocale\": \"en\",\n * \"locales\": {\n * \"en\": { \"hud.score\": \"Score: {score}\" },\n * \"fr\": { \"hud.score\": \"Score : {score}\" }\n * }\n * }\n * ```\n *\n * A game that would rather ship one file per locale loads several documents and calls\n * `app.i18n.load` on each; the service merges them, later loads winning on a repeated key.\n */\n\n/**\n * The `format` discriminator every translation document carries.\n *\n * @public\n */\nexport const I18N_FORMAT = \"ignifx.i18n\";\n\n/**\n * The `formatVersion` this build writes and is the only one it can read. Before 1.0 the number\n * stays `1` and an incompatible change invalidates files rather than migrating them\n * (`CONSTITUTION.md` §4.2); a file declaring anything else is rejected with `IGX-1302`.\n *\n * @public\n */\nexport const I18N_FORMAT_VERSION = 1;\n\n/**\n * The asset type translation documents are registered under.\n *\n * @public\n */\nexport const I18N_ASSET_TYPE = \"i18n\";\n\n/**\n * The file extensions the translation loader claims.\n *\n * @public\n */\nexport const I18N_FILE_EXTENSIONS: readonly string[] = Object.freeze([\".i18n.json\"]);\n\n/**\n * A parsed `ignifx.i18n` document.\n *\n * @public\n */\nexport interface LocaleDocument {\n /** The locale used when nothing else selected one. */\n readonly defaultLocale: string;\n /** Every locale's message table, keyed by BCP 47 tag. */\n readonly locales: Readonly<Record<string, Readonly<Record<string, string>>>>;\n}\n\n/**\n * Narrows a parsed JSON value to an object.\n *\n * @param value - The value.\n * @returns The object, or `null` when the value is an array, a primitive, or absent.\n */\nfunction asObject(value: unknown): Record<string, unknown> | null {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return null;\n }\n // The guard above is exactly \"a plain object\", which\n // is a string-keyed bag of unknowns.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return value as Record<string, unknown>;\n}\n\n/**\n * Reads one locale's table, dropping any entry whose value is not a string.\n *\n * @param value - The raw table.\n * @returns The strings.\n */\nfunction readTable(value: unknown): Record<string, string> {\n const source = asObject(value);\n const table: Record<string, string> = {};\n if (source === null) {\n return table;\n }\n for (const key of Object.keys(source).toSorted()) {\n const message = source[key];\n if (typeof message === \"string\") {\n table[key] = message;\n }\n }\n return table;\n}\n\n/**\n * Parses and validates a translation document.\n *\n * @param value - The parsed JSON.\n * @param address - The address it came from, for the error's context.\n * @returns The document.\n * @throws IgnifxError with code `IGX-1302` when the header is missing, the version does not match,\n * or the file declares no locales.\n *\n * @example\n * ```ts\n * const document = parseLocaleFile(\n * { format: \"ignifx.i18n\", formatVersion: 1, defaultLocale: \"en\", locales: { en: { ok: \"OK\" } } },\n * \"ui/strings.i18n.json\",\n * );\n * document.locales[\"en\"]?.[\"ok\"]; // \"OK\"\n * ```\n *\n * @public\n */\nexport function parseLocaleFile(value: unknown, address: string): LocaleDocument {\n const file = asObject(value);\n if (file === null || file[\"format\"] !== I18N_FORMAT || file[\"formatVersion\"] !== I18N_FORMAT_VERSION) {\n throw uiError(UiErrorCode.invalidLocaleFile, `${address} is not an ${I18N_FORMAT} document this build can read.`, {\n context: { file: address },\n hint: `This build reads ${I18N_FORMAT} version ${String(I18N_FORMAT_VERSION)}.`,\n });\n }\n const raw = asObject(file[\"locales\"]);\n const tags = raw === null ? [] : Object.keys(raw).toSorted();\n if (tags.length === 0) {\n throw uiError(UiErrorCode.invalidLocaleFile, `${address} declares no locales.`, {\n context: { file: address },\n hint: 'Add at least one entry to the \"locales\" object, keyed by BCP 47 tag.',\n });\n }\n const locales: Record<string, Readonly<Record<string, string>>> = {};\n for (const tag of tags) {\n locales[tag] = readTable(raw?.[tag]);\n }\n const declared = file[\"defaultLocale\"];\n const fallback = tags[0] ?? \"\";\n const defaultLocale = typeof declared === \"string\" && Object.hasOwn(locales, declared) ? declared : fallback;\n return { defaultLocale, locales };\n}\n\n/**\n * A loaded translation document (`docs/architecture/05-assets-and-loading.md` §5).\n *\n * @remarks\n * Pure data: it loads identically under Node and in a browser and has nothing to release.\n *\n * @example\n * ```ts\n * const strings = await app.assets.loadAsync<LocaleAsset>(\"ui/strings.i18n.json\");\n * strings.value.availableLocales; // [\"en\", \"fr\"]\n * ```\n *\n * @public\n */\nexport class LocaleAsset {\n /** The type name the asset service registers translation documents under. */\n static assetType: string = I18N_ASSET_TYPE;\n\n /** The address the document was loaded from. */\n readonly address: string;\n\n /** The parsed document. */\n readonly document: LocaleDocument;\n\n /**\n * Wraps a parsed document. The `i18n` loader constructs these.\n *\n * @param address - The address it was loaded from.\n * @param document - The parsed document.\n *\n * @internal\n */\n constructor(address: string, document: LocaleDocument) {\n this.address = address;\n this.document = document;\n }\n\n /**\n * Every locale the document declares, sorted.\n *\n * @returns The BCP 47 tags.\n */\n get availableLocales(): readonly string[] {\n return Object.keys(this.document.locales);\n }\n}\n\n/**\n * The schema a translation document is described and validated against for tooling.\n *\n * @remarks\n * The loader validates with {@link parseLocaleFile}, which produces an actionable `IGX-1302`\n * naming the file; this schema is what `pnpm docs:schemas` renders and what a JSON Schema for an\n * editor is generated from — the split `@ignifx/2d`'s `file-schemas.ts` documents.\n *\n * @returns The schema, built fresh so no module holds state (`CONSTITUTION.md` §3.5).\n *\n * @public\n */\nexport function localeFileSchema(): Schema {\n return defineSchema({\n format: str(I18N_FORMAT, { tooltip: \"Always ignifx.i18n.\" }),\n formatVersion: u32(I18N_FORMAT_VERSION, { tooltip: \"The document version this build reads.\" }),\n defaultLocale: str(\"en\", { tooltip: \"The locale used until the game picks another.\" }),\n locales: map(map(str()), { tooltip: \"Message tables keyed by BCP 47 tag, then by message key.\" }),\n });\n}\n\n/**\n * Describes the `ignifx.i18n` file format for the documentation harness.\n *\n * @returns The record `pnpm docs:schemas` renders.\n *\n * @public\n */\nexport function describeLocaleFileFormat(): SchemaDescription {\n return describeSchema(\"ignifx/i18n-file\", localeFileSchema(), {\n title: \"Translations\",\n format: I18N_FORMAT,\n description: \"Message tables for one or more locales, with {name} interpolation and ICU-style plurals.\",\n });\n}\n\n/**\n * The JSON Schema a tool validates a `.i18n.json` document against.\n *\n * @returns The JSON Schema object.\n *\n * @public\n */\nexport function localeJsonSchema(): JsonSchemaObject {\n return toJsonSchema(localeFileSchema());\n}\n","/**\n * The ICU-style message subset `app.i18n.t` understands (`docs/architecture/13-ui.md` §3:\n * \"a tiny key/value service with ICU-style plurals\"*).\n *\n * ## What is supported\n *\n * - `{name}` — substitutes a parameter. A parameter that was not supplied is left as written, so a\n * missing value shows up in the interface instead of silently becoming `undefined`.\n * - `{count, plural, one {a life} other {# lives}}` — selects a branch with `Intl.PluralRules` for\n * the active locale, and replaces `#` inside the chosen branch with the number.\n * - `{count, plural, =0 {no lives} one {…} other {…}}` — an exact match, checked before the\n * category, exactly as ICU orders them.\n *\n * ## What is not\n *\n * `select`, `selectordinal`, number and date skeletons, and ICU's apostrophe quoting. Braces are\n * structural: a literal `{` has to arrive through a parameter. Anything the parser cannot read is\n * reported rather than guessed at, and the service turns that report into `IGX-1304`.\n *\n * The parser is pure and allocates only while parsing; parsed patterns are cached by the service,\n * so a `t()` in `update` walks a node list and appends strings rather than re-parsing.\n */\n\n/** The categories `Intl.PluralRules` can return, plus the exact-match form this parser also takes. */\nconst PLURAL_CATEGORIES: readonly string[] = Object.freeze([\"zero\", \"one\", \"two\", \"few\", \"many\", \"other\"]);\n\n/**\n * What a message's parameters may be.\n *\n * @public\n */\nexport type MessageParams = Readonly<Record<string, string | number>>;\n\n/**\n * Chooses a plural category for a number, in one locale.\n *\n * @public\n */\nexport type PluralSelector = (value: number) => string;\n\n/**\n * A run of literal text.\n *\n * @public\n */\nexport interface TextNode {\n /** The discriminator. */\n readonly kind: \"text\";\n /** The literal. */\n readonly value: string;\n}\n\n/**\n * A `{name}` substitution.\n *\n * @public\n */\nexport interface ArgumentNode {\n /** The discriminator. */\n readonly kind: \"argument\";\n /** The parameter name. */\n readonly name: string;\n}\n\n/**\n * A `{name, plural, …}` selection.\n *\n * @public\n */\nexport interface PluralNode {\n /** The discriminator. */\n readonly kind: \"plural\";\n /** The parameter name holding the number. */\n readonly name: string;\n /** The branches, keyed by `\"=0\"`-style exact matches and by plural category. */\n readonly branches: ReadonlyMap<string, readonly MessageNode[]>;\n}\n\n/**\n * One piece of a parsed message.\n *\n * @public\n */\nexport type MessageNode = TextNode | ArgumentNode | PluralNode;\n\n/**\n * A parsed message, or the reason it could not be parsed.\n *\n * @public\n */\nexport interface MessagePattern {\n /** The nodes to render. Holds the raw pattern as one text node when {@link MessagePattern.error} is set. */\n readonly nodes: readonly MessageNode[];\n /** Why the pattern could not be read, or `null` when it parsed. */\n readonly error: string | null;\n}\n\n/** The parser's mutable position, kept in one object so the recursive helpers share it. */\ninterface Cursor {\n /** The pattern being read. */\n readonly source: string;\n /** The next index to read. */\n index: number;\n}\n\n/**\n * Reads literal text until an unescaped `{` or `}`.\n *\n * @param cursor - The parser position.\n * @param stopAtClose - Whether a `}` ends the run, which it does inside a branch.\n * @returns The text read; possibly empty.\n */\nfunction readText(cursor: Cursor, stopAtClose: boolean): string {\n const start = cursor.index;\n while (cursor.index < cursor.source.length) {\n const char = cursor.source[cursor.index];\n if (char === \"{\" || (char === \"}\" && stopAtClose)) {\n break;\n }\n cursor.index += 1;\n }\n return cursor.source.slice(start, cursor.index);\n}\n\n/**\n * Reads an identifier — a parameter name or a branch selector.\n *\n * @param cursor - The parser position.\n * @returns The identifier, trimmed; possibly empty.\n */\nfunction readIdentifier(cursor: Cursor): string {\n const start = cursor.index;\n while (cursor.index < cursor.source.length) {\n const char = cursor.source[cursor.index];\n if (char === undefined || char === \",\" || char === \"{\" || char === \"}\" || /\\s/u.test(char)) {\n break;\n }\n cursor.index += 1;\n }\n return cursor.source.slice(start, cursor.index);\n}\n\n/**\n * Skips whitespace.\n *\n * @param cursor - The parser position.\n */\nfunction skipSpace(cursor: Cursor): void {\n while (cursor.index < cursor.source.length) {\n const char = cursor.source[cursor.index];\n if (char === undefined || !/\\s/u.test(char)) {\n break;\n }\n cursor.index += 1;\n }\n}\n\n/** Thrown inside the parser and converted into {@link MessagePattern.error} at the top. */\nclass PatternError extends Error {}\n\n/**\n * Parses a sequence of nodes up to the end of the pattern or to the branch's closing brace.\n *\n * @param cursor - The parser position.\n * @param nested - Whether a `}` ends this sequence.\n * @returns The nodes.\n * @throws PatternError when a brace is unbalanced or an argument form is unknown.\n */\nfunction parseNodes(cursor: Cursor, nested: boolean): MessageNode[] {\n const nodes: MessageNode[] = [];\n for (;;) {\n const text = readText(cursor, nested);\n if (text.length > 0) {\n nodes.push({ kind: \"text\", value: text });\n }\n const char = cursor.source[cursor.index];\n if (char === undefined) {\n if (nested) {\n throw new PatternError(\"a branch is missing its closing brace\");\n }\n return nodes;\n }\n if (char === \"}\") {\n // Only reachable inside a branch: `readText` swallows a stray `}` at the top level, so an\n // unmatched closing brace in ordinary prose is literal text rather than an authoring error.\n return nodes;\n }\n cursor.index += 1;\n nodes.push(parseArgument(cursor));\n }\n}\n\n/**\n * Parses one `{…}` argument, having already consumed the opening brace.\n *\n * @param cursor - The parser position.\n * @returns The node.\n * @throws PatternError when the argument is malformed or names an unsupported form.\n */\nfunction parseArgument(cursor: Cursor): MessageNode {\n skipSpace(cursor);\n const name = readIdentifier(cursor);\n if (name.length === 0) {\n throw new PatternError(\"an argument has no name\");\n }\n skipSpace(cursor);\n if (cursor.source[cursor.index] === \"}\") {\n cursor.index += 1;\n return { kind: \"argument\", name };\n }\n if (cursor.source[cursor.index] !== \",\") {\n throw new PatternError(`argument ${name} is missing its closing brace`);\n }\n cursor.index += 1;\n skipSpace(cursor);\n const form = readIdentifier(cursor);\n if (form !== \"plural\") {\n throw new PatternError(`argument ${name} uses the unsupported form ${form === \"\" ? \"(empty)\" : form}`);\n }\n return { kind: \"plural\", name, branches: parseBranches(cursor, name) };\n}\n\n/**\n * Parses the branch list of a plural argument, up to and including its closing brace.\n *\n * @param cursor - The parser position.\n * @param name - The argument's name, for error messages.\n * @returns The branches.\n * @throws PatternError when a selector is unknown or the list is unterminated.\n */\nfunction parseBranches(cursor: Cursor, name: string): ReadonlyMap<string, readonly MessageNode[]> {\n const branches = new Map<string, readonly MessageNode[]>();\n for (;;) {\n skipSpace(cursor);\n if (cursor.source[cursor.index] === \",\") {\n cursor.index += 1;\n continue;\n }\n if (cursor.source[cursor.index] === \"}\") {\n cursor.index += 1;\n if (!branches.has(\"other\")) {\n throw new PatternError(`plural ${name} has no other branch`);\n }\n return branches;\n }\n const selector = readIdentifier(cursor);\n if (selector.length === 0) {\n throw new PatternError(`plural ${name} is missing its closing brace`);\n }\n if (!PLURAL_CATEGORIES.includes(selector) && !/^=\\d+$/u.test(selector)) {\n throw new PatternError(`plural ${name} has the unknown branch ${selector}`);\n }\n skipSpace(cursor);\n if (cursor.source[cursor.index] !== \"{\") {\n throw new PatternError(`branch ${selector} of plural ${name} has no body`);\n }\n cursor.index += 1;\n branches.set(selector, parseNodes(cursor, true));\n cursor.index += 1;\n }\n}\n\n/**\n * Parses one message pattern.\n *\n * @param pattern - The pattern, as written in the `.i18n.json` document.\n * @returns The parsed nodes, or the raw text plus the reason it could not be parsed.\n *\n * @example\n * ```ts\n * parseMessage(\"{count, plural, one {# life} other {# lives}}\").error; // null\n * parseMessage(\"{count, plural, one {# life}}\").error; // \"plural count has no other branch\"\n * ```\n *\n * @public\n */\nexport function parseMessage(pattern: string): MessagePattern {\n const cursor: Cursor = { source: pattern, index: 0 };\n try {\n return { nodes: parseNodes(cursor, false), error: null };\n } catch (error: unknown) {\n const reason = error instanceof PatternError ? error.message : \"the pattern could not be read\";\n return { nodes: [{ kind: \"text\", value: pattern }], error: reason };\n }\n}\n\n/**\n * Builds the plural selector for a locale.\n *\n * @remarks\n * `Intl.PluralRules` is present in every browser and in Node, but a stripped runtime without\n * `Intl` still has to work, so the fallback is English's two-category rule.\n *\n * @param locale - The BCP 47 locale tag.\n * @returns A function from a number to a plural category.\n *\n * @example\n * ```ts\n * createPluralSelector(\"en\")(1); // \"one\"\n * ```\n *\n * @public\n */\nexport function createPluralSelector(locale: string): PluralSelector {\n if (typeof Intl !== \"object\" || typeof Intl.PluralRules !== \"function\") {\n return (value: number): string => (value === 1 ? \"one\" : \"other\");\n }\n try {\n const rules = new Intl.PluralRules(locale);\n return (value: number): string => rules.select(value);\n } catch {\n // An unparseable tag — `Intl.PluralRules` throws a `RangeError` for one — falls back rather\n // than taking the frame down over a translation file.\n return (value: number): string => (value === 1 ? \"one\" : \"other\");\n }\n}\n\n/**\n * Reads a parameter as a number, for a plural selection.\n *\n * @param value - The supplied parameter.\n * @returns The number, or `null` when the parameter is absent or not numeric.\n */\nfunction asNumber(value: string | number | undefined): number | null {\n if (typeof value === \"number\") {\n return Number.isFinite(value) ? value : null;\n }\n if (typeof value !== \"string\") {\n return null;\n }\n const parsed = Number(value);\n return Number.isFinite(parsed) && value.trim().length > 0 ? parsed : null;\n}\n\n/**\n * Renders parsed nodes with a set of parameters.\n *\n * @param nodes - The nodes from {@link parseMessage}.\n * @param params - The values to substitute.\n * @param select - The active locale's plural selector.\n * @param hash - What `#` stands for in the branch being rendered, or `null` at the top level.\n * @returns The rendered string.\n */\nfunction render(\n nodes: readonly MessageNode[],\n params: MessageParams,\n select: PluralSelector,\n hash: string | null,\n): string {\n let out = \"\";\n for (let index = 0; index < nodes.length; index += 1) {\n const node = nodes[index];\n if (node === undefined) {\n continue;\n }\n if (node.kind === \"text\") {\n out += hash === null ? node.value : node.value.replaceAll(\"#\", hash);\n continue;\n }\n if (node.kind === \"argument\") {\n const value = Object.hasOwn(params, node.name) ? params[node.name] : undefined;\n out += value === undefined ? `{${node.name}}` : String(value);\n continue;\n }\n const raw = Object.hasOwn(params, node.name) ? params[node.name] : undefined;\n const count = asNumber(raw);\n if (count === null) {\n out += `{${node.name}}`;\n continue;\n }\n const branch =\n node.branches.get(`=${String(count)}`) ?? node.branches.get(select(count)) ?? node.branches.get(\"other\");\n out += branch === undefined ? \"\" : render(branch, params, select, String(count));\n }\n return out;\n}\n\n/**\n * Renders a parsed message.\n *\n * @param pattern - The parsed pattern.\n * @param params - The values to substitute.\n * @param select - The active locale's plural selector.\n * @returns The rendered string.\n *\n * @example\n * ```ts\n * const pattern = parseMessage(\"{count, plural, one {# life} other {# lives}}\");\n * renderMessage(pattern, { count: 3 }, createPluralSelector(\"en\")); // \"3 lives\"\n * ```\n *\n * @public\n */\nexport function renderMessage(pattern: MessagePattern, params: MessageParams, select: PluralSelector): string {\n return render(pattern.nodes, params, select, null);\n}\n","import { Signal } from \"@ignifx/core\";\nimport { uiError, UiErrorCode } from \"../errors.js\";\nimport { LocaleAsset } from \"./locale-file.js\";\nimport { createPluralSelector, parseMessage, renderMessage } from \"./message.js\";\nimport type { MessageParams, MessagePattern, PluralSelector } from \"./message.js\";\nimport type { AssetHandle, Logger, SignalLike } from \"@ignifx/core\";\n\n/**\n * The localization service behind `app.i18n` (`docs/architecture/13-ui.md` §3:\n * \"a tiny key/value service with ICU-style plurals, loaded from `.json` assets; UI helpers and\n * `WorldText` accept keys\"*).\n *\n * ## Missing keys are not errors\n *\n * `t(\"hud.score\")` with no such key returns `\"hud.score\"` and logs one debug line per key. A game\n * that ships a new string before the translator does then shows the key rather than an empty box,\n * and a test can assert on the key. `IGX-1304` is reserved for a message that *is* present and\n * cannot be parsed — a genuine authoring mistake.\n *\n * ## Cost\n *\n * Patterns are parsed once and cached by their text, so a `t()` in `update` walks a node list.\n * Switching locale clears nothing: the cache is keyed by pattern, not by key, and two locales that\n * share a pattern share its parse.\n */\n\n/** What a plain empty parameter set is, so `t(key)` allocates nothing. */\nconst NO_PARAMS: MessageParams = Object.freeze({});\n\n/**\n * What {@link I18nService} is constructed with.\n *\n * @internal\n */\nexport interface I18nServiceOptions {\n /** The extension's logger. */\n readonly log: Logger;\n /** The locale the app starts in, before any document is loaded. */\n readonly locale: string;\n}\n\n/**\n * The localization service, reached as `app.i18n`.\n *\n * @example\n * ```ts\n * await app.i18n.load(app.assets.load<LocaleAsset>(\"ui/strings.i18n.json\"));\n * app.i18n.locale = \"fr\";\n * app.i18n.t(\"hud.lives\", { count: 3 });\n * ```\n *\n * @public\n */\nexport class I18nService {\n readonly #log: Logger;\n\n readonly #tables = new Map<string, Map<string, string>>();\n\n readonly #patterns = new Map<string, MessagePattern>();\n\n readonly #reportedMissing = new Set<string>();\n\n readonly #localeChanged = new Signal<string>();\n\n #locale: string;\n\n #fallbackLocale: string;\n\n #select: PluralSelector;\n\n /**\n * Builds an empty service. The extension does this; a game never constructs one.\n *\n * @param options - The logger and the starting locale.\n *\n * @internal\n */\n constructor(options: I18nServiceOptions) {\n this.#log = options.log;\n this.#locale = options.locale;\n this.#fallbackLocale = options.locale;\n this.#select = createPluralSelector(options.locale);\n }\n\n /**\n * The active locale. Writing a locale no loaded document declares throws `IGX-1303`, because a\n * silent no-op there is a bug that only shows up as untranslated text much later.\n *\n * @returns The BCP 47 tag.\n * @throws IgnifxError with code `IGX-1303` when no loaded document declares the tag.\n */\n get locale(): string {\n return this.#locale;\n }\n\n // eslint-disable-next-line jsdoc/require-jsdoc -- the accessor pair is documented on the getter.\n set locale(value: string) {\n if (this.#locale === value) {\n return;\n }\n if (this.#tables.size > 0 && !this.#tables.has(value)) {\n throw uiError(UiErrorCode.unknownLocale, `${value} is not a locale any loaded document declares.`, {\n context: { locale: value },\n hint: `Loaded locales: ${this.availableLocales.join(\", \")}.`,\n });\n }\n this.#locale = value;\n this.#select = createPluralSelector(value);\n this.#localeChanged.emit(value);\n }\n\n /**\n * The locale a key falls back to when the active locale has no entry for it. Set from the first\n * document's `defaultLocale`.\n *\n * @returns The BCP 47 tag.\n */\n get fallbackLocale(): string {\n return this.#fallbackLocale;\n }\n\n // eslint-disable-next-line jsdoc/require-jsdoc -- the accessor pair is documented on the getter.\n set fallbackLocale(value: string) {\n this.#fallbackLocale = value;\n }\n\n /**\n * Every locale any loaded document declares, sorted.\n *\n * @returns The BCP 47 tags.\n */\n get availableLocales(): readonly string[] {\n return [...this.#tables.keys()].toSorted();\n }\n\n /**\n * Emitted after {@link I18nService.locale} changed. UI that caches rendered strings — `HudText`\n * does — redraws from here.\n *\n * @returns The signal.\n */\n get onLocaleChanged(): SignalLike<string> {\n return this.#localeChanged;\n }\n\n /**\n * Merges a translation document into the service.\n *\n * @remarks\n * Accepts a loaded {@link LocaleAsset} or the handle of one, in which case the merge happens when\n * the handle settles. Later loads win on a repeated key, which is what makes a per-locale\n * download or a downloadable language pack work. The first document loaded also sets\n * {@link I18nService.fallbackLocale} and, when the app is still on its starting locale and the\n * document does not declare it, moves the active locale to the document's `defaultLocale`.\n *\n * @param source - A loaded document, or its handle.\n * @returns A promise that settles once the document has been merged.\n *\n * @example\n * ```ts\n * using strings = app.assets.load<LocaleAsset>(\"ui/strings.i18n.json\");\n * await app.i18n.load(strings);\n * ```\n */\n async load(source: AssetHandle<LocaleAsset> | LocaleAsset): Promise<void> {\n const asset = source instanceof LocaleAsset ? source : await source.promise;\n const first = this.#tables.size === 0;\n for (const [tag, table] of Object.entries(asset.document.locales)) {\n const existing = this.#tables.get(tag) ?? new Map<string, string>();\n for (const [key, message] of Object.entries(table)) {\n existing.set(key, message);\n }\n this.#tables.set(tag, existing);\n }\n this.#reportedMissing.clear();\n if (!first) {\n return;\n }\n this.#fallbackLocale = asset.document.defaultLocale;\n if (!this.#tables.has(this.#locale)) {\n this.#locale = asset.document.defaultLocale;\n this.#select = createPluralSelector(this.#locale);\n this.#localeChanged.emit(this.#locale);\n }\n }\n\n /**\n * Whether the active locale, or the fallback, has an entry for a key.\n *\n * @param key - The message key.\n * @returns `true` when {@link I18nService.t} will find a message.\n */\n has(key: string): boolean {\n return this.#lookup(key) !== null;\n }\n\n /**\n * Renders a message.\n *\n * @param key - The message key.\n * @param params - The values `{name}` placeholders and plural selectors read.\n * @returns The rendered message, or the key itself when no document declares it.\n *\n * @example\n * ```ts\n * app.i18n.t(\"hud.lives\", { count: 1 }); // \"1 life\"\n * app.i18n.t(\"hud.lives\", { count: 4 }); // \"4 lives\"\n * ```\n */\n t(key: string, params: MessageParams = NO_PARAMS): string {\n const message = this.#lookup(key);\n if (message === null) {\n if (!this.#reportedMissing.has(key)) {\n this.#reportedMissing.add(key);\n this.#log.debug(`No translation for ${key} in ${this.#locale}; showing the key.`);\n }\n return key;\n }\n return renderMessage(this.#pattern(key, message), params, this.#select);\n }\n\n /**\n * Drops every loaded document.\n *\n * @internal\n */\n clear(): void {\n this.#tables.clear();\n this.#patterns.clear();\n this.#reportedMissing.clear();\n }\n\n /**\n * Releases everything the service holds.\n *\n * @internal\n */\n dispose(): void {\n this.clear();\n this.#localeChanged.clear();\n }\n\n /**\n * Finds a key in the active locale, then in the fallback.\n *\n * @param key - The message key.\n * @returns The raw pattern, or `null`.\n */\n #lookup(key: string): string | null {\n return this.#tables.get(this.#locale)?.get(key) ?? this.#tables.get(this.#fallbackLocale)?.get(key) ?? null;\n }\n\n /**\n * Parses a pattern, or returns the cached parse.\n *\n * @param key - The message key, for the `IGX-1304` context.\n * @param message - The raw pattern.\n * @returns The parsed pattern; an unreadable one renders as its own raw text.\n */\n #pattern(key: string, message: string): MessagePattern {\n const cached = this.#patterns.get(message);\n if (cached !== undefined) {\n return cached;\n }\n const parsed = parseMessage(message);\n if (parsed.error !== null) {\n const error = uiError(UiErrorCode.invalidMessagePattern, `Message ${key} could not be parsed: ${parsed.error}.`, {\n context: { key, reason: parsed.error },\n hint: \"Braces are structural in an ignifx.i18n message; a literal brace has to arrive as a parameter.\",\n });\n this.#log.warn(error.message);\n }\n this.#patterns.set(message, parsed);\n return parsed;\n }\n}\n","import { I18N_ASSET_TYPE, I18N_FILE_EXTENSIONS, LocaleAsset, parseLocaleFile } from \"./locale-file.js\";\nimport type { AssetLoader, LoaderContext } from \"@ignifx/core\";\n\n/**\n * The `i18n` asset loader: `.i18n.json` to {@link LocaleAsset}\n * (`docs/architecture/05-assets-and-loading.md` §5).\n *\n * The file is data, so the loader is identical under Node and in a browser and has nothing to\n * release on unload. `.i18n.json` is a longer suffix than `.json` and the asset service picks the\n * longest match, so registering it does not shadow the generic JSON loader.\n */\n\n/**\n * Builds the loader for `.i18n.json` addresses.\n *\n * @returns The loader to register with `ctx.registerAssetLoader`.\n *\n * @example\n * ```ts\n * ctx.registerAssetLoader(createLocaleLoader());\n * ```\n *\n * @public\n */\nexport function createLocaleLoader(): AssetLoader<LocaleAsset> {\n return {\n type: I18N_ASSET_TYPE,\n extensions: I18N_FILE_EXTENSIONS,\n async load(ctx: LoaderContext): Promise<LocaleAsset> {\n const parsed: unknown = await ctx.fetchJson();\n return new LocaleAsset(ctx.address, parseLocaleFile(parsed, ctx.address));\n },\n };\n}\n","import {\n addTextRendererLayer,\n createTextRenderer,\n disposeTextRenderer,\n enableDeviceLostTextRecovery,\n registerTextRenderer,\n removeTextRendererLayer,\n unregisterTextRenderer,\n} from \"@babylonjs/lite\";\nimport type { DeviceLostRecoveryHandle, EngineContext, SurfaceContext, TextLayer, TextRenderer } from \"@babylonjs/lite\";\n\n/**\n * The device-only half of the text adapter: the second Babylon Lite rendering context `@ignifx/ui`\n * puts on the app's surface for `HudText` and `WorldText2D`\n * (`docs/architecture/07-rendering.md` §1, `13-ui.md` §2).\n *\n * A `TextRenderer` opens its own swapchain pass and is registered directly on the engine,\n * independently of any scene — the same shape as `@ignifx/2d`'s sprite renderer. Two of Lite's own\n * statements govern how it is used:\n *\n * - `TextRendererOptions.clear` is *\"Default true. Set false for HUD overlays so the text pass\n * preserves existing scene color\"* (`index.d.ts` 12867). A HUD always passes `false`.\n * - `registerTextRenderer` *\"Register a text renderer with its surface so the engine updates and\n * records it each frame\"* (9547); `lib/text/text-renderer.js` implements it as\n * `registerRenderingContext(tr._surface, tr)`, which appends to the surface's context list, and\n * Lite draws that list in order — so a context registered after the render scene composites on\n * top of it.\n *\n * The renderer's pixel space is the **backing store**: `createTextRenderer` seeds\n * `_targetWidth`/`_targetHeight` from `surface.canvas.width`/`.height` and `textRendererUpdate`\n * re-reads them every frame (`lib/text/text-renderer.js`). A layer at `positionPx (100, 100)` is\n * therefore at render-target column 100, which is the same space `Camera.worldToScreen` and\n * `app.renderer.captureScreenshot()` answer in — and *not* CSS pixels.\n *\n * Everything here needs `engine._device` on the first frame, so the module lives under `gpu/` and\n * the root Vitest coverage config excludes it; the `browser` project covers it.\n *\n * Everything here is `@internal`.\n */\n\n/**\n * The surface a text renderer draws into.\n *\n * @remarks\n * `EngineContext extends SurfaceContext` (`index.d.ts` 4676) and an engine's index-0 surface *is*\n * the engine itself, so a single-canvas app passes `app.lite.engine` straight through.\n *\n * @internal\n */\nexport type TextSurface = SurfaceContext;\n\n/**\n * Creates the text renderer and registers it on the engine.\n *\n * @remarks\n * Call this **after** the render scene is registered, so text composites over the frame rather than\n * under it. `clear` is always `false`: a HUD that cleared the swapchain would erase the game.\n *\n * @param surface - The surface to draw into; the engine, for a single-canvas app.\n * @returns The registered renderer.\n *\n * @internal\n */\nexport function createRegisteredTextRenderer(surface: TextSurface): TextRenderer {\n const renderer = createTextRenderer(surface, { layers: [], clear: false });\n registerTextRenderer(renderer);\n return renderer;\n}\n\n/**\n * Adds a layer to a renderer's draw list (`index.d.ts` 214).\n *\n * @param renderer - The text renderer.\n * @param layer - The layer to draw.\n *\n * @internal\n */\nexport function attachTextLayer(renderer: TextRenderer, layer: TextLayer): void {\n addTextRendererLayer(renderer, layer);\n}\n\n/**\n * Removes a layer from a renderer's draw list and frees its per-layer GPU buffers\n * (`index.d.ts` 9671).\n *\n * @param renderer - The text renderer.\n * @param layer - The layer to stop drawing.\n * @returns `true` when the layer was there.\n *\n * @internal\n */\nexport function detachTextLayer(renderer: TextRenderer, layer: TextLayer): boolean {\n return removeTextRendererLayer(renderer, layer);\n}\n\n/**\n * Unregisters and disposes a text renderer (`index.d.ts` 13218 and 4103).\n *\n * @param renderer - The renderer to tear down.\n *\n * @internal\n */\nexport function destroyTextRenderer(renderer: TextRenderer): void {\n unregisterTextRenderer(renderer);\n disposeTextRenderer(renderer);\n}\n\n/**\n * Turns on best-effort WebGPU device-lost recovery for every registered text renderer\n * (`index.d.ts` 4388).\n *\n * @remarks\n * Unlike the sprite adapter, this one has no ordering requirement. Lite's own comment at\n * `index.d.ts` 4383-4384 says that `GlyphStorage` already retains the CPU atlas data needed for\n * reconstruction, so the adapter adds no renderer-specific capture outside the loss path. It is\n * still enabled in `onStart`, before the first layer exists, so the two adapters read the same.\n *\n * @param engine - The engine to protect.\n * @param onRecovered - Called after the replacement device and every rendering context are ready.\n * @param onFailed - Called when reacquisition or rebuilding fails.\n * @returns The handle whose `disable()` turns recovery off again.\n *\n * @internal\n */\nexport function enableTextDeviceLostRecovery(\n engine: EngineContext,\n onRecovered: () => void,\n onFailed: (error: unknown) => void,\n): DeviceLostRecoveryHandle {\n return enableDeviceLostTextRecovery(engine, { onRecovered, onRecoveryFailed: onFailed });\n}\n","import {\n addTextRenderable,\n createDefaultTextData,\n createTextLayer,\n createTextRenderable,\n disposeDefaultTextData,\n disposeTextRenderable,\n setTextLayerPosition,\n updateDefaultTextData,\n} from \"@babylonjs/lite\";\nimport type {\n DefaultTextData,\n Font,\n SceneContext,\n TextLayer,\n TextLayoutOptions,\n TextRenderable,\n TextRenderer,\n} from \"@babylonjs/lite\";\n\n/**\n * The device-free half of the Babylon Lite text adapter (`docs/architecture/13-ui.md` §2).\n * Everything here shapes text, measures it, and builds the pure-data objects a renderer later\n * draws; nothing touches `engine._device`, which is why this module is **not** under `./gpu/` and\n * is covered by the node suite. Only `createTextRenderer` needs a surface, and that lives in\n * `./gpu/text-renderer.ts`.\n *\n * ## What was verified against `@babylonjs/lite@1.27.0`\n *\n * - `createDefaultTextData(font, fontSizePx, text, textColor?, options?)` (`index.d.ts` 2377)\n * shapes the string, extracts the glyph outlines, and **owns its own `GlyphStorage`** — the\n * doc comment at 2375 says so, and `disposeDefaultTextData` (3948) releases both. The returned\n * `DefaultTextData` carries the laid-out `width` and `height` in pixels (3736-3741), which is\n * the only text measurement Lite offers.\n * - `updateDefaultTextData(data, text, textColor?)` (13247) re-shapes **with the font size and the\n * layout options the block was created with** — `lib/text/default-text-data.js` reads\n * `data._fontSizePx` and `data._options` and never takes new ones — and writes fresh `width`\n * and `height` onto the block. Changing `fontSize`, `maxWidth`, `align`, `lineHeight`, or the\n * font therefore means **recreating** the block; changing `text` or `color` does not. Omitting\n * `textColor` preserves the run's existing colour (13245-13246).\n * - `TextLayoutOptions` (12821) is `{ maxWidth, lineHeight, align, letterSpacing, tabSize }`, in\n * output pixels, with simple LTR word wrapping.\n * - `align` aligns the lines of a block against **the longest line**, not against `maxWidth`:\n * measured on the pinned build, `\"AAAA\\nB\"` at 32 px puts the `B` at x 0, 25.92 and 51.84 for\n * `\"left\"`, `\"center\"` and `\"right\"`, with `width` 69.12 in all three. Centring a block on the\n * screen is therefore the caller's arithmetic, against {@link measureText}.\n * - Glyph baselines run **downwards in negative y**: line n sits at `-n × fontSizePx × lineHeight`\n * (`PlacedGlyph`, 8854-8858). A block's first baseline is at the layer's `positionPx`, so its\n * ascent is above that point.\n * - `createTextLayer(data, options)` (3257) and `createTextRenderable(data, options)` (3264) are\n * pure object construction; `lib/text/text-renderer.js` and `lib/text/text-renderable.js` build\n * plain records with `_gpu: null` and allocate GPU resources lazily on the first frame.\n * - **There is no `removeTextRenderable`.** `addTextRenderable(scene, renderable)` (208) pushes a\n * deferred builder onto the scene (`lib/text/text-renderable.js` 242-249) and Lite exposes no\n * inverse — `removeFromScene` (9613) takes meshes, lights, cameras, shadow generators, transform\n * nodes and asset containers, and not a `TextRenderable`. {@link detachSceneText} therefore\n * empties the block and zeroes its opacity, which makes it draw nothing; the record itself stays\n * in the scene's renderable list until the scene is disposed. This is reported as a Lite gap.\n *\n * Everything here is `@internal` apart from the type aliases the `.lite` escape hatches name.\n */\n\n/**\n * The Babylon Lite font handle, re-exported under an ignifx name so feature code can name the type\n * without importing `@babylonjs/lite` (`CONSTITUTION.md` §3.4).\n *\n * @remarks\n * Unstable: it is Lite's own type, reachable only through documented `.lite` escape hatches.\n *\n * @public\n */\nexport type LiteFont = Font;\n\n/**\n * A shaped block of text, with its glyph storage.\n *\n * @remarks\n * Unstable escape-hatch type.\n *\n * @public\n */\nexport type LiteTextData = DefaultTextData;\n\n/**\n * A 2D text layer placed in render-target pixel space.\n *\n * @remarks\n * Unstable escape-hatch type.\n *\n * @public\n */\nexport type LiteTextLayer = TextLayer;\n\n/**\n * A scene renderable that draws a block of text in world space.\n *\n * @remarks\n * Unstable escape-hatch type.\n *\n * @public\n */\nexport type LiteTextRenderable = TextRenderable;\n\n/**\n * The standalone rendering context that draws 2D text layers onto the swapchain.\n *\n * @remarks\n * Unstable escape-hatch type.\n *\n * @public\n */\nexport type LiteTextRenderer = TextRenderer;\n\n/**\n * Straight RGBA in `0` to `1`, in the order Lite wants it.\n *\n * @internal\n */\nexport type TextColor = readonly [number, number, number, number];\n\n/**\n * Everything that decides how a block is laid out. Changing any of it means a new block.\n *\n * @internal\n */\nexport interface TextShape {\n /** The parsed font. */\n readonly font: LiteFont;\n /** The em size, in render-target pixels. */\n readonly fontSizePx: number;\n /** The string to shape. */\n readonly text: string;\n /** The colour every glyph starts with. */\n readonly color: TextColor;\n /** The wrap width in pixels; `0` or less means no wrapping. */\n readonly maxWidth: number;\n /** Which edge the lines align to, against the longest line. */\n readonly align: \"left\" | \"center\" | \"right\";\n /** The line-height multiplier. */\n readonly lineHeight: number;\n}\n\n/**\n * The pixel size of a laid-out block.\n *\n * @public\n */\nexport interface TextMetrics {\n /** The width of the longest line, in render-target pixels. */\n readonly width: number;\n /** The number of lines times the line height, in render-target pixels. */\n readonly height: number;\n}\n\n/**\n * Shapes a block of text.\n *\n * @param shape - The font, size, string, colour, and layout.\n * @returns The block, which owns its glyph storage.\n *\n * @internal\n */\nexport function createTextBlock(shape: TextShape): LiteTextData {\n const options: TextLayoutOptions = {\n ...(shape.maxWidth > 0 ? { maxWidth: shape.maxWidth } : {}),\n lineHeight: shape.lineHeight,\n align: shape.align,\n };\n return createDefaultTextData(shape.font, shape.fontSizePx, shape.text, shape.color, options);\n}\n\n/**\n * Re-shapes a block's string and colour, reusing its font size and layout options.\n *\n * @param data - The block.\n * @param text - The new string.\n * @param color - The new colour.\n *\n * @internal\n */\nexport function updateTextBlock(data: LiteTextData, text: string, color: TextColor): void {\n updateDefaultTextData(data, text, color);\n}\n\n/**\n * Reads a block's laid-out size.\n *\n * @param data - The block.\n * @returns The width and height, in render-target pixels.\n *\n * @internal\n */\nexport function measureText(data: LiteTextData): TextMetrics {\n return { width: data.width, height: data.height };\n}\n\n/**\n * Releases a block's GPU buffers and its glyph storage.\n *\n * @param data - The block.\n *\n * @internal\n */\nexport function destroyTextBlock(data: LiteTextData): void {\n disposeDefaultTextData(data);\n}\n\n/**\n * Builds a pixel-space layer for a block.\n *\n * @param data - The block to draw.\n * @param order - The sort order within the renderer; lower draws first.\n * @param opacity - The whole-block alpha multiplier.\n * @returns The layer.\n *\n * @internal\n */\nexport function createPixelTextLayer(data: LiteTextData, order: number, opacity: number): LiteTextLayer {\n return createTextLayer(data, { order, opacity });\n}\n\n/**\n * Moves a layer to a pixel position, measured from the render target's top-left corner.\n *\n * @param layer - The layer.\n * @param x - The x position, in render-target pixels.\n * @param y - The y position of the first baseline, in render-target pixels.\n *\n * @internal\n */\nexport function movePixelTextLayer(layer: LiteTextLayer, x: number, y: number): void {\n setTextLayerPosition(layer, x, y);\n}\n\n/**\n * Builds a world-space renderable for a block.\n *\n * @param data - The block to draw.\n * @param opacity - The whole-block alpha multiplier.\n * @returns The renderable.\n *\n * @internal\n */\nexport function createSceneText(data: LiteTextData, opacity: number): LiteTextRenderable {\n return createTextRenderable(data, { opacity });\n}\n\n/**\n * Adds a renderable to a scene's draw list.\n *\n * @remarks\n * One-way: Lite has no `removeTextRenderable`. See the module's own remarks.\n *\n * @param scene - The Lite scene, from `app.lite.scene`.\n * @param renderable - The renderable to draw.\n *\n * @internal\n */\nexport function attachSceneText(scene: SceneContext, renderable: LiteTextRenderable): void {\n addTextRenderable(scene, renderable);\n}\n\n/**\n * Makes a renderable draw nothing, which is as close to removing it as Lite allows.\n *\n * @param renderable - The renderable to silence.\n *\n * @internal\n */\nexport function detachSceneText(renderable: LiteTextRenderable): void {\n renderable.opacity = 0;\n}\n\n/**\n * Releases a renderable's GPU buffers. The block it draws is released separately.\n *\n * @param renderable - The renderable.\n *\n * @internal\n */\nexport function destroySceneText(renderable: LiteTextRenderable): void {\n disposeTextRenderable(renderable);\n}\n\n/**\n * Writes a renderable's world position, in metres.\n *\n * @param renderable - The renderable.\n * @param x - The x position.\n * @param y - The y position.\n * @param z - The z position.\n *\n * @internal\n */\nexport function moveSceneText(renderable: LiteTextRenderable, x: number, y: number, z: number): void {\n renderable.position.set(x, y, z);\n}\n\n/**\n * Writes a renderable's world rotation, as a quaternion.\n *\n * @param renderable - The renderable.\n * @param x - The x component.\n * @param y - The y component.\n * @param z - The z component.\n * @param w - The w component.\n *\n * @internal\n */\nexport function rotateSceneText(renderable: LiteTextRenderable, x: number, y: number, z: number, w: number): void {\n renderable.rotationQuaternion.set(x, y, z, w);\n}\n\n/**\n * Writes a renderable's uniform scale.\n *\n * @remarks\n * A block is laid out in **pixels**, so a world-space renderable is scaled down by\n * `1 / pixelsPerUnit` to occupy a sensible number of metres.\n *\n * @param renderable - The renderable.\n * @param scale - The uniform scale.\n *\n * @internal\n */\nexport function scaleSceneText(renderable: LiteTextRenderable, scale: number): void {\n renderable.scaling.set(scale, scale, scale);\n}\n","/**\n * Where a shaped block goes on the screen (`docs/architecture/13-ui.md` §2).\n *\n * Pure arithmetic, so the node suite covers all nine anchors with no GPU and no DOM.\n *\n * ## What Lite gives, and what it does not\n *\n * A `DefaultTextData` reports the laid-out `width` and `height` of the block and nothing else — no\n * ascent, no descent, no baseline offset (`index.d.ts` 3736-3741). Glyph baselines run downwards\n * in negative y from the layer's `positionPx`, verified on the pinned build: `\"A\\nB\\nC\"` at 32 px\n * with `lineHeight` 2 places the three baselines at y `0`, `-64`, `-128`.\n *\n * So the **first baseline** is at `positionPx.y`, and the box the reader perceives starts one em\n * above it. `ascentOf` is that approximation, stated once here rather than guessed at in three\n * components: an em is the right order of magnitude for every Latin face and it is what makes\n * `anchor: \"topLeft\"` put the text just inside the top-left corner rather than half off-screen.\n */\n\n/**\n * The nine points of a rectangle a block can be anchored to.\n *\n * @public\n */\nexport const HUD_ANCHORS = [\n \"topLeft\",\n \"top\",\n \"topRight\",\n \"left\",\n \"center\",\n \"right\",\n \"bottomLeft\",\n \"bottom\",\n \"bottomRight\",\n] as const;\n\n/**\n * Which point of the render target a `HudText`'s position is measured from, and which point of the\n * block sits there.\n *\n * @public\n */\nexport type HudAnchor = (typeof HUD_ANCHORS)[number];\n\n/** The horizontal fraction of each anchor: `0` at the left edge, `1` at the right. */\nconst ANCHOR_X: Readonly<Record<HudAnchor, number>> = Object.freeze({\n topLeft: 0,\n top: 0.5,\n topRight: 1,\n left: 0,\n center: 0.5,\n right: 1,\n bottomLeft: 0,\n bottom: 0.5,\n bottomRight: 1,\n});\n\n/** The vertical fraction of each anchor: `0` at the top edge, `1` at the bottom. */\nconst ANCHOR_Y: Readonly<Record<HudAnchor, number>> = Object.freeze({\n topLeft: 0,\n top: 0,\n topRight: 0,\n left: 0.5,\n center: 0.5,\n right: 0.5,\n bottomLeft: 1,\n bottom: 1,\n bottomRight: 1,\n});\n\n/**\n * The distance from a block's first baseline up to the top of the box a reader perceives.\n *\n * @param fontSize - The em size the block was shaped at.\n * @returns The ascent, in render-target pixels.\n *\n * @internal\n */\nexport function ascentOf(fontSize: number): number {\n return fontSize;\n}\n\n/**\n * A layer position, written in place so the per-frame path allocates nothing.\n *\n * @public\n */\nexport interface HudPlacement {\n /** The layer's x, in render-target pixels. */\n x: number;\n /** The layer's y — the first baseline — in render-target pixels. */\n y: number;\n}\n\n/**\n * What {@link computeHudPlacement} needs.\n *\n * @public\n */\nexport interface HudPlacementInput {\n /** Which point of the target the position is measured from, and which point of the block lands there. */\n readonly anchor: HudAnchor;\n /** The offset from that point, in render-target pixels; x grows right, y grows down. */\n readonly offsetX: number;\n /** The offset from that point, in render-target pixels. */\n readonly offsetY: number;\n /** The render target's width, in pixels. */\n readonly targetWidth: number;\n /** The render target's height, in pixels. */\n readonly targetHeight: number;\n /** The block's laid-out width. */\n readonly blockWidth: number;\n /** The block's laid-out height. */\n readonly blockHeight: number;\n /** The em size the block was shaped at. */\n readonly fontSize: number;\n}\n\n/**\n * Places a block against one of the nine anchors of the render target.\n *\n * @param input - The anchor, the offset, the target size, and the block's size.\n * @param out - Receives the layer position.\n * @returns `out`, for chaining.\n *\n * @example\n * ```ts\n * const out = { x: 0, y: 0 };\n * computeHudPlacement(\n * {\n * anchor: \"topRight\",\n * offsetX: -16,\n * offsetY: 16,\n * targetWidth: 800,\n * targetHeight: 600,\n * blockWidth: 100,\n * blockHeight: 40,\n * fontSize: 32,\n * },\n * out,\n * );\n * out.x; // 684 — 16 px in from the right edge\n * ```\n *\n * @public\n */\nexport function computeHudPlacement(input: HudPlacementInput, out: HudPlacement): HudPlacement {\n const fractionX = ANCHOR_X[input.anchor];\n const fractionY = ANCHOR_Y[input.anchor];\n const boxLeft = fractionX * input.targetWidth + input.offsetX - fractionX * input.blockWidth;\n const boxTop = fractionY * input.targetHeight + input.offsetY - fractionY * input.blockHeight;\n out.x = boxLeft;\n out.y = boxTop + ascentOf(input.fontSize);\n return out;\n}\n\n/**\n * Places a block around a point, with the given point of the block sitting on it.\n *\n * @param pivot - Which point of the block lands on the position.\n * @param x - The point's x, in render-target pixels.\n * @param y - The point's y, in render-target pixels.\n * @param blockWidth - The block's laid-out width.\n * @param blockHeight - The block's laid-out height.\n * @param fontSize - The em size the block was shaped at.\n * @param out - Receives the layer position.\n * @returns `out`, for chaining.\n *\n * @example\n * ```ts\n * const out = { x: 0, y: 0 };\n * computePivotPlacement(\"center\", 400, 300, 100, 40, 32, out);\n * out.x; // 350\n * ```\n *\n * @public\n */\nexport function computePivotPlacement(\n pivot: HudAnchor,\n x: number,\n y: number,\n blockWidth: number,\n blockHeight: number,\n fontSize: number,\n out: HudPlacement,\n): HudPlacement {\n out.x = x - ANCHOR_X[pivot] * blockWidth;\n out.y = y - ANCHOR_Y[pivot] * blockHeight + ascentOf(fontSize);\n return out;\n}\n","import { asset, color, Component, enumOf, f32, FontAsset, str } from \"@ignifx/core\";\nimport { createTextBlock, destroyTextBlock, measureText, updateTextBlock } from \"../lite/text.js\";\nimport type { I18nService } from \"../i18n/i18n-service.js\";\nimport type { LiteTextData, TextColor, TextMetrics } from \"../lite/text.js\";\nimport type { AssetHandle, ColorLike, FieldDefinition } from \"@ignifx/core\";\n\n/**\n * The fields and the block lifecycle every text component shares (`docs/architecture/13-ui.md` §2:\n * \"`text`, `fontSize`, `color`, `align`, `maxWidth`, `opacity`, `billboard`\"*).\n *\n * ## Why the block is rebuilt for some changes and updated for others\n *\n * `updateDefaultTextData` re-shapes with the font size and layout options the block was created\n * with, and only those — verified in `@babylonjs/lite@1.27.0`'s `lib/text/default-text-data.js`, which reads\n * `data._fontSizePx` and `data._options` and never takes new ones. So a change to `text` or\n * `color` is an update, which keeps the glyph storage and its atlas; a change to `font`,\n * `fontSize`, `maxWidth`, `align`, or `lineHeight` is a rebuild. The component tracks both, so a\n * HUD counter that changes every frame pays for one re-shape and nothing else.\n *\n * ## Localization\n *\n * `i18nKey` wins over `text` when it is set, and the block is re-shaped whenever\n * `app.i18n.onLocaleChanged` fires. A component with neither draws nothing rather than drawing an\n * empty box.\n */\n\n/**\n * The alignments Lite's default layout supports (`index.d.ts` 12826-12827).\n *\n * @public\n */\nexport const TEXT_ALIGNMENTS = [\"left\", \"center\", \"right\"] as const;\n\n/**\n * Which edge a block's lines align to. Lite aligns lines against the block's **longest line**, not\n * against `maxWidth`, so a single-line block looks the same in all three.\n *\n * @public\n */\nexport type TextAlignment = (typeof TEXT_ALIGNMENTS)[number];\n\n/**\n * The schema fields every text component declares, so the three components stay in step.\n *\n * @returns The field definitions to spread into a `defineSchema` call.\n *\n * @internal\n */\nexport function textSchemaFields(): {\n font: FieldDefinition<AssetHandle<FontAsset> | null>;\n text: FieldDefinition<string>;\n i18nKey: FieldDefinition<string>;\n fontSize: FieldDefinition<number>;\n color: FieldDefinition<ColorLike>;\n align: FieldDefinition<TextAlignment>;\n maxWidth: FieldDefinition<number>;\n lineHeight: FieldDefinition<number>;\n opacity: FieldDefinition<number>;\n} {\n return {\n font: asset(FontAsset, { tooltip: \"The TTF or OTF the glyphs come from.\" }),\n text: str(\"\", { tooltip: \"The literal string to draw; ignored when i18nKey is set.\" }),\n i18nKey: str(\"\", { tooltip: \"A translation key looked up in app.i18n; wins over text.\" }),\n fontSize: f32(32, { min: 1, tooltip: \"The em size, in render-target pixels.\" }),\n color: color({ r: 1, g: 1, b: 1, a: 1 }, { tooltip: \"The colour every glyph starts with.\" }),\n align: enumOf(TEXT_ALIGNMENTS, \"left\", { tooltip: \"Which edge the lines align to.\" }),\n maxWidth: f32(0, { min: 0, tooltip: \"The wrap width in pixels; 0 does not wrap.\" }),\n lineHeight: f32(1.2, { min: 0.1, tooltip: \"The line-height multiplier.\" }),\n opacity: f32(1, { min: 0, max: 1, tooltip: \"The whole-block alpha multiplier.\" }),\n };\n}\n\n/** The block-shaping inputs that force a rebuild rather than an update. */\ninterface ShapeKey {\n /** The font handle the block was built from. */\n font: AssetHandle<FontAsset> | null;\n /** The em size. */\n fontSize: number;\n /** The wrap width. */\n maxWidth: number;\n /** The alignment. */\n align: TextAlignment;\n /** The line-height multiplier. */\n lineHeight: number;\n}\n\n/**\n * The base of `HudText`, `WorldText2D`, and `WorldText`: the schema fields and the shaped block.\n *\n * @remarks\n * Abstract, and never registered as a component itself; the three concrete classes are.\n *\n * @public\n */\nexport abstract class TextComponent extends Component {\n /** The TTF or OTF the glyphs come from. */\n declare font: AssetHandle<FontAsset> | null;\n\n /** The literal string to draw; ignored when {@link TextComponent.i18nKey} is set. */\n declare text: string;\n\n /** A translation key looked up in `app.i18n`; wins over {@link TextComponent.text}. */\n declare i18nKey: string;\n\n /** The em size, in render-target pixels. */\n declare fontSize: number;\n\n /** The colour every glyph starts with. */\n declare color: ColorLike;\n\n /** Which edge the lines align to. */\n declare align: TextAlignment;\n\n /** The wrap width, in render-target pixels; `0` does not wrap. */\n declare maxWidth: number;\n\n /** The line-height multiplier. */\n declare lineHeight: number;\n\n /** The whole-block alpha multiplier. */\n declare opacity: number;\n\n #block: LiteTextData | null = null;\n\n #shape: ShapeKey = { font: null, fontSize: 0, maxWidth: -1, align: \"left\", lineHeight: 0 };\n\n #lastText = \"\u0000\";\n\n readonly #lastColor: [number, number, number, number] = [-1, -1, -1, -1];\n\n /**\n * The shaped block, or `null` until a font and a non-empty string are both present.\n *\n * @returns The block.\n *\n * @internal\n */\n get block(): LiteTextData | null {\n return this.#block;\n }\n\n /**\n * The block's laid-out size, in render-target pixels.\n *\n * @remarks\n * `{ width: 0, height: 0 }` until the block exists. This is Lite's only text measurement, and\n * it is what a caller centring a block on the screen needs — Lite's `align` aligns lines against\n * each other, not against the screen.\n *\n * @returns The size.\n *\n * @example\n * ```ts\n * const label = entity.addComponent(HudText);\n * label.metrics.width; // 0 until a font and a string are set\n * ```\n */\n get metrics(): TextMetrics {\n const block = this.#block;\n return block === null ? { width: 0, height: 0 } : measureText(block);\n }\n\n /**\n * The string that will actually be drawn: the translated `i18nKey`, or `text`.\n *\n * @param i18n - The localization service, or `null` when the app has none.\n * @returns The resolved string.\n */\n resolveText(i18n: I18nService | null): string {\n if (this.i18nKey === \"\") {\n return this.text;\n }\n return i18n === null ? this.i18nKey : i18n.t(this.i18nKey);\n }\n\n /**\n * Brings the shaped block in line with the component's fields.\n *\n * @remarks\n * The one place a block is created, re-shaped, or destroyed. Called by the UI text system once a\n * frame; it does nothing at all when nothing changed, which is what keeps a static label free.\n *\n * @param i18n - The localization service, or `null`.\n * @returns `\"created\"` when a new block was built (the caller has to rebuild its layer or\n * renderable), `\"updated\"` when the existing one was re-shaped, `\"removed\"` when the block went\n * away, and `\"unchanged\"` otherwise.\n *\n * @internal\n */\n syncBlock(i18n: I18nService | null): \"created\" | \"updated\" | \"removed\" | \"unchanged\" {\n const font = this.font;\n const value = this.resolveText(i18n);\n if (font === null || font.state !== \"loaded\" || value === \"\") {\n return this.#destroy();\n }\n const rebuild =\n this.#block === null ||\n this.#shape.font !== font ||\n this.#shape.fontSize !== this.fontSize ||\n this.#shape.maxWidth !== this.maxWidth ||\n this.#shape.align !== this.align ||\n this.#shape.lineHeight !== this.lineHeight;\n const colour: TextColor = [this.color.r, this.color.g, this.color.b, this.color.a];\n if (rebuild) {\n this.#destroy();\n this.#block = createTextBlock({\n font: font.value.lite.font,\n fontSizePx: this.fontSize,\n text: value,\n color: colour,\n maxWidth: this.maxWidth,\n align: this.align,\n lineHeight: this.lineHeight,\n });\n this.#shape = {\n font,\n fontSize: this.fontSize,\n maxWidth: this.maxWidth,\n align: this.align,\n lineHeight: this.lineHeight,\n };\n this.#remember(value, colour);\n return \"created\";\n }\n if (value === this.#lastText && this.#colourUnchanged(colour)) {\n return \"unchanged\";\n }\n const block = this.#block;\n if (block !== null) {\n updateTextBlock(block, value, colour);\n }\n this.#remember(value, colour);\n return \"updated\";\n }\n\n /**\n * Releases the shaped block. The concrete components call it from `onDestroy`.\n *\n * @internal\n */\n releaseBlock(): void {\n this.#destroy();\n }\n\n /**\n * Destroys the block, if there is one.\n *\n * @returns `\"removed\"` when a block went away, `\"unchanged\"` otherwise.\n */\n #destroy(): \"removed\" | \"unchanged\" {\n const block = this.#block;\n if (block === null) {\n return \"unchanged\";\n }\n destroyTextBlock(block);\n this.#block = null;\n this.#shape = { font: null, fontSize: 0, maxWidth: -1, align: \"left\", lineHeight: 0 };\n this.#lastText = \"\u0000\";\n this.#lastColor[0] = -1;\n return \"removed\";\n }\n\n /**\n * Records the string and colour the block currently holds.\n *\n * @param value - The string.\n * @param colour - The colour.\n */\n #remember(value: string, colour: TextColor): void {\n this.#lastText = value;\n this.#lastColor[0] = colour[0];\n this.#lastColor[1] = colour[1];\n this.#lastColor[2] = colour[2];\n this.#lastColor[3] = colour[3];\n }\n\n /**\n * Whether the colour matches the one the block holds.\n *\n * @param colour - The colour the fields ask for.\n * @returns `true` when all four channels match.\n */\n #colourUnchanged(colour: TextColor): boolean {\n return (\n this.#lastColor[0] === colour[0] &&\n this.#lastColor[1] === colour[1] &&\n this.#lastColor[2] === colour[2] &&\n this.#lastColor[3] === colour[3]\n );\n }\n}\n","import { createDefaults, defineSchema, enumOf, i32, vec2 } from \"@ignifx/core\";\nimport { createPixelTextLayer, movePixelTextLayer } from \"../lite/text.js\";\nimport { computeHudPlacement, HUD_ANCHORS } from \"./hud-layout.js\";\nimport { TextComponent, textSchemaFields } from \"./text-component.js\";\nimport type { HudAnchor, HudPlacement } from \"./hud-layout.js\";\nimport type { TextRuntime } from \"./text-runtime.js\";\nimport type { I18nService } from \"../i18n/i18n-service.js\";\nimport type { LiteTextLayer } from \"../lite/text.js\";\nimport type { ComponentHooks, Schema, Vec2Like } from \"@ignifx/core\";\n\n/**\n * `HudText` (`docs/architecture/13-ui.md` §2): pixel-space text drawn by Babylon Lite rather than\n * by the DOM, *\"when DOM text is not desirable (e.g. capture-perfect pixel HUDs, screenshots via\n * `captureScreenshot`)\"*.\n *\n * ## The coordinate system is the render target, not CSS\n *\n * Lite's text renderer positions a layer against `surface.canvas.width`/`.height`\n * (`lib/text/text-renderer.js`), so `position` is in **backing-store pixels**. That is deliberate\n * and is the whole point of the component: the pixel a `HudText` draws on is the pixel\n * `app.renderer.captureScreenshot()` reads back, so a golden test asserts on an exact address. A\n * DOM label in `app.ui.layer(\"hud\")` is the right tool whenever that is not what you want.\n */\n\n/**\n * Pixel-space HUD text.\n *\n * @example\n * ```ts\n * const label = app.world.createEntity(\"score\").addComponent(HudText);\n * label.font = app.assets.load<FontAsset>(\"ui/Inter-Regular.ttf\");\n * label.anchor = \"topLeft\";\n * label.position = { x: 16, y: 16 };\n * label.i18nKey = \"hud.score\";\n * ```\n *\n * @public\n */\nexport class HudText extends TextComponent implements ComponentHooks {\n /** The registration id the serializer writes into scene files. */\n static typeId = \"ignifx/HudText\";\n\n /** One HUD label per entity; a second belongs on a second entity. */\n static allowMultiple = false;\n\n /** The declarative fields (ADR-0004). */\n static schema: Schema = hudTextSchema();\n\n /** Which point of the render target {@link HudText.position} is measured from. */\n declare anchor: HudAnchor;\n\n /** The offset from the anchor, in render-target pixels; x grows right, y grows down. */\n declare position: Vec2Like;\n\n /** The sort order within the text renderer; lower draws first. */\n declare order: number;\n\n #layer: LiteTextLayer | null = null;\n\n #runtime: TextRuntime | null = null;\n\n readonly #placement: HudPlacement = { x: 0, y: 0 };\n\n /** Builds a HUD label with the schema's defaults. */\n constructor() {\n super();\n Object.assign(this, createDefaults(HudText.schema));\n }\n\n /**\n * The Babylon Lite objects the component owns. Unstable escape hatch\n * (`docs/architecture/00-overview.md` §3).\n *\n * @returns The text layer, or `null` before the first frame that had a font and a string.\n */\n get lite(): { readonly layer: LiteTextLayer | null } {\n return { layer: this.#layer };\n }\n\n /** Drops the layer and the block when the component goes away. */\n onDetach(): void {\n this.#dropLayer();\n this.releaseBlock();\n }\n\n /**\n * Brings the layer in line with the component's fields. The UI text system calls it once a frame.\n *\n * @param runtime - The renderer the layer is registered on.\n * @param i18n - The localization service, or `null`.\n * @param targetWidth - The render target's width, in pixels.\n * @param targetHeight - The render target's height, in pixels.\n *\n * @internal\n */\n sync(runtime: TextRuntime, i18n: I18nService | null, targetWidth: number, targetHeight: number): void {\n this.#runtime = runtime;\n const change = this.syncBlock(i18n);\n const block = this.block;\n if (block === null) {\n this.#dropLayer();\n return;\n }\n if (change === \"created\" || this.#layer === null) {\n this.#dropLayer();\n const layer = createPixelTextLayer(block, this.order, this.opacity);\n this.#layer = layer;\n runtime.addLayer(layer);\n }\n const layer = this.#layer;\n layer.opacity = this.opacity;\n layer.order = this.order;\n layer.visible = this.isEnabledInHierarchy;\n const metrics = this.metrics;\n computeHudPlacement(\n {\n anchor: this.anchor,\n offsetX: this.position.x,\n offsetY: this.position.y,\n targetWidth,\n targetHeight,\n blockWidth: metrics.width,\n blockHeight: metrics.height,\n fontSize: this.fontSize,\n },\n this.#placement,\n );\n if (layer.positionPx.x !== this.#placement.x || layer.positionPx.y !== this.#placement.y) {\n movePixelTextLayer(layer, this.#placement.x, this.#placement.y);\n }\n }\n\n /** Removes the layer from the renderer, if it has one. */\n #dropLayer(): void {\n const layer = this.#layer;\n if (layer === null) {\n return;\n }\n this.#runtime?.removeLayer(layer);\n this.#layer = null;\n }\n}\n\n/**\n * The `HudText` schema.\n *\n * @returns The schema, built fresh so no module holds state (`CONSTITUTION.md` §3.5).\n */\nfunction hudTextSchema(): Schema {\n return defineSchema({\n ...textSchemaFields(),\n anchor: enumOf(HUD_ANCHORS, \"topLeft\", { tooltip: \"Which corner of the screen the position is measured from.\" }),\n position: vec2({ x: 0, y: 0 }, { tooltip: \"The offset from the anchor, in render-target pixels.\" }),\n order: i32(0, { tooltip: \"Sort order within the text renderer; lower draws first.\" }),\n });\n}\n","import type { LiteTextLayer, LiteTextRenderer } from \"../lite/text.js\";\n\n/**\n * The text renderer's life, injected rather than imported so the node suite covers it\n * (`docs/architecture/11-2d-toolkit.md` §1 uses the same shape for the sprite renderer, and\n * `07-rendering.md` §1 is the rule both follow).\n *\n * ## Why the renderer is created lazily\n *\n * A `TextRenderer` must be registered **after** the render scene, so it composites over the frame\n * rather than under it. An extension's `register` runs before the scene exists and its `onStart`\n * runs only when a game calls `app.start()` — which a headless tool never does. Creating it on the\n * first `PreRender` tick is the one moment that satisfies both: the scene is registered, and a\n * headless app never gets there because it has no renderer factory in the first place.\n */\n\n/**\n * The renderer operations the runtime needs, supplied by the extension so this module never imports\n * `@babylonjs/lite`.\n *\n * @internal\n */\nexport interface TextRuntimeOptions {\n /** Creates and registers the renderer, or `null` under a headless app. */\n readonly createRenderer: (() => LiteTextRenderer) | null;\n /** Adds a layer to the renderer's draw list. */\n readonly attachLayer: (renderer: LiteTextRenderer, layer: LiteTextLayer) => void;\n /** Removes a layer from the renderer's draw list. */\n readonly detachLayer: (renderer: LiteTextRenderer, layer: LiteTextLayer) => boolean;\n /** Unregisters and disposes the renderer. */\n readonly destroyRenderer: (renderer: LiteTextRenderer) => void;\n}\n\n/**\n * Owns the one text renderer an app has, and the layers registered on it.\n *\n * @internal\n */\nexport class TextRuntime {\n readonly #options: TextRuntimeOptions;\n\n readonly #pending = new Set<LiteTextLayer>();\n\n readonly #attached = new Set<LiteTextLayer>();\n\n #renderer: LiteTextRenderer | null = null;\n\n #disposed = false;\n\n /**\n * Builds the runtime. The extension does this.\n *\n * @param options - The renderer operations.\n */\n constructor(options: TextRuntimeOptions) {\n this.#options = options;\n }\n\n /**\n * The renderer, once it exists.\n *\n * @returns The renderer, or `null` before the first frame and under a headless app.\n */\n get renderer(): LiteTextRenderer | null {\n return this.#renderer;\n }\n\n /**\n * How many layers are currently drawn.\n *\n * @returns The count.\n */\n get layerCount(): number {\n return this.#attached.size + this.#pending.size;\n }\n\n /**\n * Creates the renderer if it does not exist yet and flushes the layers that were registered\n * before it did. The UI text system calls this at the top of every `PreRender`.\n */\n ensureRenderer(): void {\n if (this.#disposed || this.#renderer !== null || this.#options.createRenderer === null) {\n return;\n }\n const renderer = this.#options.createRenderer();\n this.#renderer = renderer;\n for (const layer of this.#pending) {\n this.#options.attachLayer(renderer, layer);\n this.#attached.add(layer);\n }\n this.#pending.clear();\n }\n\n /**\n * Starts drawing a layer.\n *\n * @param layer - The layer.\n */\n addLayer(layer: LiteTextLayer): void {\n if (this.#disposed || this.#attached.has(layer) || this.#pending.has(layer)) {\n return;\n }\n const renderer = this.#renderer;\n if (renderer === null) {\n this.#pending.add(layer);\n return;\n }\n this.#options.attachLayer(renderer, layer);\n this.#attached.add(layer);\n }\n\n /**\n * Stops drawing a layer and frees its per-layer GPU buffers.\n *\n * @param layer - The layer.\n */\n removeLayer(layer: LiteTextLayer): void {\n this.#pending.delete(layer);\n if (!this.#attached.delete(layer)) {\n return;\n }\n const renderer = this.#renderer;\n if (renderer !== null) {\n this.#options.detachLayer(renderer, layer);\n }\n }\n\n /** Tears the renderer down. The extension calls this from `onDispose`. */\n dispose(): void {\n if (this.#disposed) {\n return;\n }\n this.#disposed = true;\n const renderer = this.#renderer;\n this.#pending.clear();\n this.#attached.clear();\n this.#renderer = null;\n if (renderer !== null) {\n this.#options.destroyRenderer(renderer);\n }\n }\n}\n","import { bool, createDefaults, defineSchema, enumOf, i32, vec2, vec3 } from \"@ignifx/core\";\nimport { createPixelTextLayer, movePixelTextLayer } from \"../lite/text.js\";\nimport { computePivotPlacement, HUD_ANCHORS } from \"./hud-layout.js\";\nimport { TextComponent, textSchemaFields } from \"./text-component.js\";\nimport type { HudAnchor, HudPlacement } from \"./hud-layout.js\";\nimport type { TextRuntime } from \"./text-runtime.js\";\nimport type { I18nService } from \"../i18n/i18n-service.js\";\nimport type { LiteTextLayer } from \"../lite/text.js\";\nimport type { ComponentHooks, Schema, Vec2Like, Vec3Like } from \"@ignifx/core\";\n\n/**\n * `WorldText2D` (`docs/architecture/13-ui.md` §2): text that belongs to the world — damage numbers,\n * floating names — but is drawn as a flat pixel-space layer rather than as geometry, so it never\n * shrinks with distance and never intersects a wall.\n *\n * It is `HudText`'s twin: the same Lite text layer, positioned from the entity's **projected**\n * screen position instead of from a screen anchor. `WorldText` is the other choice, and the one to\n * take when the text should be occluded by the world.\n */\n\n/**\n * World-anchored pixel-space text.\n *\n * @example\n * ```ts\n * const damage = app.world.createEntity(\"damage\").addComponent(WorldText2D);\n * damage.font = app.assets.load<FontAsset>(\"ui/Inter-Regular.ttf\");\n * damage.text = \"-12\";\n * damage.offset = { x: 0, y: 1.8, z: 0 };\n * ```\n *\n * @public\n */\nexport class WorldText2D extends TextComponent implements ComponentHooks {\n /** The registration id the serializer writes into scene files. */\n static typeId = \"ignifx/WorldText2D\";\n\n /** One floating label per entity. */\n static allowMultiple = false;\n\n /** The declarative fields (ADR-0004). */\n static schema: Schema = worldText2DSchema();\n\n /** A world-space offset added to the entity's position before projecting, in metres. */\n declare offset: Vec3Like;\n\n /** A screen-space offset added after projecting, in render-target pixels. */\n declare screenOffset: Vec2Like;\n\n /** Which point of the block sits on the projected position. */\n declare pivot: HudAnchor;\n\n /** Whether the label is hidden when the anchor point is behind the camera. */\n declare hideWhenBehindCamera: boolean;\n\n /** The sort order within the text renderer; lower draws first. */\n declare order: number;\n\n #layer: LiteTextLayer | null = null;\n\n #runtime: TextRuntime | null = null;\n\n readonly #placement: HudPlacement = { x: 0, y: 0 };\n\n /** Builds a floating label with the schema's defaults. */\n constructor() {\n super();\n Object.assign(this, createDefaults(WorldText2D.schema));\n }\n\n /**\n * The Babylon Lite objects the component owns. Unstable escape hatch.\n *\n * @returns The text layer, or `null` before the first frame that had a font and a string.\n */\n get lite(): { readonly layer: LiteTextLayer | null } {\n return { layer: this.#layer };\n }\n\n /** Drops the layer and the block when the component goes away. */\n onDetach(): void {\n this.#dropLayer();\n this.releaseBlock();\n }\n\n /**\n * Brings the layer in line with the component's fields and the projected position.\n *\n * @param runtime - The renderer the layer is registered on.\n * @param i18n - The localization service, or `null`.\n * @param screenX - The entity's projected x, in render-target pixels.\n * @param screenY - The entity's projected y, in render-target pixels.\n * @param inFront - Whether the anchor point is in front of the camera.\n *\n * @internal\n */\n sync(runtime: TextRuntime, i18n: I18nService | null, screenX: number, screenY: number, inFront: boolean): void {\n this.#runtime = runtime;\n const change = this.syncBlock(i18n);\n const block = this.block;\n if (block === null) {\n this.#dropLayer();\n return;\n }\n if (change === \"created\" || this.#layer === null) {\n this.#dropLayer();\n const layer = createPixelTextLayer(block, this.order, this.opacity);\n this.#layer = layer;\n runtime.addLayer(layer);\n }\n const layer = this.#layer;\n layer.opacity = this.opacity;\n layer.order = this.order;\n layer.visible = this.isEnabledInHierarchy && (inFront || !this.hideWhenBehindCamera);\n const metrics = this.metrics;\n computePivotPlacement(\n this.pivot,\n screenX + this.screenOffset.x,\n screenY + this.screenOffset.y,\n metrics.width,\n metrics.height,\n this.fontSize,\n this.#placement,\n );\n if (layer.positionPx.x !== this.#placement.x || layer.positionPx.y !== this.#placement.y) {\n movePixelTextLayer(layer, this.#placement.x, this.#placement.y);\n }\n }\n\n /** Removes the layer from the renderer, if it has one. */\n #dropLayer(): void {\n const layer = this.#layer;\n if (layer === null) {\n return;\n }\n this.#runtime?.removeLayer(layer);\n this.#layer = null;\n }\n}\n\n/**\n * The `WorldText2D` schema.\n *\n * @returns The schema, built fresh so no module holds state (`CONSTITUTION.md` §3.5).\n */\nfunction worldText2DSchema(): Schema {\n return defineSchema({\n ...textSchemaFields(),\n offset: vec3({ x: 0, y: 0, z: 0 }, { tooltip: \"A world-space offset added before projecting, in metres.\" }),\n screenOffset: vec2({ x: 0, y: 0 }, { tooltip: \"A screen-space offset added after projecting, in pixels.\" }),\n pivot: enumOf(HUD_ANCHORS, \"center\", { tooltip: \"Which point of the block sits on the projected position.\" }),\n hideWhenBehindCamera: bool(true, { tooltip: \"Hide the label when the anchor is behind the camera.\" }),\n order: i32(0, { tooltip: \"Sort order within the text renderer; lower draws first.\" }),\n });\n}\n","import { bool, createDefaults, defineSchema, f32, Quat, vec3, Vec3 } from \"@ignifx/core\";\nimport { UiErrorCode } from \"../errors.js\";\nimport {\n attachSceneText,\n createSceneText,\n destroySceneText,\n detachSceneText,\n moveSceneText,\n rotateSceneText,\n scaleSceneText,\n} from \"../lite/text.js\";\nimport { TextComponent, textSchemaFields } from \"./text-component.js\";\nimport type { I18nService } from \"../i18n/i18n-service.js\";\nimport type { LiteTextRenderable } from \"../lite/text.js\";\nimport type { ComponentHooks, LiteScene, MutableQuat, MutableVec3, QuatLike, Schema, Vec3Like } from \"@ignifx/core\";\n\n/**\n * `WorldText` (`docs/architecture/13-ui.md` §2): text that is part of the world — a sign, a\n * banner, a floating label that is hidden by the wall in front of it — drawn as a Babylon Lite\n * `TextRenderable` inside the render scene.\n *\n * ## Blocks are laid out in pixels, so the renderable is scaled down\n *\n * `createDefaultTextData` shapes in pixels: at `fontSize` 32 a capital letter is about 32 units\n * tall. A renderable at scale 1 would therefore be tens of metres high. {@link WorldText.pixelsPerUnit}\n * is the divisor, defaulting to 100 to match `@ignifx/2d`'s own default, so a 32-pixel block is\n * 0.32 m tall.\n *\n * ## It has to exist before `app.start()`\n *\n * `addTextRenderable` (`index.d.ts` 208) pushes a **deferred builder** onto the scene\n * (`lib/text/text-renderable.js` 242-249), and the only thing that drains those builders is\n * `buildScene`, which `registerScene` calls once (`lib/scene/scene-core.js` 228-241 and 246-262).\n * `rebuildSceneRenderables` — the one public rebuild — explicitly does not: it rebuilds *groups*\n * and returns early on an unbuilt scene, and Lite's runtime-build machinery is for meshes only. So\n * a renderable added after `app.start()` has registered the scene never materialises, and there is\n * no public call that would make it.\n *\n * A `WorldText` whose font and text are both present before the app starts therefore draws; one\n * that first gets its text mid-game does not, and says so once with `IGX-1308`. Until Lite exposes\n * a way to drain a late deferred renderable, the answers are to author signs in the scene file the\n * game starts with, or to use {@link WorldText2D}, which owns a text *layer* and can be added at\n * any time.\n *\n * ## Removal is one-way\n *\n * Babylon Lite 1.27.0 has `addTextRenderable` (`index.d.ts` 208) and **no inverse**:\n * `removeFromScene` (9613) accepts meshes, lights, cameras, shadow generators, transform nodes and\n * asset containers, and a `TextRenderable` is none of them. A destroyed `WorldText` therefore\n * empties its block and zeroes the renderable's opacity — it draws nothing and holds no GPU\n * buffers — but the record itself stays in the scene's renderable list until the scene is disposed.\n * A game that spawns and destroys thousands of signs should pool the components rather than the\n * entities. This is recorded as a Lite gap rather than worked around.\n */\n\n/**\n * World-space 3D text.\n *\n * @example\n * ```ts\n * const sign = app.world.createEntity(\"sign\").addComponent(WorldText);\n * sign.font = app.assets.load<FontAsset>(\"ui/Inter-Regular.ttf\");\n * sign.text = \"Danger\";\n * sign.billboard = true;\n * ```\n *\n * @public\n */\nexport class WorldText extends TextComponent implements ComponentHooks {\n /** The registration id the serializer writes into scene files. */\n static typeId = \"ignifx/WorldText\";\n\n /** One sign per entity. */\n static allowMultiple = false;\n\n /** The declarative fields (ADR-0004). */\n static schema: Schema = worldTextSchema();\n\n /** A local offset added to the entity's world position, in metres. */\n declare offset: Vec3Like;\n\n /** How many pixels of laid-out text span one world metre. */\n declare pixelsPerUnit: number;\n\n /** Whether the text turns to face the camera instead of following the entity's rotation. */\n declare billboard: boolean;\n\n /** Whether the text draws through geometry in front of it. */\n declare alwaysOnTop: boolean;\n\n #renderable: LiteTextRenderable | null = null;\n\n #scene: LiteScene | null = null;\n\n readonly #position: MutableVec3 = new Vec3();\n\n readonly #rotation: MutableQuat = new Quat();\n\n /** Builds a sign with the schema's defaults. */\n constructor() {\n super();\n Object.assign(this, createDefaults(WorldText.schema));\n }\n\n /**\n * The Babylon Lite objects the component owns. Unstable escape hatch.\n *\n * @returns The renderable, or `null` before the first frame that had a font and a string.\n */\n get lite(): { readonly renderable: LiteTextRenderable | null } {\n return { renderable: this.#renderable };\n }\n\n /** Silences and releases the renderable when the component goes away. */\n onDetach(): void {\n const renderable = this.#renderable;\n if (renderable !== null) {\n detachSceneText(renderable);\n destroySceneText(renderable);\n this.#renderable = null;\n }\n this.releaseBlock();\n }\n\n /**\n * Brings the renderable in line with the component's fields and the entity's transform.\n *\n * @param scene - The Lite scene the renderable is added to, from `app.lite.scene`.\n * @param i18n - The localization service, or `null`.\n * @param cameraRotation - The main camera's world rotation, for billboarding, or `null` when the\n * world has no camera.\n *\n * @internal\n */\n sync(scene: LiteScene, i18n: I18nService | null, cameraRotation: QuatLike | null): void {\n const change = this.syncBlock(i18n);\n const block = this.block;\n if (block === null) {\n const existing = this.#renderable;\n if (existing !== null) {\n detachSceneText(existing);\n destroySceneText(existing);\n this.#renderable = null;\n }\n return;\n }\n if (change === \"created\" || this.#renderable === null) {\n const previous = this.#renderable;\n if (previous !== null) {\n detachSceneText(previous);\n destroySceneText(previous);\n }\n const renderable = createSceneText(block, this.opacity);\n renderable.ignoreDepth = this.alwaysOnTop;\n attachSceneText(scene, renderable);\n this.#renderable = renderable;\n this.#scene = scene;\n this.#warnIfLate();\n }\n const renderable = this.#renderable;\n renderable.opacity = this.isEnabledInHierarchy ? this.opacity : 0;\n renderable.ignoreDepth = this.alwaysOnTop;\n const transform = this.transform;\n transform.positionToRef(this.#position);\n moveSceneText(\n renderable,\n this.#position.x + this.offset.x,\n this.#position.y + this.offset.y,\n this.#position.z + this.offset.z,\n );\n const rotation =\n this.billboard && cameraRotation !== null ? cameraRotation : transform.rotationToRef(this.#rotation);\n rotateSceneText(renderable, rotation.x, rotation.y, rotation.z, rotation.w);\n const divisor = this.pixelsPerUnit > 0 ? this.pixelsPerUnit : 1;\n scaleSceneText(renderable, 1 / divisor);\n }\n\n /**\n * Reports `IGX-1308` once when the renderable was built too late for Lite to draw it. See the\n * module's own remarks.\n */\n #warnIfLate(): void {\n const app = this.app;\n if (!app.isRunning || app.isHeadless) {\n return;\n }\n app.log.warnOnce(\n \"ignifx/ui/world-text-late\",\n `${WorldText.typeId} was given its text after app.start(), so Babylon Lite will not draw it ` +\n `(${UiErrorCode.sceneAlreadyBuilt}). Author the sign before starting, or use WorldText2D.`,\n );\n }\n\n /**\n * The scene the renderable was added to, for diagnostics.\n *\n * @returns The scene, or `null` when nothing has been added yet.\n *\n * @internal\n */\n get scene(): LiteScene | null {\n return this.#scene;\n }\n}\n\n/**\n * The `WorldText` schema.\n *\n * @returns The schema, built fresh so no module holds state (`CONSTITUTION.md` §3.5).\n */\nfunction worldTextSchema(): Schema {\n return defineSchema({\n ...textSchemaFields(),\n offset: vec3({ x: 0, y: 0, z: 0 }, { tooltip: \"A local offset added to the entity's position, in metres.\" }),\n pixelsPerUnit: f32(100, { min: 1, tooltip: \"How many pixels of laid-out text span one metre.\" }),\n billboard: bool(false, { tooltip: \"Turn the text to face the camera.\" }),\n alwaysOnTop: bool(false, { tooltip: \"Draw through geometry in front of the text.\" }),\n });\n}\n","/**\n * The package's own version, reported as `Extension.version`\n * (`docs/architecture/04-extensions.md` §1). First-party packages ship one version line, so this\n * tracks `package.json` and the release tooling bumps both together.\n */\n\n/**\n * The `@ignifx/ui` version this build was cut from.\n *\n * @public\n */\nexport const VERSION = \"0.0.0\";\n","import { clamp } from \"@ignifx/core\";\nimport type { UiPixelMapping } from \"../dom/scaling.js\";\n\n/**\n * Convert camera backing-store pixels to overlay units through `UiPixelMapping`.\n * Behind-camera projections are mirrored: hide them, or reflect before clamping to the viewport\n * edge. Keep the arithmetic independent of the DOM for headless tests.\n */\n\n/**\n * Everything {@link computeAnchorPlacement} reads.\n *\n * @public\n */\nexport interface AnchorInput {\n /** The projected x, in render-target pixels. */\n readonly screenX: number;\n /** The projected y, in render-target pixels. */\n readonly screenY: number;\n /** Whether the point is in front of the camera. */\n readonly inFront: boolean;\n /** How far the point is from the camera, in metres. */\n readonly distance: number;\n /** The overlay root's width, in UI units. */\n readonly viewWidth: number;\n /** The overlay root's height, in UI units. */\n readonly viewHeight: number;\n /** The render-target-pixel to UI-unit conversion. */\n readonly mapping: UiPixelMapping;\n /** Whether the element is hidden when the point is behind the camera. */\n readonly hideWhenBehindCamera: boolean;\n /** Whether the element is kept inside the overlay's bounds. */\n readonly clampToScreen: boolean;\n /** Whether the element shrinks with distance. */\n readonly scaleWithDistance: boolean;\n /** The distance at which {@link AnchorInput.scaleWithDistance} produces a scale of `1`. */\n readonly referenceDistance: number;\n /** The smallest scale distance scaling may produce. */\n readonly minScale: number;\n /** The largest scale distance scaling may produce. */\n readonly maxScale: number;\n}\n\n/**\n * Where the element goes, written in place so the per-frame path allocates nothing.\n *\n * @public\n */\nexport interface AnchorPlacement {\n /** Whether the element is shown at all. */\n visible: boolean;\n /** The x, in UI units from the overlay root's left edge. */\n x: number;\n /** The y, in UI units from the overlay root's top edge. */\n y: number;\n /** The uniform scale to draw the element at. */\n scale: number;\n}\n\n/**\n * Builds a zeroed placement, for a component to reuse every frame.\n *\n * @returns The placement.\n *\n * @internal\n */\nexport function createAnchorPlacement(): AnchorPlacement {\n return { visible: false, x: 0, y: 0, scale: 1 };\n}\n\n/**\n * The smallest distance the scale divisor accepts, so an anchor sitting on the camera does not\n * produce an infinite scale.\n */\nconst MIN_DISTANCE = 0.001;\n\n/**\n * Computes where an anchored element goes this frame.\n *\n * @param input - The projection, the flags, and the conversion.\n * @param out - Receives the placement.\n * @returns `out`, for chaining.\n *\n * @example\n * ```ts\n * const out = createAnchorPlacement();\n * computeAnchorPlacement(\n * {\n * screenX: 400,\n * screenY: 300,\n * inFront: true,\n * distance: 10,\n * viewWidth: 800,\n * viewHeight: 600,\n * mapping: { scaleX: 1, originX: 0, scaleY: 1, originY: 0 },\n * hideWhenBehindCamera: true,\n * clampToScreen: false,\n * scaleWithDistance: false,\n * referenceDistance: 10,\n * minScale: 0.5,\n * maxScale: 2,\n * },\n * out,\n * );\n * out.x; // 400\n * ```\n *\n * @public\n */\nexport function computeAnchorPlacement(input: AnchorInput, out: AnchorPlacement): AnchorPlacement {\n let x = input.screenX * input.mapping.scaleX - input.mapping.originX;\n let y = input.screenY * input.mapping.scaleY - input.mapping.originY;\n if (!input.inFront) {\n if (input.hideWhenBehindCamera || !input.clampToScreen) {\n out.visible = false;\n out.x = x;\n out.y = y;\n out.scale = 1;\n return out;\n }\n x = input.viewWidth - x;\n y = input.viewHeight - y;\n }\n if (input.clampToScreen) {\n x = clamp(x, 0, input.viewWidth);\n y = clamp(y, 0, input.viewHeight);\n }\n out.visible = input.clampToScreen || (x >= 0 && x <= input.viewWidth && y >= 0 && y <= input.viewHeight);\n out.x = x;\n out.y = y;\n out.scale = input.scaleWithDistance\n ? clamp(input.referenceDistance / Math.max(input.distance, MIN_DISTANCE), input.minScale, input.maxScale)\n : 1;\n return out;\n}\n","import { bool, Component, createDefaults, defineSchema, f32, vec3 } from \"@ignifx/core\";\nimport { computeAnchorPlacement, createAnchorPlacement } from \"./anchor-math.js\";\nimport type { AnchorPlacement } from \"./anchor-math.js\";\nimport type { UiPixelMapping } from \"../dom/scaling.js\";\nimport type { ComponentHooks, Schema, Vec3Like } from \"@ignifx/core\";\n\n/**\n * Position a game-owned DOM element without changing its contents or ownership.\n * Cache pose and camera state to avoid redundant style writes; changing a CSS transform still\n * requires a string allocation.\n */\n\n/**\n * An entity-to-element anchor.\n *\n * @example\n * ```ts\n * const tag = document.createElement(\"div\");\n * tag.textContent = \"Boss\";\n * app.ui.layer(\"hud\").element?.append(tag);\n *\n * const anchor = enemy.addComponent(WorldAnchor);\n * anchor.element = tag;\n * anchor.offset = { x: 0, y: 2, z: 0 };\n * ```\n *\n * @public\n */\nexport class WorldAnchor extends Component implements ComponentHooks {\n /** The registration id the serializer writes into scene files. */\n static typeId = \"ignifx/WorldAnchor\";\n\n /** One anchored element per entity. */\n static allowMultiple = false;\n\n /** The declarative fields (ADR-0004). */\n static schema: Schema = worldAnchorSchema();\n\n /** A world-space offset added to the entity's position before projecting, in metres. */\n declare offset: Vec3Like;\n\n /** Whether the element is hidden when the anchor point is behind the camera. */\n declare hideWhenBehindCamera: boolean;\n\n /** Whether the element is kept inside the overlay's bounds instead of being hidden off-screen. */\n declare clampToScreen: boolean;\n\n /** Whether the element shrinks with distance. */\n declare scaleWithDistance: boolean;\n\n /** The distance at which {@link WorldAnchor.scaleWithDistance} produces a scale of `1`, in metres. */\n declare referenceDistance: number;\n\n /** The smallest scale distance scaling may produce. */\n declare minScale: number;\n\n /** The largest scale distance scaling may produce. */\n declare maxScale: number;\n\n /**\n * The element to position. Not serialised — a DOM node cannot be — so a scene file carries the\n * flags and the game assigns the element in `awake`.\n */\n element: HTMLElement | null = null;\n\n readonly #placement: AnchorPlacement = createAnchorPlacement();\n\n #prepared: HTMLElement | null = null;\n\n #lastX = Number.NaN;\n\n #lastY = Number.NaN;\n\n #lastScale = Number.NaN;\n\n #lastVisible: boolean | null = null;\n\n /** Builds an anchor with the schema's defaults. */\n constructor() {\n super();\n Object.assign(this, createDefaults(WorldAnchor.schema));\n }\n\n /**\n * Where the element was placed on the last synchronised frame.\n *\n * @returns The placement; `visible` is `false` before the first sync.\n */\n get placement(): Readonly<AnchorPlacement> {\n return this.#placement;\n }\n\n /** Hides the element when the component goes away, so an orphaned tag does not linger. */\n onDetach(): void {\n const element = this.element;\n if (element !== null) {\n element.style.setProperty(\"display\", \"none\");\n }\n this.#prepared = null;\n }\n\n /**\n * Places the element for this frame.\n *\n * @param screenX - The anchor point's projected x, in render-target pixels.\n * @param screenY - The anchor point's projected y, in render-target pixels.\n * @param inFront - Whether the point is in front of the camera.\n * @param distance - How far the point is from the camera, in metres.\n * @param viewWidth - The overlay root's width, in UI units.\n * @param viewHeight - The overlay root's height, in UI units.\n * @param mapping - The render-target-pixel to UI-unit conversion.\n *\n * @internal\n */\n place(\n screenX: number,\n screenY: number,\n inFront: boolean,\n distance: number,\n viewWidth: number,\n viewHeight: number,\n mapping: UiPixelMapping,\n ): void {\n const element = this.element;\n if (element === null) {\n return;\n }\n computeAnchorPlacement(\n {\n screenX,\n screenY,\n inFront,\n distance,\n viewWidth,\n viewHeight,\n mapping,\n hideWhenBehindCamera: this.hideWhenBehindCamera,\n clampToScreen: this.clampToScreen,\n scaleWithDistance: this.scaleWithDistance,\n referenceDistance: this.referenceDistance,\n minScale: this.minScale,\n maxScale: this.maxScale,\n },\n this.#placement,\n );\n this.#write(element);\n }\n\n /**\n * Writes the placement onto the element, skipping every property that did not change.\n *\n * @param element - The element to write.\n */\n #write(element: HTMLElement): void {\n if (this.#prepared !== element) {\n const style = element.style;\n style.setProperty(\"position\", \"absolute\");\n style.setProperty(\"left\", \"0px\");\n style.setProperty(\"top\", \"0px\");\n this.#prepared = element;\n this.#lastVisible = null;\n this.#lastX = Number.NaN;\n }\n const visible = this.#placement.visible && this.isEnabledInHierarchy;\n if (this.#lastVisible !== visible) {\n element.style.setProperty(\"display\", visible ? \"block\" : \"none\");\n this.#lastVisible = visible;\n }\n if (!visible) {\n return;\n }\n const { x, y, scale } = this.#placement;\n if (this.#lastX === x && this.#lastY === y && this.#lastScale === scale) {\n return;\n }\n this.#lastX = x;\n this.#lastY = y;\n this.#lastScale = scale;\n element.style.setProperty(\n \"transform\",\n `translate(${String(x)}px, ${String(y)}px) translate(-50%, -50%) scale(${String(scale)})`,\n );\n }\n}\n\n/**\n * The `WorldAnchor` schema.\n *\n * @returns The schema, built fresh so no module holds state (`CONSTITUTION.md` §3.5).\n */\nfunction worldAnchorSchema(): Schema {\n return defineSchema({\n offset: vec3({ x: 0, y: 0, z: 0 }, { tooltip: \"A world-space offset added before projecting, in metres.\" }),\n hideWhenBehindCamera: bool(true, { tooltip: \"Hide the element when the anchor is behind the camera.\" }),\n clampToScreen: bool(false, { tooltip: \"Keep the element inside the overlay instead of hiding it.\" }),\n scaleWithDistance: bool(false, { tooltip: \"Shrink the element as the anchor gets further away.\" }),\n referenceDistance: f32(10, { min: 0.001, tooltip: \"The distance at which the scale is 1, in metres.\" }),\n minScale: f32(0.25, { min: 0, tooltip: \"The smallest scale distance scaling may produce.\" }),\n maxScale: f32(2, { min: 0, tooltip: \"The largest scale distance scaling may produce.\" }),\n });\n}\n","import { Quat, Vec3 } from \"@ignifx/core\";\nimport { HudText } from \"../text/hud-text.js\";\nimport { WorldText2D } from \"../text/world-text-2d.js\";\nimport { WorldText } from \"../text/world-text.js\";\nimport { WorldAnchor } from \"./world-anchor.js\";\nimport type { UiHost } from \"../dom/host.js\";\nimport type { I18nService } from \"../i18n/i18n-service.js\";\nimport type { TextRuntime } from \"../text/text-runtime.js\";\nimport type {\n App,\n Camera,\n MutableQuat,\n MutableVec3,\n System,\n SystemContext,\n Transform,\n Vec3Like,\n World,\n} from \"@ignifx/core\";\n\n/**\n * Run after core's camera sync so projections use the current pose and render-target size.\n * With no main camera, hide anchored elements. Text shaping only repeats when content changes.\n */\n\n/**\n * The `PreRender` order the UI system runs at.\n *\n * @remarks\n * After `RENDER_SYNC_ORDER` (900), which is the frame's camera synchronisation, and inside the\n * extension band. See the module's own remarks.\n *\n * @public\n */\nexport const UI_SYNC_ORDER = 1100;\n\n/**\n * What the system is built with. Only `uiExtension` builds one, through `UiSystem`'s `@internal`\n * constructor.\n *\n * @internal\n */\nexport interface UiSystemOptions {\n /** The app, for the render surface's size and the Lite scene. */\n readonly app: App;\n /** The overlay host, for the layout the anchors are placed in. */\n readonly host: UiHost;\n /** The text renderer's life. */\n readonly runtime: TextRuntime;\n /** The localization service `i18nKey` is resolved through. */\n readonly i18n: I18nService;\n}\n\n/**\n * Projects world anchors and re-shapes text once per frame.\n *\n * @public\n */\nexport class UiSystem implements System {\n /** The name diagnostics and error reports use. */\n readonly name = \"ignifx/ui-sync\";\n\n readonly #options: UiSystemOptions;\n\n readonly #point: MutableVec3 = new Vec3();\n\n readonly #screen: MutableVec3 = new Vec3();\n\n readonly #cameraPosition: MutableVec3 = new Vec3();\n\n readonly #cameraRotation: MutableQuat = new Quat();\n\n readonly #targetSize = { width: 1, height: 1 };\n\n /**\n * Builds the system. The extension does this; a game never constructs one.\n *\n * @param options - The app, the host, the text runtime, and the localization service.\n *\n * @internal\n */\n constructor(options: UiSystemOptions) {\n this.#options = options;\n }\n\n /**\n * Builds the overlay, now that the engine and its canvas exist.\n *\n * @remarks\n * This is the only hook that fires inside `createApp` **after** the Lite engine was created:\n * `register` runs before it, and `onStart` runs only when a game calls `app.start()`, which a\n * headless tool never does. `@ignifx/2d` uses the same hook for the same reason.\n *\n * @param _world - The new world, which the overlay does not need.\n */\n onWorldCreated(_world: World): void {\n this.#options.host.mount();\n }\n\n /**\n * Runs one frame's synchronisation.\n *\n * @param ctx - The world, clock, phase, and delta.\n */\n update(ctx: SystemContext): void {\n const { app, host, runtime, i18n } = this.#options;\n runtime.ensureRenderer();\n this.#readTargetSize(app);\n const camera = ctx.world.mainCamera;\n const hasCamera = camera !== null;\n if (hasCamera) {\n camera.transform.positionToRef(this.#cameraPosition);\n camera.transform.rotationToRef(this.#cameraRotation);\n }\n this.#syncAnchors(ctx.world, camera, host);\n this.#syncWorldText2D(ctx.world, camera, runtime, i18n);\n this.#syncHudText(ctx.world, runtime, i18n);\n this.#syncWorldText(ctx.world, app, i18n, hasCamera);\n }\n\n /**\n * Reads the render target's size, in device pixels; a headless app reports 1x1.\n *\n * @param app - The app, for its render surface.\n */\n #readTargetSize(app: App): void {\n const surface = app.renderer.surface;\n this.#targetSize.width = surface === null ? 1 : Math.max(1, surface.width);\n this.#targetSize.height = surface === null ? 1 : Math.max(1, surface.height);\n }\n\n /**\n * Projects and places every anchored element.\n *\n * @param world - The world.\n * @param camera - The main camera, or `null`.\n * @param host - The overlay host.\n */\n #syncAnchors(world: World, camera: Camera | null, host: UiHost): void {\n const anchors = world.components(WorldAnchor);\n if (anchors.length === 0) {\n return;\n }\n const layout = host.layout;\n const mapping = host.pixelMapping;\n for (let index = 0; index < anchors.length; index += 1) {\n const anchor = anchors[index];\n if (anchor === undefined || anchor.element === null) {\n continue;\n }\n if (camera === null) {\n anchor.place(0, 0, false, 0, layout.width, layout.height, mapping);\n continue;\n }\n const inFront = this.#project(camera, anchor.transform, anchor.offset);\n anchor.place(\n this.#screen.x,\n this.#screen.y,\n inFront,\n this.#distanceToCamera(),\n layout.width,\n layout.height,\n mapping,\n );\n }\n }\n\n /**\n * Projects and re-shapes every world-anchored pixel label.\n *\n * @param world - The world.\n * @param camera - The main camera, or `null`.\n * @param runtime - The text renderer's life.\n * @param i18n - The localization service.\n */\n #syncWorldText2D(world: World, camera: Camera | null, runtime: TextRuntime, i18n: I18nService): void {\n const labels = world.components(WorldText2D);\n for (let index = 0; index < labels.length; index += 1) {\n const label = labels[index];\n if (label === undefined) {\n continue;\n }\n if (camera === null) {\n label.sync(runtime, i18n, 0, 0, false);\n continue;\n }\n const inFront = this.#project(camera, label.transform, label.offset);\n label.sync(runtime, i18n, this.#screen.x, this.#screen.y, inFront);\n }\n }\n\n /**\n * Re-shapes and places every screen-anchored pixel label.\n *\n * @param world - The world.\n * @param runtime - The text renderer's life.\n * @param i18n - The localization service.\n */\n #syncHudText(world: World, runtime: TextRuntime, i18n: I18nService): void {\n const labels = world.components(HudText);\n for (let index = 0; index < labels.length; index += 1) {\n labels[index]?.sync(runtime, i18n, this.#targetSize.width, this.#targetSize.height);\n }\n }\n\n /**\n * Re-shapes and places every world-space sign.\n *\n * @param world - The world.\n * @param app - The app, for the Lite scene.\n * @param i18n - The localization service.\n * @param hasCamera - Whether a billboard has a rotation to copy.\n */\n #syncWorldText(world: World, app: App, i18n: I18nService, hasCamera: boolean): void {\n const signs = world.components(WorldText);\n if (signs.length === 0) {\n return;\n }\n const scene = app.lite.scene;\n const rotation = hasCamera ? this.#cameraRotation : null;\n for (let index = 0; index < signs.length; index += 1) {\n signs[index]?.sync(scene, i18n, rotation);\n }\n }\n\n /**\n * Projects an entity's offset position onto the render target.\n *\n * @param camera - The main camera.\n * @param transform - The entity's transform.\n * @param offset - The world-space offset to add first.\n * @returns `true` when the point is in front of the camera.\n */\n #project(camera: Camera, transform: Transform, offset: Vec3Like): boolean {\n transform.positionToRef(this.#point);\n this.#point.x += offset.x;\n this.#point.y += offset.y;\n this.#point.z += offset.z;\n return camera.worldToScreen(this.#point, this.#screen);\n }\n\n /**\n * How far the point last projected is from the camera.\n *\n * @returns The distance, in metres.\n */\n #distanceToCamera(): number {\n const dx = this.#point.x - this.#cameraPosition.x;\n const dy = this.#point.y - this.#cameraPosition.y;\n const dz = this.#point.z - this.#cameraPosition.z;\n return Math.sqrt(dx * dx + dy * dy + dz * dz);\n }\n}\n","import { defineExtension, Phase } from \"@ignifx/core\";\nimport { defineI18nAppProperty, defineUiAppProperty } from \"./augmentation.js\";\nimport { resolveDomTarget } from \"./dom/dom-target.js\";\nimport { UiHost } from \"./dom/host.js\";\nimport { uiError, UI_ERROR_MESSAGES, UiErrorCode } from \"./errors.js\";\nimport { I18nService } from \"./i18n/i18n-service.js\";\nimport { createLocaleLoader } from \"./i18n/loader.js\";\nimport {\n attachTextLayer,\n createRegisteredTextRenderer,\n destroyTextRenderer,\n detachTextLayer,\n enableTextDeviceLostRecovery,\n} from \"./lite/gpu/text-renderer.js\";\nimport { defaultUiSettings, UI_SETTINGS_SECTION, uiSettingsSchema } from \"./settings.js\";\nimport { HudText } from \"./text/hud-text.js\";\nimport { TextRuntime } from \"./text/text-runtime.js\";\nimport { WorldText2D } from \"./text/world-text-2d.js\";\nimport { WorldText } from \"./text/world-text.js\";\nimport { VERSION } from \"./version.js\";\nimport { UI_SYNC_ORDER, UiSystem } from \"./world/ui-system.js\";\nimport { WorldAnchor } from \"./world/world-anchor.js\";\nimport type { UiDomTarget } from \"./dom/dom-target.js\";\nimport type { LocaleAsset } from \"./i18n/locale-file.js\";\nimport type { LiteTextRenderer } from \"./lite/text.js\";\nimport type { UiScalingMode, UiSettings } from \"./settings.js\";\nimport type { App, AssetHandle, Extension, ExtensionContext } from \"@ignifx/core\";\n\n/**\n * The `@ignifx/ui` extension (`docs/architecture/04-extensions.md` §1, `13-ui.md`).\n * Registering it is the whole installation: `ui()` gives a game `app.ui`, `app.i18n`, four\n * components, the `i18n` asset type, the `ui` settings section, and the one `PreRender` system that\n * projects anchors and re-shapes text.\n *\n * ## What it needs, and what it does not\n *\n * `@ignifx/input` is an **optional** peer. The overlay host, the text components, and the\n * localization service work without it; only `VirtualJoystick` and `VirtualButton` need it, and\n * they say so with `IGX-1305`. The extension never imports it — it reaches\n * `app.input.uiHasFocus` structurally, for the reason `src/widgets/virtual-device.ts` records.\n *\n * ## Headless\n *\n * Everything registers headlessly. With no DOM canvas the host is inert (`13-ui.md` §1's\n * \"the host hides itself in headless mode\"*, read through `07-rendering.md` §6's rule that a\n * headless member is a documented no-op rather than a throw), no text renderer is created, and the\n * `PreRender` system still runs — so `WorldText` keeps its state and a test asserts on it.\n */\n\n/**\n * What `ui()` accepts. Every field that names a settings value overrides the matching `ui` section\n * value, which is the shape `04-extensions.md` §1 shows for `physics()`.\n *\n * @public\n */\nexport interface UiOptions {\n /** How the overlay's coordinate system relates to the canvas. */\n readonly scaling?: UiScalingMode;\n /** The `[width, height]` the `\"fit\"` mode scales to. */\n readonly referenceResolution?: readonly number[];\n /** The layers created up front, back to front. */\n readonly layers?: readonly string[];\n /** Whether the overlay starts shown. */\n readonly visible?: boolean;\n /**\n * The address of a `.i18n.json` document to load into `app.i18n` at start-up. Empty loads\n * nothing; a game that ships one file per locale calls `app.i18n.load` itself.\n */\n readonly strings?: string;\n /** The locale the app starts in, before any document is loaded. Defaults to `\"en\"`. */\n readonly locale?: string;\n}\n\n/**\n * Merges the extension's options over the resolved settings section.\n *\n * @param settings - The resolved `ui` section.\n * @param options - What the game passed to `ui(...)`.\n * @returns The effective settings.\n */\nfunction mergeSettings(settings: UiSettings, options: UiOptions): UiSettings {\n return {\n scaling: options.scaling ?? settings.scaling,\n referenceResolution: options.referenceResolution ?? settings.referenceResolution,\n layers: options.layers ?? settings.layers,\n visible: options.visible ?? settings.visible,\n };\n}\n\n/**\n * Builds the setter that writes `app.input.uiHasFocus`, or a no-op when `@ignifx/input` is not\n * registered.\n *\n * @remarks\n * `InputService.uiHasFocus` is a plain settable property whose own documentation says\n * \"`@ignifx/ui` assigns it\"* (`packages/input/src/service/input-service.ts` 340-349). This is that\n * assignment. It is looked up once, at registration, because `app.input` cannot appear later:\n * extensions all register before the first frame.\n *\n * @param app - The app being built.\n * @returns The setter.\n */\nfunction inputFocusSetter(app: App): (value: boolean) => void {\n return inputFlagSetter(app, \"uiHasFocus\");\n}\n\n/**\n * Builds the setter for one of `@ignifx/input`'s two UI flags, or a no-op when the extension is\n * absent or predates the flag.\n * @param app - The app being built.\n * @param flag - `uiHasFocus` (a text field owns the keyboard) or `uiHasPointer` (a pointer is\n * pressed on the overlay).\n * @returns The setter.\n */\nfunction inputFlagSetter(app: App, flag: \"uiHasFocus\" | \"uiHasPointer\"): (value: boolean) => void {\n const input: unknown = Reflect.get(app, \"input\");\n if (input === null || typeof input !== \"object\" || !(flag in input)) {\n return (): void => {\n // No input extension, or one without this flag: nothing consumes it, so nothing is written.\n };\n }\n return (value: boolean): void => {\n Reflect.set(input, flag, value);\n };\n}\n\n/**\n * The components the extension registers, in the order the API report lists them.\n *\n * @returns The classes.\n */\nfunction components(): readonly [typeof WorldAnchor, typeof HudText, typeof WorldText, typeof WorldText2D] {\n return [WorldAnchor, HudText, WorldText, WorldText2D];\n}\n\n/**\n * Registers everything the package contributes.\n *\n * @param ctx - The registration surface.\n * @param options - What the game passed to `ui(...)`.\n * @throws IgnifxError with code `IGX-1301` when a second `ui()` is registered on one app.\n */\nfunction registerUi(ctx: ExtensionContext, options: UiOptions): void {\n const app = ctx.app;\n // `Reflect.has` rather than `\"ui\" in app`: the augmentation in `./augmentation.js` declares the\n // property on `App`, so an `in` check narrows the negative branch to `never` and every later use\n // of `app` in this function stops type-checking.\n if (Reflect.has(app, \"ui\")) {\n throw uiError(UiErrorCode.duplicateExtension, \"The ui() extension is already registered on this app.\", {\n hint: \"Register ui() once; pass its options to that one call.\",\n });\n }\n ctx.registerErrorCodes(UI_ERROR_MESSAGES);\n ctx.registerSettings<UiSettings>(UI_SETTINGS_SECTION, uiSettingsSchema(), defaultUiSettings());\n const settings = mergeSettings(ctx.settings<UiSettings>(UI_SETTINGS_SECTION), options);\n const host = new UiHost({\n // A thunk, not a value: `AppImpl.initialize` registers every extension before it creates the\n // Lite engine, so `app.renderer.surface` throws `IGX-0107` here. `UiSystem.onWorldCreated`\n // calls `mount()` once the engine exists, still inside this `createApp` call.\n resolveTarget: (): UiDomTarget | null => (app.isHeadless ? null : resolveDomTarget(app.renderer.surface)),\n settings,\n log: ctx.log,\n setInputFocus: inputFocusSetter(app),\n setInputPointer: inputFlagSetter(app, \"uiHasPointer\"),\n });\n const i18n = new I18nService({ log: ctx.log, locale: options.locale ?? \"en\" });\n const runtime = new TextRuntime({\n createRenderer: app.isHeadless ? null : (): LiteTextRenderer => createRegisteredTextRenderer(app.lite.engine),\n attachLayer: attachTextLayer,\n detachLayer: detachTextLayer,\n destroyRenderer: destroyTextRenderer,\n });\n ctx.registerService(UiHost, host);\n ctx.registerService(I18nService, i18n);\n defineUiAppProperty(ctx, host);\n defineI18nAppProperty(ctx, i18n);\n ctx.registerAssetLoader(createLocaleLoader());\n ctx.registerComponents(components());\n ctx.registerSystem(new UiSystem({ app, host, runtime, i18n }), {\n phase: Phase.PreRender,\n order: UI_SYNC_ORDER,\n });\n let strings: AssetHandle<LocaleAsset> | null = null;\n if (options.strings !== undefined && options.strings !== \"\") {\n strings = app.assets.load<LocaleAsset>(options.strings);\n // Not awaited: delivery needs a frame and `register` runs before the first one\n // (`05-assets-and-loading.md` §4). Text that names an `i18nKey` shows the key until then.\n const handle = strings;\n void i18n.load(handle).catch((error: unknown): void => {\n app.onError.emit({ error, source: \"extension\", phase: null, entity: null, component: null });\n });\n }\n ctx.onDispose((): void => {\n runtime.dispose();\n host.dispose();\n i18n.dispose();\n strings?.release();\n });\n}\n\n/**\n * Turns on device-lost recovery for the text renderer.\n *\n * @param app - The app being started.\n */\nfunction startUi(app: App): void {\n if (app.isHeadless || !app.renderer.features.deviceLostRecovery) {\n return;\n }\n enableTextDeviceLostRecovery(\n app.lite.engine,\n (): void => {\n app.log.info(\"UI text resources recovered after device loss.\");\n },\n (error: unknown): void => {\n app.onError.emit({ error, source: \"extension\", phase: null, entity: null, component: null });\n },\n );\n}\n\n/**\n * The `@ignifx/ui` extension factory.\n *\n * @param options - Overrides for the `ui` settings section, plus the start-up translation document.\n * @returns The extension descriptor to pass to `createApp`.\n *\n * @example\n * ```ts\n * const app = await createApp({\n * canvas,\n * extensions: [ui({ scaling: \"fit\", referenceResolution: [640, 360] })],\n * });\n * ```\n *\n * @public\n */\nexport const ui: (options?: UiOptions) => Extension = defineExtension<UiOptions | undefined>((raw) => {\n // `defineExtension` hands the factory whatever the caller passed, which is `undefined` when the\n // game wrote `ui()`; the typed signature cannot express that, so the default lands here.\n const options: UiOptions = raw ?? {};\n return {\n name: \"@ignifx/ui\",\n version: VERSION,\n engine: \">=0.0.0 <1.0.0\",\n requires: [\"@ignifx/core\"],\n register(ctx: ExtensionContext): void {\n registerUi(ctx, options);\n },\n onStart(app: App): void {\n startUi(app);\n },\n };\n});\n","import { describeSchema } from \"@ignifx/core\";\nimport { describeLocaleFileFormat } from \"./i18n/locale-file.js\";\nimport { HudText } from \"./text/hud-text.js\";\nimport { WorldText2D } from \"./text/world-text-2d.js\";\nimport { WorldText } from \"./text/world-text.js\";\nimport { WorldAnchor } from \"./world/world-anchor.js\";\nimport type { SchemaDescription } from \"@ignifx/core\";\n\n/**\n * The documentation harness's view of everything `@ignifx/ui` declares\n * (`docs/architecture/16-docs-harness-and-skill.md` §3, `scripts/README.md`).\n *\n * `pnpm docs:schemas` imports the built entry point, calls {@link describeSchemas}, and renders\n * `skills/ignifx/references/formats/<format>.md` plus `ignifx.schemas.json` from the result. The\n * **function** form is what a package exports rather than a `schemas` object: building the record\n * means calling `describeSchema` for every component, and module scope holds declarations only\n * (`CONSTITUTION.md` §3.5).\n *\n * The translation document is keyed `ignifx/i18n-file` rather than `ignifx.i18n`: the harness\n * rejects a key with no `/` (`scripts/lib/schema-source.ts`), and it is the entry's `format` — not\n * its key — that decides which page it lands on. `@ignifx/core` and `@ignifx/audio` key their file\n * formats the same way.\n */\n\n/**\n * Describes every component and file format this package declares, for the documentation harness.\n *\n * @returns The records, keyed by namespaced type id.\n *\n * @example\n * ```ts\n * describeSchemas()[\"ignifx/HudText\"].fields[\"fontSize\"].default; // 32\n * ```\n *\n * @public\n */\nexport function describeSchemas(): Readonly<Record<string, SchemaDescription>> {\n return {\n \"ignifx/WorldAnchor\": describeSchema(\"ignifx/WorldAnchor\", WorldAnchor.schema, {\n description: \"Keeps a DOM element at an entity's screen position, with clamping and distance scaling.\",\n }),\n \"ignifx/HudText\": describeSchema(\"ignifx/HudText\", HudText.schema, {\n description: \"Pixel-space text drawn by Babylon Lite, anchored to a corner of the render target.\",\n }),\n \"ignifx/WorldText\": describeSchema(\"ignifx/WorldText\", WorldText.schema, {\n description: \"3D text in the render scene: signs and banners, optionally billboarded.\",\n }),\n \"ignifx/WorldText2D\": describeSchema(\"ignifx/WorldText2D\", WorldText2D.schema, {\n description: \"Pixel-space text placed at an entity's projected position: damage numbers and name tags.\",\n }),\n \"ignifx/i18n-file\": describeLocaleFileFormat(),\n };\n}\n","import { Signal } from \"@ignifx/core\";\nimport { UI_CLASS_NAMES } from \"../dom/styles.js\";\nimport type { UiHost } from \"../dom/host.js\";\nimport type { SignalLike } from \"@ignifx/core\";\n\n/**\n * Modal dialogs use a higher stacking level than menus so their panels and backdrops stay above\n * other layer content. Without a DOM overlay, methods are no-ops and `element` is `null`.\n */\n\n/**\n * One button in a dialog.\n *\n * @public\n */\nexport interface DialogButton {\n /** The identifier `onChosen` reports. */\n readonly id: string;\n /** The text drawn on the button. */\n readonly label: string;\n}\n\n/**\n * What `new Dialog(app.ui, options)` accepts.\n *\n * @public\n */\nexport interface DialogOptions {\n /** The heading. Omit for a dialog with no title. */\n readonly title?: string;\n /** The body text. Omit for a dialog with no message. */\n readonly message?: string;\n /** The buttons, left to right. */\n readonly buttons?: readonly DialogButton[];\n /** The layer to mount into. Defaults to `\"menu\"`. */\n readonly layer?: string;\n /** Whether the dialog starts shown. Defaults to `false`. */\n readonly visible?: boolean;\n /** Whether a click on the backdrop dismisses the dialog. Defaults to `false`. */\n readonly dismissOnBackdrop?: boolean;\n /** The stacking order inside the layer. Defaults to `UI_DIALOG_Z_INDEX`, from the stylesheet. */\n readonly zIndex?: number;\n}\n\n/**\n * A modal panel with a title, a message, and buttons.\n *\n * @public\n */\nexport class Dialog {\n readonly #root: HTMLDivElement | null;\n\n readonly #title: HTMLHeadingElement | null = null;\n\n readonly #message: HTMLParagraphElement | null = null;\n\n readonly #buttonRow: HTMLDivElement | null = null;\n\n readonly #buttonCleanups: (() => void)[] = [];\n\n readonly #chosen = new Signal<string>();\n\n readonly #dismissed = new Signal();\n\n readonly #cleanups: (() => void)[] = [];\n\n #visible: boolean;\n\n #disposed = false;\n\n /**\n * Builds the dialog and mounts it hidden.\n *\n * @param host - The overlay host, normally `app.ui`.\n * @param options - The title, the message, the buttons, and the layer.\n */\n constructor(host: UiHost, options: DialogOptions = {}) {\n this.#visible = options.visible ?? false;\n const layerElement = host.layer(options.layer ?? \"menu\").element;\n if (layerElement === null) {\n this.#root = null;\n return;\n }\n const document = layerElement.ownerDocument;\n const root = document.createElement(\"div\");\n root.className = UI_CLASS_NAMES.dialog;\n root.setAttribute(\"role\", \"dialog\");\n root.setAttribute(\"aria-modal\", \"true\");\n const backdrop = document.createElement(\"div\");\n backdrop.className = UI_CLASS_NAMES.dialogBackdrop;\n root.append(backdrop);\n if (options.dismissOnBackdrop === true) {\n const onBackdrop = (): void => {\n this.hide();\n };\n backdrop.addEventListener(\"pointerdown\", onBackdrop);\n this.#cleanups.push((): void => {\n backdrop.removeEventListener(\"pointerdown\", onBackdrop);\n });\n }\n const panel = document.createElement(\"div\");\n panel.className = UI_CLASS_NAMES.dialogPanel;\n if (options.title !== undefined) {\n const heading = document.createElement(\"h2\");\n heading.className = UI_CLASS_NAMES.dialogTitle;\n heading.textContent = options.title;\n panel.append(heading);\n this.#title = heading;\n }\n if (options.message !== undefined) {\n const paragraph = document.createElement(\"p\");\n paragraph.className = UI_CLASS_NAMES.dialogMessage;\n paragraph.textContent = options.message;\n panel.append(paragraph);\n this.#message = paragraph;\n }\n const row = document.createElement(\"div\");\n row.className = UI_CLASS_NAMES.dialogButtons;\n panel.append(row);\n this.#buttonRow = row;\n root.append(panel);\n root.style.setProperty(\"display\", this.#visible ? \"flex\" : \"none\");\n if (options.zIndex !== undefined) {\n root.style.setProperty(\"z-index\", String(options.zIndex));\n }\n layerElement.append(root);\n this.#root = root;\n this.setButtons(options.buttons ?? []);\n }\n\n /**\n * The dialog's outermost element, so a template can restyle it or mount more into it.\n *\n * @returns The element, or `null` when the app has no DOM overlay.\n */\n get element(): HTMLDivElement | null {\n return this.#root;\n }\n\n /**\n * Whether the dialog is shown.\n *\n * @returns `true` while it is on screen.\n */\n get isVisible(): boolean {\n return this.#visible;\n }\n\n /**\n * Emitted with a button's `id` when it is pressed. The dialog does not hide itself; the game\n * decides, because \"Cancel\" and \"Delete everything\" want different follow-ups.\n *\n * @returns The signal.\n */\n get onChosen(): SignalLike<string> {\n return this.#chosen;\n }\n\n /**\n * Emitted after {@link Dialog.hide}, whatever caused it.\n *\n * @returns The signal.\n */\n get onDismissed(): SignalLike {\n return this.#dismissed;\n }\n\n /** Shows the dialog. */\n show(): void {\n if (this.#visible || this.#disposed) {\n return;\n }\n this.#visible = true;\n this.#root?.style.setProperty(\"display\", \"flex\");\n }\n\n /** Hides the dialog and emits {@link Dialog.onDismissed}. */\n hide(): void {\n if (!this.#visible || this.#disposed) {\n return;\n }\n this.#visible = false;\n this.#root?.style.setProperty(\"display\", \"none\");\n this.#dismissed.emit();\n }\n\n /**\n * Replaces the heading, if the dialog was built with one.\n *\n * @param text - The new heading.\n */\n setTitle(text: string): void {\n if (this.#title !== null) {\n this.#title.textContent = text;\n }\n }\n\n /**\n * Replaces the body text, if the dialog was built with one.\n *\n * @param text - The new message.\n */\n setMessage(text: string): void {\n if (this.#message !== null) {\n this.#message.textContent = text;\n }\n }\n\n /**\n * Replaces the buttons.\n *\n * @remarks\n * One dialog re-used for every question is cheaper than one dialog per question and keeps the\n * stacking predictable, so the buttons have to be able to change: a confirmation asks\n * \"Yes\"/\"No\", a save error offers \"Retry\"/\"Cancel\", and a locale change relabels both.\n *\n * @param buttons - The buttons, left to right. An empty list leaves the row empty.\n *\n * @example\n * ```ts ignore-check\n * dialog.setMessage(\"Delete this save?\");\n * dialog.setButtons([{ id: \"no\", label: \"No\" }, { id: \"yes\", label: \"Yes\" }]);\n * ```\n */\n setButtons(buttons: readonly DialogButton[]): void {\n const row = this.#buttonRow;\n if (row === null || this.#disposed) {\n return;\n }\n for (const cleanup of this.#buttonCleanups) {\n cleanup();\n }\n this.#buttonCleanups.length = 0;\n row.replaceChildren();\n const document = row.ownerDocument;\n for (const button of buttons) {\n row.append(this.#createButton(document, button));\n }\n }\n\n /** Removes the dialog and unsubscribes. */\n dispose(): void {\n if (this.#disposed) {\n return;\n }\n this.#disposed = true;\n for (const cleanup of [...this.#cleanups, ...this.#buttonCleanups]) {\n cleanup();\n }\n this.#cleanups.length = 0;\n this.#buttonCleanups.length = 0;\n this.#root?.remove();\n this.#chosen.clear();\n this.#dismissed.clear();\n }\n\n /**\n * Builds one button and wires it to {@link Dialog.onChosen}.\n *\n * @param document - The document to create in.\n * @param button - The button's id and label.\n * @returns The element.\n */\n #createButton(document: Document, button: DialogButton): HTMLButtonElement {\n const element = document.createElement(\"button\");\n element.type = \"button\";\n element.className = UI_CLASS_NAMES.dialogButton;\n element.textContent = button.label;\n element.dataset[\"ignifxDialogButton\"] = button.id;\n const onClick = (): void => {\n this.#chosen.emit(button.id);\n };\n element.addEventListener(\"click\", onClick);\n this.#buttonCleanups.push((): void => {\n element.removeEventListener(\"click\", onClick);\n });\n return element;\n }\n}\n","import { clamp01, Signal } from \"@ignifx/core\";\nimport { UI_CLASS_NAMES } from \"../dom/styles.js\";\nimport type { UiHost } from \"../dom/host.js\";\nimport type { AssetProgress, Assets, Disconnect, SignalLike } from \"@ignifx/core\";\n\n/**\n * Prefer byte-weighted progress, falling back to handle counts when sizes are unknown.\n * Boot loads can be awaited before `app.start`; running games deliver loads in `PreUpdate`.\n * Both paths update through asset signals, without polling.\n */\n\n/**\n * What `new LoadingScreen(app.ui, options)` accepts.\n *\n * @public\n */\nexport interface LoadingScreenOptions {\n /** The layer to mount into. Defaults to `\"overlay\"`. */\n readonly layer?: string;\n /** The initial label. Defaults to `\"Loading…\"`. */\n readonly label?: string;\n /** Whether the screen starts shown. Defaults to `true` — a boot screen is up before anything else. */\n readonly visible?: boolean;\n}\n\n/**\n * The fraction of an asset batch that is done.\n *\n * @remarks\n * Bytes when the build recorded sizes, handles otherwise, and `1` for an empty batch — a loading\n * screen that never reaches 100% because nothing was queued is worse than one that closes at once.\n *\n * @param progress - The payload of `app.assets.onProgress`.\n * @returns The fraction, in `[0, 1]`.\n *\n * @example\n * ```ts\n * progressFraction({ loaded: 1, total: 4, bytesLoaded: 0, bytesTotal: 0 }); // 0.25\n * ```\n *\n * @public\n */\nexport function progressFraction(progress: AssetProgress): number {\n if (progress.bytesTotal > 0) {\n return clamp01(progress.bytesLoaded / progress.bytesTotal);\n }\n if (progress.total > 0) {\n return clamp01(progress.loaded / progress.total);\n }\n return 1;\n}\n\n/**\n * A full-overlay loading panel.\n *\n * @example\n * ```ts\n * const screen = new LoadingScreen(app.ui, { label: \"Loading…\" });\n * screen.bindTo(app.assets);\n * await app.assets.preloadGroup(\"boot\").promise;\n * screen.hide();\n * ```\n *\n * @public\n */\nexport class LoadingScreen {\n readonly #root: HTMLDivElement | null;\n\n readonly #label: HTMLDivElement | null = null;\n\n readonly #bar: HTMLDivElement | null = null;\n\n readonly #dismissed = new Signal();\n\n #disconnect: Disconnect | null = null;\n\n #progress = 0;\n\n #visible: boolean;\n\n #disposed = false;\n\n /**\n * Builds the screen and mounts it.\n *\n * @param host - The overlay host, normally `app.ui`.\n * @param options - The layer, the label, and the initial visibility.\n */\n constructor(host: UiHost, options: LoadingScreenOptions = {}) {\n this.#visible = options.visible ?? true;\n const layerElement = host.layer(options.layer ?? \"overlay\").element;\n if (layerElement === null) {\n this.#root = null;\n return;\n }\n const document = layerElement.ownerDocument;\n const root = document.createElement(\"div\");\n root.className = UI_CLASS_NAMES.loading;\n root.setAttribute(\"role\", \"progressbar\");\n root.setAttribute(\"aria-valuemin\", \"0\");\n root.setAttribute(\"aria-valuemax\", \"1\");\n root.setAttribute(\"aria-valuenow\", \"0\");\n const label = document.createElement(\"div\");\n label.className = UI_CLASS_NAMES.loadingLabel;\n label.textContent = options.label ?? \"Loading…\";\n const track = document.createElement(\"div\");\n track.className = UI_CLASS_NAMES.loadingTrack;\n const bar = document.createElement(\"div\");\n bar.className = UI_CLASS_NAMES.loadingBar;\n track.append(bar);\n root.append(label, track);\n root.style.setProperty(\"display\", this.#visible ? \"flex\" : \"none\");\n layerElement.append(root);\n this.#root = root;\n this.#label = label;\n this.#bar = bar;\n }\n\n /**\n * The screen's outermost element, so a template can restyle it or add a logo.\n *\n * @returns The element, or `null` when the app has no DOM overlay.\n */\n get element(): HTMLDivElement | null {\n return this.#root;\n }\n\n /**\n * Whether the screen is shown.\n *\n * @returns `true` while it is on screen.\n */\n get isVisible(): boolean {\n return this.#visible;\n }\n\n /**\n * How far along the bar is, in `[0, 1]`. Writing it moves the bar; values outside the range are\n * clamped.\n *\n * @returns The fraction.\n */\n get progress(): number {\n return this.#progress;\n }\n\n // eslint-disable-next-line jsdoc/require-jsdoc -- the accessor pair is documented on the getter.\n set progress(value: number) {\n const fraction = clamp01(value);\n if (this.#progress === fraction) {\n return;\n }\n this.#progress = fraction;\n this.#bar?.style.setProperty(\"width\", `${String(fraction * 100)}%`);\n this.#root?.setAttribute(\"aria-valuenow\", String(fraction));\n }\n\n /**\n * Emitted after {@link LoadingScreen.hide}, whatever caused it.\n *\n * @returns The signal.\n */\n get onDismissed(): SignalLike {\n return this.#dismissed;\n }\n\n /**\n * Follows an asset service's aggregate progress until {@link LoadingScreen.dispose} or a second\n * call to this method.\n *\n * @param assets - The asset service, normally `app.assets`.\n * @returns A function that stops following.\n */\n bindTo(assets: Assets): Disconnect {\n this.#disconnect?.();\n const disconnect = assets.onProgress.connect((progress: AssetProgress): void => {\n this.progress = progressFraction(progress);\n });\n this.#disconnect = disconnect;\n return disconnect;\n }\n\n /**\n * Replaces the label.\n *\n * @param text - The new label.\n */\n setLabel(text: string): void {\n if (this.#label !== null) {\n this.#label.textContent = text;\n }\n }\n\n /** Shows the screen. */\n show(): void {\n if (this.#visible || this.#disposed) {\n return;\n }\n this.#visible = true;\n this.#root?.style.setProperty(\"display\", \"flex\");\n }\n\n /** Hides the screen and emits {@link LoadingScreen.onDismissed}. */\n hide(): void {\n if (!this.#visible || this.#disposed) {\n return;\n }\n this.#visible = false;\n this.#root?.style.setProperty(\"display\", \"none\");\n this.#dismissed.emit();\n }\n\n /** Removes the screen and stops following the asset service. */\n dispose(): void {\n if (this.#disposed) {\n return;\n }\n this.#disposed = true;\n this.#disconnect?.();\n this.#disconnect = null;\n this.#root?.remove();\n this.#dismissed.clear();\n }\n}\n","/**\n * Rows declare the values they edit through `get` and `set`. The menu handles rendering,\n * clamping, formatting, and input repeat so each settings screen can share that behaviour.\n */\n\n/**\n * Text that is either fixed or re-read on every refresh.\n *\n * @remarks\n * A function is what makes a menu localizable: `label: () => app.i18n.t(\"menu.resume\")` re-renders\n * itself when `app.i18n.locale` changes, because {@link Menu.refresh} calls it again.\n *\n * @public\n */\nexport type MenuLabel = string | (() => string);\n\n/**\n * The values a `\"choice\"` row cycles through: a fixed list, or one read per use.\n *\n * @public\n */\nexport type MenuChoiceValues = readonly string[] | (() => readonly string[]);\n\n/**\n * What every selectable row carries.\n *\n * @public\n */\nexport interface MenuRowBase {\n /** A stable id. It becomes the row's `data-row` attribute, which is what a test selects on. */\n readonly id: string;\n /** The left-hand text. */\n readonly label: MenuLabel;\n /** Whether the row can be selected. A row that answers `false` is drawn dimmed and skipped. */\n readonly enabled?: () => boolean;\n}\n\n/**\n * A row that runs something when it is activated.\n *\n * @public\n */\nexport interface MenuActionRow extends MenuRowBase {\n /** What kind of row this is. */\n readonly kind: \"action\";\n /** The right-hand text, when the row shows one. */\n readonly value?: MenuLabel;\n /** What Enter, the pad's south button and a click do. */\n readonly activate?: () => void;\n}\n\n/**\n * A row that flips a flag.\n *\n * @public\n */\nexport interface MenuToggleRow extends MenuRowBase {\n /** What kind of row this is. */\n readonly kind: \"toggle\";\n /** Reads the flag. */\n readonly get: () => boolean;\n /** Writes the flag. */\n readonly set: (value: boolean) => void;\n /** Renders the flag. Defaults to the menu's `text.on` / `text.off`. */\n readonly format?: (value: boolean) => string;\n}\n\n/**\n * A row that edits a number over a range.\n *\n * @remarks\n * Drawn as a native `<input type=\"range\">` plus the formatted value, because dragging a knob is\n * worth having and `@ignifx/ui`'s own focus policy deliberately does not count a slider as a text\n * field (`docs/architecture/13-ui.md` §1), so a slider under the pointer never suppresses gameplay\n * input.\n *\n * @public\n */\nexport interface MenuSliderRow extends MenuRowBase {\n /** What kind of row this is. */\n readonly kind: \"slider\";\n /** The lowest value the row may take. */\n readonly min: number;\n /** The highest value the row may take. */\n readonly max: number;\n /** How far one Left or Right press moves the value. */\n readonly step: number;\n /** Reads the current value. */\n readonly get: () => number;\n /** Writes a new value, already clamped and snapped to the step. */\n readonly set: (value: number) => void;\n /** Renders the value. Defaults to the number itself. */\n readonly format?: (value: number) => string;\n}\n\n/**\n * A row that cycles through a list of values.\n *\n * @public\n */\nexport interface MenuChoiceRow extends MenuRowBase {\n /** What kind of row this is. */\n readonly kind: \"choice\";\n /** The values to cycle through, in order. */\n readonly values: MenuChoiceValues;\n /** Reads the current value. */\n readonly get: () => string;\n /** Writes the new value. */\n readonly set: (value: string) => void;\n /** Renders a value for display. Defaults to the value itself. */\n readonly format?: (value: string) => string;\n}\n\n/**\n * A row that shows one input binding and starts a rebind when it is activated.\n *\n * @remarks\n * The row knows nothing about `@ignifx/input`: it is handed the binding's path as a string and a\n * callback that starts whatever rebinding flow the game uses. `@ignifx/input`'s\n * `performInteractiveRebind` is the usual one.\n *\n * @public\n */\nexport interface MenuBindingRow extends MenuRowBase {\n /** What kind of row this is. */\n readonly kind: \"binding\";\n /** Reads the binding path, such as `<Keyboard>/arrowUp`, or `\"\"` when nothing is bound. */\n readonly path: () => string;\n /** Starts the rebind. */\n readonly rebind?: () => void;\n /** Whether this row's rebind is listening right now, which changes what the row shows. */\n readonly listening?: () => boolean;\n}\n\n/**\n * A non-selectable label that groups the rows under it.\n *\n * @public\n */\nexport interface MenuHeadingRow {\n /** What kind of row this is. */\n readonly kind: \"heading\";\n /** A stable id, which becomes the row's `data-row` attribute. */\n readonly id: string;\n /** The heading text. */\n readonly label: MenuLabel;\n}\n\n/**\n * A non-selectable rule between groups of rows.\n *\n * @public\n */\nexport interface MenuSeparatorRow {\n /** What kind of row this is. */\n readonly kind: \"separator\";\n /** A stable id, which becomes the row's `data-row` attribute. */\n readonly id: string;\n}\n\n/**\n * One row of a {@link Menu}.\n *\n * @public\n */\nexport type MenuRow =\n | MenuActionRow\n | MenuBindingRow\n | MenuChoiceRow\n | MenuHeadingRow\n | MenuSeparatorRow\n | MenuSliderRow\n | MenuToggleRow;\n\n/**\n * The words a menu uses for the states its rows can be in, so a localized game sets them once per\n * menu rather than on every row.\n *\n * @public\n */\nexport interface MenuText {\n /** What a `\"toggle\"` row shows when it is on. Defaults to `\"On\"`. */\n readonly on?: MenuLabel;\n /** What a `\"toggle\"` row shows when it is off. Defaults to `\"Off\"`. */\n readonly off?: MenuLabel;\n /** What a `\"binding\"` row shows when nothing is bound. Defaults to `\"—\"`. */\n readonly unbound?: MenuLabel;\n /** What a `\"binding\"` row shows while it is listening. Defaults to `\"Press any key…\"`. */\n readonly listening?: MenuLabel;\n}\n\n/**\n * Reads a {@link MenuLabel}.\n *\n * @param label - The fixed string, the function, or nothing.\n * @param fallback - What to answer when `label` is `undefined`.\n * @returns The text to draw.\n *\n * @public\n */\nexport function resolveMenuLabel(label: MenuLabel | undefined, fallback: string): string {\n if (label === undefined) {\n return fallback;\n }\n return typeof label === \"string\" ? label : label();\n}\n\n/**\n * Reads a {@link MenuChoiceValues}.\n *\n * @param values - The fixed list or the function.\n * @returns The values, in order.\n *\n * @public\n */\nexport function resolveMenuChoices(values: MenuChoiceValues): readonly string[] {\n return typeof values === \"function\" ? values() : values;\n}\n\n/**\n * Clamps a number into a range and snaps it to the step.\n *\n * @remarks\n * Snapping rather than accumulating is what stops a slider from drifting by floating-point error\n * after a few hundred key presses: every value is recomputed from `min` and a whole number of\n * steps.\n *\n * @param value - The raw value.\n * @param min - The lowest allowed value.\n * @param max - The highest allowed value.\n * @param step - The grid the value is snapped to. A step of `0` or less disables snapping.\n * @returns The clamped, snapped value.\n *\n * @example\n * ```ts\n * snapToStep(0.37, 0, 1, 0.05); // 0.35\n * ```\n *\n * @public\n */\nexport function snapToStep(value: number, min: number, max: number, step: number): number {\n const clamped = Math.min(max, Math.max(min, value));\n if (step <= 0) {\n return clamped;\n }\n const steps = Math.round((clamped - min) / step);\n return Math.min(max, Math.max(min, min + steps * step));\n}\n\n/**\n * Renders an `@ignifx/input` binding path the way a player reads it.\n *\n * @param path - The binding path, such as `<Keyboard>/arrowUp`, or `\"\"` for none.\n * @param unbound - What to answer for an empty path.\n * @returns The label, such as `Keyboard: Arrow up`.\n *\n * @example\n * ```ts\n * formatBindingPath(\"<Keyboard>/arrowUp\", \"—\"); // \"Keyboard: Arrow up\"\n * formatBindingPath(\"\", \"—\"); // \"—\"\n * ```\n *\n * @public\n */\nexport function formatBindingPath(path: string, unbound: string): string {\n if (path === \"\") {\n return unbound;\n }\n const slash = path.indexOf(\"/\");\n const device = slash > 0 ? path.slice(1, slash - 1) : \"\";\n const control = slash > 0 ? path.slice(slash + 1) : path;\n const spaced = control.replaceAll(\"/\", \" \").replaceAll(/(?<lower>[a-z])(?<upper>[A-Z])/gu, \"$<lower> $<upper>\");\n const pretty = spaced.charAt(0).toUpperCase() + spaced.slice(1).toLowerCase();\n return device === \"\" ? pretty : `${device}: ${pretty}`;\n}\n","import { assertNever, Signal } from \"@ignifx/core\";\nimport { UI_CLASS_NAMES } from \"../dom/styles.js\";\nimport { formatBindingPath, resolveMenuChoices, resolveMenuLabel, snapToStep } from \"./menu-row.js\";\nimport type { MenuLabel, MenuRow, MenuSliderRow, MenuText } from \"./menu-row.js\";\nimport type { UiHost } from \"../dom/host.js\";\nimport type { SignalLike } from \"@ignifx/core\";\n\n/**\n * Share one selection model across keyboard, gamepad, and pointer input.\n * DOM focus stays on the list; `aria-activedescendant` identifies the selected row.\n * Toggle rows expose `aria-checked`. Sliders expose their value through the row's accessible name;\n * the range input is pointer-only, while Left/Right also adjust the value.\n * Without a DOM overlay, methods are no-ops and `element` is `null`.\n */\n\n/**\n * What `new Menu(app.ui, options)` accepts.\n *\n * @public\n */\nexport interface MenuOptions {\n /** A stable id; it becomes the panel's `data-menu` attribute. */\n readonly id: string;\n /** The panel's heading. Re-read on every {@link Menu.refresh}. */\n readonly title?: MenuLabel;\n /** A line of prose under the heading. */\n readonly subtitle?: MenuLabel;\n /** The overlay layer to mount into. Defaults to `\"menu\"`. */\n readonly layer?: string;\n /** The rows to start with. More usually arrive through {@link Menu.setRows}. */\n readonly rows?: readonly MenuRow[];\n /** Whether the menu starts shown. Defaults to `false`. */\n readonly visible?: boolean;\n /** Whether Escape and {@link Menu.cancel} back out of the menu. Defaults to `true`. */\n readonly cancelable?: boolean;\n /**\n * Whether the widget reads the keyboard itself. Defaults to `true`.\n *\n * @remarks\n * Turn it off when the game drives navigation from its own input actions, or every arrow press\n * moves the selection twice. A {@link MenuStack} built with a navigation\n * source does that for you.\n */\n readonly keyboard?: boolean;\n /** Whether the selection wraps at both ends. Defaults to `true`. */\n readonly wrap?: boolean;\n /** The words the rows use for their states. */\n readonly text?: MenuText;\n}\n\n/** The elements one row is drawn from. */\ninterface MenuRowElements {\n /** The row's outermost element. */\n readonly root: HTMLElement;\n /** The left-hand text. */\n readonly label: HTMLElement;\n /** The right-hand text, or `null` for a row that shows none. */\n readonly value: HTMLElement | null;\n /** The range input, or `null` for anything but a `\"slider\"` row. */\n readonly slider: HTMLInputElement | null;\n}\n\n/** The default words a menu uses when {@link MenuOptions.text} does not override them. */\nconst DEFAULT_TEXT = {\n /** What a `\"toggle\"` row shows when it is on. */\n on: \"On\",\n /** What a `\"toggle\"` row shows when it is off. */\n off: \"Off\",\n /** What a `\"binding\"` row shows when nothing is bound. */\n unbound: \"—\",\n /** What a `\"binding\"` row shows while it is listening. */\n listening: \"Press any key…\",\n} as const;\n\n/**\n * A panel of selectable rows in an overlay layer.\n *\n * @example\n * ```ts ignore-check\n * const pause = new Menu(app.ui, { id: \"pause\", title: \"Paused\" });\n * pause.setRows([\n * { kind: \"action\", id: \"resume\", label: \"Resume\", activate: () => pause.hide() },\n * { kind: \"slider\", id: \"music\", label: \"Music\", min: 0, max: 1, step: 0.05,\n * get: () => music.volume, set: (v) => { music.volume = v; },\n * format: (v) => `${String(Math.round(v * 100))}%` },\n * ]);\n * pause.show();\n * ```\n *\n * @public\n */\nexport class Menu {\n /** The id the menu was built with. */\n readonly id: string;\n\n readonly #options: MenuOptions;\n\n readonly #panel: HTMLDivElement | null;\n\n readonly #heading: HTMLElement | null;\n\n readonly #subtitle: HTMLElement | null;\n\n readonly #list: HTMLElement | null;\n\n readonly #cleanups: (() => void)[] = [];\n\n /** Every range input this menu drew, so the key handler can leave their own keys alone. */\n readonly #sliders = new Set<EventTarget>();\n\n readonly #selectionChanged = new Signal<MenuRow>();\n\n readonly #activated = new Signal<MenuRow>();\n\n readonly #back = new Signal();\n\n #rows: readonly MenuRow[] = [];\n\n #elements: readonly MenuRowElements[] = [];\n\n #index = 0;\n\n #visible: boolean;\n\n #cancelable: boolean;\n\n #keyboard: boolean;\n\n #disposed = false;\n\n /**\n * Builds the panel and mounts it, hidden unless `options.visible` says otherwise.\n *\n * @param host - The overlay host, normally `app.ui`.\n * @param options - The id, the heading, the layer, and the starting rows.\n */\n constructor(host: UiHost, options: MenuOptions) {\n this.id = options.id;\n this.#options = options;\n this.#visible = options.visible ?? false;\n this.#cancelable = options.cancelable ?? true;\n this.#keyboard = options.keyboard ?? true;\n const layerElement = host.layer(options.layer ?? \"menu\").element;\n if (layerElement === null) {\n this.#panel = null;\n this.#heading = null;\n this.#subtitle = null;\n this.#list = null;\n this.setRows(options.rows ?? []);\n return;\n }\n const document = layerElement.ownerDocument;\n const panel = document.createElement(\"div\");\n panel.className = UI_CLASS_NAMES.menu;\n panel.dataset[\"menu\"] = options.id;\n panel.setAttribute(\"role\", \"dialog\");\n panel.setAttribute(\"aria-modal\", \"true\");\n panel.hidden = !this.#visible;\n\n const heading = document.createElement(\"h2\");\n heading.className = UI_CLASS_NAMES.menuTitle;\n panel.append(heading);\n\n let subtitle: HTMLElement | null = null;\n if (options.subtitle !== undefined) {\n subtitle = document.createElement(\"p\");\n subtitle.className = UI_CLASS_NAMES.menuSubtitle;\n panel.append(subtitle);\n }\n\n const list = document.createElement(\"div\");\n list.className = UI_CLASS_NAMES.menuRows;\n list.setAttribute(\"role\", \"menu\");\n list.tabIndex = -1;\n panel.append(list);\n const onKeyDown = (event: KeyboardEvent): void => {\n this.#onKeyDown(event);\n };\n list.addEventListener(\"keydown\", onKeyDown);\n this.#cleanups.push((): void => {\n list.removeEventListener(\"keydown\", onKeyDown);\n });\n layerElement.append(panel);\n\n this.#panel = panel;\n this.#heading = heading;\n this.#subtitle = subtitle;\n this.#list = list;\n this.setRows(options.rows ?? []);\n }\n\n /**\n * The panel element, so a game can restyle it or a test can read it.\n *\n * @returns The element, or `null` under an app with no DOM overlay.\n */\n get element(): HTMLDivElement | null {\n return this.#panel;\n }\n\n /**\n * Whether the panel is on screen.\n *\n * @returns `true` between {@link Menu.show} and {@link Menu.hide}.\n */\n get isVisible(): boolean {\n return this.#visible;\n }\n\n /**\n * The rows the menu is drawing.\n *\n * @returns The rows, in draw order.\n */\n get rows(): readonly MenuRow[] {\n return this.#rows;\n }\n\n /**\n * The selected row.\n *\n * @returns The row under the selection, or `null` when nothing can be selected.\n */\n get selected(): MenuRow | null {\n return this.#rows[this.#index] ?? null;\n }\n\n /**\n * Where the selection sits.\n *\n * @returns The index into {@link Menu.rows}.\n */\n get selectedIndex(): number {\n return this.#index;\n }\n\n /**\n * Whether Escape and {@link Menu.cancel} back out of this menu. A title screen sets it `false`.\n *\n * @returns `true` when the menu can be dismissed.\n */\n get cancelable(): boolean {\n return this.#cancelable;\n }\n\n // eslint-disable-next-line jsdoc/require-jsdoc -- the accessor pair is documented on the getter.\n set cancelable(value: boolean) {\n this.#cancelable = value;\n }\n\n /**\n * Whether the widget reads the keyboard itself.\n *\n * @returns `true` while its own `keydown` handler acts.\n */\n get keyboardEnabled(): boolean {\n return this.#keyboard;\n }\n\n // eslint-disable-next-line jsdoc/require-jsdoc -- the accessor pair is documented on the getter.\n set keyboardEnabled(value: boolean) {\n this.#keyboard = value;\n }\n\n /**\n * Emitted with the newly selected row whenever the selection moves, from any device. A game\n * connects a click sound to it.\n *\n * @returns The signal.\n */\n get onSelectionChanged(): SignalLike<MenuRow> {\n return this.#selectionChanged;\n }\n\n /**\n * Emitted with the row that was activated, after its own handler ran.\n *\n * @returns The signal.\n */\n get onActivated(): SignalLike<MenuRow> {\n return this.#activated;\n }\n\n /**\n * Emitted by {@link Menu.cancel} — Escape, the pad's east button, or a call — when the menu is\n * {@link Menu.cancelable}. A {@link MenuStack} connects `pop` to it.\n *\n * @returns The signal.\n */\n get onBack(): SignalLike {\n return this.#back;\n }\n\n /**\n * Replaces the rows and rebuilds the panel.\n *\n * @remarks\n * Rebuilding rather than diffing is deliberate: the row list changes when a save appears, when a\n * control scheme changes and when the locale changes, and a menu of at most a few dozen rows is\n * not worth a reconciler. The selection stays on the same row id when that id is still present.\n *\n * @param rows - The rows, in draw order.\n */\n setRows(rows: readonly MenuRow[]): void {\n const previous = this.#rows[this.#index]?.id ?? \"\";\n this.#rows = rows;\n this.#buildRows();\n const restored = rows.findIndex((row: MenuRow): boolean => row.id === previous);\n this.#index = restored >= 0 ? restored : this.#firstSelectable();\n this.refresh();\n }\n\n /** Re-reads every label and value and redraws the selection. */\n refresh(): void {\n const title = resolveMenuLabel(this.#options.title, \"\");\n if (this.#heading !== null) {\n this.#heading.textContent = title;\n }\n this.#panel?.setAttribute(\"aria-label\", title);\n this.#list?.setAttribute(\"aria-label\", title);\n if (this.#subtitle !== null) {\n this.#subtitle.textContent = resolveMenuLabel(this.#options.subtitle, \"\");\n }\n for (let index = 0; index < this.#rows.length; index += 1) {\n const row = this.#rows[index];\n const elements = this.#elements[index];\n if (row !== undefined && elements !== undefined) {\n this.#refreshRow(row, elements, index);\n }\n }\n this.#applyActiveDescendant();\n }\n\n /** Shows the panel, puts the selection on the first row that can take it, and focuses the list. */\n show(): void {\n if (this.#disposed) {\n return;\n }\n this.#visible = true;\n this.#index = this.#firstSelectable();\n if (this.#panel !== null) {\n this.#panel.hidden = false;\n }\n this.refresh();\n this.#list?.focus({ preventScroll: true });\n }\n\n /** Hides the panel. */\n hide(): void {\n if (this.#disposed) {\n return;\n }\n this.#visible = false;\n if (this.#panel !== null) {\n this.#panel.hidden = true;\n }\n this.refresh();\n }\n\n /**\n * Moves the selection, skipping headings, separators and disabled rows.\n *\n * @param delta - `-1` for up, `1` for down.\n */\n moveSelection(delta: -1 | 1): void {\n const count = this.#rows.length;\n if (count === 0) {\n return;\n }\n const wrap = this.#options.wrap ?? true;\n for (let step = 1; step <= count; step += 1) {\n const raw = this.#index + delta * step;\n if (!wrap && (raw < 0 || raw >= count)) {\n return;\n }\n const candidate = (raw + count * step) % count;\n if (this.#isSelectable(candidate)) {\n this.#select(candidate);\n return;\n }\n }\n }\n\n /**\n * Puts the selection on a row by id.\n *\n * @param id - The row's {@link MenuRowBase.id}.\n * @returns `true` when a selectable row with that id was found.\n */\n select(id: string): boolean {\n const index = this.#rows.findIndex((row: MenuRow): boolean => row.id === id);\n if (index < 0 || !this.#isSelectable(index)) {\n return false;\n }\n this.#select(index);\n return true;\n }\n\n /**\n * Runs the selected row's Left or Right behaviour: a slider moves by one step, a toggle flips,\n * and a choice advances.\n *\n * @param direction - `-1` for left, `1` for right.\n */\n adjustSelection(direction: -1 | 1): void {\n const row = this.#rows[this.#index];\n if (row === undefined || !this.#isSelectable(this.#index)) {\n return;\n }\n switch (row.kind) {\n case \"slider\": {\n row.set(snapToStep(row.get() + direction * row.step, row.min, row.max, row.step));\n break;\n }\n case \"toggle\": {\n row.set(!row.get());\n break;\n }\n case \"choice\": {\n const values = resolveMenuChoices(row.values);\n const here = values.indexOf(row.get());\n const next = values[(Math.max(here, 0) + direction + values.length) % values.length];\n if (next !== undefined && next !== row.get()) {\n row.set(next);\n }\n break;\n }\n case \"action\":\n case \"binding\":\n case \"heading\":\n case \"separator\": {\n break;\n }\n }\n this.refresh();\n }\n\n /** Runs the selected row's activate behaviour. */\n activateSelection(): void {\n const row = this.#rows[this.#index];\n if (row === undefined || !this.#isSelectable(this.#index)) {\n return;\n }\n switch (row.kind) {\n case \"action\": {\n row.activate?.();\n break;\n }\n case \"binding\": {\n row.rebind?.();\n break;\n }\n // A slider, a toggle and a choice all move on by one: Enter on a row whose only content is a\n // value is what a player expects to change that value.\n case \"choice\":\n case \"slider\":\n case \"toggle\": {\n this.adjustSelection(1);\n break;\n }\n // Unreachable: `#isSelectable` already turned these away.\n case \"heading\":\n case \"separator\": {\n break;\n }\n }\n this.refresh();\n this.#activated.emit(row);\n }\n\n /**\n * Backs out of the menu, if it is {@link Menu.cancelable}.\n *\n * @returns `true` when {@link Menu.onBack} was emitted, so the caller knows the press was used.\n */\n cancel(): boolean {\n if (!this.#cancelable || this.#disposed) {\n return false;\n }\n this.#back.emit();\n return true;\n }\n\n /** Removes the panel from the overlay and unsubscribes everything. */\n dispose(): void {\n if (this.#disposed) {\n return;\n }\n this.#disposed = true;\n for (const cleanup of this.#cleanups) {\n cleanup();\n }\n this.#cleanups.length = 0;\n this.#sliders.clear();\n this.#panel?.remove();\n this.#selectionChanged.clear();\n this.#activated.clear();\n this.#back.clear();\n }\n\n /**\n * Moves the selection and tells everyone.\n *\n * @param index - The row to select.\n */\n #select(index: number): void {\n if (index === this.#index) {\n return;\n }\n this.#index = index;\n this.refresh();\n this.#scrollIntoView();\n const row = this.#rows[index];\n if (row !== undefined) {\n this.#selectionChanged.emit(row);\n }\n }\n\n /**\n * Handles the keys the widget owns while the list has DOM focus.\n *\n * @param event - The key event.\n */\n #onKeyDown(event: KeyboardEvent): void {\n // A pointer press focuses a range input in most browsers even at `tabindex=\"-1\"`; while it has\n // focus its own arrow keys are the right behaviour, and the `input` event carries the change\n // back here.\n if (!this.#keyboard || (event.target !== null && this.#sliders.has(event.target))) {\n return;\n }\n switch (event.key) {\n case \"ArrowUp\": {\n this.moveSelection(-1);\n break;\n }\n case \"ArrowDown\": {\n this.moveSelection(1);\n break;\n }\n case \"ArrowLeft\": {\n this.adjustSelection(-1);\n break;\n }\n case \"ArrowRight\": {\n this.adjustSelection(1);\n break;\n }\n case \" \":\n case \"Enter\": {\n this.activateSelection();\n break;\n }\n case \"Escape\": {\n if (!this.cancel()) {\n return;\n }\n break;\n }\n default: {\n return;\n }\n }\n // Only for a key the menu acted on: an arrow that scrolled the page, or a space that scrolled\n // it, would otherwise move the panel out from under the player.\n event.preventDefault();\n }\n\n /** Rebuilds every row element from {@link Menu.setRows}'s list. */\n #buildRows(): void {\n const list = this.#list;\n if (list === null) {\n this.#elements = [];\n return;\n }\n const document = list.ownerDocument;\n list.replaceChildren();\n this.#sliders.clear();\n const built: MenuRowElements[] = [];\n for (let index = 0; index < this.#rows.length; index += 1) {\n const row = this.#rows[index];\n if (row !== undefined) {\n built.push(this.#buildRow(document, list, row, index));\n }\n }\n this.#elements = built;\n }\n\n /**\n * Builds one row's elements and connects its pointer handlers.\n *\n * @param document - The overlay's document.\n * @param list - The element to append to.\n * @param row - The row being drawn.\n * @param index - The row's position, captured by the pointer handlers.\n * @returns The row's elements.\n */\n #buildRow(document: Document, list: HTMLElement, row: MenuRow, index: number): MenuRowElements {\n const selectable = row.kind !== \"heading\" && row.kind !== \"separator\";\n const root = document.createElement(selectable ? \"button\" : \"div\");\n root.className = selectable ? UI_CLASS_NAMES.menuRow : rowClassName(row.kind);\n root.id = `${UI_CLASS_NAMES.menu}-${this.id}-${row.id}`;\n root.dataset[\"row\"] = row.id;\n root.dataset[\"kind\"] = row.kind;\n root.setAttribute(\"role\", rowRole(row.kind));\n root.tabIndex = -1;\n if (selectable) {\n root.setAttribute(\"type\", \"button\");\n }\n\n const label = document.createElement(\"span\");\n label.className = UI_CLASS_NAMES.menuRowLabel;\n root.append(label);\n\n let slider: HTMLInputElement | null = null;\n if (row.kind === \"slider\") {\n slider = document.createElement(\"input\");\n slider.type = \"range\";\n slider.className = UI_CLASS_NAMES.menuRowSlider;\n slider.tabIndex = -1;\n // Not in the accessibility tree: the row is a `menuitem`, which may not own an interactive\n // element, and the value is announced through the row's own name. See this file's header.\n slider.setAttribute(\"aria-hidden\", \"true\");\n slider.min = String(row.min);\n slider.max = String(row.max);\n slider.step = String(row.step);\n root.append(slider);\n this.#sliders.add(slider);\n }\n\n let value: HTMLElement | null = null;\n if (row.kind !== \"heading\" && row.kind !== \"separator\") {\n value = document.createElement(\"span\");\n value.className = UI_CLASS_NAMES.menuRowValue;\n root.append(value);\n }\n\n if (selectable) {\n this.#connectRowPointer(root, index);\n }\n if (slider !== null && row.kind === \"slider\") {\n this.#connectSlider(slider, row, index);\n }\n list.append(root);\n return { root, label, value, slider };\n }\n\n /**\n * Wires hover and click on a selectable row.\n *\n * @param root - The row element.\n * @param index - The row's position.\n */\n #connectRowPointer(root: HTMLElement, index: number): void {\n const onEnter = (): void => {\n if (this.#isSelectable(index)) {\n this.#select(index);\n }\n };\n const onClick = (): void => {\n if (!this.#isSelectable(index)) {\n return;\n }\n this.#select(index);\n this.activateSelection();\n };\n root.addEventListener(\"pointerenter\", onEnter);\n root.addEventListener(\"click\", onClick);\n this.#cleanups.push((): void => {\n root.removeEventListener(\"pointerenter\", onEnter);\n root.removeEventListener(\"click\", onClick);\n });\n }\n\n /**\n * Wires a range input to its row.\n *\n * @param slider - The input element.\n * @param row - The row it belongs to.\n * @param index - The row's position.\n */\n #connectSlider(slider: HTMLInputElement, row: MenuSliderRow, index: number): void {\n const onInput = (): void => {\n this.#index = index;\n row.set(snapToStep(Number(slider.value), row.min, row.max, row.step));\n this.refresh();\n };\n slider.addEventListener(\"input\", onInput);\n // A drag on the knob is a click on the row; without `stopSliderClick` the row would activate —\n // and a menu built out of one slider would advance a step — as soon as the player let go.\n slider.addEventListener(\"click\", stopSliderClick);\n this.#cleanups.push((): void => {\n slider.removeEventListener(\"input\", onInput);\n slider.removeEventListener(\"click\", stopSliderClick);\n });\n }\n\n /**\n * Re-reads one row and writes it onto its elements.\n *\n * @param row - The row.\n * @param elements - Its elements.\n * @param index - Its position, compared against the selection.\n */\n #refreshRow(row: MenuRow, elements: MenuRowElements, index: number): void {\n elements.label.textContent = row.kind === \"separator\" ? \"\" : resolveMenuLabel(row.label, \"\");\n if (elements.value !== null) {\n elements.value.textContent = this.#rowValueText(row);\n }\n if (elements.slider !== null && row.kind === \"slider\") {\n elements.slider.value = String(row.get());\n }\n if (row.kind === \"toggle\") {\n elements.root.setAttribute(\"aria-checked\", row.get() ? \"true\" : \"false\");\n }\n const enabled = this.#isSelectable(index);\n const selectable = row.kind !== \"heading\" && row.kind !== \"separator\";\n elements.root.toggleAttribute(\"data-disabled\", selectable && !enabled);\n if (selectable) {\n elements.root.setAttribute(\"aria-disabled\", enabled ? \"false\" : \"true\");\n }\n elements.root.toggleAttribute(\"data-focused\", enabled && index === this.#index && this.#visible);\n }\n\n /**\n * The right-hand text of one row.\n *\n * @param row - The row.\n * @returns The text, or `\"\"` when the row shows none.\n */\n #rowValueText(row: MenuRow): string {\n const text = this.#options.text ?? {};\n switch (row.kind) {\n case \"action\": {\n return resolveMenuLabel(row.value, \"\");\n }\n case \"toggle\": {\n const on = row.get();\n return row.format?.(on) ?? resolveMenuLabel(on ? text.on : text.off, on ? DEFAULT_TEXT.on : DEFAULT_TEXT.off);\n }\n case \"slider\": {\n const value = row.get();\n return row.format?.(value) ?? String(value);\n }\n case \"choice\": {\n const value = row.get();\n return row.format?.(value) ?? value;\n }\n case \"binding\": {\n if (row.listening?.() === true) {\n return resolveMenuLabel(text.listening, DEFAULT_TEXT.listening);\n }\n return formatBindingPath(row.path(), resolveMenuLabel(text.unbound, DEFAULT_TEXT.unbound));\n }\n case \"heading\":\n case \"separator\": {\n return \"\";\n }\n default: {\n return assertNever(row, \"menu row kind\");\n }\n }\n }\n\n /** Points `aria-activedescendant` at the selected row, or clears it. */\n #applyActiveDescendant(): void {\n const list = this.#list;\n if (list === null) {\n return;\n }\n const active = this.#isSelectable(this.#index) ? this.#elements[this.#index]?.root : undefined;\n if (active === undefined) {\n list.removeAttribute(\"aria-activedescendant\");\n return;\n }\n list.setAttribute(\"aria-activedescendant\", active.id);\n }\n\n /**\n * Whether a row can take the selection.\n *\n * @param index - The row's position.\n * @returns `true` when the row exists, is selectable, and is enabled.\n */\n #isSelectable(index: number): boolean {\n const row = this.#rows[index];\n if (row === undefined || row.kind === \"heading\" || row.kind === \"separator\") {\n return false;\n }\n return row.enabled?.() ?? true;\n }\n\n /**\n * The first row that can take the selection.\n *\n * @returns Its index, or `0` when there is none.\n */\n #firstSelectable(): number {\n for (let index = 0; index < this.#rows.length; index += 1) {\n if (this.#isSelectable(index)) {\n return index;\n }\n }\n return 0;\n }\n\n /** Brings the selected row into view in a scrolling list. */\n #scrollIntoView(): void {\n this.#elements[this.#index]?.root.scrollIntoView({ block: \"nearest\" });\n }\n}\n\n/**\n * Keeps the click that ends a slider drag from reaching the row and activating it.\n *\n * @param event - The click.\n */\nfunction stopSliderClick(event: Event): void {\n event.stopPropagation();\n}\n\n/**\n * The ARIA role one row kind is drawn with.\n *\n * @param kind - The row kind.\n * @returns The role attribute value.\n */\nfunction rowRole(kind: MenuRow[\"kind\"]): string {\n switch (kind) {\n case \"toggle\": {\n return \"menuitemcheckbox\";\n }\n case \"heading\":\n case \"separator\": {\n return \"separator\";\n }\n case \"action\":\n case \"binding\":\n case \"choice\":\n case \"slider\": {\n return \"menuitem\";\n }\n default: {\n return assertNever(kind, \"menu row kind\");\n }\n }\n}\n\n/**\n * The class name a non-selectable row kind is drawn with.\n *\n * @param kind - The row kind.\n * @returns The class name.\n */\nfunction rowClassName(kind: MenuRow[\"kind\"]): string {\n return kind === \"heading\" ? UI_CLASS_NAMES.menuHeading : UI_CLASS_NAMES.menuSeparator;\n}\n","import { Signal } from \"@ignifx/core\";\nimport type { MenuRow } from \"./menu-row.js\";\nimport type { Menu } from \"./menu.js\";\nimport type { Disconnect, SignalLike, Vec2Like } from \"@ignifx/core\";\n\n/**\n * Show one menu at a time and unwind one level per back action. Use unscaled time for input repeat\n * so navigation works while paused. Navigation accepts action-shaped objects without importing input.\n * When a navigation source is supplied, disable each stacked menu's keyboard handling to avoid\n * processing the same key twice; restore it on removal.\n */\n\n/**\n * Anything with a two-dimensional value, which `@ignifx/input`'s `InputAction` is.\n *\n * @public\n */\nexport interface MenuVectorSource {\n /** The direction, `-1` to `1` on each axis. Positive `y` is up. */\n readonly vector: Vec2Like;\n}\n\n/**\n * Anything with a press edge, which `@ignifx/input`'s `InputAction` is.\n *\n * @public\n */\nexport interface MenuButtonSource {\n /** Whether the control went down this frame. */\n readonly wasPressedThisFrame: boolean;\n}\n\n/**\n * The three controls a menu stack reads.\n *\n * @public\n */\nexport interface MenuNavigation {\n /** Moves the selection (`y`) and adjusts the selected row (`x`). */\n readonly move?: MenuVectorSource | null;\n /** Activates the selected row. */\n readonly submit?: MenuButtonSource | null;\n /** Backs out one screen. */\n readonly back?: MenuButtonSource | null;\n}\n\n/**\n * What `new MenuStack(options)` accepts.\n *\n * @public\n */\nexport interface MenuStackOptions {\n /** The controls to read in {@link MenuStack.update}. Omit to drive the stack by hand. */\n readonly navigation?: MenuNavigation;\n /** How long the first repeat of a held direction waits, in seconds. Defaults to `0.35`. */\n readonly repeatDelay?: number;\n /** How long each following repeat waits, in seconds. Defaults to `0.12`. */\n readonly repeatInterval?: number;\n /** How far an axis must move before it counts as a direction. Defaults to `0.5`. */\n readonly threshold?: number;\n}\n\n/** What the stack remembers about one menu it pushed. */\ninterface StackEntry {\n /** The menu. */\n readonly menu: Menu;\n /** The subscriptions to drop when it is popped. */\n readonly disconnects: readonly Disconnect[];\n /** What the menu's `keyboardEnabled` was before the stack turned it off. */\n readonly keyboard: boolean;\n}\n\n/**\n * A stack of {@link Menu} screens, innermost last.\n *\n * @example\n * ```ts ignore-check\n * const stack = new MenuStack({ navigation });\n * stack.push(title);\n * // in a script that runs while paused:\n * stack.update(app.time.unscaledDeltaTime);\n * ```\n *\n * @public\n */\nexport class MenuStack {\n readonly #entries: StackEntry[] = [];\n\n readonly #navigation: MenuNavigation | null;\n\n readonly #repeatDelay: number;\n\n readonly #repeatInterval: number;\n\n readonly #threshold: number;\n\n readonly #changed = new Signal<Menu | null>();\n\n readonly #selectionChanged = new Signal<MenuRow>();\n\n readonly #activated = new Signal<MenuRow>();\n\n #heldX: -1 | 0 | 1 = 0;\n\n #heldY: -1 | 0 | 1 = 0;\n\n #repeatIn = 0;\n\n #suspended = false;\n\n /**\n * Builds an empty stack.\n *\n * @param options - The controls to read, and the repeat timings.\n */\n constructor(options: MenuStackOptions = {}) {\n this.#navigation = options.navigation ?? null;\n this.#repeatDelay = options.repeatDelay ?? 0.35;\n this.#repeatInterval = options.repeatInterval ?? 0.12;\n this.#threshold = options.threshold ?? 0.5;\n }\n\n /**\n * The menus on the stack, outermost first.\n *\n * @returns The menus, in push order.\n */\n get menus(): readonly Menu[] {\n return this.#entries.map((entry: StackEntry): Menu => entry.menu);\n }\n\n /**\n * The menu on top, which is the visible one.\n *\n * @returns The top menu, or `null` when the stack is empty.\n */\n get top(): Menu | null {\n return this.#entries.at(-1)?.menu ?? null;\n }\n\n /**\n * The menu at the bottom, which is the one the stack was opened with.\n *\n * @returns The first menu pushed, or `null` when the stack is empty.\n */\n get bottom(): Menu | null {\n return this.#entries[0]?.menu ?? null;\n }\n\n /**\n * How deep the stack is.\n *\n * @returns The number of menus on it.\n */\n get depth(): number {\n return this.#entries.length;\n }\n\n /**\n * Whether any menu is open.\n *\n * @returns `true` while the stack is not empty.\n */\n get isOpen(): boolean {\n return this.#entries.length > 0;\n }\n\n /**\n * Whether {@link MenuStack.update} is reading its controls.\n *\n * @remarks\n * Set it while something modal is on top of the menu — a confirmation `Dialog`, or a rebind that\n * is listening for the next key — so that the same press does not reach both.\n *\n * @returns `true` while navigation is suspended.\n */\n get suspended(): boolean {\n return this.#suspended;\n }\n\n // eslint-disable-next-line jsdoc/require-jsdoc -- the accessor pair is documented on the getter.\n set suspended(value: boolean) {\n this.#suspended = value;\n if (value) {\n this.#releaseHeld();\n }\n }\n\n /**\n * Emitted with the new top menu — `null` when the stack empties — whenever the stack changes. A\n * game connects its audio ducking and its pause state to it.\n *\n * @returns The signal.\n */\n get onChanged(): SignalLike<Menu | null> {\n return this.#changed;\n }\n\n /**\n * Emitted with the newly selected row whenever the selection moves on the top menu.\n *\n * @returns The signal.\n */\n get onSelectionChanged(): SignalLike<MenuRow> {\n return this.#selectionChanged;\n }\n\n /**\n * Emitted with the row that was activated on the top menu.\n *\n * @returns The signal.\n */\n get onActivated(): SignalLike<MenuRow> {\n return this.#activated;\n }\n\n /**\n * Hides whatever is on top and shows `menu` over it.\n *\n * @param menu - The menu to open.\n */\n push(menu: Menu): void {\n this.top?.hide();\n const keyboard = menu.keyboardEnabled;\n if (this.#navigation !== null) {\n menu.keyboardEnabled = false;\n }\n this.#entries.push({\n menu,\n keyboard,\n disconnects: [\n menu.onBack.connect((): void => {\n this.pop();\n }),\n menu.onSelectionChanged.connect((row: MenuRow): void => {\n this.#selectionChanged.emit(row);\n }),\n menu.onActivated.connect((row: MenuRow): void => {\n this.#activated.emit(row);\n }),\n ],\n });\n menu.show();\n this.#releaseHeld();\n this.#changed.emit(menu);\n }\n\n /**\n * Closes the top menu and shows the one underneath.\n *\n * @returns The menu that was closed, or `null` when the stack was already empty.\n */\n pop(): Menu | null {\n const entry = this.#entries.pop();\n if (entry === undefined) {\n return null;\n }\n this.#release(entry);\n entry.menu.hide();\n this.top?.show();\n this.#releaseHeld();\n this.#changed.emit(this.top);\n return entry.menu;\n }\n\n /** Closes every menu on the stack. */\n closeAll(): void {\n if (this.#entries.length === 0) {\n return;\n }\n for (let index = this.#entries.length - 1; index >= 0; index -= 1) {\n const entry = this.#entries[index];\n if (entry !== undefined) {\n this.#release(entry);\n entry.menu.hide();\n }\n }\n this.#entries.length = 0;\n this.#releaseHeld();\n this.#changed.emit(null);\n }\n\n /** Re-reads every label on every menu on the stack, for a locale change. */\n refresh(): void {\n for (const entry of this.#entries) {\n entry.menu.refresh();\n }\n }\n\n /**\n * Reads the navigation controls and applies them to the top menu.\n *\n * @remarks\n * Call it from a script that declares `static updateWhenPaused = true`, with\n * `app.time.unscaledDeltaTime`: a menu that repeats a held direction has to keep time while the\n * game is stopped, and scaled time is pinned at zero while it is.\n *\n * @param unscaledDelta - Seconds since the last call, on the unscaled clock.\n */\n update(unscaledDelta: number): void {\n const top = this.top;\n const navigation = this.#navigation;\n if (top === null || navigation === null || this.#suspended) {\n this.#releaseHeld();\n return;\n }\n const move = navigation.move ?? null;\n const x = this.#direction(move === null ? 0 : move.vector.x);\n const y = this.#direction(move === null ? 0 : move.vector.y);\n if (x !== this.#heldX || y !== this.#heldY) {\n this.#heldX = x;\n this.#heldY = y;\n this.#repeatIn = this.#repeatDelay;\n this.#applyDirection(top, x, y);\n } else if (x !== 0 || y !== 0) {\n this.#repeatIn -= unscaledDelta;\n if (this.#repeatIn <= 0) {\n this.#repeatIn = this.#repeatInterval;\n this.#applyDirection(top, x, y);\n }\n }\n if (navigation.submit?.wasPressedThisFrame === true) {\n top.activateSelection();\n return;\n }\n if (navigation.back?.wasPressedThisFrame === true) {\n top.cancel();\n }\n }\n\n /** Drops every subscription. The menus themselves belong to the game and are not disposed. */\n dispose(): void {\n for (const entry of this.#entries) {\n this.#release(entry);\n }\n this.#entries.length = 0;\n this.#changed.clear();\n this.#selectionChanged.clear();\n this.#activated.clear();\n }\n\n /**\n * Applies one direction to the top menu.\n *\n * @param top - The menu on top.\n * @param x - `-1`, `0` or `1` on the horizontal axis.\n * @param y - `-1`, `0` or `1` on the vertical axis, positive up.\n */\n #applyDirection(top: Menu, x: -1 | 0 | 1, y: -1 | 0 | 1): void {\n if (y !== 0) {\n top.moveSelection(y > 0 ? -1 : 1);\n }\n if (x !== 0) {\n top.adjustSelection(x);\n }\n }\n\n /**\n * Turns an axis into a direction, so a stick and a keyboard composite read the same.\n *\n * @param value - The axis value.\n * @returns `-1`, `0` or `1`.\n */\n #direction(value: number): -1 | 0 | 1 {\n if (value >= this.#threshold) {\n return 1;\n }\n return value <= -this.#threshold ? -1 : 0;\n }\n\n /** Forgets the held direction, so the next frame starts a fresh press. */\n #releaseHeld(): void {\n this.#heldX = 0;\n this.#heldY = 0;\n this.#repeatIn = 0;\n }\n\n /**\n * Drops one entry's subscriptions and gives its menu its keyboard handling back.\n *\n * @param entry - The entry being removed.\n */\n #release(entry: StackEntry): void {\n for (const disconnect of entry.disconnects) {\n disconnect();\n }\n entry.menu.keyboardEnabled = entry.keyboard;\n }\n}\n","import { Signal } from \"@ignifx/core\";\nimport { UI_CLASS_NAMES } from \"../dom/styles.js\";\nimport type { UiHost } from \"../dom/host.js\";\nimport type { SignalLike } from \"@ignifx/core\";\n\n/**\n * The caller advances toast lifetime; no browser timer can outlive the app.\n * For messages that expire while paused, call `advance(app.time.unscaledDeltaTime)` from a script\n * with `updateWhenPaused = true`. The UI system does not advance toasts automatically.\n */\n\n/**\n * What `new Toast(app.ui, options)` accepts.\n *\n * @public\n */\nexport interface ToastOptions {\n /** The layer to mount the stack into. Defaults to `\"overlay\"`. */\n readonly layer?: string;\n /** How long a message stays up, in seconds, unless {@link Toast.show} overrides it. */\n readonly duration?: number;\n /** How many messages are stacked before the oldest is dropped. Defaults to `4`. */\n readonly maxVisible?: number;\n}\n\n/** One message on screen, and how much of its life is left. */\ninterface LiveToast {\n /** The element, or `null` under a headless app. */\n readonly element: HTMLDivElement | null;\n /** The text, so a headless test can assert on it. */\n readonly text: string;\n /** Seconds left before it is removed. */\n remaining: number;\n}\n\n/**\n * A stack of transient messages.\n *\n * @example\n * ```ts\n * const toasts = new Toast(app.ui);\n * toasts.show(\"Checkpoint reached\");\n * // in the update of a script that declares `static updateWhenPaused = true`:\n * toasts.advance(app.time.unscaledDeltaTime);\n * ```\n *\n * @public\n */\nexport class Toast {\n readonly #stack: HTMLDivElement | null;\n\n readonly #live: LiveToast[] = [];\n\n readonly #duration: number;\n\n readonly #maxVisible: number;\n\n readonly #expired = new Signal<string>();\n\n #disposed = false;\n\n /**\n * Builds the stack and mounts it.\n *\n * @param host - The overlay host, normally `app.ui`.\n * @param options - The layer, the default duration, and the stack depth.\n */\n constructor(host: UiHost, options: ToastOptions = {}) {\n this.#duration = options.duration ?? 3;\n this.#maxVisible = Math.max(1, options.maxVisible ?? 4);\n const layerElement = host.layer(options.layer ?? \"overlay\").element;\n if (layerElement === null) {\n this.#stack = null;\n return;\n }\n const stack = layerElement.ownerDocument.createElement(\"div\");\n stack.className = UI_CLASS_NAMES.toastStack;\n stack.setAttribute(\"role\", \"status\");\n stack.setAttribute(\"aria-live\", \"polite\");\n layerElement.append(stack);\n this.#stack = stack;\n }\n\n /**\n * The stack element, so a template can reposition it.\n *\n * @returns The element, or `null` when the app has no DOM overlay.\n */\n get element(): HTMLDivElement | null {\n return this.#stack;\n }\n\n /**\n * The messages currently on screen, oldest first.\n *\n * @returns The texts.\n */\n get messages(): readonly string[] {\n return this.#live.map((entry: LiveToast): string => entry.text);\n }\n\n /**\n * Emitted with a message's text when it times out or is pushed off the stack.\n *\n * @returns The signal.\n */\n get onDismissed(): SignalLike<string> {\n return this.#expired;\n }\n\n /**\n * Shows a message.\n *\n * @param text - The message.\n * @param duration - How long it stays up, in seconds; defaults to the stack's own duration.\n */\n show(text: string, duration?: number): void {\n if (this.#disposed) {\n return;\n }\n const stack = this.#stack;\n let element: HTMLDivElement | null = null;\n if (stack !== null) {\n element = stack.ownerDocument.createElement(\"div\");\n element.className = UI_CLASS_NAMES.toast;\n element.textContent = text;\n stack.append(element);\n }\n this.#live.push({ element, text, remaining: duration ?? this.#duration });\n while (this.#live.length > this.#maxVisible) {\n this.#remove(0);\n }\n }\n\n /**\n * Advances every message's timer.\n *\n * @remarks\n * Nothing calls this for you. The script that does must declare `static updateWhenPaused = true`\n * if toasts are to expire while the game is paused — a menu's \"Saved\" message is shown from a\n * paused game, and an ordinary script gets no `update` there.\n *\n * @param deltaSeconds - Seconds elapsed since the previous call; `dt` from a script's `update`, or\n * `app.time.unscaledDeltaTime` when the toast has to expire while the game is paused.\n */\n advance(deltaSeconds: number): void {\n for (let index = this.#live.length - 1; index >= 0; index -= 1) {\n const entry = this.#live[index];\n if (entry === undefined) {\n continue;\n }\n entry.remaining -= deltaSeconds;\n if (entry.remaining <= 0) {\n this.#remove(index);\n }\n }\n }\n\n /** Removes every message at once. */\n clear(): void {\n while (this.#live.length > 0) {\n this.#remove(this.#live.length - 1);\n }\n }\n\n /** Removes the stack and unsubscribes. */\n dispose(): void {\n if (this.#disposed) {\n return;\n }\n this.#disposed = true;\n this.#live.length = 0;\n this.#stack?.remove();\n this.#expired.clear();\n }\n\n /**\n * Removes one message and reports it.\n *\n * @param index - Its position in the stack.\n */\n #remove(index: number): void {\n const entry = this.#live[index];\n if (entry === undefined) {\n return;\n }\n this.#live.splice(index, 1);\n entry.element?.remove();\n this.#expired.emit(entry.text);\n }\n}\n","import { uiError, UiErrorCode } from \"../errors.js\";\nimport type { App } from \"@ignifx/core\";\n\n/**\n * Reach virtual input through its two-method shape. Importing the optional input peer, even for\n * types, would augment core and expose `app.input` to games that have not installed it.\n */\n\n/**\n * The part of `@ignifx/input`'s virtual device the touch widgets use.\n *\n * @remarks\n * Structural on purpose. A test passes a recording double; a game passes\n * `app.input.devices.virtual`.\n *\n * @public\n */\nexport interface VirtualDeviceLike {\n /**\n * Writes a scalar control, creating it when it does not exist.\n *\n * @param name - The control name, as it appears after `<Virtual>/`.\n * @param value - The new value.\n */\n set(name: string, value: number): void;\n /**\n * Writes a vector control, creating it when it does not exist.\n *\n * @param name - The control name.\n * @param x - The new x component.\n * @param y - The new y component.\n */\n setVector(name: string, x: number, y: number): void;\n}\n\n/**\n * Whether a value has the two methods {@link VirtualDeviceLike} declares.\n *\n * @param value - The candidate.\n * @returns `true` when both methods are functions.\n */\nfunction isVirtualDevice(value: unknown): value is VirtualDeviceLike {\n if (value === null || typeof value !== \"object\") {\n return false;\n }\n return typeof Reflect.get(value, \"set\") === \"function\" && typeof Reflect.get(value, \"setVector\") === \"function\";\n}\n\n/**\n * Finds `app.input.devices.virtual`, if `@ignifx/input` is registered.\n *\n * @param app - The running app.\n * @returns The device, or `null` when the input extension is not installed.\n *\n * @example\n * ```ts\n * const device = findVirtualDevice(app);\n * device?.setVector(\"joystick\", 0, 1);\n * ```\n *\n * @public\n */\nexport function findVirtualDevice(app: App): VirtualDeviceLike | null {\n const input: unknown = Reflect.get(app, \"input\");\n if (input === null || typeof input !== \"object\") {\n return null;\n }\n const devices: unknown = Reflect.get(input, \"devices\");\n if (devices === null || typeof devices !== \"object\") {\n return null;\n }\n const virtual: unknown = Reflect.get(devices, \"virtual\");\n return isVirtualDevice(virtual) ? virtual : null;\n}\n\n/**\n * Finds the virtual device, or explains why the widget cannot work.\n *\n * @param app - The running app.\n * @param widget - The widget's name, for the error's context.\n * @returns The device.\n * @throws IgnifxError with code `IGX-1305` when `@ignifx/input` is not registered.\n *\n * @internal\n */\nexport function requireVirtualDevice(app: App, widget: string): VirtualDeviceLike {\n const device = findVirtualDevice(app);\n if (device === null) {\n throw uiError(UiErrorCode.inputExtensionMissing, `${widget} needs the @ignifx/input extension.`, {\n context: { widget },\n hint: \"Add input() to createApp({ extensions }) before constructing the widget.\",\n });\n }\n return device;\n}\n\n/**\n * Claims a pointer for an element, best effort.\n *\n * @remarks\n * `setPointerCapture` throws `NotFoundError` when the id names no *active* pointer — a pointer that\n * was already released, or a synthetic `PointerEvent` dispatched by a test. Capture is an\n * improvement, not a requirement: without it a drag that leaves the widget stops updating, and the\n * `pointerup` still arrives. Losing the frame over it would be worse than losing the capture.\n *\n * @param element - The element to capture on.\n * @param pointerId - The pointer to claim.\n *\n * @internal\n */\nexport function capturePointer(element: Element, pointerId: number): void {\n try {\n element.setPointerCapture(pointerId);\n } catch {\n // See the remarks: capture is best effort.\n }\n}\n","import { UI_CLASS_NAMES } from \"../dom/styles.js\";\nimport { capturePointer, requireVirtualDevice } from \"./virtual-device.js\";\nimport type { VirtualDeviceLike } from \"./virtual-device.js\";\nimport type { App } from \"@ignifx/core\";\n\n/**\n * `VirtualButton` (`docs/architecture/13-ui.md` §3): an on-screen button that writes a\n * `<Virtual>/…` button control, so `jump` is one action bound to a key, a gamepad face button, and\n * this widget at the same time.\n *\n * A real `<button>` element rather than a `<div>`, so it is focusable, announced by a screen\n * reader, and reachable by keyboard. That has one consequence worth knowing: pressing it with the\n * keyboard fires a `click`, not a `pointerdown`, so the button also releases on `blur` — otherwise a\n * `Tab` away mid-press would stick.\n */\n\n/**\n * What `new VirtualButton(app, options)` accepts.\n *\n * @public\n */\nexport interface VirtualButtonOptions {\n /** The `<Virtual>/…` control to write. */\n readonly control: string;\n /** The glyph or word drawn on the button. Defaults to the control name. */\n readonly label?: string;\n /** The layer to mount into. Defaults to `\"hud\"`. */\n readonly layer?: string;\n /** Inline styles applied to the button, for placement. */\n readonly style?: Readonly<Record<string, string>>;\n /** An accessible label. Defaults to the control name. */\n readonly ariaLabel?: string;\n}\n\n/**\n * An on-screen button.\n *\n * @example\n * ```ts\n * const jump = new VirtualButton(app, { control: \"jump\", label: \"A\" });\n * ```\n *\n * @public\n */\nexport class VirtualButton {\n readonly #device: VirtualDeviceLike;\n\n readonly #control: string;\n\n readonly #element: HTMLButtonElement | null;\n\n #pressed = false;\n\n #disposed = false;\n\n readonly #onPress = (event: PointerEvent): void => {\n this.#set(true);\n const element = this.#element;\n if (element !== null) {\n capturePointer(element, event.pointerId);\n }\n event.preventDefault();\n };\n\n readonly #onRelease = (event: PointerEvent): void => {\n this.#set(false);\n event.preventDefault();\n };\n\n readonly #onBlur = (): void => {\n this.#set(false);\n };\n\n /**\n * Builds the widget and mounts it.\n *\n * @param app - The running app; `app.ui` and `app.input.devices.virtual` are the parts used.\n * @param options - The control name, the label, the layer, and the placement styles.\n * @throws IgnifxError with code `IGX-1305` when `@ignifx/input` is not registered.\n */\n constructor(app: App, options: VirtualButtonOptions) {\n this.#control = options.control;\n this.#device = requireVirtualDevice(app, \"VirtualButton\");\n const host = app.ui.layer(options.layer ?? \"hud\").element;\n if (host === null) {\n this.#element = null;\n return;\n }\n const element = host.ownerDocument.createElement(\"button\");\n element.type = \"button\";\n element.className = UI_CLASS_NAMES.button;\n element.textContent = options.label ?? options.control;\n element.setAttribute(\"aria-label\", options.ariaLabel ?? options.control);\n // The button takes DOM focus when tapped, and a focused `<button>` is not a text field, so\n // `isEditableElement` leaves `app.input.uiHasFocus` alone and the keyboard keeps driving the\n // game while a thumb is on the screen.\n for (const [name, value] of Object.entries(options.style ?? {})) {\n element.style.setProperty(name, value);\n }\n host.append(element);\n this.#element = element;\n element.addEventListener(\"pointerdown\", this.#onPress);\n element.addEventListener(\"pointerup\", this.#onRelease);\n element.addEventListener(\"pointercancel\", this.#onRelease);\n element.addEventListener(\"blur\", this.#onBlur);\n this.#device.set(this.#control, 0);\n }\n\n /**\n * The button element, so a template can restyle or reposition it.\n *\n * @returns The element, or `null` when the app has no DOM overlay.\n */\n get element(): HTMLButtonElement | null {\n return this.#element;\n }\n\n /**\n * The control this button writes.\n *\n * @returns The name, as it appears after `<Virtual>/`.\n */\n get control(): string {\n return this.#control;\n }\n\n /**\n * Whether the button is currently held.\n *\n * @returns `true` while it is pressed.\n */\n get isPressed(): boolean {\n return this.#pressed;\n }\n\n /** Removes the widget, unsubscribes, and releases the control. */\n dispose(): void {\n if (this.#disposed) {\n return;\n }\n this.#disposed = true;\n const element = this.#element;\n if (element !== null) {\n element.removeEventListener(\"pointerdown\", this.#onPress);\n element.removeEventListener(\"pointerup\", this.#onRelease);\n element.removeEventListener(\"pointercancel\", this.#onRelease);\n element.removeEventListener(\"blur\", this.#onBlur);\n element.remove();\n }\n this.#device.set(this.#control, 0);\n }\n\n /**\n * Writes the control, if the state changed.\n *\n * @param pressed - Whether the button is held.\n */\n #set(pressed: boolean): void {\n if (this.#pressed === pressed) {\n return;\n }\n this.#pressed = pressed;\n this.#device.set(this.#control, pressed ? 1 : 0);\n }\n}\n","import { clamp } from \"@ignifx/core\";\nimport { UI_CLASS_NAMES } from \"../dom/styles.js\";\nimport { capturePointer, requireVirtualDevice } from \"./virtual-device.js\";\nimport type { VirtualDeviceLike } from \"./virtual-device.js\";\nimport type { UiLayer } from \"../dom/layer.js\";\nimport type { App } from \"@ignifx/core\";\n\n/**\n * Write a virtual vector control with Y up, converting screen Y-down motion here.\n * Claim one pointer at a time so the stick and buttons support separate touches.\n * Clear the control on both release and cancellation to prevent stuck movement.\n */\n\n/**\n * What `new VirtualJoystick(app, options)` accepts.\n *\n * @public\n */\nexport interface VirtualJoystickOptions {\n /** The `<Virtual>/…` control to write. Defaults to `\"joystick\"`. */\n readonly control?: string;\n /** The layer to mount into. Defaults to `\"hud\"`. */\n readonly layer?: string;\n /** How far the knob travels, in UI units, before the stick reads as fully deflected. */\n readonly radius?: number;\n /** Deflections shorter than this fraction of the radius read as zero. Defaults to `0.15`. */\n readonly deadZone?: number;\n /** Inline styles applied to the pad, for placement. */\n readonly style?: Readonly<Record<string, string>>;\n /** An accessible label for the pad. Defaults to the control name. */\n readonly ariaLabel?: string;\n}\n\n/**\n * Converts a raw deflection into the value written to the control.\n *\n * @param delta - The deflection along one axis, in UI units.\n * @param length - The deflection's length, in UI units.\n * @param radius - The radius at which the stick is fully deflected.\n * @param deadZone - The fraction of the radius below which the stick reads as centred.\n * @returns The axis value, in `-1` to `1`.\n *\n * @example\n * ```ts\n * stickAxis(0, 0, 44, 0.15); // 0\n * stickAxis(44, 44, 44, 0.15); // 1\n * ```\n *\n * @public\n */\nexport function stickAxis(delta: number, length: number, radius: number, deadZone: number): number {\n if (radius <= 0 || length <= 0) {\n return 0;\n }\n const magnitude = Math.min(length, radius) / radius;\n if (magnitude <= deadZone) {\n return 0;\n }\n // Rescaled so the value leaves the dead zone at 0 rather than jumping to `deadZone`, which is\n // what makes a slow walk possible on a touch screen.\n const scaled = (magnitude - deadZone) / (1 - deadZone);\n return clamp((delta / length) * scaled, -1, 1);\n}\n\n/**\n * An on-screen thumbstick.\n *\n * @example\n * ```ts\n * const stick = new VirtualJoystick(app, { control: \"joystick\" });\n * // later\n * stick.dispose();\n * ```\n *\n * @public\n */\nexport class VirtualJoystick {\n readonly #device: VirtualDeviceLike;\n\n readonly #control: string;\n\n readonly #radius: number;\n\n readonly #deadZone: number;\n\n readonly #pad: HTMLDivElement | null;\n\n readonly #knob: HTMLDivElement | null;\n\n #pointerId: number | null = null;\n\n #originX = 0;\n\n #originY = 0;\n\n #disposed = false;\n\n readonly #onPointerDown = (event: PointerEvent): void => {\n if (this.#pointerId !== null || this.#pad === null) {\n return;\n }\n this.#pointerId = event.pointerId;\n const box = this.#pad.getBoundingClientRect();\n this.#originX = box.left + box.width / 2;\n this.#originY = box.top + box.height / 2;\n capturePointer(this.#pad, event.pointerId);\n this.#move(event);\n event.preventDefault();\n };\n\n readonly #onPointerMove = (event: PointerEvent): void => {\n if (event.pointerId === this.#pointerId) {\n this.#move(event);\n event.preventDefault();\n }\n };\n\n readonly #onPointerUp = (event: PointerEvent): void => {\n if (event.pointerId === this.#pointerId) {\n this.#release();\n event.preventDefault();\n }\n };\n\n /**\n * Builds the widget and mounts it.\n *\n * @param app - The running app; `app.ui` and `app.input.devices.virtual` are the parts used.\n * @param options - The control name, the layer, the geometry, and the placement styles.\n * @throws IgnifxError with code `IGX-1305` when `@ignifx/input` is not registered.\n */\n constructor(app: App, options: VirtualJoystickOptions = {}) {\n this.#control = options.control ?? \"joystick\";\n this.#device = requireVirtualDevice(app, \"VirtualJoystick\");\n this.#radius = options.radius ?? 44;\n this.#deadZone = clamp(options.deadZone ?? 0.15, 0, 0.9);\n const layer: UiLayer = app.ui.layer(options.layer ?? \"hud\");\n const host = layer.element;\n if (host === null) {\n this.#pad = null;\n this.#knob = null;\n return;\n }\n const document = host.ownerDocument;\n const pad = document.createElement(\"div\");\n pad.className = UI_CLASS_NAMES.joystick;\n pad.setAttribute(\"role\", \"application\");\n pad.setAttribute(\"aria-label\", options.ariaLabel ?? this.#control);\n for (const [name, value] of Object.entries(options.style ?? {})) {\n pad.style.setProperty(name, value);\n }\n const knob = document.createElement(\"div\");\n knob.className = UI_CLASS_NAMES.joystickKnob;\n pad.append(knob);\n host.append(pad);\n this.#pad = pad;\n this.#knob = knob;\n pad.addEventListener(\"pointerdown\", this.#onPointerDown);\n pad.addEventListener(\"pointermove\", this.#onPointerMove);\n pad.addEventListener(\"pointerup\", this.#onPointerUp);\n pad.addEventListener(\"pointercancel\", this.#onPointerUp);\n this.#device.setVector(this.#control, 0, 0);\n }\n\n /**\n * The pad element, so a template can restyle or reposition it.\n *\n * @returns The element, or `null` when the app has no DOM overlay.\n */\n get element(): HTMLDivElement | null {\n return this.#pad;\n }\n\n /**\n * The control this stick writes.\n *\n * @returns The name, as it appears after `<Virtual>/`.\n */\n get control(): string {\n return this.#control;\n }\n\n /**\n * Whether a pointer currently holds the stick.\n *\n * @returns `true` while the stick is being dragged.\n */\n get isActive(): boolean {\n return this.#pointerId !== null;\n }\n\n /** Removes the widget, unsubscribes, and centres the control. */\n dispose(): void {\n if (this.#disposed) {\n return;\n }\n this.#disposed = true;\n const pad = this.#pad;\n if (pad !== null) {\n pad.removeEventListener(\"pointerdown\", this.#onPointerDown);\n pad.removeEventListener(\"pointermove\", this.#onPointerMove);\n pad.removeEventListener(\"pointerup\", this.#onPointerUp);\n pad.removeEventListener(\"pointercancel\", this.#onPointerUp);\n pad.remove();\n }\n this.#device.setVector(this.#control, 0, 0);\n }\n\n /**\n * Reads one pointer position and writes the control.\n *\n * @param event - The pointer event.\n */\n #move(event: PointerEvent): void {\n const dx = event.clientX - this.#originX;\n // Screen `+Y` points down and the world's points up, so the vertical axis is negated here and\n // nowhere else — the same convention the templates' own widget used.\n const dy = this.#originY - event.clientY;\n const length = Math.hypot(dx, dy);\n const scale = length > this.#radius ? this.#radius / length : 1;\n this.#knob?.style.setProperty(\"transform\", `translate(${String(dx * scale)}px, ${String(-dy * scale)}px)`);\n this.#device.setVector(\n this.#control,\n stickAxis(dx, length, this.#radius, this.#deadZone),\n stickAxis(dy, length, this.#radius, this.#deadZone),\n );\n }\n\n /** Centres the knob and the control. */\n #release(): void {\n this.#pointerId = null;\n this.#knob?.style.setProperty(\"transform\", \"translate(0px, 0px)\");\n this.#device.setVector(this.#control, 0, 0);\n }\n}\n"],"mappings":";;;;;;;;;;;;AAkCA,SAAgB,oBAAoB,KAAuB,MAAoB;CAC7E,IAAI,kBAAkB,YAAqB,IAAI;AACjD;;;;;;;;;;AAWA,SAAgB,sBAAsB,KAAuB,SAA4B;CACvF,IAAI,kBAAkB,cAAuB,OAAO;AACtD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACjBA,MAAa,qBAAqB;;;;;AAMlC,MAAM,uBAA0C,OAAO,OAAO;CAC5D;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;;;;AAiBD,SAAS,UAAU,WAA2B,MAA6B;CACzE,MAAM,SAAS,UAAU;CACzB,IAAI,OAAO,WAAW,YACpB,OAAO;CAET,MAAM,QAAiB,QAAQ,MAAM,QAAQ,WAAW,CAAC,IAAI,CAAC;CAC9D,OAAO,OAAO,UAAU,WAAW,QAAQ;AAC7C;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,kBAAkB,MAAwB;CACxD,IAAI,SAAS,QAAQ,OAAO,SAAS,UACnC,OAAO;CAET,MAAM,YAA4B;CAClC,MAAM,WAAW,UAAU,WAAW,kBAAkB;CACxD,IAAI,aAAa,WACf,OAAO;CAET,IAAI,aAAa,UACf,OAAO;CAET,IAAI,UAAU,sBAAsB,MAClC,OAAO;CAET,MAAM,UAAU,OAAO,UAAU,YAAY,WAAW,UAAU,QAAQ,YAAY,IAAI;CAC1F,IAAI,YAAY,cAAc,YAAY,UACxC,OAAO;CAET,IAAI,YAAY,SACd,OAAO;CAET,MAAM,OAAO,OAAO,UAAU,SAAS,WAAW,UAAU,KAAK,YAAY,IAAI;CACjF,OAAO,CAAC,qBAAqB,SAAS,IAAI;AAC5C;;;;;;;;;;;;AAyBA,IAAa,iBAAb,MAA4B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.ts","../src/settings.ts","../src/dom/styles.ts","../src/dom/layer.ts","../src/dom/scaling.ts","../src/dom/host.ts","../src/errors.ts","../src/dom/dom-target.ts","../src/i18n/locale-file.ts","../src/i18n/message.ts","../src/i18n/i18n-service.ts","../src/i18n/loader.ts","../src/lite/gpu/text-renderer.ts","../src/lite/text.ts","../src/text/hud-layout.ts","../src/text/text-component.ts","../src/text/hud-text.ts","../src/text/text-runtime.ts","../src/text/world-text-2d.ts","../src/text/world-text.ts","../src/version.ts","../src/world/anchor-math.ts","../src/world/world-anchor.ts","../src/world/ui-system.ts","../src/extension.ts","../src/schemas.ts","../src/widgets/dialog.ts","../src/widgets/loading-screen.ts","../src/widgets/menu-row.ts","../src/widgets/menu.ts","../src/widgets/menu-stack.ts","../src/widgets/toast.ts","../src/widgets/virtual-device.ts","../src/widgets/virtual-button.ts","../src/widgets/virtual-joystick.ts"],"sourcesContent":["import type { UiHost } from \"./dom/host.js\";\nimport type { I18nService } from \"./i18n/i18n-service.js\";\nimport type { ExtensionContext } from \"@ignifx/core\";\n\n/**\n * Import core before augmenting it so TypeScript resolves the target module.\n * Keep the barrel's bare augmentation import: declaration bundling otherwise drops these types.\n * The augmentation emits no runtime registration (docs/architecture/03-scripting-and-components.md §7).\n */\n\ndeclare module \"@ignifx/core\" {\n interface App {\n /**\n * The DOM overlay host (`docs/architecture/13-ui.md` §1): the root over the canvas, the named\n * layers, the scaling modes, the safe-area variables, and the focus flag.\n */\n readonly ui: UiHost;\n /**\n * The localization service (`docs/architecture/13-ui.md` §3): `.i18n.json` documents,\n * `{name}` interpolation, ICU-style plurals, and the active locale.\n */\n readonly i18n: I18nService;\n }\n}\n\n/**\n * Defines `app.ui`, pairing with the augmentation above.\n *\n * @param ctx - The extension registration surface.\n * @param host - The host the property returns.\n * @throws IgnifxError with code `IGX-0401` when something already defined `app.ui`.\n *\n * @internal\n */\nexport function defineUiAppProperty(ctx: ExtensionContext, host: UiHost): void {\n ctx.defineAppProperty(\"ui\", (): unknown => host);\n}\n\n/**\n * Defines `app.i18n`, pairing with the augmentation above.\n *\n * @param ctx - The extension registration surface.\n * @param service - The service the property returns.\n * @throws IgnifxError with code `IGX-0401` when something already defined `app.i18n`.\n *\n * @internal\n */\nexport function defineI18nAppProperty(ctx: ExtensionContext, service: I18nService): void {\n ctx.defineAppProperty(\"i18n\", (): unknown => service);\n}\n","/**\n * Focus routing (`docs/architecture/13-ui.md` §1, `08-input.md` §5).\n *\n * ## What `@ignifx/input` does and does not do\n *\n * `InputService.uiHasFocus` is a **plain settable property**; its own documentation says so —\n * \"`@ignifx/ui` assigns it\"* (`packages/input/src/service/input-service.ts` 340-349). Nothing in\n * `@ignifx/input` watches the DOM for it: `FocusSource` subscribes only to `blur` and\n * `visibilitychange`, and translates both into one `releaseAll`. So the policy for *what counts as\n * a focused text field* is defined here, by this module, and this module is the only thing that\n * ever writes the flag. While it is `true`, `Binding.readRef` reports every keyboard control as\n * released (`packages/input/src/bindings/binding.ts` 330 and 350), which is what makes typing in a\n * field stop firing actions; pointer and gamepad controls are untouched.\n *\n * ## The policy\n *\n * An element takes the keyboard when it is a text-entry element: a `<textarea>`, a `<select>`, a\n * `contenteditable` element, or an `<input>` whose type is not one of the button-like or\n * slider-like types (which games legitimately want to drive with the keyboard *and* have the\n * player use). Two data attributes override the guess in either direction, for the widgets a\n * framework builds out of `<div role=\"textbox\">` and for the search box a game wants to keep\n * transparent to gameplay:\n *\n * - `data-ignifx-focus=\"capture\"` — always takes the keyboard.\n * - `data-ignifx-focus=\"ignore\"` — never takes it.\n */\n\n/**\n * The attribute that overrides the editability guess in either direction.\n *\n * @public\n */\nexport const UI_FOCUS_ATTRIBUTE = \"data-ignifx-focus\";\n\n/**\n * The `<input>` types that are **not** text entry: a player may want to drive them with the\n * keyboard, so focusing one must not stop gameplay actions.\n */\nconst NON_TEXT_INPUT_TYPES: readonly string[] = Object.freeze([\n \"button\",\n \"checkbox\",\n \"color\",\n \"file\",\n \"hidden\",\n \"image\",\n \"radio\",\n \"range\",\n \"reset\",\n \"submit\",\n]);\n\n/** The element members this module reads, so a fake in a node test only has to provide these. */\ninterface FocusCandidate {\n readonly tagName?: unknown;\n readonly type?: unknown;\n readonly isContentEditable?: unknown;\n readonly getAttribute?: unknown;\n}\n\n/**\n * Reads one attribute off a candidate without assuming it is a real `Element`.\n *\n * @param candidate - The focused node.\n * @param name - The attribute name.\n * @returns The attribute's value, or `null` when there is none or the node cannot answer.\n */\nfunction attribute(candidate: FocusCandidate, name: string): string | null {\n const getter = candidate.getAttribute;\n if (typeof getter !== \"function\") {\n return null;\n }\n const value: unknown = Reflect.apply(getter, candidate, [name]);\n return typeof value === \"string\" ? value : null;\n}\n\n/**\n * Reports whether a focused node is a text-entry element, and therefore owns the keyboard.\n *\n * @remarks\n * Deliberately structural rather than `instanceof HTMLInputElement`: the same function then answers\n * for a real element in Chromium and for the fake DOM the node suite builds, and two documents in\n * one page (an `<iframe>`) do not need their constructors to match.\n *\n * @param node - The node that just received focus, or `null`.\n * @returns `true` when typing into it must stop keyboard actions from firing.\n *\n * @example\n * ```ts\n * const field = document.createElement(\"input\");\n * isEditableElement(field); // true — an <input> with no type is a text field\n * ```\n *\n * @public\n */\nexport function isEditableElement(node: unknown): boolean {\n if (node === null || typeof node !== \"object\") {\n return false;\n }\n const candidate: FocusCandidate = node;\n const override = attribute(candidate, UI_FOCUS_ATTRIBUTE);\n if (override === \"capture\") {\n return true;\n }\n if (override === \"ignore\") {\n return false;\n }\n if (candidate.isContentEditable === true) {\n return true;\n }\n const tagName = typeof candidate.tagName === \"string\" ? candidate.tagName.toUpperCase() : \"\";\n if (tagName === \"TEXTAREA\" || tagName === \"SELECT\") {\n return true;\n }\n if (tagName !== \"INPUT\") {\n return false;\n }\n const type = typeof candidate.type === \"string\" ? candidate.type.toLowerCase() : \"text\";\n return !NON_TEXT_INPUT_TYPES.includes(type);\n}\n\n/**\n * What {@link UiFocusWatcher} needs.\n *\n * @internal\n */\nexport interface UiFocusWatcherOptions {\n /** The document `focusin` and `focusout` are read from. */\n readonly document: Document;\n /** Called whenever the answer changes; the host forwards it to `app.input.uiHasFocus`. */\n readonly onChanged: (hasFocus: boolean) => void;\n}\n\n/**\n * Watches the document's focus and reports whether a text field owns the keyboard.\n *\n * @remarks\n * Scoped to the whole document rather than to `app.ui.root`, because a game may portal a menu\n * anywhere — a React portal on `document.body`, a `<dialog>` in the top layer — and a field that\n * fires gameplay actions is a bug wherever it lives. `focusout` re-reads `document.activeElement`\n * rather than trusting `relatedTarget`, which is `null` for a blur that leaves the page entirely.\n *\n * @internal\n */\nexport class UiFocusWatcher {\n readonly #document: Document;\n\n readonly #onChanged: (hasFocus: boolean) => void;\n\n #hasFocus = false;\n\n #attached = false;\n\n readonly #onFocusIn = (event: Event): void => {\n this.#set(isEditableElement(event.target));\n };\n\n readonly #onFocusOut = (): void => {\n // `focusout` fires *before* the new element is focused, so the answer is read on the next\n // microtask — by which time `activeElement` is the element that actually took focus, or the\n // body when nothing did.\n void Promise.resolve().then((): void => {\n if (this.#attached) {\n this.#set(isEditableElement(this.#document.activeElement));\n }\n });\n };\n\n /**\n * Builds the watcher. It subscribes nothing until {@link UiFocusWatcher.attach} is called.\n *\n * @param options - The document to watch and the callback to report through.\n */\n constructor(options: UiFocusWatcherOptions) {\n this.#document = options.document;\n this.#onChanged = options.onChanged;\n }\n\n /**\n * Whether a text field currently owns the keyboard.\n *\n * @returns The last reported answer.\n */\n get hasFocus(): boolean {\n return this.#hasFocus;\n }\n\n /** Subscribes to the document, and reports the element that is already focused. */\n attach(): void {\n if (this.#attached) {\n return;\n }\n this.#attached = true;\n this.#document.addEventListener(\"focusin\", this.#onFocusIn);\n this.#document.addEventListener(\"focusout\", this.#onFocusOut);\n this.#set(isEditableElement(this.#document.activeElement));\n }\n\n /** Unsubscribes and reports `false`, so a disposed overlay never leaves the keyboard captured. */\n detach(): void {\n if (!this.#attached) {\n return;\n }\n this.#attached = false;\n this.#document.removeEventListener(\"focusin\", this.#onFocusIn);\n this.#document.removeEventListener(\"focusout\", this.#onFocusOut);\n this.#set(false);\n }\n\n /**\n * Reports a new answer, if it changed.\n *\n * @param value - The new answer.\n */\n #set(value: boolean): void {\n if (this.#hasFocus === value) {\n return;\n }\n this.#hasFocus = value;\n this.#onChanged(value);\n }\n}\n","import { array, bool, defineSchema, enumOf, str, u32 } from \"@ignifx/core\";\nimport type { Schema } from \"@ignifx/core\";\n\n/**\n * The `ui` project settings section (`docs/architecture/04-extensions.md` §5, `13-ui.md` §1).\n * Everything here is what a game writes in `ignifx.config.ts`; the knobs a game changes per frame\n * live on `app.ui` and on the individual layers instead.\n */\n\n/**\n * The section name as it appears in `ignifx.config.ts`.\n *\n * @public\n */\nexport const UI_SETTINGS_SECTION = \"ui\";\n\n/**\n * Every scaling mode the overlay host supports, in the order an inspector should list them\n * (`docs/architecture/13-ui.md` §1).\n *\n * @public\n */\nexport const UI_SCALING_MODES = [\"css\", \"fit\", \"dpi\"] as const;\n\n/**\n * How the overlay's coordinate system relates to the canvas.\n *\n * @remarks\n * - `\"css\"` — one UI unit is one CSS pixel and nothing is scaled. The browser default, and what a\n * responsive HTML menu wants.\n * - `\"fit\"` — the root is exactly {@link UiSettings.referenceResolution} CSS pixels and is scaled\n * uniformly to fit inside the canvas, keeping aspect and centring the letterbox. A HUD authored\n * once at 1920x1080 then looks the same on every window size.\n * - `\"dpi\"` — one UI unit is one **render-target** pixel: the root is sized to the canvas's\n * backing store and scaled by `1 / devicePixelRatio` so it still covers the same area. This is\n * the space `Camera.worldToScreen`, `HudText`, and `app.renderer.captureScreenshot()` all work\n * in, so an element placed at `left: 100px` lands on render-target column 100 exactly.\n *\n * @public\n */\nexport type UiScalingMode = (typeof UI_SCALING_MODES)[number];\n\n/**\n * The resolved `ui` settings section.\n *\n * @example\n * ```ts\n * // ignifx.config.ts\n * export default defineConfig({\n * ui: { scaling: \"fit\", referenceResolution: [640, 360], layers: [\"hud\", \"menu\"] },\n * });\n * ```\n *\n * @public\n */\nexport interface UiSettings {\n /** How the overlay's coordinate system relates to the canvas. Defaults to `\"css\"`. */\n readonly scaling: UiScalingMode;\n /**\n * The `[width, height]`, in UI units, that `\"fit\"` scales to. Ignored by the other two modes.\n * Defaults to `[1920, 1080]`.\n */\n readonly referenceResolution: readonly number[];\n /**\n * The layers created eagerly, back to front. Declaring them here is what makes their stacking\n * order independent of the order the game happens to call {@link UiHost.layer} in.\n */\n readonly layers: readonly string[];\n /** Whether the overlay is shown at all. Defaults to `true`. */\n readonly visible: boolean;\n}\n\n/**\n * The z-index step between two consecutive layers. The first declared layer sits at\n * `UI_LAYER_Z_STEP`, the second at twice that, and so on, which leaves nine free slots between any\n * two layers for a game that wants to interleave its own elements.\n *\n * @public\n */\nexport const UI_LAYER_Z_STEP = 10;\n\n/**\n * The values used for everything a project omits.\n *\n * @returns The default `ui` section.\n *\n * @public\n */\nexport function defaultUiSettings(): UiSettings {\n return { scaling: \"css\", referenceResolution: [1920, 1080], layers: [\"hud\", \"menu\", \"overlay\"], visible: true };\n}\n\n/**\n * The schema the `ui` section is validated against.\n *\n * @returns The schema, built fresh so no module holds state (`CONSTITUTION.md` §3.5).\n *\n * @public\n */\nexport function uiSettingsSchema(): Schema {\n return defineSchema({\n scaling: enumOf(UI_SCALING_MODES, \"css\", { tooltip: \"How the overlay's units map onto the canvas.\" }),\n referenceResolution: array(u32(1), [1920, 1080], {\n tooltip: 'The [width, height] the \"fit\" mode scales to.',\n }),\n layers: array(str(), [\"hud\", \"menu\", \"overlay\"], {\n tooltip: \"The layers created up front, back to front.\",\n }),\n visible: bool(true, { tooltip: \"Whether the overlay is shown.\" }),\n });\n}\n","/**\n * The one stylesheet `@ignifx/ui` injects, and the class names it defines\n * (`docs/architecture/13-ui.md` §3: *\"plain DOM helper classes with no styling opinions beyond a\n * minimal stylesheet; templates ship their own CSS\"*).\n *\n * The rules do only what a game cannot reasonably be asked to repeat: position the root over the\n * canvas, make it click-through, and give the helper widgets a shape that is visible before any\n * game CSS loads. No rule uses `!important`, and every rule is a single class selector — except the\n * two that carry a state a game must not be able to defeat by accident: `.ignifx-ui-menu[hidden]`,\n * which is what actually hides a menu, and the `[data-focused]` / `[data-disabled]` row states,\n * which a game restyles by writing the same selector.\n */\n\n/**\n * The `id` of the injected `<style>` element, so a second app in one document reuses it.\n *\n * @public\n */\nexport const UI_STYLE_ELEMENT_ID = \"ignifx-ui-styles\";\n\n/**\n * The `z-index` a `Dialog` is drawn at inside its layer.\n *\n * @remarks\n * A dialog is modal, and a modal that paints under the panel that opened it swallows every click\n * on that panel. Siblings with no `z-index` paint in DOM order, so a `Dialog` created before a\n * `Menu` in the same layer would lose; giving every dialog one number puts it above every other\n * root of its layer whatever order they were built in. Two dialogs in one layer still stack in DOM\n * order, and `DialogOptions.zIndex` overrides the number for a dialog that must sit elsewhere.\n *\n * @public\n */\nexport const UI_DIALOG_Z_INDEX = 1000;\n\n/**\n * The class names the host and the helper widgets set, so a template's CSS can target them without\n * guessing (`docs/architecture/13-ui.md` §3).\n *\n * @public\n */\nexport const UI_CLASS_NAMES = {\n /** The overlay root. */\n root: \"ignifx-ui-root\",\n /** A named layer inside the root. */\n layer: \"ignifx-ui-layer\",\n /** Anything that should receive pointer events; the root does not. */\n interactive: \"ignifx-ui-interactive\",\n /** A `Dialog`'s outermost element. */\n dialog: \"ignifx-ui-dialog\",\n /** A `Dialog`'s backdrop. */\n dialogBackdrop: \"ignifx-ui-dialog-backdrop\",\n /** A `Dialog`'s panel. */\n dialogPanel: \"ignifx-ui-dialog-panel\",\n /** A `Dialog`'s title. */\n dialogTitle: \"ignifx-ui-dialog-title\",\n /** A `Dialog`'s message. */\n dialogMessage: \"ignifx-ui-dialog-message\",\n /** A `Dialog`'s button row. */\n dialogButtons: \"ignifx-ui-dialog-buttons\",\n /** One `Dialog` button. */\n dialogButton: \"ignifx-ui-dialog-button\",\n /** A `Menu`'s outermost panel. */\n menu: \"ignifx-ui-menu\",\n /** A `Menu`'s heading. */\n menuTitle: \"ignifx-ui-menu-title\",\n /** A `Menu`'s subtitle. */\n menuSubtitle: \"ignifx-ui-menu-subtitle\",\n /** The list a `Menu`'s rows are appended to. */\n menuRows: \"ignifx-ui-menu-rows\",\n /** One selectable `Menu` row. */\n menuRow: \"ignifx-ui-menu-row\",\n /** A `Menu` row's left-hand text. */\n menuRowLabel: \"ignifx-ui-menu-row-label\",\n /** A `Menu` row's right-hand text. */\n menuRowValue: \"ignifx-ui-menu-row-value\",\n /** A `Menu` slider row's range input. */\n menuRowSlider: \"ignifx-ui-menu-row-slider\",\n /** A `Menu`'s `\"heading\"` row. */\n menuHeading: \"ignifx-ui-menu-heading\",\n /** A `Menu`'s `\"separator\"` row. */\n menuSeparator: \"ignifx-ui-menu-separator\",\n /** A `Toast`'s stack container. */\n toastStack: \"ignifx-ui-toasts\",\n /** One toast. */\n toast: \"ignifx-ui-toast\",\n /** A `LoadingScreen`'s outermost element. */\n loading: \"ignifx-ui-loading\",\n /** A `LoadingScreen`'s label. */\n loadingLabel: \"ignifx-ui-loading-label\",\n /** A `LoadingScreen`'s progress track. */\n loadingTrack: \"ignifx-ui-loading-track\",\n /** A `LoadingScreen`'s progress bar. */\n loadingBar: \"ignifx-ui-loading-bar\",\n /** A `VirtualJoystick`'s outer pad. */\n joystick: \"ignifx-ui-joystick\",\n /** A `VirtualJoystick`'s knob. */\n joystickKnob: \"ignifx-ui-joystick-knob\",\n /** A `VirtualButton`. */\n button: \"ignifx-ui-button\",\n} as const;\n\n/**\n * The CSS custom properties the root carries, so game CSS can read the safe area and the current\n * scale without measuring anything (`docs/architecture/13-ui.md` §1).\n *\n * @public\n */\nexport const UI_CSS_VARIABLES = {\n /** The top safe-area inset, from `env(safe-area-inset-top)`. */\n safeTop: \"--ignifx-safe-top\",\n /** The right safe-area inset. */\n safeRight: \"--ignifx-safe-right\",\n /** The bottom safe-area inset. */\n safeBottom: \"--ignifx-safe-bottom\",\n /** The left safe-area inset. */\n safeLeft: \"--ignifx-safe-left\",\n /** The uniform scale the root is drawn at, as a bare number. */\n scale: \"--ignifx-ui-scale\",\n} as const;\n\n/**\n * The stylesheet text.\n *\n * @remarks\n * A function rather than a module constant so nothing but a declaration lives at module scope\n * (`CONSTITUTION.md` §3.5, and the `ignifx/no-module-side-effects` rule).\n *\n * @returns The CSS the host injects once per document.\n *\n * @internal\n */\nexport function uiStyleSheet(): string {\n const c = UI_CLASS_NAMES;\n return [\n `.${c.root}{position:absolute;top:0;left:0;pointer-events:none;overflow:hidden;transform-origin:0 0;}`,\n `.${c.layer}{position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none;}`,\n `.${c.interactive}{pointer-events:auto;}`,\n `.${c.dialog}{position:absolute;top:0;left:0;width:100%;height:100%;display:flex;` +\n `align-items:center;justify-content:center;pointer-events:auto;z-index:${String(UI_DIALOG_Z_INDEX)};}`,\n `.${c.dialogBackdrop}{position:absolute;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);}`,\n `.${c.dialogPanel}{position:relative;min-width:12rem;padding:1rem;border-radius:0.5rem;` +\n `background:#1b1d22;color:#f5f5f5;font:inherit;}`,\n `.${c.dialogTitle}{margin:0 0 0.5rem;font-size:1.1em;}`,\n `.${c.dialogMessage}{margin:0 0 1rem;}`,\n `.${c.dialogButtons}{display:flex;gap:0.5rem;justify-content:flex-end;}`,\n `.${c.dialogButton}{padding:0.4rem 0.9rem;border:0;border-radius:0.25rem;background:#3a6df0;` +\n `color:#fff;font:inherit;cursor:pointer;}`,\n `.${c.menu}{position:absolute;top:0;left:0;width:100%;height:100%;display:flex;` +\n `flex-direction:column;align-items:center;justify-content:center;gap:0.5rem;pointer-events:auto;}`,\n // The UA rule for `[hidden]` is a type selector, so a game's own `.ignifx-ui-menu { display: … }`\n // would beat it; this class-plus-attribute selector stays ahead of a single-class rule without\n // an `!important`.\n `.${c.menu}[hidden]{display:none;}`,\n `.${c.menuRows}{display:flex;flex-direction:column;min-width:12rem;max-height:100%;overflow:auto;}`,\n `.${c.menuRow}{display:flex;align-items:center;justify-content:space-between;gap:0.75rem;` +\n `padding:0.4rem 0.75rem;border:1px solid transparent;border-radius:0.25rem;background:transparent;` +\n `color:inherit;font:inherit;text-align:left;cursor:pointer;}`,\n `.${c.menuRow}[data-focused]{border-color:currentColor;background:rgba(255,255,255,0.1);}`,\n `.${c.menuRow}[data-disabled]{opacity:0.4;cursor:default;}`,\n `.${c.menuHeading}{padding:0.6rem 0.75rem 0.2rem;opacity:0.6;}`,\n `.${c.menuSeparator}{margin:0.4rem 0.75rem;border-top:1px solid currentColor;opacity:0.25;}`,\n `.${c.toastStack}{position:absolute;right:1rem;bottom:1rem;display:flex;flex-direction:column;` +\n `gap:0.5rem;align-items:flex-end;}`,\n `.${c.toast}{padding:0.5rem 0.9rem;border-radius:0.25rem;background:#1b1d22;color:#f5f5f5;}`,\n `.${c.loading}{position:absolute;top:0;left:0;width:100%;height:100%;display:flex;` +\n `flex-direction:column;align-items:center;justify-content:center;gap:0.75rem;` +\n `background:#0d0f12;color:#f5f5f5;pointer-events:auto;}`,\n `.${c.loadingTrack}{width:60%;max-width:24rem;height:0.5rem;border-radius:0.25rem;background:#2a2e36;}`,\n `.${c.loadingBar}{height:100%;width:0;border-radius:0.25rem;background:#3a6df0;}`,\n `.${c.joystick}{position:absolute;width:7rem;height:7rem;border-radius:50%;` +\n `background:rgba(255,255,255,0.12);touch-action:none;pointer-events:auto;}`,\n `.${c.joystickKnob}{position:absolute;top:50%;left:50%;width:3rem;height:3rem;margin:-1.5rem 0 0 -1.5rem;` +\n `border-radius:50%;background:rgba(255,255,255,0.35);}`,\n `.${c.button}{position:absolute;width:4rem;height:4rem;border:0;border-radius:50%;` +\n `background:rgba(255,255,255,0.2);color:#fff;font:inherit;touch-action:none;pointer-events:auto;}`,\n ].join(\"\\n\");\n}\n\n/**\n * Injects the stylesheet into a document, once.\n *\n * @remarks\n * Keyed by {@link UI_STYLE_ELEMENT_ID}, so two apps sharing a document share one `<style>` element\n * and neither removes the other's (`CONSTITUTION.md` §3.6). Nothing removes it: a stylesheet with\n * no matching elements costs nothing, and unmounting it would break the app that is still running.\n *\n * It is **prepended** to the head rather than appended, which is what actually makes this file's\n * promise true. The overlay is built inside `createApp`, long after the page's own `<style>` and\n * `<link>` elements have been parsed; appending would put every package rule *after* the game's,\n * and a game rule of equal specificity would silently lose. Prepending puts the defaults where\n * defaults belong — first — so a single-class rule in the game's stylesheet wins on order.\n *\n * @param document - The document to inject into.\n *\n * @internal\n */\nexport function ensureUiStyles(document: Document): void {\n // `getElementById` rather than `querySelector`: the id is the whole query, and the node test's\n // fake document then needs one method instead of a selector parser.\n // oxlint-disable-next-line unicorn/prefer-query-selector\n if (document.getElementById(UI_STYLE_ELEMENT_ID) !== null) {\n return;\n }\n const style = document.createElement(\"style\");\n style.id = UI_STYLE_ELEMENT_ID;\n style.textContent = uiStyleSheet();\n document.head.prepend(style);\n}\n","import { UI_CLASS_NAMES } from \"./styles.js\";\n\n/**\n * One named stacking layer inside the overlay root (`docs/architecture/13-ui.md` §1:\n * \"games mount React/Preact/Svelte/Vue/vanilla trees into it, or into named layers\"*).\n *\n * A layer is a plain absolutely-positioned `<div>` that fills the root, carries a `z-index`, and is\n * `pointer-events: none` like the root — children opt in with the\n * {@link UI_CLASS_NAMES.interactive} class or their own CSS. Under a headless app the layer still\n * exists as an object, with `element` `null` and every mutation a no-op, so game code never has to\n * branch on the environment.\n */\n\n/**\n * Options accepted by `app.ui.layer`.\n *\n * @public\n */\nexport interface UiLayerOptions {\n /** The stacking order. Defaults to the layer's declaration index times `UI_LAYER_Z_STEP`. */\n readonly zIndex?: number;\n /** Whether the layer starts visible. Defaults to `true`. */\n readonly visible?: boolean;\n}\n\n/**\n * A named layer of the overlay.\n *\n * @example\n * ```ts\n * const hud = app.ui.layer(\"hud\");\n * hud.element?.append(document.createElement(\"div\"));\n * hud.visible = false;\n * ```\n *\n * @public\n */\nexport class UiLayer {\n /** The name the layer is addressed by. */\n readonly name: string;\n\n #element: HTMLDivElement | null;\n\n #zIndex: number;\n\n #visible: boolean;\n\n /**\n * Builds a layer. `app.ui.layer` does this; a game never constructs one.\n *\n * @param name - The layer name.\n * @param element - The layer's element, or `null` under a headless app.\n * @param zIndex - The initial stacking order.\n * @param visible - Whether the layer starts visible.\n *\n * @internal\n */\n constructor(name: string, element: HTMLDivElement | null, zIndex: number, visible: boolean) {\n this.name = name;\n this.#element = element;\n this.#zIndex = zIndex;\n this.#visible = visible;\n if (element !== null) {\n this.#dress(element);\n }\n }\n\n /**\n * Gives a layer that was created before the overlay mounted its element.\n *\n * @remarks\n * The host builds its root when the world is created, which is after every extension registered;\n * a layer declared in the `ui` settings section therefore exists as an object first and gets its\n * element a moment later. Nothing observable changes: an unmounted layer is exactly a headless\n * one.\n *\n * @param element - The layer's element.\n *\n * @internal\n */\n attach(element: HTMLDivElement): void {\n this.#element = element;\n this.#dress(element);\n }\n\n /**\n * The layer's element, or `null` when the app has no DOM overlay.\n *\n * @returns The `<div>` a game mounts its tree into.\n */\n get element(): HTMLDivElement | null {\n return this.#element;\n }\n\n /**\n * The layer's stacking order within the root.\n *\n * @returns The `z-index`.\n */\n get zIndex(): number {\n return this.#zIndex;\n }\n\n // eslint-disable-next-line jsdoc/require-jsdoc -- the accessor pair is documented on the getter.\n set zIndex(value: number) {\n if (this.#zIndex === value) {\n return;\n }\n this.#zIndex = value;\n this.#applyZIndex();\n }\n\n /**\n * Whether the layer is shown. Hiding a layer hides everything mounted in it without unmounting\n * anything, which is what a pause menu wants.\n *\n * @returns `true` while the layer is shown.\n */\n get visible(): boolean {\n return this.#visible;\n }\n\n // eslint-disable-next-line jsdoc/require-jsdoc -- the accessor pair is documented on the getter.\n set visible(value: boolean) {\n if (this.#visible === value) {\n return;\n }\n this.#visible = value;\n this.#applyVisibility();\n }\n\n /**\n * Removes every child of the layer without removing the layer itself.\n *\n * @remarks\n * A no-op under a headless app.\n */\n clear(): void {\n const element = this.#element;\n if (element !== null) {\n element.replaceChildren();\n }\n }\n\n /**\n * Writes the layer's name, class, order, and visibility onto a fresh element.\n *\n * @param element - The element to dress.\n */\n #dress(element: HTMLDivElement): void {\n element.className = UI_CLASS_NAMES.layer;\n element.dataset[\"ignifxLayer\"] = this.name;\n this.#applyZIndex();\n this.#applyVisibility();\n }\n\n /** Writes the current `z-index` onto the element. */\n #applyZIndex(): void {\n this.#element?.style.setProperty(\"z-index\", String(this.#zIndex));\n }\n\n /** Writes the current visibility onto the element. */\n #applyVisibility(): void {\n this.#element?.style.setProperty(\"display\", this.#visible ? \"block\" : \"none\");\n }\n}\n","import type { UiScalingMode } from \"../settings.js\";\n\n/**\n * The scaling arithmetic behind `app.ui.scaling` (`docs/architecture/13-ui.md` §1). Every function\n * here is pure: it takes measurements and returns numbers, so the three modes are unit-testable\n * under Node with no DOM at all, and the host is left with nothing but the DOM writes.\n *\n * ## The three coordinate systems\n *\n * A canvas has two sizes: its **CSS** size, which is what layout and pointer coordinates use, and\n * its **backing-store** size (`canvas.width`/`canvas.height`), which is what WebGPU renders into.\n * Their ratio is the effective device pixel ratio. `Camera.worldToScreen`, Lite's text renderer,\n * and `app.renderer.captureScreenshot()` all work in backing-store pixels; a DOM element is placed\n * in CSS pixels. A \"UI unit\" is whichever of the two — or neither — the scaling mode picks:\n *\n * | Mode | One UI unit is | Root size | Scale |\n * | ------- | -------------------- | ------------------------ | ---------------------------- |\n * | `\"css\"` | one CSS pixel | the canvas's CSS size | `1` |\n * | `\"fit\"` | one reference pixel | `referenceResolution` | `min(cssW/refW, cssH/refH)` |\n * | `\"dpi\"` | one backing pixel | the canvas's pixel size | `cssW / backingW` |\n */\n\n/**\n * The two sizes of the canvas the overlay covers, both measured by the host.\n *\n * @public\n */\nexport interface UiSurfaceMetrics {\n /** The canvas's laid-out width, in CSS pixels. */\n readonly cssWidth: number;\n /** The canvas's laid-out height, in CSS pixels. */\n readonly cssHeight: number;\n /** The canvas's backing-store width, in device pixels — `canvas.width`. */\n readonly deviceWidth: number;\n /** The canvas's backing-store height, in device pixels — `canvas.height`. */\n readonly deviceHeight: number;\n}\n\n/**\n * Where the overlay root sits and how big it is, in the units the mode chose.\n *\n * @public\n */\nexport interface UiLayout {\n /** The mode this layout was computed for. */\n readonly mode: UiScalingMode;\n /** The root's width, in UI units. */\n readonly width: number;\n /** The root's height, in UI units. */\n readonly height: number;\n /** The uniform CSS scale applied to the root. */\n readonly scale: number;\n /** The root's left edge, in CSS pixels from the canvas's left edge. */\n readonly offsetX: number;\n /** The root's top edge, in CSS pixels from the canvas's top edge. */\n readonly offsetY: number;\n}\n\n/** The smallest size any measurement is treated as, so no ratio divides by zero. */\nconst MIN_EXTENT = 1;\n\n/**\n * Clamps a measurement to something a ratio can safely divide by.\n *\n * @param value - The measured extent.\n * @returns The extent, or {@link MIN_EXTENT} when it is absent, zero, or not a finite number.\n */\nfunction extent(value: number): number {\n return Number.isFinite(value) && value > 0 ? value : MIN_EXTENT;\n}\n\n/**\n * The `[width, height]` a `\"fit\"` layout scales to, with both entries made safe.\n *\n * @param reference - The `ui.referenceResolution` setting.\n * @returns The width and height, each at least {@link MIN_EXTENT}.\n *\n * @internal\n */\nexport function resolveReferenceResolution(reference: readonly number[]): { width: number; height: number } {\n return { width: extent(reference[0] ?? 0), height: extent(reference[1] ?? 0) };\n}\n\n/**\n * Computes the overlay root's size, scale, and offset for one mode and one measured canvas.\n *\n * @param mode - The scaling mode.\n * @param metrics - The canvas's CSS and backing-store sizes.\n * @param reference - The `[width, height]` a `\"fit\"` layout scales to; ignored by the other modes.\n * @returns The layout to write onto the root.\n *\n * @example\n * ```ts\n * computeUiLayout(\"fit\", { cssWidth: 800, cssHeight: 600, deviceWidth: 800, deviceHeight: 600 }, [\n * 400, 300,\n * ]).scale; // 2\n * ```\n *\n * @public\n */\nexport function computeUiLayout(\n mode: UiScalingMode,\n metrics: UiSurfaceMetrics,\n reference: readonly number[],\n): UiLayout {\n const cssWidth = extent(metrics.cssWidth);\n const cssHeight = extent(metrics.cssHeight);\n if (mode === \"fit\") {\n const { width, height } = resolveReferenceResolution(reference);\n const scale = Math.min(cssWidth / width, cssHeight / height);\n return {\n mode,\n width,\n height,\n scale,\n offsetX: (cssWidth - width * scale) / 2,\n offsetY: (cssHeight - height * scale) / 2,\n };\n }\n if (mode === \"dpi\") {\n const deviceWidth = extent(metrics.deviceWidth);\n const deviceHeight = extent(metrics.deviceHeight);\n const scale = cssWidth / deviceWidth;\n return { mode, width: deviceWidth, height: deviceHeight, scale, offsetX: 0, offsetY: 0 };\n }\n return { mode: \"css\", width: cssWidth, height: cssHeight, scale: 1, offsetX: 0, offsetY: 0 };\n}\n\n/**\n * Whether two layouts are the same, so the host can skip the DOM writes when a resize changed\n * nothing (coding standards §7).\n *\n * @param left - One layout.\n * @param right - The other.\n * @returns `true` when every field matches.\n *\n * @internal\n */\nexport function layoutsEqual(left: UiLayout, right: UiLayout): boolean {\n return (\n left.mode === right.mode &&\n left.width === right.width &&\n left.height === right.height &&\n left.scale === right.scale &&\n left.offsetX === right.offsetX &&\n left.offsetY === right.offsetY\n );\n}\n\n/**\n * How a render-target pixel maps onto a UI unit under one layout.\n *\n * @remarks\n * `Camera.worldToScreen` answers in **backing-store** pixels (it divides by\n * `RendererImpl.readTargetSize`, which reads `canvas.width`/`canvas.height`), and a DOM element is\n * placed in UI units inside a root that is itself translated by `offsetX`/`offsetY` CSS pixels and\n * scaled by `scale`. This is the conversion between the two, expressed so a per-frame loop needs\n * two multiplies and a subtract and allocates nothing.\n *\n * @public\n */\nexport interface UiPixelMapping {\n /** Multiply a backing-store x by this. */\n readonly scaleX: number;\n /** Then subtract this. */\n readonly originX: number;\n /** Multiply a backing-store y by this. */\n readonly scaleY: number;\n /** Then subtract this. */\n readonly originY: number;\n}\n\n/**\n * Builds the backing-store-pixel to UI-unit conversion for one layout and one canvas.\n *\n * @param layout - The current layout.\n * @param metrics - The canvas's CSS and backing-store sizes.\n * @returns The mapping.\n *\n * @example\n * ```ts\n * const metrics = { cssWidth: 400, cssHeight: 300, deviceWidth: 800, deviceHeight: 600 };\n * const layout = computeUiLayout(\"css\", metrics, [400, 300]);\n * const map = pixelMapping(layout, metrics);\n * map.scaleX * 800 - map.originX; // 400 — the canvas's right edge, in CSS pixels\n * ```\n *\n * @public\n */\nexport function pixelMapping(layout: UiLayout, metrics: UiSurfaceMetrics): UiPixelMapping {\n const cssPerDeviceX = extent(metrics.cssWidth) / extent(metrics.deviceWidth);\n const cssPerDeviceY = extent(metrics.cssHeight) / extent(metrics.deviceHeight);\n const scale = layout.scale === 0 ? 1 : layout.scale;\n return {\n scaleX: cssPerDeviceX / scale,\n originX: layout.offsetX / scale,\n scaleY: cssPerDeviceY / scale,\n originY: layout.offsetY / scale,\n };\n}\n","import { Signal } from \"@ignifx/core\";\nimport { UI_LAYER_Z_STEP } from \"../settings.js\";\nimport { UiFocusWatcher } from \"./focus.js\";\nimport { UiLayer } from \"./layer.js\";\nimport { computeUiLayout, layoutsEqual, pixelMapping } from \"./scaling.js\";\nimport { ensureUiStyles, UI_CLASS_NAMES, UI_CSS_VARIABLES } from \"./styles.js\";\nimport type { UiDomTarget } from \"./dom-target.js\";\nimport type { UiLayerOptions } from \"./layer.js\";\nimport type { UiLayout, UiPixelMapping, UiSurfaceMetrics } from \"./scaling.js\";\nimport type { UiScalingMode, UiSettings } from \"../settings.js\";\nimport type { Logger, SignalLike } from \"@ignifx/core\";\n\n/**\n * The overlay host behind `app.ui` (`docs/architecture/13-ui.md` §1).\n *\n * ## What it is\n *\n * One absolutely-positioned `<div>` laid over the canvas, `pointer-events: none`, holding one\n * `<div>` per named layer. Everything a game mounts goes inside a layer. The host owns four things\n * and nothing else: the root's geometry (the three scaling modes), the safe-area custom properties,\n * the layer stack, and the focus flag it writes into `@ignifx/input`.\n *\n * ## Headless\n *\n * `07-rendering.md` §6 says a headless app's render objects are inert rather than absent. The host\n * follows the same rule: with no DOM canvas — a headless app, an `OffscreenCanvas`, a canvas that\n * is not in a document — {@link UiHost.root} is `null`, every layer's `element` is `null`, every\n * mutation is a no-op, and one debug line is logged at construction. Nothing throws, so a script\n * that puts a name tag on a monster is the same script in a test and in a browser.\n *\n * ## When the root is built\n *\n * Not in the extension's `register`: `AppImpl.initialize` registers every extension **before** it\n * creates the Lite engine, so `app.renderer.surface` throws `IGX-0107` there\n * (`packages/core/src/app/app.ts` 416-424). The host is therefore constructed inert and\n * {@link UiHost.mount}ed from `UiSystem.onWorldCreated`, which fires later inside the same\n * `createApp` call — the same hook `@ignifx/2d` uses for the same reason. By the time\n * `await createApp(...)` resolves, `app.ui.root` is an element.\n *\n * ## Where the root is attached\n *\n * As the canvas's next sibling, inside the canvas's own parent, rather than on `document.body`. A\n * game that puts its canvas inside a positioned wrapper — every template does — then gets an\n * overlay that moves with the canvas, and two apps in one document get one overlay each\n * (`CONSTITUTION.md` §3.6). When the canvas has no parent element the root is appended to the\n * document body instead, which is what a bare test page looks like.\n */\n\n/** The `ResizeObserver` shape the host uses, duck-typed so a node test can inject a fake. */\ninterface ResizeObserverLike {\n /** Starts observing an element. */\n observe(target: Element): void;\n /** Stops observing everything. */\n disconnect(): void;\n}\n\n/** The constructor of {@link ResizeObserverLike}, as it appears on a window. */\ntype ResizeObserverConstructor = new (callback: () => void) => ResizeObserverLike;\n\n/**\n * Reads a `ResizeObserver` constructor off a window, if it has one.\n *\n * @param view - The window.\n * @returns The constructor, or `null` on a platform without one.\n */\nfunction resizeObserverOf(view: Window): ResizeObserverConstructor | null {\n const candidate: unknown = Reflect.get(view, \"ResizeObserver\");\n if (typeof candidate !== \"function\") {\n return null;\n }\n // The platform either has the constructor the spec\n // defines or it has nothing, and a fake injected by a test declares the same two methods.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return candidate as ResizeObserverConstructor;\n}\n\n/**\n * What {@link UiHost} is constructed with.\n *\n * @internal\n */\nexport interface UiHostOptions {\n /**\n * Finds the DOM to build the overlay in, or answers `null` for a headless app. Called once, from\n * {@link UiHost.mount}, because the render surface does not exist while extensions register.\n */\n readonly resolveTarget: () => UiDomTarget | null;\n /** The resolved `ui` settings section, already merged with the extension's options. */\n readonly settings: UiSettings;\n /** The extension's logger. */\n readonly log: Logger;\n /**\n * Writes `app.input.uiHasFocus`. The extension supplies a setter that duck-types the input\n * service, so `@ignifx/ui` never imports `@ignifx/input` and the peer stays genuinely optional.\n */\n readonly setInputFocus: (value: boolean) => void;\n /**\n * Writes `app.input.uiHasPointer`: `true` while at least one pointer is pressed on the overlay,\n * so pointing-device actions read as released during a drag that began on UI. Same duck-typing\n * as {@link UiHostOptions.setInputFocus}.\n */\n readonly setInputPointer: (value: boolean) => void;\n}\n\n/** The metrics a headless host reports, so every conversion degenerates predictably. */\nconst HEADLESS_METRICS: UiSurfaceMetrics = Object.freeze({\n cssWidth: 1,\n cssHeight: 1,\n deviceWidth: 1,\n deviceHeight: 1,\n});\n\n/**\n * The DOM overlay host, reached as `app.ui`.\n *\n * @example\n * ```ts\n * const hud = app.ui.layer(\"hud\");\n * app.ui.scaling = \"fit\";\n * app.ui.referenceResolution = [640, 360];\n * ```\n *\n * @public\n */\nexport class UiHost {\n readonly #resolveTarget: () => UiDomTarget | null;\n\n readonly #log: Logger;\n\n readonly #setInputFocus: (value: boolean) => void;\n readonly #setInputPointer: (value: boolean) => void;\n\n #target: UiDomTarget | null = null;\n\n #root: HTMLDivElement | null = null;\n\n readonly #layers = new Map<string, UiLayer>();\n\n readonly #layerOrder: UiLayer[] = [];\n\n #focus: UiFocusWatcher | null = null;\n\n readonly #layoutChanged = new Signal<UiLayout>();\n\n readonly #metrics: { cssWidth: number; cssHeight: number; deviceWidth: number; deviceHeight: number } = {\n cssWidth: 1,\n cssHeight: 1,\n deviceWidth: 1,\n deviceHeight: 1,\n };\n\n #observer: ResizeObserverLike | null = null;\n\n #scaling: UiScalingMode;\n\n #reference: readonly number[];\n\n #visible: boolean;\n\n #layout: UiLayout;\n\n #mapping: UiPixelMapping;\n\n #pointerCount = 0;\n\n #mounted = false;\n\n #disposed = false;\n\n readonly #onResize = (): void => {\n this.refresh();\n };\n\n readonly #onPointerDown = (): void => {\n this.#pointerCount += 1;\n if (this.#pointerCount === 1) {\n this.#setInputPointer(true);\n }\n };\n\n readonly #onPointerUp = (): void => {\n if (this.#pointerCount === 0) {\n return;\n }\n this.#pointerCount -= 1;\n if (this.#pointerCount === 0) {\n this.#setInputPointer(false);\n }\n };\n\n /**\n * Builds the host and, when there is a DOM, the root and the declared layers.\n *\n * @param options - The DOM target, the settings, the logger, and the focus setter.\n *\n * @internal\n */\n constructor(options: UiHostOptions) {\n const { settings, log } = options;\n this.#resolveTarget = options.resolveTarget;\n this.#log = log;\n this.#setInputFocus = options.setInputFocus;\n this.#setInputPointer = options.setInputPointer;\n this.#scaling = settings.scaling;\n this.#reference = [...settings.referenceResolution];\n this.#visible = settings.visible;\n this.#layout = computeUiLayout(this.#scaling, HEADLESS_METRICS, this.#reference);\n this.#mapping = pixelMapping(this.#layout, HEADLESS_METRICS);\n for (const name of settings.layers) {\n this.#createLayer(name, {});\n }\n }\n\n /**\n * Builds the root, the layer elements, the focus watcher, and the resize subscriptions. Called\n * once, from `UiSystem.onWorldCreated`; calling it again does nothing.\n *\n * @internal\n */\n mount(): void {\n if (this.#mounted || this.#disposed) {\n return;\n }\n this.#mounted = true;\n const target = this.#resolveTarget();\n if (target === null) {\n this.#log.debug(\"No DOM canvas: app.ui.root is null and every overlay member is a no-op.\");\n return;\n }\n this.#target = target;\n ensureUiStyles(target.document);\n const root = this.#createRoot(target);\n this.#root = root;\n this.#focus = new UiFocusWatcher({ document: target.document, onChanged: this.#setInputFocus });\n this.#focus.attach();\n for (const layer of this.#layerOrder) {\n const element = target.document.createElement(\"div\");\n layer.attach(element);\n root.append(element);\n }\n this.#observe(target);\n this.refresh();\n }\n\n /**\n * The overlay root: an absolutely positioned `<div>` covering the canvas, `pointer-events: none`.\n *\n * @returns The root, or `null` when the app has no DOM overlay.\n */\n get root(): HTMLDivElement | null {\n return this.#root;\n }\n\n /**\n * Whether there is a DOM overlay at all. `false` under a headless app, an `OffscreenCanvas`, or a\n * detached canvas — the three cases in which every other member is a no-op.\n *\n * @returns `true` when {@link UiHost.root} is an element.\n */\n get isActive(): boolean {\n return this.#root !== null;\n }\n\n /**\n * How the overlay's coordinate system relates to the canvas. Writing it recomputes the layout\n * immediately.\n *\n * @returns The current mode.\n */\n get scaling(): UiScalingMode {\n return this.#scaling;\n }\n\n // eslint-disable-next-line jsdoc/require-jsdoc -- the accessor pair is documented on the getter.\n set scaling(value: UiScalingMode) {\n if (this.#scaling === value) {\n return;\n }\n this.#scaling = value;\n this.refresh();\n }\n\n /**\n * The `[width, height]` the `\"fit\"` mode scales to. Writing it recomputes the layout.\n *\n * @returns A copy of the current reference resolution.\n */\n get referenceResolution(): readonly number[] {\n return this.#reference;\n }\n\n // eslint-disable-next-line jsdoc/require-jsdoc -- the accessor pair is documented on the getter.\n set referenceResolution(value: readonly number[]) {\n this.#reference = [...value];\n this.refresh();\n }\n\n /**\n * Whether the whole overlay is shown. Per-layer visibility is `app.ui.layer(name).visible`.\n *\n * @returns `true` while the overlay is shown.\n */\n get visible(): boolean {\n return this.#visible;\n }\n\n // eslint-disable-next-line jsdoc/require-jsdoc -- the accessor pair is documented on the getter.\n set visible(value: boolean) {\n if (this.#visible === value) {\n return;\n }\n this.#visible = value;\n this.#root?.style.setProperty(\"display\", value ? \"block\" : \"none\");\n }\n\n /**\n * The root's current size, scale, and offset, in the units the scaling mode chose.\n *\n * @returns The layout last computed.\n */\n get layout(): UiLayout {\n return this.#layout;\n }\n\n /**\n * The conversion from render-target pixels — the space `Camera.worldToScreen`, `HudText`, and\n * `app.renderer.captureScreenshot()` work in — to UI units.\n *\n * @returns The mapping last computed.\n */\n get pixelMapping(): UiPixelMapping {\n return this.#mapping;\n }\n\n /**\n * Every layer, back to front.\n *\n * @returns The layers, ordered by `zIndex`.\n */\n get layers(): readonly UiLayer[] {\n return this.#layerOrder;\n }\n\n /**\n * Whether a pointer is currently pressed on an interactive element of the overlay.\n *\n * @remarks\n * A click on a UI element never reaches gameplay in the first place: `@ignifx/input` reads\n * `pointerdown` and `wheel` from the **canvas** (`packages/input/src/dom/pointer-source.ts`), and\n * the overlay root is the canvas's sibling rather than its child, so a press that lands on a\n * `pointer-events: auto` element is not on the canvas and is never queued. This flag covers the\n * remaining case: `pointermove` and `pointerup` are read from the **window**, so a drag that\n * started on a slider still moves `<Pointer>/delta`. A camera script that must ignore that reads\n * this flag.\n *\n * @returns `true` while at least one pointer is down on the overlay.\n */\n get pointerOverUi(): boolean {\n return this.#pointerCount > 0;\n }\n\n /**\n * Whether a text field currently owns the keyboard — the same value the host writes into\n * `app.input.uiHasFocus`.\n *\n * @returns `true` while typing must not fire keyboard actions.\n */\n get keyboardHasFocus(): boolean {\n return this.#focus?.hasFocus ?? false;\n }\n\n /**\n * Emitted after every recomputation that changed the layout: a canvas resize, a device-pixel-ratio\n * change, or a write to {@link UiHost.scaling} or {@link UiHost.referenceResolution}.\n *\n * @returns The signal.\n */\n get onLayoutChanged(): SignalLike<UiLayout> {\n return this.#layoutChanged;\n }\n\n /**\n * Returns the named layer, creating it the first time it is asked for.\n *\n * @param name - The layer name.\n * @param options - The stacking order and the initial visibility, used only on creation.\n * @returns The layer.\n *\n * @example\n * ```ts\n * const menu = app.ui.layer(\"menu\", { zIndex: 100 });\n * ```\n */\n layer(name: string, options?: UiLayerOptions): UiLayer {\n const existing = this.#layers.get(name);\n if (existing !== undefined) {\n if (options?.zIndex !== undefined) {\n existing.zIndex = options.zIndex;\n this.#sortLayers();\n }\n return existing;\n }\n return this.#createLayer(name, options ?? {});\n }\n\n /**\n * Re-measures the canvas and rewrites the root's geometry.\n *\n * @remarks\n * Called by the `ResizeObserver`, by the window's `resize` event — which is what a\n * device-pixel-ratio change fires — and by every write to a scaling property. Games call it after\n * changing the canvas's size by hand. A recomputation that produces the same layout writes\n * nothing and emits nothing.\n */\n refresh(): void {\n const target = this.#target;\n const root = this.#root;\n if (target === null || root === null || this.#disposed) {\n return;\n }\n const rect = target.canvas.getBoundingClientRect();\n this.#metrics.cssWidth = rect.width;\n this.#metrics.cssHeight = rect.height;\n this.#metrics.deviceWidth = target.canvas.width;\n this.#metrics.deviceHeight = target.canvas.height;\n const layout = computeUiLayout(this.#scaling, this.#metrics, this.#reference);\n this.#mapping = pixelMapping(layout, this.#metrics);\n if (layoutsEqual(this.#layout, layout)) {\n return;\n }\n this.#layout = layout;\n const style = root.style;\n style.setProperty(\"width\", `${String(layout.width)}px`);\n style.setProperty(\"height\", `${String(layout.height)}px`);\n style.setProperty(\n \"transform\",\n `translate(${String(layout.offsetX)}px, ${String(layout.offsetY)}px) scale(${String(layout.scale)})`,\n );\n style.setProperty(UI_CSS_VARIABLES.scale, String(layout.scale));\n this.#layoutChanged.emit(layout);\n }\n\n /**\n * Removes the overlay from the document and unsubscribes from everything.\n *\n * @internal\n */\n dispose(): void {\n if (this.#disposed) {\n return;\n }\n this.#disposed = true;\n this.#mounted = true;\n this.#observer?.disconnect();\n this.#observer = null;\n this.#focus?.detach();\n const target = this.#target;\n const root = this.#root;\n if (target !== null && root !== null) {\n target.window.removeEventListener(\"resize\", this.#onResize);\n root.removeEventListener(\"pointerdown\", this.#onPointerDown);\n target.window.removeEventListener(\"pointerup\", this.#onPointerUp);\n target.window.removeEventListener(\"pointercancel\", this.#onPointerUp);\n root.remove();\n }\n this.#layers.clear();\n this.#layerOrder.length = 0;\n this.#layoutChanged.clear();\n }\n\n /**\n * Builds the root element, sets the safe-area variables, and puts it over the canvas.\n *\n * @param target - The DOM target.\n * @returns The root.\n */\n #createRoot(target: UiDomTarget): HTMLDivElement {\n const root = target.document.createElement(\"div\");\n root.className = UI_CLASS_NAMES.root;\n const style = root.style;\n style.setProperty(\"display\", this.#visible ? \"block\" : \"none\");\n // `env()` is resolved by the browser against the actual display, so the four variables are set\n // once and never recomputed; a game reads them with `var(--ignifx-safe-top)`. The `0px`\n // fallback is what a desktop browser and the node fake both report.\n style.setProperty(UI_CSS_VARIABLES.safeTop, \"env(safe-area-inset-top, 0px)\");\n style.setProperty(UI_CSS_VARIABLES.safeRight, \"env(safe-area-inset-right, 0px)\");\n style.setProperty(UI_CSS_VARIABLES.safeBottom, \"env(safe-area-inset-bottom, 0px)\");\n style.setProperty(UI_CSS_VARIABLES.safeLeft, \"env(safe-area-inset-left, 0px)\");\n const parent = target.canvas.parentElement;\n if (parent === null) {\n target.document.body.append(root);\n } else {\n target.canvas.after(root);\n }\n return root;\n }\n\n /**\n * Subscribes to the canvas's size and the window's resize event.\n *\n * @param target - The DOM target.\n */\n #observe(target: UiDomTarget): void {\n const Observer = resizeObserverOf(target.window);\n if (Observer !== null) {\n const observer = new Observer(this.#onResize);\n observer.observe(target.canvas);\n this.#observer = observer;\n }\n // The window's `resize` is the one event a device-pixel-ratio change reliably fires; a\n // `ResizeObserver` on the canvas sees the CSS box, which does not change when the ratio does.\n target.window.addEventListener(\"resize\", this.#onResize);\n this.#root?.addEventListener(\"pointerdown\", this.#onPointerDown);\n target.window.addEventListener(\"pointerup\", this.#onPointerUp);\n target.window.addEventListener(\"pointercancel\", this.#onPointerUp);\n }\n\n /**\n * Creates one layer and inserts it in stacking order.\n *\n * @param name - The layer name.\n * @param options - The stacking order and the initial visibility.\n * @returns The new layer.\n */\n #createLayer(name: string, options: UiLayerOptions): UiLayer {\n const zIndex = options.zIndex ?? (this.#layerOrder.length + 1) * UI_LAYER_Z_STEP;\n const element = this.#target === null ? null : this.#target.document.createElement(\"div\");\n const layer = new UiLayer(name, element, zIndex, options.visible ?? true);\n this.#layers.set(name, layer);\n this.#layerOrder.push(layer);\n if (element !== null) {\n this.#root?.append(element);\n }\n this.#sortLayers();\n return layer;\n }\n\n /** Re-sorts the layer list by `zIndex`; the DOM order follows the `z-index` property itself. */\n #sortLayers(): void {\n this.#layerOrder.sort((left: UiLayer, right: UiLayer): number => left.zIndex - right.zIndex);\n }\n}\n","import { IgnifxError } from \"@ignifx/core\";\nimport type { ErrorContext } from \"@ignifx/core\";\n\n/**\n * The diagnostic codes `@ignifx/ui` owns. The UI subsystem sits in the `13` range of\n * `docs/architecture/15-devtools-and-diagnostics.md` §1 — *\"`13xx` UI\"* — so every code reads\n * `IGX-13##`. `@ignifx/ui` is the only package in the range and owns all of it.\n *\n * The table lives here rather than in `@ignifx/core`'s `CoreErrorCode`: an extension owns its own\n * codes and hands them to the app through `ExtensionContext.registerErrorCodes`\n * (`docs/architecture/04-extensions.md` §3).\n */\n\n/**\n * Every diagnostic code `@ignifx/ui` can throw or log, keyed by an intention-revealing name so call\n * sites read as prose and the compiler catches typos (coding standards §5.2).\n *\n * @example\n * ```ts\n * throw uiError(UiErrorCode.unknownLayer, \"hud is not a declared UI layer.\", {\n * context: { layer: \"hud\" },\n * });\n * ```\n *\n * @public\n */\nexport const UiErrorCode = {\n /** A second `ui()` extension was registered on one app. */\n duplicateExtension: \"IGX-1301\",\n /** A `.i18n.json` file is not an `ignifx.i18n` document this build can read. */\n invalidLocaleFile: \"IGX-1302\",\n /** `app.i18n.locale` was set to a locale the loaded document does not declare. */\n unknownLocale: \"IGX-1303\",\n /** A message pattern could not be parsed: an unbalanced brace or an unknown argument form. */\n invalidMessagePattern: \"IGX-1304\",\n /** A widget that needs `@ignifx/input` was built on an app that did not register it. */\n inputExtensionMissing: \"IGX-1305\",\n /** A `WorldText` or `HudText` was asked to draw before its `font` asset was assigned. */\n missingFont: \"IGX-1306\",\n /** A DOM-only member was reached on a host with no document, and did nothing. */\n headlessNoOp: \"IGX-1307\",\n /** A `WorldText` needed a scene renderable after the render scene had already been built. */\n sceneAlreadyBuilt: \"IGX-1308\",\n} as const;\n\n/**\n * The union of the codes the `UiErrorCode` table declares.\n *\n * @public\n */\nexport type UiErrorCode = (typeof UiErrorCode)[keyof typeof UiErrorCode];\n\n/**\n * The one-line message template of every code, as `ExtensionContext.registerErrorCodes` wants it.\n * Context keys appear in braces, matching the core table's convention.\n *\n * @public\n */\nexport const UI_ERROR_MESSAGES: Readonly<Record<string, string>> = Object.freeze({\n \"IGX-1301\": \"The ui() extension is already registered on this app.\",\n \"IGX-1302\": \"{file} is not an ignifx.i18n document this build can read.\",\n \"IGX-1303\": \"{locale} is not a locale the loaded translation document declares.\",\n \"IGX-1304\": \"Message {key} could not be parsed: {reason}.\",\n \"IGX-1305\": \"{widget} needs the @ignifx/input extension, which this app did not register.\",\n \"IGX-1306\": \"{component} has no font asset assigned, so it has nothing to draw.\",\n \"IGX-1307\": \"{member} did nothing: this app has no DOM overlay host.\",\n \"IGX-1308\": \"{component} was given its text after app.start(), so Babylon Lite will not draw it.\",\n});\n\n/**\n * Options accepted by {@link uiError}: the same subset of `IgnifxErrorOptions` this package uses.\n *\n * @public\n */\nexport interface UiErrorOptions {\n /** Identifiers that locate the failure. */\n readonly context?: ErrorContext;\n /** One sentence telling the developer what to do about it. */\n readonly hint?: string;\n /** The failure being wrapped, when there is one. */\n readonly cause?: unknown;\n}\n\n/**\n * Builds an `IgnifxError` carrying one of this package's codes.\n *\n * @param code - The code from the `UiErrorCode` table.\n * @param message - The actionable development sentence.\n * @param options - Context identifiers, a remedy hint, and the wrapped cause.\n * @returns The error to throw or to reject with.\n *\n * @example\n * ```ts\n * throw uiError(UiErrorCode.unknownLocale, \"fr is not a locale strings.i18n.json declares.\", {\n * context: { locale: \"fr\" },\n * });\n * ```\n *\n * @public\n */\nexport function uiError(code: UiErrorCode, message: string, options?: UiErrorOptions): IgnifxError {\n return new IgnifxError(code, message, {\n ...(options?.context === undefined ? {} : { context: options.context }),\n ...(options?.hint === undefined ? {} : { hint: options.hint }),\n ...(options?.cause === undefined ? {} : { cause: options.cause }),\n });\n}\n","/**\n * What the overlay host needs from the host page (`docs/architecture/13-ui.md` §1). Passing it\n * explicitly, instead of reaching for `globalThis.document`, is what makes two apps in one document\n * possible (`CONSTITUTION.md` §3.6) and what lets a test hand in a fake.\n *\n * The whole module is written against the real DOM types rather than structural stand-ins, which is\n * the choice `@ignifx/input`'s `DomTarget` already made: games get real elements to mount React or\n * Svelte into, and the node test suite passes a fake through one `as unknown as` in\n * `test/support/fake-dom.ts` rather than every call site paying for an abstraction.\n */\n\n/**\n * The DOM objects one app's overlay is built in.\n *\n * @public\n */\nexport interface UiDomTarget {\n /** The canvas the overlay is positioned over. */\n readonly canvas: HTMLCanvasElement;\n /** The document the overlay's elements and its stylesheet are created in. */\n readonly document: Document;\n /** The window resize and focus events are read from, and the pixel ratio is read from. */\n readonly window: Window;\n}\n\n/**\n * Narrows an unknown render surface to a DOM canvas, so a headless app or an `OffscreenCanvas`\n * simply gets no overlay.\n *\n * @param surface - The renderer's surface, or anything else.\n * @returns The canvas, or `null` when there is no DOM canvas to overlay.\n *\n * @internal\n */\nexport function asDomCanvas(surface: unknown): HTMLCanvasElement | null {\n if (typeof HTMLCanvasElement === \"undefined\") {\n return null;\n }\n return surface instanceof HTMLCanvasElement ? surface : null;\n}\n\n/**\n * Builds the DOM target from a render surface.\n *\n * @remarks\n * Returns `null` — which is what makes every overlay member a documented no-op\n * (`docs/architecture/07-rendering.md` §6) — for a headless app, for an `OffscreenCanvas`, and for\n * a canvas that has been removed from its document, because a detached canvas has no\n * `defaultView` to subscribe to.\n *\n * @param surface - The renderer's surface, or anything else.\n * @returns The target, or `null` when there is no DOM to build an overlay in.\n *\n * @internal\n */\nexport function resolveDomTarget(surface: unknown): UiDomTarget | null {\n const canvas = asDomCanvas(surface);\n if (canvas === null) {\n return null;\n }\n const document = canvas.ownerDocument;\n const view = document.defaultView;\n if (view === null) {\n return null;\n }\n return { canvas, document, window: view };\n}\n","import { defineSchema, describeSchema, map, str, toJsonSchema, u32 } from \"@ignifx/core\";\nimport { uiError, UiErrorCode } from \"../errors.js\";\nimport type { JsonSchemaObject, Schema, SchemaDescription } from \"@ignifx/core\";\n\n/**\n * The `ignifx.i18n` document (`docs/architecture/06-serialization-and-scene-format.md` §6,\n * `13-ui.md` §3: *\"loaded from `.json` assets\"*).\n *\n * One file carries **every** locale, keyed by BCP 47 tag, because a game with two languages should\n * not need two fetches and a `locale` switch should not need a load at all:\n *\n * ```json\n * {\n * \"format\": \"ignifx.i18n\",\n * \"formatVersion\": 1,\n * \"defaultLocale\": \"en\",\n * \"locales\": {\n * \"en\": { \"hud.score\": \"Score: {score}\" },\n * \"fr\": { \"hud.score\": \"Score : {score}\" }\n * }\n * }\n * ```\n *\n * A game that would rather ship one file per locale loads several documents and calls\n * `app.i18n.load` on each; the service merges them, later loads winning on a repeated key.\n */\n\n/**\n * The `format` discriminator every translation document carries.\n *\n * @public\n */\nexport const I18N_FORMAT = \"ignifx.i18n\";\n\n/**\n * The `formatVersion` this build writes and is the only one it can read. Before 1.0 the number\n * stays `1` and an incompatible change invalidates files rather than migrating them\n * (`CONSTITUTION.md` §4.2); a file declaring anything else is rejected with `IGX-1302`.\n *\n * @public\n */\nexport const I18N_FORMAT_VERSION = 1;\n\n/**\n * The asset type translation documents are registered under.\n *\n * @public\n */\nexport const I18N_ASSET_TYPE = \"i18n\";\n\n/**\n * The file extensions the translation loader claims.\n *\n * @public\n */\nexport const I18N_FILE_EXTENSIONS: readonly string[] = Object.freeze([\".i18n.json\"]);\n\n/**\n * A parsed `ignifx.i18n` document.\n *\n * @public\n */\nexport interface LocaleDocument {\n /** The locale used when nothing else selected one. */\n readonly defaultLocale: string;\n /** Every locale's message table, keyed by BCP 47 tag. */\n readonly locales: Readonly<Record<string, Readonly<Record<string, string>>>>;\n}\n\n/**\n * Narrows a parsed JSON value to an object.\n *\n * @param value - The value.\n * @returns The object, or `null` when the value is an array, a primitive, or absent.\n */\nfunction asObject(value: unknown): Record<string, unknown> | null {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return null;\n }\n // The guard above is exactly \"a plain object\", which\n // is a string-keyed bag of unknowns.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return value as Record<string, unknown>;\n}\n\n/**\n * Reads one locale's table, dropping any entry whose value is not a string.\n *\n * @param value - The raw table.\n * @returns The strings.\n */\nfunction readTable(value: unknown): Record<string, string> {\n const source = asObject(value);\n const table: Record<string, string> = {};\n if (source === null) {\n return table;\n }\n for (const key of Object.keys(source).toSorted()) {\n const message = source[key];\n if (typeof message === \"string\") {\n table[key] = message;\n }\n }\n return table;\n}\n\n/**\n * Parses and validates a translation document.\n *\n * @param value - The parsed JSON.\n * @param address - The address it came from, for the error's context.\n * @returns The document.\n * @throws IgnifxError with code `IGX-1302` when the header is missing, the version does not match,\n * or the file declares no locales.\n *\n * @example\n * ```ts\n * const document = parseLocaleFile(\n * { format: \"ignifx.i18n\", formatVersion: 1, defaultLocale: \"en\", locales: { en: { ok: \"OK\" } } },\n * \"ui/strings.i18n.json\",\n * );\n * document.locales[\"en\"]?.[\"ok\"]; // \"OK\"\n * ```\n *\n * @public\n */\nexport function parseLocaleFile(value: unknown, address: string): LocaleDocument {\n const file = asObject(value);\n if (file === null || file[\"format\"] !== I18N_FORMAT || file[\"formatVersion\"] !== I18N_FORMAT_VERSION) {\n throw uiError(UiErrorCode.invalidLocaleFile, `${address} is not an ${I18N_FORMAT} document this build can read.`, {\n context: { file: address },\n hint: `This build reads ${I18N_FORMAT} version ${String(I18N_FORMAT_VERSION)}.`,\n });\n }\n const raw = asObject(file[\"locales\"]);\n const tags = raw === null ? [] : Object.keys(raw).toSorted();\n if (tags.length === 0) {\n throw uiError(UiErrorCode.invalidLocaleFile, `${address} declares no locales.`, {\n context: { file: address },\n hint: 'Add at least one entry to the \"locales\" object, keyed by BCP 47 tag.',\n });\n }\n const locales: Record<string, Readonly<Record<string, string>>> = {};\n for (const tag of tags) {\n locales[tag] = readTable(raw?.[tag]);\n }\n const declared = file[\"defaultLocale\"];\n const fallback = tags[0] ?? \"\";\n const defaultLocale = typeof declared === \"string\" && Object.hasOwn(locales, declared) ? declared : fallback;\n return { defaultLocale, locales };\n}\n\n/**\n * A loaded translation document (`docs/architecture/05-assets-and-loading.md` §5).\n *\n * @remarks\n * Pure data: it loads identically under Node and in a browser and has nothing to release.\n *\n * @example\n * ```ts\n * const strings = await app.assets.loadAsync<LocaleAsset>(\"ui/strings.i18n.json\");\n * strings.value.availableLocales; // [\"en\", \"fr\"]\n * ```\n *\n * @public\n */\nexport class LocaleAsset {\n /** The type name the asset service registers translation documents under. */\n static assetType: string = I18N_ASSET_TYPE;\n\n /** The address the document was loaded from. */\n readonly address: string;\n\n /** The parsed document. */\n readonly document: LocaleDocument;\n\n /**\n * Wraps a parsed document. The `i18n` loader constructs these.\n *\n * @param address - The address it was loaded from.\n * @param document - The parsed document.\n *\n * @internal\n */\n constructor(address: string, document: LocaleDocument) {\n this.address = address;\n this.document = document;\n }\n\n /**\n * Every locale the document declares, sorted.\n *\n * @returns The BCP 47 tags.\n */\n get availableLocales(): readonly string[] {\n return Object.keys(this.document.locales);\n }\n}\n\n/**\n * The schema a translation document is described and validated against for tooling.\n *\n * @remarks\n * The loader validates with {@link parseLocaleFile}, which produces an actionable `IGX-1302`\n * naming the file; this schema is what `pnpm docs:schemas` renders and what a JSON Schema for an\n * editor is generated from — the split `@ignifx/2d`'s `file-schemas.ts` documents.\n *\n * @returns The schema, built fresh so no module holds state (`CONSTITUTION.md` §3.5).\n *\n * @public\n */\nexport function localeFileSchema(): Schema {\n return defineSchema({\n format: str(I18N_FORMAT, { tooltip: \"Always ignifx.i18n.\" }),\n formatVersion: u32(I18N_FORMAT_VERSION, { tooltip: \"The document version this build reads.\" }),\n defaultLocale: str(\"en\", { tooltip: \"The locale used until the game picks another.\" }),\n locales: map(map(str()), { tooltip: \"Message tables keyed by BCP 47 tag, then by message key.\" }),\n });\n}\n\n/**\n * Describes the `ignifx.i18n` file format for the documentation harness.\n *\n * @returns The record `pnpm docs:schemas` renders.\n *\n * @public\n */\nexport function describeLocaleFileFormat(): SchemaDescription {\n return describeSchema(\"ignifx/i18n-file\", localeFileSchema(), {\n title: \"Translations\",\n format: I18N_FORMAT,\n description: \"Message tables for one or more locales, with {name} interpolation and ICU-style plurals.\",\n });\n}\n\n/**\n * The JSON Schema a tool validates a `.i18n.json` document against.\n *\n * @returns The JSON Schema object.\n *\n * @public\n */\nexport function localeJsonSchema(): JsonSchemaObject {\n return toJsonSchema(localeFileSchema());\n}\n","/**\n * The ICU-style message subset `app.i18n.t` understands (`docs/architecture/13-ui.md` §3:\n * \"a tiny key/value service with ICU-style plurals\"*).\n *\n * ## What is supported\n *\n * - `{name}` — substitutes a parameter. A parameter that was not supplied is left as written, so a\n * missing value shows up in the interface instead of silently becoming `undefined`.\n * - `{count, plural, one {a life} other {# lives}}` — selects a branch with `Intl.PluralRules` for\n * the active locale, and replaces `#` inside the chosen branch with the number.\n * - `{count, plural, =0 {no lives} one {…} other {…}}` — an exact match, checked before the\n * category, exactly as ICU orders them.\n *\n * ## What is not\n *\n * `select`, `selectordinal`, number and date skeletons, and ICU's apostrophe quoting. Braces are\n * structural: a literal `{` has to arrive through a parameter. Anything the parser cannot read is\n * reported rather than guessed at, and the service turns that report into `IGX-1304`.\n *\n * The parser is pure and allocates only while parsing; parsed patterns are cached by the service,\n * so a `t()` in `update` walks a node list and appends strings rather than re-parsing.\n */\n\n/** The categories `Intl.PluralRules` can return, plus the exact-match form this parser also takes. */\nconst PLURAL_CATEGORIES: readonly string[] = Object.freeze([\"zero\", \"one\", \"two\", \"few\", \"many\", \"other\"]);\n\n/**\n * What a message's parameters may be.\n *\n * @public\n */\nexport type MessageParams = Readonly<Record<string, string | number>>;\n\n/**\n * Chooses a plural category for a number, in one locale.\n *\n * @public\n */\nexport type PluralSelector = (value: number) => string;\n\n/**\n * A run of literal text.\n *\n * @public\n */\nexport interface TextNode {\n /** The discriminator. */\n readonly kind: \"text\";\n /** The literal. */\n readonly value: string;\n}\n\n/**\n * A `{name}` substitution.\n *\n * @public\n */\nexport interface ArgumentNode {\n /** The discriminator. */\n readonly kind: \"argument\";\n /** The parameter name. */\n readonly name: string;\n}\n\n/**\n * A `{name, plural, …}` selection.\n *\n * @public\n */\nexport interface PluralNode {\n /** The discriminator. */\n readonly kind: \"plural\";\n /** The parameter name holding the number. */\n readonly name: string;\n /** The branches, keyed by `\"=0\"`-style exact matches and by plural category. */\n readonly branches: ReadonlyMap<string, readonly MessageNode[]>;\n}\n\n/**\n * One piece of a parsed message.\n *\n * @public\n */\nexport type MessageNode = TextNode | ArgumentNode | PluralNode;\n\n/**\n * A parsed message, or the reason it could not be parsed.\n *\n * @public\n */\nexport interface MessagePattern {\n /** The nodes to render. Holds the raw pattern as one text node when {@link MessagePattern.error} is set. */\n readonly nodes: readonly MessageNode[];\n /** Why the pattern could not be read, or `null` when it parsed. */\n readonly error: string | null;\n}\n\n/** The parser's mutable position, kept in one object so the recursive helpers share it. */\ninterface Cursor {\n /** The pattern being read. */\n readonly source: string;\n /** The next index to read. */\n index: number;\n}\n\n/**\n * Reads literal text until an unescaped `{` or `}`.\n *\n * @param cursor - The parser position.\n * @param stopAtClose - Whether a `}` ends the run, which it does inside a branch.\n * @returns The text read; possibly empty.\n */\nfunction readText(cursor: Cursor, stopAtClose: boolean): string {\n const start = cursor.index;\n while (cursor.index < cursor.source.length) {\n const char = cursor.source[cursor.index];\n if (char === \"{\" || (char === \"}\" && stopAtClose)) {\n break;\n }\n cursor.index += 1;\n }\n return cursor.source.slice(start, cursor.index);\n}\n\n/**\n * Reads an identifier — a parameter name or a branch selector.\n *\n * @param cursor - The parser position.\n * @returns The identifier, trimmed; possibly empty.\n */\nfunction readIdentifier(cursor: Cursor): string {\n const start = cursor.index;\n while (cursor.index < cursor.source.length) {\n const char = cursor.source[cursor.index];\n if (char === undefined || char === \",\" || char === \"{\" || char === \"}\" || /\\s/u.test(char)) {\n break;\n }\n cursor.index += 1;\n }\n return cursor.source.slice(start, cursor.index);\n}\n\n/**\n * Skips whitespace.\n *\n * @param cursor - The parser position.\n */\nfunction skipSpace(cursor: Cursor): void {\n while (cursor.index < cursor.source.length) {\n const char = cursor.source[cursor.index];\n if (char === undefined || !/\\s/u.test(char)) {\n break;\n }\n cursor.index += 1;\n }\n}\n\n/** Thrown inside the parser and converted into {@link MessagePattern.error} at the top. */\nclass PatternError extends Error {}\n\n/**\n * Parses a sequence of nodes up to the end of the pattern or to the branch's closing brace.\n *\n * @param cursor - The parser position.\n * @param nested - Whether a `}` ends this sequence.\n * @returns The nodes.\n * @throws PatternError when a brace is unbalanced or an argument form is unknown.\n */\nfunction parseNodes(cursor: Cursor, nested: boolean): MessageNode[] {\n const nodes: MessageNode[] = [];\n for (;;) {\n const text = readText(cursor, nested);\n if (text.length > 0) {\n nodes.push({ kind: \"text\", value: text });\n }\n const char = cursor.source[cursor.index];\n if (char === undefined) {\n if (nested) {\n throw new PatternError(\"a branch is missing its closing brace\");\n }\n return nodes;\n }\n if (char === \"}\") {\n // Only reachable inside a branch: `readText` swallows a stray `}` at the top level, so an\n // unmatched closing brace in ordinary prose is literal text rather than an authoring error.\n return nodes;\n }\n cursor.index += 1;\n nodes.push(parseArgument(cursor));\n }\n}\n\n/**\n * Parses one `{…}` argument, having already consumed the opening brace.\n *\n * @param cursor - The parser position.\n * @returns The node.\n * @throws PatternError when the argument is malformed or names an unsupported form.\n */\nfunction parseArgument(cursor: Cursor): MessageNode {\n skipSpace(cursor);\n const name = readIdentifier(cursor);\n if (name.length === 0) {\n throw new PatternError(\"an argument has no name\");\n }\n skipSpace(cursor);\n if (cursor.source[cursor.index] === \"}\") {\n cursor.index += 1;\n return { kind: \"argument\", name };\n }\n if (cursor.source[cursor.index] !== \",\") {\n throw new PatternError(`argument ${name} is missing its closing brace`);\n }\n cursor.index += 1;\n skipSpace(cursor);\n const form = readIdentifier(cursor);\n if (form !== \"plural\") {\n throw new PatternError(`argument ${name} uses the unsupported form ${form === \"\" ? \"(empty)\" : form}`);\n }\n return { kind: \"plural\", name, branches: parseBranches(cursor, name) };\n}\n\n/**\n * Parses the branch list of a plural argument, up to and including its closing brace.\n *\n * @param cursor - The parser position.\n * @param name - The argument's name, for error messages.\n * @returns The branches.\n * @throws PatternError when a selector is unknown or the list is unterminated.\n */\nfunction parseBranches(cursor: Cursor, name: string): ReadonlyMap<string, readonly MessageNode[]> {\n const branches = new Map<string, readonly MessageNode[]>();\n for (;;) {\n skipSpace(cursor);\n if (cursor.source[cursor.index] === \",\") {\n cursor.index += 1;\n continue;\n }\n if (cursor.source[cursor.index] === \"}\") {\n cursor.index += 1;\n if (!branches.has(\"other\")) {\n throw new PatternError(`plural ${name} has no other branch`);\n }\n return branches;\n }\n const selector = readIdentifier(cursor);\n if (selector.length === 0) {\n throw new PatternError(`plural ${name} is missing its closing brace`);\n }\n if (!PLURAL_CATEGORIES.includes(selector) && !/^=\\d+$/u.test(selector)) {\n throw new PatternError(`plural ${name} has the unknown branch ${selector}`);\n }\n skipSpace(cursor);\n if (cursor.source[cursor.index] !== \"{\") {\n throw new PatternError(`branch ${selector} of plural ${name} has no body`);\n }\n cursor.index += 1;\n branches.set(selector, parseNodes(cursor, true));\n cursor.index += 1;\n }\n}\n\n/**\n * Parses one message pattern.\n *\n * @param pattern - The pattern, as written in the `.i18n.json` document.\n * @returns The parsed nodes, or the raw text plus the reason it could not be parsed.\n *\n * @example\n * ```ts\n * parseMessage(\"{count, plural, one {# life} other {# lives}}\").error; // null\n * parseMessage(\"{count, plural, one {# life}}\").error; // \"plural count has no other branch\"\n * ```\n *\n * @public\n */\nexport function parseMessage(pattern: string): MessagePattern {\n const cursor: Cursor = { source: pattern, index: 0 };\n try {\n return { nodes: parseNodes(cursor, false), error: null };\n } catch (error: unknown) {\n const reason = error instanceof PatternError ? error.message : \"the pattern could not be read\";\n return { nodes: [{ kind: \"text\", value: pattern }], error: reason };\n }\n}\n\n/**\n * Builds the plural selector for a locale.\n *\n * @remarks\n * `Intl.PluralRules` is present in every browser and in Node, but a stripped runtime without\n * `Intl` still has to work, so the fallback is English's two-category rule.\n *\n * @param locale - The BCP 47 locale tag.\n * @returns A function from a number to a plural category.\n *\n * @example\n * ```ts\n * createPluralSelector(\"en\")(1); // \"one\"\n * ```\n *\n * @public\n */\nexport function createPluralSelector(locale: string): PluralSelector {\n if (typeof Intl !== \"object\" || typeof Intl.PluralRules !== \"function\") {\n return (value: number): string => (value === 1 ? \"one\" : \"other\");\n }\n try {\n const rules = new Intl.PluralRules(locale);\n return (value: number): string => rules.select(value);\n } catch {\n // An unparseable tag — `Intl.PluralRules` throws a `RangeError` for one — falls back rather\n // than taking the frame down over a translation file.\n return (value: number): string => (value === 1 ? \"one\" : \"other\");\n }\n}\n\n/**\n * Reads a parameter as a number, for a plural selection.\n *\n * @param value - The supplied parameter.\n * @returns The number, or `null` when the parameter is absent or not numeric.\n */\nfunction asNumber(value: string | number | undefined): number | null {\n if (typeof value === \"number\") {\n return Number.isFinite(value) ? value : null;\n }\n if (typeof value !== \"string\") {\n return null;\n }\n const parsed = Number(value);\n return Number.isFinite(parsed) && value.trim().length > 0 ? parsed : null;\n}\n\n/**\n * Renders parsed nodes with a set of parameters.\n *\n * @param nodes - The nodes from {@link parseMessage}.\n * @param params - The values to substitute.\n * @param select - The active locale's plural selector.\n * @param hash - What `#` stands for in the branch being rendered, or `null` at the top level.\n * @returns The rendered string.\n */\nfunction render(\n nodes: readonly MessageNode[],\n params: MessageParams,\n select: PluralSelector,\n hash: string | null,\n): string {\n let out = \"\";\n for (let index = 0; index < nodes.length; index += 1) {\n const node = nodes[index];\n if (node === undefined) {\n continue;\n }\n if (node.kind === \"text\") {\n out += hash === null ? node.value : node.value.replaceAll(\"#\", hash);\n continue;\n }\n if (node.kind === \"argument\") {\n const value = Object.hasOwn(params, node.name) ? params[node.name] : undefined;\n out += value === undefined ? `{${node.name}}` : String(value);\n continue;\n }\n const raw = Object.hasOwn(params, node.name) ? params[node.name] : undefined;\n const count = asNumber(raw);\n if (count === null) {\n out += `{${node.name}}`;\n continue;\n }\n const branch =\n node.branches.get(`=${String(count)}`) ?? node.branches.get(select(count)) ?? node.branches.get(\"other\");\n out += branch === undefined ? \"\" : render(branch, params, select, String(count));\n }\n return out;\n}\n\n/**\n * Renders a parsed message.\n *\n * @param pattern - The parsed pattern.\n * @param params - The values to substitute.\n * @param select - The active locale's plural selector.\n * @returns The rendered string.\n *\n * @example\n * ```ts\n * const pattern = parseMessage(\"{count, plural, one {# life} other {# lives}}\");\n * renderMessage(pattern, { count: 3 }, createPluralSelector(\"en\")); // \"3 lives\"\n * ```\n *\n * @public\n */\nexport function renderMessage(pattern: MessagePattern, params: MessageParams, select: PluralSelector): string {\n return render(pattern.nodes, params, select, null);\n}\n","import { Signal } from \"@ignifx/core\";\nimport { uiError, UiErrorCode } from \"../errors.js\";\nimport { LocaleAsset } from \"./locale-file.js\";\nimport { createPluralSelector, parseMessage, renderMessage } from \"./message.js\";\nimport type { MessageParams, MessagePattern, PluralSelector } from \"./message.js\";\nimport type { AssetHandle, Logger, SignalLike } from \"@ignifx/core\";\n\n/**\n * The localization service behind `app.i18n` (`docs/architecture/13-ui.md` §3:\n * \"a tiny key/value service with ICU-style plurals, loaded from `.json` assets; UI helpers and\n * `WorldText` accept keys\"*).\n *\n * ## Missing keys are not errors\n *\n * `t(\"hud.score\")` with no such key returns `\"hud.score\"` and logs one debug line per key. A game\n * that ships a new string before the translator does then shows the key rather than an empty box,\n * and a test can assert on the key. `IGX-1304` is reserved for a message that *is* present and\n * cannot be parsed — a genuine authoring mistake.\n *\n * ## Cost\n *\n * Patterns are parsed once and cached by their text, so a `t()` in `update` walks a node list.\n * Switching locale clears nothing: the cache is keyed by pattern, not by key, and two locales that\n * share a pattern share its parse.\n */\n\n/** What a plain empty parameter set is, so `t(key)` allocates nothing. */\nconst NO_PARAMS: MessageParams = Object.freeze({});\n\n/**\n * What {@link I18nService} is constructed with.\n *\n * @internal\n */\nexport interface I18nServiceOptions {\n /** The extension's logger. */\n readonly log: Logger;\n /** The locale the app starts in, before any document is loaded. */\n readonly locale: string;\n}\n\n/**\n * The localization service, reached as `app.i18n`.\n *\n * @example\n * ```ts\n * await app.i18n.load(app.assets.load<LocaleAsset>(\"ui/strings.i18n.json\"));\n * app.i18n.locale = \"fr\";\n * app.i18n.t(\"hud.lives\", { count: 3 });\n * ```\n *\n * @public\n */\nexport class I18nService {\n readonly #log: Logger;\n\n readonly #tables = new Map<string, Map<string, string>>();\n\n readonly #patterns = new Map<string, MessagePattern>();\n\n readonly #reportedMissing = new Set<string>();\n\n readonly #localeChanged = new Signal<string>();\n\n #locale: string;\n\n #fallbackLocale: string;\n\n #select: PluralSelector;\n\n /**\n * Builds an empty service. The extension does this; a game never constructs one.\n *\n * @param options - The logger and the starting locale.\n *\n * @internal\n */\n constructor(options: I18nServiceOptions) {\n this.#log = options.log;\n this.#locale = options.locale;\n this.#fallbackLocale = options.locale;\n this.#select = createPluralSelector(options.locale);\n }\n\n /**\n * The active locale. Writing a locale no loaded document declares throws `IGX-1303`, because a\n * silent no-op there is a bug that only shows up as untranslated text much later.\n *\n * @returns The BCP 47 tag.\n * @throws IgnifxError with code `IGX-1303` when no loaded document declares the tag.\n */\n get locale(): string {\n return this.#locale;\n }\n\n // eslint-disable-next-line jsdoc/require-jsdoc -- the accessor pair is documented on the getter.\n set locale(value: string) {\n if (this.#locale === value) {\n return;\n }\n if (this.#tables.size > 0 && !this.#tables.has(value)) {\n throw uiError(UiErrorCode.unknownLocale, `${value} is not a locale any loaded document declares.`, {\n context: { locale: value },\n hint: `Loaded locales: ${this.availableLocales.join(\", \")}.`,\n });\n }\n this.#locale = value;\n this.#select = createPluralSelector(value);\n this.#localeChanged.emit(value);\n }\n\n /**\n * The locale a key falls back to when the active locale has no entry for it. Set from the first\n * document's `defaultLocale`.\n *\n * @returns The BCP 47 tag.\n */\n get fallbackLocale(): string {\n return this.#fallbackLocale;\n }\n\n // eslint-disable-next-line jsdoc/require-jsdoc -- the accessor pair is documented on the getter.\n set fallbackLocale(value: string) {\n this.#fallbackLocale = value;\n }\n\n /**\n * Every locale any loaded document declares, sorted.\n *\n * @returns The BCP 47 tags.\n */\n get availableLocales(): readonly string[] {\n return [...this.#tables.keys()].toSorted();\n }\n\n /**\n * Emitted after {@link I18nService.locale} changed. UI that caches rendered strings — `HudText`\n * does — redraws from here.\n *\n * @returns The signal.\n */\n get onLocaleChanged(): SignalLike<string> {\n return this.#localeChanged;\n }\n\n /**\n * Merges a translation document into the service.\n *\n * @remarks\n * Accepts a loaded {@link LocaleAsset} or the handle of one, in which case the merge happens when\n * the handle settles. Later loads win on a repeated key, which is what makes a per-locale\n * download or a downloadable language pack work. The first document loaded also sets\n * {@link I18nService.fallbackLocale} and, when the app is still on its starting locale and the\n * document does not declare it, moves the active locale to the document's `defaultLocale`.\n *\n * @param source - A loaded document, or its handle.\n * @returns A promise that settles once the document has been merged.\n *\n * @example\n * ```ts\n * using strings = app.assets.load<LocaleAsset>(\"ui/strings.i18n.json\");\n * await app.i18n.load(strings);\n * ```\n */\n async load(source: AssetHandle<LocaleAsset> | LocaleAsset): Promise<void> {\n const asset = source instanceof LocaleAsset ? source : await source.promise;\n const first = this.#tables.size === 0;\n for (const [tag, table] of Object.entries(asset.document.locales)) {\n const existing = this.#tables.get(tag) ?? new Map<string, string>();\n for (const [key, message] of Object.entries(table)) {\n existing.set(key, message);\n }\n this.#tables.set(tag, existing);\n }\n this.#reportedMissing.clear();\n if (!first) {\n return;\n }\n this.#fallbackLocale = asset.document.defaultLocale;\n if (!this.#tables.has(this.#locale)) {\n this.#locale = asset.document.defaultLocale;\n this.#select = createPluralSelector(this.#locale);\n this.#localeChanged.emit(this.#locale);\n }\n }\n\n /**\n * Whether the active locale, or the fallback, has an entry for a key.\n *\n * @param key - The message key.\n * @returns `true` when {@link I18nService.t} will find a message.\n */\n has(key: string): boolean {\n return this.#lookup(key) !== null;\n }\n\n /**\n * Renders a message.\n *\n * @param key - The message key.\n * @param params - The values `{name}` placeholders and plural selectors read.\n * @returns The rendered message, or the key itself when no document declares it.\n *\n * @example\n * ```ts\n * app.i18n.t(\"hud.lives\", { count: 1 }); // \"1 life\"\n * app.i18n.t(\"hud.lives\", { count: 4 }); // \"4 lives\"\n * ```\n */\n t(key: string, params: MessageParams = NO_PARAMS): string {\n const message = this.#lookup(key);\n if (message === null) {\n if (!this.#reportedMissing.has(key)) {\n this.#reportedMissing.add(key);\n this.#log.debug(`No translation for ${key} in ${this.#locale}; showing the key.`);\n }\n return key;\n }\n return renderMessage(this.#pattern(key, message), params, this.#select);\n }\n\n /**\n * Drops every loaded document.\n *\n * @internal\n */\n clear(): void {\n this.#tables.clear();\n this.#patterns.clear();\n this.#reportedMissing.clear();\n }\n\n /**\n * Releases everything the service holds.\n *\n * @internal\n */\n dispose(): void {\n this.clear();\n this.#localeChanged.clear();\n }\n\n /**\n * Finds a key in the active locale, then in the fallback.\n *\n * @param key - The message key.\n * @returns The raw pattern, or `null`.\n */\n #lookup(key: string): string | null {\n return this.#tables.get(this.#locale)?.get(key) ?? this.#tables.get(this.#fallbackLocale)?.get(key) ?? null;\n }\n\n /**\n * Parses a pattern, or returns the cached parse.\n *\n * @param key - The message key, for the `IGX-1304` context.\n * @param message - The raw pattern.\n * @returns The parsed pattern; an unreadable one renders as its own raw text.\n */\n #pattern(key: string, message: string): MessagePattern {\n const cached = this.#patterns.get(message);\n if (cached !== undefined) {\n return cached;\n }\n const parsed = parseMessage(message);\n if (parsed.error !== null) {\n const error = uiError(UiErrorCode.invalidMessagePattern, `Message ${key} could not be parsed: ${parsed.error}.`, {\n context: { key, reason: parsed.error },\n hint: \"Braces are structural in an ignifx.i18n message; a literal brace has to arrive as a parameter.\",\n });\n this.#log.warn(error.message);\n }\n this.#patterns.set(message, parsed);\n return parsed;\n }\n}\n","import { I18N_ASSET_TYPE, I18N_FILE_EXTENSIONS, LocaleAsset, parseLocaleFile } from \"./locale-file.js\";\nimport type { AssetLoader, LoaderContext } from \"@ignifx/core\";\n\n/**\n * The `i18n` asset loader: `.i18n.json` to {@link LocaleAsset}\n * (`docs/architecture/05-assets-and-loading.md` §5).\n *\n * The file is data, so the loader is identical under Node and in a browser and has nothing to\n * release on unload. `.i18n.json` is a longer suffix than `.json` and the asset service picks the\n * longest match, so registering it does not shadow the generic JSON loader.\n */\n\n/**\n * Builds the loader for `.i18n.json` addresses.\n *\n * @returns The loader to register with `ctx.registerAssetLoader`.\n *\n * @example\n * ```ts\n * ctx.registerAssetLoader(createLocaleLoader());\n * ```\n *\n * @public\n */\nexport function createLocaleLoader(): AssetLoader<LocaleAsset> {\n return {\n type: I18N_ASSET_TYPE,\n extensions: I18N_FILE_EXTENSIONS,\n async load(ctx: LoaderContext): Promise<LocaleAsset> {\n const parsed: unknown = await ctx.fetchJson();\n return new LocaleAsset(ctx.address, parseLocaleFile(parsed, ctx.address));\n },\n };\n}\n","import {\n addTextRendererLayer,\n createTextRenderer,\n disposeTextRenderer,\n enableDeviceLostTextRecovery,\n registerTextRenderer,\n removeTextRendererLayer,\n unregisterTextRenderer,\n} from \"@babylonjs/lite\";\nimport type { DeviceLostRecoveryHandle, EngineContext, SurfaceContext, TextLayer, TextRenderer } from \"@babylonjs/lite\";\n\n/**\n * The device-only half of the text adapter: the second Babylon Lite rendering context `@ignifx/ui`\n * puts on the app's surface for `HudText` and `WorldText2D`\n * (`docs/architecture/07-rendering.md` §1, `13-ui.md` §2).\n *\n * A `TextRenderer` opens its own swapchain pass and is registered directly on the engine,\n * independently of any scene — the same shape as `@ignifx/2d`'s sprite renderer. Two of Lite's own\n * statements govern how it is used:\n *\n * - `TextRendererOptions.clear` is *\"Default true. Set false for HUD overlays so the text pass\n * preserves existing scene color\"* (`index.d.ts` 12867). A HUD always passes `false`.\n * - `registerTextRenderer` *\"Register a text renderer with its surface so the engine updates and\n * records it each frame\"* (9547); `lib/text/text-renderer.js` implements it as\n * `registerRenderingContext(tr._surface, tr)`, which appends to the surface's context list, and\n * Lite draws that list in order — so a context registered after the render scene composites on\n * top of it.\n *\n * The renderer's pixel space is the **backing store**: `createTextRenderer` seeds\n * `_targetWidth`/`_targetHeight` from `surface.canvas.width`/`.height` and `textRendererUpdate`\n * re-reads them every frame (`lib/text/text-renderer.js`). A layer at `positionPx (100, 100)` is\n * therefore at render-target column 100, which is the same space `Camera.worldToScreen` and\n * `app.renderer.captureScreenshot()` answer in — and *not* CSS pixels.\n *\n * Everything here needs `engine._device` on the first frame, so the module lives under `gpu/` and\n * the root Vitest coverage config excludes it; the `browser` project covers it.\n *\n * Everything here is `@internal`.\n */\n\n/**\n * The surface a text renderer draws into.\n *\n * @remarks\n * `EngineContext extends SurfaceContext` (`index.d.ts` 4676) and an engine's index-0 surface *is*\n * the engine itself, so a single-canvas app passes `app.lite.engine` straight through.\n *\n * @internal\n */\nexport type TextSurface = SurfaceContext;\n\n/**\n * Creates the text renderer and registers it on the engine.\n *\n * @remarks\n * Call this **after** the render scene is registered, so text composites over the frame rather than\n * under it. `clear` is always `false`: a HUD that cleared the swapchain would erase the game.\n *\n * @param surface - The surface to draw into; the engine, for a single-canvas app.\n * @returns The registered renderer.\n *\n * @internal\n */\nexport function createRegisteredTextRenderer(surface: TextSurface): TextRenderer {\n const renderer = createTextRenderer(surface, { layers: [], clear: false });\n registerTextRenderer(renderer);\n return renderer;\n}\n\n/**\n * Adds a layer to a renderer's draw list (`index.d.ts` 214).\n *\n * @param renderer - The text renderer.\n * @param layer - The layer to draw.\n *\n * @internal\n */\nexport function attachTextLayer(renderer: TextRenderer, layer: TextLayer): void {\n addTextRendererLayer(renderer, layer);\n}\n\n/**\n * Removes a layer from a renderer's draw list and frees its per-layer GPU buffers\n * (`index.d.ts` 9671).\n *\n * @param renderer - The text renderer.\n * @param layer - The layer to stop drawing.\n * @returns `true` when the layer was there.\n *\n * @internal\n */\nexport function detachTextLayer(renderer: TextRenderer, layer: TextLayer): boolean {\n return removeTextRendererLayer(renderer, layer);\n}\n\n/**\n * Unregisters and disposes a text renderer (`index.d.ts` 13218 and 4103).\n *\n * @param renderer - The renderer to tear down.\n *\n * @internal\n */\nexport function destroyTextRenderer(renderer: TextRenderer): void {\n unregisterTextRenderer(renderer);\n disposeTextRenderer(renderer);\n}\n\n/**\n * Turns on best-effort WebGPU device-lost recovery for every registered text renderer\n * (`index.d.ts` 4388).\n *\n * @remarks\n * Unlike the sprite adapter, this one has no ordering requirement. Lite's own comment at\n * `index.d.ts` 4383-4384 says that `GlyphStorage` already retains the CPU atlas data needed for\n * reconstruction, so the adapter adds no renderer-specific capture outside the loss path. It is\n * still enabled in `onStart`, before the first layer exists, so the two adapters read the same.\n *\n * @param engine - The engine to protect.\n * @param onRecovered - Called after the replacement device and every rendering context are ready.\n * @param onFailed - Called when reacquisition or rebuilding fails.\n * @returns The handle whose `disable()` turns recovery off again.\n *\n * @internal\n */\nexport function enableTextDeviceLostRecovery(\n engine: EngineContext,\n onRecovered: () => void,\n onFailed: (error: unknown) => void,\n): DeviceLostRecoveryHandle {\n return enableDeviceLostTextRecovery(engine, { onRecovered, onRecoveryFailed: onFailed });\n}\n","import {\n addTextRenderable,\n createDefaultTextData,\n createTextLayer,\n createTextRenderable,\n disposeDefaultTextData,\n disposeTextRenderable,\n setTextLayerPosition,\n updateDefaultTextData,\n} from \"@babylonjs/lite\";\nimport type {\n DefaultTextData,\n Font,\n SceneContext,\n TextLayer,\n TextLayoutOptions,\n TextRenderable,\n TextRenderer,\n} from \"@babylonjs/lite\";\n\n/**\n * The device-free half of the Babylon Lite text adapter (`docs/architecture/13-ui.md` §2).\n * Everything here shapes text, measures it, and builds the pure-data objects a renderer later\n * draws; nothing touches `engine._device`, which is why this module is **not** under `./gpu/` and\n * is covered by the node suite. Only `createTextRenderer` needs a surface, and that lives in\n * `./gpu/text-renderer.ts`.\n *\n * ## What was verified against `@babylonjs/lite@1.27.0`\n *\n * - `createDefaultTextData(font, fontSizePx, text, textColor?, options?)` (`index.d.ts` 2377)\n * shapes the string, extracts the glyph outlines, and **owns its own `GlyphStorage`** — the\n * doc comment at 2375 says so, and `disposeDefaultTextData` (3948) releases both. The returned\n * `DefaultTextData` carries the laid-out `width` and `height` in pixels (3736-3741), which is\n * the only text measurement Lite offers.\n * - `updateDefaultTextData(data, text, textColor?)` (13247) re-shapes **with the font size and the\n * layout options the block was created with** — `lib/text/default-text-data.js` reads\n * `data._fontSizePx` and `data._options` and never takes new ones — and writes fresh `width`\n * and `height` onto the block. Changing `fontSize`, `maxWidth`, `align`, `lineHeight`, or the\n * font therefore means **recreating** the block; changing `text` or `color` does not. Omitting\n * `textColor` preserves the run's existing colour (13245-13246).\n * - `TextLayoutOptions` (12821) is `{ maxWidth, lineHeight, align, letterSpacing, tabSize }`, in\n * output pixels, with simple LTR word wrapping.\n * - `align` aligns the lines of a block against **the longest line**, not against `maxWidth`:\n * measured on the pinned build, `\"AAAA\\nB\"` at 32 px puts the `B` at x 0, 25.92 and 51.84 for\n * `\"left\"`, `\"center\"` and `\"right\"`, with `width` 69.12 in all three. Centring a block on the\n * screen is therefore the caller's arithmetic, against {@link measureText}.\n * - Glyph baselines run **downwards in negative y**: line n sits at `-n × fontSizePx × lineHeight`\n * (`PlacedGlyph`, 8854-8858). A block's first baseline is at the layer's `positionPx`, so its\n * ascent is above that point.\n * - `createTextLayer(data, options)` (3257) and `createTextRenderable(data, options)` (3264) are\n * pure object construction; `lib/text/text-renderer.js` and `lib/text/text-renderable.js` build\n * plain records with `_gpu: null` and allocate GPU resources lazily on the first frame.\n * - **There is no `removeTextRenderable`.** `addTextRenderable(scene, renderable)` (208) pushes a\n * deferred builder onto the scene (`lib/text/text-renderable.js` 242-249) and Lite exposes no\n * inverse — `removeFromScene` (9613) takes meshes, lights, cameras, shadow generators, transform\n * nodes and asset containers, and not a `TextRenderable`. {@link detachSceneText} therefore\n * empties the block and zeroes its opacity, which makes it draw nothing; the record itself stays\n * in the scene's renderable list until the scene is disposed. This is reported as a Lite gap.\n *\n * Everything here is `@internal` apart from the type aliases the `.lite` escape hatches name.\n */\n\n/**\n * The Babylon Lite font handle, re-exported under an ignifx name so feature code can name the type\n * without importing `@babylonjs/lite` (`CONSTITUTION.md` §3.4).\n *\n * @remarks\n * Unstable: it is Lite's own type, reachable only through documented `.lite` escape hatches.\n *\n * @public\n */\nexport type LiteFont = Font;\n\n/**\n * A shaped block of text, with its glyph storage.\n *\n * @remarks\n * Unstable escape-hatch type.\n *\n * @public\n */\nexport type LiteTextData = DefaultTextData;\n\n/**\n * A 2D text layer placed in render-target pixel space.\n *\n * @remarks\n * Unstable escape-hatch type.\n *\n * @public\n */\nexport type LiteTextLayer = TextLayer;\n\n/**\n * A scene renderable that draws a block of text in world space.\n *\n * @remarks\n * Unstable escape-hatch type.\n *\n * @public\n */\nexport type LiteTextRenderable = TextRenderable;\n\n/**\n * The standalone rendering context that draws 2D text layers onto the swapchain.\n *\n * @remarks\n * Unstable escape-hatch type.\n *\n * @public\n */\nexport type LiteTextRenderer = TextRenderer;\n\n/**\n * Straight RGBA in `0` to `1`, in the order Lite wants it.\n *\n * @internal\n */\nexport type TextColor = readonly [number, number, number, number];\n\n/**\n * Everything that decides how a block is laid out. Changing any of it means a new block.\n *\n * @internal\n */\nexport interface TextShape {\n /** The parsed font. */\n readonly font: LiteFont;\n /** The em size, in render-target pixels. */\n readonly fontSizePx: number;\n /** The string to shape. */\n readonly text: string;\n /** The colour every glyph starts with. */\n readonly color: TextColor;\n /** The wrap width in pixels; `0` or less means no wrapping. */\n readonly maxWidth: number;\n /** Which edge the lines align to, against the longest line. */\n readonly align: \"left\" | \"center\" | \"right\";\n /** The line-height multiplier. */\n readonly lineHeight: number;\n}\n\n/**\n * The pixel size of a laid-out block.\n *\n * @public\n */\nexport interface TextMetrics {\n /** The width of the longest line, in render-target pixels. */\n readonly width: number;\n /** The number of lines times the line height, in render-target pixels. */\n readonly height: number;\n}\n\n/**\n * Shapes a block of text.\n *\n * @param shape - The font, size, string, colour, and layout.\n * @returns The block, which owns its glyph storage.\n *\n * @internal\n */\nexport function createTextBlock(shape: TextShape): LiteTextData {\n const options: TextLayoutOptions = {\n ...(shape.maxWidth > 0 ? { maxWidth: shape.maxWidth } : {}),\n lineHeight: shape.lineHeight,\n align: shape.align,\n };\n return createDefaultTextData(shape.font, shape.fontSizePx, shape.text, shape.color, options);\n}\n\n/**\n * Re-shapes a block's string and colour, reusing its font size and layout options.\n *\n * @param data - The block.\n * @param text - The new string.\n * @param color - The new colour.\n *\n * @internal\n */\nexport function updateTextBlock(data: LiteTextData, text: string, color: TextColor): void {\n updateDefaultTextData(data, text, color);\n}\n\n/**\n * Reads a block's laid-out size.\n *\n * @param data - The block.\n * @returns The width and height, in render-target pixels.\n *\n * @internal\n */\nexport function measureText(data: LiteTextData): TextMetrics {\n return { width: data.width, height: data.height };\n}\n\n/**\n * Releases a block's GPU buffers and its glyph storage.\n *\n * @param data - The block.\n *\n * @internal\n */\nexport function destroyTextBlock(data: LiteTextData): void {\n disposeDefaultTextData(data);\n}\n\n/**\n * Builds a pixel-space layer for a block.\n *\n * @param data - The block to draw.\n * @param order - The sort order within the renderer; lower draws first.\n * @param opacity - The whole-block alpha multiplier.\n * @returns The layer.\n *\n * @internal\n */\nexport function createPixelTextLayer(data: LiteTextData, order: number, opacity: number): LiteTextLayer {\n return createTextLayer(data, { order, opacity });\n}\n\n/**\n * Moves a layer to a pixel position, measured from the render target's top-left corner.\n *\n * @param layer - The layer.\n * @param x - The x position, in render-target pixels.\n * @param y - The y position of the first baseline, in render-target pixels.\n *\n * @internal\n */\nexport function movePixelTextLayer(layer: LiteTextLayer, x: number, y: number): void {\n setTextLayerPosition(layer, x, y);\n}\n\n/**\n * Builds a world-space renderable for a block.\n *\n * @param data - The block to draw.\n * @param opacity - The whole-block alpha multiplier.\n * @returns The renderable.\n *\n * @internal\n */\nexport function createSceneText(data: LiteTextData, opacity: number): LiteTextRenderable {\n return createTextRenderable(data, { opacity });\n}\n\n/**\n * Adds a renderable to a scene's draw list.\n *\n * @remarks\n * One-way: Lite has no `removeTextRenderable`. See the module's own remarks.\n *\n * @param scene - The Lite scene, from `app.lite.scene`.\n * @param renderable - The renderable to draw.\n *\n * @internal\n */\nexport function attachSceneText(scene: SceneContext, renderable: LiteTextRenderable): void {\n addTextRenderable(scene, renderable);\n}\n\n/**\n * Makes a renderable draw nothing, which is as close to removing it as Lite allows.\n *\n * @param renderable - The renderable to silence.\n *\n * @internal\n */\nexport function detachSceneText(renderable: LiteTextRenderable): void {\n renderable.opacity = 0;\n}\n\n/**\n * Releases a renderable's GPU buffers. The block it draws is released separately.\n *\n * @param renderable - The renderable.\n *\n * @internal\n */\nexport function destroySceneText(renderable: LiteTextRenderable): void {\n disposeTextRenderable(renderable);\n}\n\n/**\n * Writes a renderable's world position, in metres.\n *\n * @param renderable - The renderable.\n * @param x - The x position.\n * @param y - The y position.\n * @param z - The z position.\n *\n * @internal\n */\nexport function moveSceneText(renderable: LiteTextRenderable, x: number, y: number, z: number): void {\n renderable.position.set(x, y, z);\n}\n\n/**\n * Writes a renderable's world rotation, as a quaternion.\n *\n * @param renderable - The renderable.\n * @param x - The x component.\n * @param y - The y component.\n * @param z - The z component.\n * @param w - The w component.\n *\n * @internal\n */\nexport function rotateSceneText(renderable: LiteTextRenderable, x: number, y: number, z: number, w: number): void {\n renderable.rotationQuaternion.set(x, y, z, w);\n}\n\n/**\n * Writes a renderable's uniform scale.\n *\n * @remarks\n * A block is laid out in **pixels**, so a world-space renderable is scaled down by\n * `1 / pixelsPerUnit` to occupy a sensible number of metres.\n *\n * @param renderable - The renderable.\n * @param scale - The uniform scale.\n *\n * @internal\n */\nexport function scaleSceneText(renderable: LiteTextRenderable, scale: number): void {\n renderable.scaling.set(scale, scale, scale);\n}\n","/**\n * Where a shaped block goes on the screen (`docs/architecture/13-ui.md` §2).\n *\n * Pure arithmetic, so the node suite covers all nine anchors with no GPU and no DOM.\n *\n * ## What Lite gives, and what it does not\n *\n * A `DefaultTextData` reports the laid-out `width` and `height` of the block and nothing else — no\n * ascent, no descent, no baseline offset (`index.d.ts` 3736-3741). Glyph baselines run downwards\n * in negative y from the layer's `positionPx`, verified on the pinned build: `\"A\\nB\\nC\"` at 32 px\n * with `lineHeight` 2 places the three baselines at y `0`, `-64`, `-128`.\n *\n * So the **first baseline** is at `positionPx.y`, and the box the reader perceives starts one em\n * above it. `ascentOf` is that approximation, stated once here rather than guessed at in three\n * components: an em is the right order of magnitude for every Latin face and it is what makes\n * `anchor: \"topLeft\"` put the text just inside the top-left corner rather than half off-screen.\n */\n\n/**\n * The nine points of a rectangle a block can be anchored to.\n *\n * @public\n */\nexport const HUD_ANCHORS = [\n \"topLeft\",\n \"top\",\n \"topRight\",\n \"left\",\n \"center\",\n \"right\",\n \"bottomLeft\",\n \"bottom\",\n \"bottomRight\",\n] as const;\n\n/**\n * Which point of the render target a `HudText`'s position is measured from, and which point of the\n * block sits there.\n *\n * @public\n */\nexport type HudAnchor = (typeof HUD_ANCHORS)[number];\n\n/** The horizontal fraction of each anchor: `0` at the left edge, `1` at the right. */\nconst ANCHOR_X: Readonly<Record<HudAnchor, number>> = Object.freeze({\n topLeft: 0,\n top: 0.5,\n topRight: 1,\n left: 0,\n center: 0.5,\n right: 1,\n bottomLeft: 0,\n bottom: 0.5,\n bottomRight: 1,\n});\n\n/** The vertical fraction of each anchor: `0` at the top edge, `1` at the bottom. */\nconst ANCHOR_Y: Readonly<Record<HudAnchor, number>> = Object.freeze({\n topLeft: 0,\n top: 0,\n topRight: 0,\n left: 0.5,\n center: 0.5,\n right: 0.5,\n bottomLeft: 1,\n bottom: 1,\n bottomRight: 1,\n});\n\n/**\n * The distance from a block's first baseline up to the top of the box a reader perceives.\n *\n * @param fontSize - The em size the block was shaped at.\n * @returns The ascent, in render-target pixels.\n *\n * @internal\n */\nexport function ascentOf(fontSize: number): number {\n return fontSize;\n}\n\n/**\n * A layer position, written in place so the per-frame path allocates nothing.\n *\n * @public\n */\nexport interface HudPlacement {\n /** The layer's x, in render-target pixels. */\n x: number;\n /** The layer's y — the first baseline — in render-target pixels. */\n y: number;\n}\n\n/**\n * What {@link computeHudPlacement} needs.\n *\n * @public\n */\nexport interface HudPlacementInput {\n /** Which point of the target the position is measured from, and which point of the block lands there. */\n readonly anchor: HudAnchor;\n /** The offset from that point, in render-target pixels; x grows right, y grows down. */\n readonly offsetX: number;\n /** The offset from that point, in render-target pixels. */\n readonly offsetY: number;\n /** The render target's width, in pixels. */\n readonly targetWidth: number;\n /** The render target's height, in pixels. */\n readonly targetHeight: number;\n /** The block's laid-out width. */\n readonly blockWidth: number;\n /** The block's laid-out height. */\n readonly blockHeight: number;\n /** The em size the block was shaped at. */\n readonly fontSize: number;\n}\n\n/**\n * Places a block against one of the nine anchors of the render target.\n *\n * @param input - The anchor, the offset, the target size, and the block's size.\n * @param out - Receives the layer position.\n * @returns `out`, for chaining.\n *\n * @example\n * ```ts\n * const out = { x: 0, y: 0 };\n * computeHudPlacement(\n * {\n * anchor: \"topRight\",\n * offsetX: -16,\n * offsetY: 16,\n * targetWidth: 800,\n * targetHeight: 600,\n * blockWidth: 100,\n * blockHeight: 40,\n * fontSize: 32,\n * },\n * out,\n * );\n * out.x; // 684 — 16 px in from the right edge\n * ```\n *\n * @public\n */\nexport function computeHudPlacement(input: HudPlacementInput, out: HudPlacement): HudPlacement {\n const fractionX = ANCHOR_X[input.anchor];\n const fractionY = ANCHOR_Y[input.anchor];\n const boxLeft = fractionX * input.targetWidth + input.offsetX - fractionX * input.blockWidth;\n const boxTop = fractionY * input.targetHeight + input.offsetY - fractionY * input.blockHeight;\n out.x = boxLeft;\n out.y = boxTop + ascentOf(input.fontSize);\n return out;\n}\n\n/**\n * Places a block around a point, with the given point of the block sitting on it.\n *\n * @param pivot - Which point of the block lands on the position.\n * @param x - The point's x, in render-target pixels.\n * @param y - The point's y, in render-target pixels.\n * @param blockWidth - The block's laid-out width.\n * @param blockHeight - The block's laid-out height.\n * @param fontSize - The em size the block was shaped at.\n * @param out - Receives the layer position.\n * @returns `out`, for chaining.\n *\n * @example\n * ```ts\n * const out = { x: 0, y: 0 };\n * computePivotPlacement(\"center\", 400, 300, 100, 40, 32, out);\n * out.x; // 350\n * ```\n *\n * @public\n */\nexport function computePivotPlacement(\n pivot: HudAnchor,\n x: number,\n y: number,\n blockWidth: number,\n blockHeight: number,\n fontSize: number,\n out: HudPlacement,\n): HudPlacement {\n out.x = x - ANCHOR_X[pivot] * blockWidth;\n out.y = y - ANCHOR_Y[pivot] * blockHeight + ascentOf(fontSize);\n return out;\n}\n","import { asset, color, Component, enumOf, f32, FontAsset, str } from \"@ignifx/core\";\nimport { createTextBlock, destroyTextBlock, measureText, updateTextBlock } from \"../lite/text.js\";\nimport type { I18nService } from \"../i18n/i18n-service.js\";\nimport type { LiteTextData, TextColor, TextMetrics } from \"../lite/text.js\";\nimport type { AssetHandle, ColorLike, FieldDefinition } from \"@ignifx/core\";\n\n/**\n * The fields and the block lifecycle every text component shares (`docs/architecture/13-ui.md` §2:\n * \"`text`, `fontSize`, `color`, `align`, `maxWidth`, `opacity`, `billboard`\"*).\n *\n * ## Why the block is rebuilt for some changes and updated for others\n *\n * `updateDefaultTextData` re-shapes with the font size and layout options the block was created\n * with, and only those — verified in `@babylonjs/lite@1.27.0`'s `lib/text/default-text-data.js`, which reads\n * `data._fontSizePx` and `data._options` and never takes new ones. So a change to `text` or\n * `color` is an update, which keeps the glyph storage and its atlas; a change to `font`,\n * `fontSize`, `maxWidth`, `align`, or `lineHeight` is a rebuild. The component tracks both, so a\n * HUD counter that changes every frame pays for one re-shape and nothing else.\n *\n * ## Localization\n *\n * `i18nKey` wins over `text` when it is set, and the block is re-shaped whenever\n * `app.i18n.onLocaleChanged` fires. A component with neither draws nothing rather than drawing an\n * empty box.\n */\n\n/**\n * The alignments Lite's default layout supports (`index.d.ts` 12826-12827).\n *\n * @public\n */\nexport const TEXT_ALIGNMENTS = [\"left\", \"center\", \"right\"] as const;\n\n/**\n * Which edge a block's lines align to. Lite aligns lines against the block's **longest line**, not\n * against `maxWidth`, so a single-line block looks the same in all three.\n *\n * @public\n */\nexport type TextAlignment = (typeof TEXT_ALIGNMENTS)[number];\n\n/**\n * The schema fields every text component declares, so the three components stay in step.\n *\n * @returns The field definitions to spread into a `defineSchema` call.\n *\n * @internal\n */\nexport function textSchemaFields(): {\n font: FieldDefinition<AssetHandle<FontAsset> | null>;\n text: FieldDefinition<string>;\n i18nKey: FieldDefinition<string>;\n fontSize: FieldDefinition<number>;\n color: FieldDefinition<ColorLike>;\n align: FieldDefinition<TextAlignment>;\n maxWidth: FieldDefinition<number>;\n lineHeight: FieldDefinition<number>;\n opacity: FieldDefinition<number>;\n} {\n return {\n font: asset(FontAsset, { tooltip: \"The TTF or OTF the glyphs come from.\" }),\n text: str(\"\", { tooltip: \"The literal string to draw; ignored when i18nKey is set.\" }),\n i18nKey: str(\"\", { tooltip: \"A translation key looked up in app.i18n; wins over text.\" }),\n fontSize: f32(32, { min: 1, tooltip: \"The em size, in render-target pixels.\" }),\n color: color({ r: 1, g: 1, b: 1, a: 1 }, { tooltip: \"The colour every glyph starts with.\" }),\n align: enumOf(TEXT_ALIGNMENTS, \"left\", { tooltip: \"Which edge the lines align to.\" }),\n maxWidth: f32(0, { min: 0, tooltip: \"The wrap width in pixels; 0 does not wrap.\" }),\n lineHeight: f32(1.2, { min: 0.1, tooltip: \"The line-height multiplier.\" }),\n opacity: f32(1, { min: 0, max: 1, tooltip: \"The whole-block alpha multiplier.\" }),\n };\n}\n\n/** The block-shaping inputs that force a rebuild rather than an update. */\ninterface ShapeKey {\n /** The font handle the block was built from. */\n font: AssetHandle<FontAsset> | null;\n /** The em size. */\n fontSize: number;\n /** The wrap width. */\n maxWidth: number;\n /** The alignment. */\n align: TextAlignment;\n /** The line-height multiplier. */\n lineHeight: number;\n}\n\n/**\n * The base of `HudText`, `WorldText2D`, and `WorldText`: the schema fields and the shaped block.\n *\n * @remarks\n * Abstract, and never registered as a component itself; the three concrete classes are.\n *\n * @public\n */\nexport abstract class TextComponent extends Component {\n /** The TTF or OTF the glyphs come from. */\n declare font: AssetHandle<FontAsset> | null;\n\n /** The literal string to draw; ignored when {@link TextComponent.i18nKey} is set. */\n declare text: string;\n\n /** A translation key looked up in `app.i18n`; wins over {@link TextComponent.text}. */\n declare i18nKey: string;\n\n /** The em size, in render-target pixels. */\n declare fontSize: number;\n\n /** The colour every glyph starts with. */\n declare color: ColorLike;\n\n /** Which edge the lines align to. */\n declare align: TextAlignment;\n\n /** The wrap width, in render-target pixels; `0` does not wrap. */\n declare maxWidth: number;\n\n /** The line-height multiplier. */\n declare lineHeight: number;\n\n /** The whole-block alpha multiplier. */\n declare opacity: number;\n\n #block: LiteTextData | null = null;\n\n #shape: ShapeKey = { font: null, fontSize: 0, maxWidth: -1, align: \"left\", lineHeight: 0 };\n\n #lastText = \"\\u0000\";\n\n readonly #lastColor: [number, number, number, number] = [-1, -1, -1, -1];\n\n /**\n * The shaped block, or `null` until a font and a non-empty string are both present.\n *\n * @returns The block.\n *\n * @internal\n */\n get block(): LiteTextData | null {\n return this.#block;\n }\n\n /**\n * The block's laid-out size, in render-target pixels.\n *\n * @remarks\n * `{ width: 0, height: 0 }` until the block exists. This is Lite's only text measurement, and\n * it is what a caller centring a block on the screen needs — Lite's `align` aligns lines against\n * each other, not against the screen.\n *\n * @returns The size.\n *\n * @example\n * ```ts\n * const label = entity.addComponent(HudText);\n * label.metrics.width; // 0 until a font and a string are set\n * ```\n */\n get metrics(): TextMetrics {\n const block = this.#block;\n return block === null ? { width: 0, height: 0 } : measureText(block);\n }\n\n /**\n * The string that will actually be drawn: the translated `i18nKey`, or `text`.\n *\n * @param i18n - The localization service, or `null` when the app has none.\n * @returns The resolved string.\n */\n resolveText(i18n: I18nService | null): string {\n if (this.i18nKey === \"\") {\n return this.text;\n }\n return i18n === null ? this.i18nKey : i18n.t(this.i18nKey);\n }\n\n /**\n * Brings the shaped block in line with the component's fields.\n *\n * @remarks\n * The one place a block is created, re-shaped, or destroyed. Called by the UI text system once a\n * frame; it does nothing at all when nothing changed, which is what keeps a static label free.\n *\n * @param i18n - The localization service, or `null`.\n * @returns `\"created\"` when a new block was built (the caller has to rebuild its layer or\n * renderable), `\"updated\"` when the existing one was re-shaped, `\"removed\"` when the block went\n * away, and `\"unchanged\"` otherwise.\n *\n * @internal\n */\n syncBlock(i18n: I18nService | null): \"created\" | \"updated\" | \"removed\" | \"unchanged\" {\n const font = this.font;\n const value = this.resolveText(i18n);\n if (font === null || font.state !== \"loaded\" || value === \"\") {\n return this.#destroy();\n }\n const rebuild =\n this.#block === null ||\n this.#shape.font !== font ||\n this.#shape.fontSize !== this.fontSize ||\n this.#shape.maxWidth !== this.maxWidth ||\n this.#shape.align !== this.align ||\n this.#shape.lineHeight !== this.lineHeight;\n const colour: TextColor = [this.color.r, this.color.g, this.color.b, this.color.a];\n if (rebuild) {\n this.#destroy();\n this.#block = createTextBlock({\n font: font.value.lite.font,\n fontSizePx: this.fontSize,\n text: value,\n color: colour,\n maxWidth: this.maxWidth,\n align: this.align,\n lineHeight: this.lineHeight,\n });\n this.#shape = {\n font,\n fontSize: this.fontSize,\n maxWidth: this.maxWidth,\n align: this.align,\n lineHeight: this.lineHeight,\n };\n this.#remember(value, colour);\n return \"created\";\n }\n if (value === this.#lastText && this.#colourUnchanged(colour)) {\n return \"unchanged\";\n }\n const block = this.#block;\n if (block !== null) {\n updateTextBlock(block, value, colour);\n }\n this.#remember(value, colour);\n return \"updated\";\n }\n\n /**\n * Releases the shaped block. The concrete components call it from `onDestroy`.\n *\n * @internal\n */\n releaseBlock(): void {\n this.#destroy();\n }\n\n /**\n * Destroys the block, if there is one.\n *\n * @returns `\"removed\"` when a block went away, `\"unchanged\"` otherwise.\n */\n #destroy(): \"removed\" | \"unchanged\" {\n const block = this.#block;\n if (block === null) {\n return \"unchanged\";\n }\n destroyTextBlock(block);\n this.#block = null;\n this.#shape = { font: null, fontSize: 0, maxWidth: -1, align: \"left\", lineHeight: 0 };\n this.#lastText = \"\\u0000\";\n this.#lastColor[0] = -1;\n return \"removed\";\n }\n\n /**\n * Records the string and colour the block currently holds.\n *\n * @param value - The string.\n * @param colour - The colour.\n */\n #remember(value: string, colour: TextColor): void {\n this.#lastText = value;\n this.#lastColor[0] = colour[0];\n this.#lastColor[1] = colour[1];\n this.#lastColor[2] = colour[2];\n this.#lastColor[3] = colour[3];\n }\n\n /**\n * Whether the colour matches the one the block holds.\n *\n * @param colour - The colour the fields ask for.\n * @returns `true` when all four channels match.\n */\n #colourUnchanged(colour: TextColor): boolean {\n return (\n this.#lastColor[0] === colour[0] &&\n this.#lastColor[1] === colour[1] &&\n this.#lastColor[2] === colour[2] &&\n this.#lastColor[3] === colour[3]\n );\n }\n}\n","import { createDefaults, defineSchema, enumOf, i32, vec2 } from \"@ignifx/core\";\nimport { createPixelTextLayer, movePixelTextLayer } from \"../lite/text.js\";\nimport { computeHudPlacement, HUD_ANCHORS } from \"./hud-layout.js\";\nimport { TextComponent, textSchemaFields } from \"./text-component.js\";\nimport type { HudAnchor, HudPlacement } from \"./hud-layout.js\";\nimport type { TextRuntime } from \"./text-runtime.js\";\nimport type { I18nService } from \"../i18n/i18n-service.js\";\nimport type { LiteTextLayer } from \"../lite/text.js\";\nimport type { ComponentHooks, Schema, Vec2Like } from \"@ignifx/core\";\n\n/**\n * `HudText` (`docs/architecture/13-ui.md` §2): pixel-space text drawn by Babylon Lite rather than\n * by the DOM, *\"when DOM text is not desirable (e.g. capture-perfect pixel HUDs, screenshots via\n * `captureScreenshot`)\"*.\n *\n * ## The coordinate system is the render target, not CSS\n *\n * Lite's text renderer positions a layer against `surface.canvas.width`/`.height`\n * (`lib/text/text-renderer.js`), so `position` is in **backing-store pixels**. That is deliberate\n * and is the whole point of the component: the pixel a `HudText` draws on is the pixel\n * `app.renderer.captureScreenshot()` reads back, so a golden test asserts on an exact address. A\n * DOM label in `app.ui.layer(\"hud\")` is the right tool whenever that is not what you want.\n */\n\n/**\n * Pixel-space HUD text.\n *\n * @example\n * ```ts\n * const label = app.world.createEntity(\"score\").addComponent(HudText);\n * label.font = app.assets.load<FontAsset>(\"ui/Inter-Regular.ttf\");\n * label.anchor = \"topLeft\";\n * label.position = { x: 16, y: 16 };\n * label.i18nKey = \"hud.score\";\n * ```\n *\n * @public\n */\nexport class HudText extends TextComponent implements ComponentHooks {\n /** The registration id the serializer writes into scene files. */\n static typeId = \"ignifx/HudText\";\n\n /** One HUD label per entity; a second belongs on a second entity. */\n static allowMultiple = false;\n\n /** The declarative fields (ADR-0004). */\n static schema: Schema = hudTextSchema();\n\n /** Which point of the render target {@link HudText.position} is measured from. */\n declare anchor: HudAnchor;\n\n /** The offset from the anchor, in render-target pixels; x grows right, y grows down. */\n declare position: Vec2Like;\n\n /** The sort order within the text renderer; lower draws first. */\n declare order: number;\n\n #layer: LiteTextLayer | null = null;\n\n #runtime: TextRuntime | null = null;\n\n readonly #placement: HudPlacement = { x: 0, y: 0 };\n\n /** Builds a HUD label with the schema's defaults. */\n constructor() {\n super();\n Object.assign(this, createDefaults(HudText.schema));\n }\n\n /**\n * The Babylon Lite objects the component owns. Unstable escape hatch\n * (`docs/architecture/00-overview.md` §3).\n *\n * @returns The text layer, or `null` before the first frame that had a font and a string.\n */\n get lite(): { readonly layer: LiteTextLayer | null } {\n return { layer: this.#layer };\n }\n\n /** Drops the layer and the block when the component goes away. */\n onDetach(): void {\n this.#dropLayer();\n this.releaseBlock();\n }\n\n /**\n * Brings the layer in line with the component's fields. The UI text system calls it once a frame.\n *\n * @param runtime - The renderer the layer is registered on.\n * @param i18n - The localization service, or `null`.\n * @param targetWidth - The render target's width, in pixels.\n * @param targetHeight - The render target's height, in pixels.\n *\n * @internal\n */\n sync(runtime: TextRuntime, i18n: I18nService | null, targetWidth: number, targetHeight: number): void {\n this.#runtime = runtime;\n const change = this.syncBlock(i18n);\n const block = this.block;\n if (block === null) {\n this.#dropLayer();\n return;\n }\n if (change === \"created\" || this.#layer === null) {\n this.#dropLayer();\n const layer = createPixelTextLayer(block, this.order, this.opacity);\n this.#layer = layer;\n runtime.addLayer(layer);\n }\n const layer = this.#layer;\n layer.opacity = this.opacity;\n layer.order = this.order;\n layer.visible = this.isEnabledInHierarchy;\n const metrics = this.metrics;\n computeHudPlacement(\n {\n anchor: this.anchor,\n offsetX: this.position.x,\n offsetY: this.position.y,\n targetWidth,\n targetHeight,\n blockWidth: metrics.width,\n blockHeight: metrics.height,\n fontSize: this.fontSize,\n },\n this.#placement,\n );\n if (layer.positionPx.x !== this.#placement.x || layer.positionPx.y !== this.#placement.y) {\n movePixelTextLayer(layer, this.#placement.x, this.#placement.y);\n }\n }\n\n /** Removes the layer from the renderer, if it has one. */\n #dropLayer(): void {\n const layer = this.#layer;\n if (layer === null) {\n return;\n }\n this.#runtime?.removeLayer(layer);\n this.#layer = null;\n }\n}\n\n/**\n * The `HudText` schema.\n *\n * @returns The schema, built fresh so no module holds state (`CONSTITUTION.md` §3.5).\n */\nfunction hudTextSchema(): Schema {\n return defineSchema({\n ...textSchemaFields(),\n anchor: enumOf(HUD_ANCHORS, \"topLeft\", { tooltip: \"Which corner of the screen the position is measured from.\" }),\n position: vec2({ x: 0, y: 0 }, { tooltip: \"The offset from the anchor, in render-target pixels.\" }),\n order: i32(0, { tooltip: \"Sort order within the text renderer; lower draws first.\" }),\n });\n}\n","import type { LiteTextLayer, LiteTextRenderer } from \"../lite/text.js\";\n\n/**\n * The text renderer's life, injected rather than imported so the node suite covers it\n * (`docs/architecture/11-2d-toolkit.md` §1 uses the same shape for the sprite renderer, and\n * `07-rendering.md` §1 is the rule both follow).\n *\n * ## Why the renderer is created lazily\n *\n * A `TextRenderer` must be registered **after** the render scene, so it composites over the frame\n * rather than under it. An extension's `register` runs before the scene exists and its `onStart`\n * runs only when a game calls `app.start()` — which a headless tool never does. Creating it on the\n * first `PreRender` tick is the one moment that satisfies both: the scene is registered, and a\n * headless app never gets there because it has no renderer factory in the first place.\n */\n\n/**\n * The renderer operations the runtime needs, supplied by the extension so this module never imports\n * `@babylonjs/lite`.\n *\n * @internal\n */\nexport interface TextRuntimeOptions {\n /** Creates and registers the renderer, or `null` under a headless app. */\n readonly createRenderer: (() => LiteTextRenderer) | null;\n /** Adds a layer to the renderer's draw list. */\n readonly attachLayer: (renderer: LiteTextRenderer, layer: LiteTextLayer) => void;\n /** Removes a layer from the renderer's draw list. */\n readonly detachLayer: (renderer: LiteTextRenderer, layer: LiteTextLayer) => boolean;\n /** Unregisters and disposes the renderer. */\n readonly destroyRenderer: (renderer: LiteTextRenderer) => void;\n}\n\n/**\n * Owns the one text renderer an app has, and the layers registered on it.\n *\n * @internal\n */\nexport class TextRuntime {\n readonly #options: TextRuntimeOptions;\n\n readonly #pending = new Set<LiteTextLayer>();\n\n readonly #attached = new Set<LiteTextLayer>();\n\n #renderer: LiteTextRenderer | null = null;\n\n #disposed = false;\n\n /**\n * Builds the runtime. The extension does this.\n *\n * @param options - The renderer operations.\n */\n constructor(options: TextRuntimeOptions) {\n this.#options = options;\n }\n\n /**\n * The renderer, once it exists.\n *\n * @returns The renderer, or `null` before the first frame and under a headless app.\n */\n get renderer(): LiteTextRenderer | null {\n return this.#renderer;\n }\n\n /**\n * How many layers are currently drawn.\n *\n * @returns The count.\n */\n get layerCount(): number {\n return this.#attached.size + this.#pending.size;\n }\n\n /**\n * Creates the renderer if it does not exist yet and flushes the layers that were registered\n * before it did. The UI text system calls this at the top of every `PreRender`.\n */\n ensureRenderer(): void {\n if (this.#disposed || this.#renderer !== null || this.#options.createRenderer === null) {\n return;\n }\n const renderer = this.#options.createRenderer();\n this.#renderer = renderer;\n for (const layer of this.#pending) {\n this.#options.attachLayer(renderer, layer);\n this.#attached.add(layer);\n }\n this.#pending.clear();\n }\n\n /**\n * Starts drawing a layer.\n *\n * @param layer - The layer.\n */\n addLayer(layer: LiteTextLayer): void {\n if (this.#disposed || this.#attached.has(layer) || this.#pending.has(layer)) {\n return;\n }\n const renderer = this.#renderer;\n if (renderer === null) {\n this.#pending.add(layer);\n return;\n }\n this.#options.attachLayer(renderer, layer);\n this.#attached.add(layer);\n }\n\n /**\n * Stops drawing a layer and frees its per-layer GPU buffers.\n *\n * @param layer - The layer.\n */\n removeLayer(layer: LiteTextLayer): void {\n this.#pending.delete(layer);\n if (!this.#attached.delete(layer)) {\n return;\n }\n const renderer = this.#renderer;\n if (renderer !== null) {\n this.#options.detachLayer(renderer, layer);\n }\n }\n\n /** Tears the renderer down. The extension calls this from `onDispose`. */\n dispose(): void {\n if (this.#disposed) {\n return;\n }\n this.#disposed = true;\n const renderer = this.#renderer;\n this.#pending.clear();\n this.#attached.clear();\n this.#renderer = null;\n if (renderer !== null) {\n this.#options.destroyRenderer(renderer);\n }\n }\n}\n","import { bool, createDefaults, defineSchema, enumOf, i32, vec2, vec3 } from \"@ignifx/core\";\nimport { createPixelTextLayer, movePixelTextLayer } from \"../lite/text.js\";\nimport { computePivotPlacement, HUD_ANCHORS } from \"./hud-layout.js\";\nimport { TextComponent, textSchemaFields } from \"./text-component.js\";\nimport type { HudAnchor, HudPlacement } from \"./hud-layout.js\";\nimport type { TextRuntime } from \"./text-runtime.js\";\nimport type { I18nService } from \"../i18n/i18n-service.js\";\nimport type { LiteTextLayer } from \"../lite/text.js\";\nimport type { ComponentHooks, Schema, Vec2Like, Vec3Like } from \"@ignifx/core\";\n\n/**\n * `WorldText2D` (`docs/architecture/13-ui.md` §2): text that belongs to the world — damage numbers,\n * floating names — but is drawn as a flat pixel-space layer rather than as geometry, so it never\n * shrinks with distance and never intersects a wall.\n *\n * It is `HudText`'s twin: the same Lite text layer, positioned from the entity's **projected**\n * screen position instead of from a screen anchor. `WorldText` is the other choice, and the one to\n * take when the text should be occluded by the world.\n */\n\n/**\n * World-anchored pixel-space text.\n *\n * @example\n * ```ts\n * const damage = app.world.createEntity(\"damage\").addComponent(WorldText2D);\n * damage.font = app.assets.load<FontAsset>(\"ui/Inter-Regular.ttf\");\n * damage.text = \"-12\";\n * damage.offset = { x: 0, y: 1.8, z: 0 };\n * ```\n *\n * @public\n */\nexport class WorldText2D extends TextComponent implements ComponentHooks {\n /** The registration id the serializer writes into scene files. */\n static typeId = \"ignifx/WorldText2D\";\n\n /** One floating label per entity. */\n static allowMultiple = false;\n\n /** The declarative fields (ADR-0004). */\n static schema: Schema = worldText2DSchema();\n\n /** A world-space offset added to the entity's position before projecting, in metres. */\n declare offset: Vec3Like;\n\n /** A screen-space offset added after projecting, in render-target pixels. */\n declare screenOffset: Vec2Like;\n\n /** Which point of the block sits on the projected position. */\n declare pivot: HudAnchor;\n\n /** Whether the label is hidden when the anchor point is behind the camera. */\n declare hideWhenBehindCamera: boolean;\n\n /** The sort order within the text renderer; lower draws first. */\n declare order: number;\n\n #layer: LiteTextLayer | null = null;\n\n #runtime: TextRuntime | null = null;\n\n readonly #placement: HudPlacement = { x: 0, y: 0 };\n\n /** Builds a floating label with the schema's defaults. */\n constructor() {\n super();\n Object.assign(this, createDefaults(WorldText2D.schema));\n }\n\n /**\n * The Babylon Lite objects the component owns. Unstable escape hatch.\n *\n * @returns The text layer, or `null` before the first frame that had a font and a string.\n */\n get lite(): { readonly layer: LiteTextLayer | null } {\n return { layer: this.#layer };\n }\n\n /** Drops the layer and the block when the component goes away. */\n onDetach(): void {\n this.#dropLayer();\n this.releaseBlock();\n }\n\n /**\n * Brings the layer in line with the component's fields and the projected position.\n *\n * @param runtime - The renderer the layer is registered on.\n * @param i18n - The localization service, or `null`.\n * @param screenX - The entity's projected x, in render-target pixels.\n * @param screenY - The entity's projected y, in render-target pixels.\n * @param inFront - Whether the anchor point is in front of the camera.\n *\n * @internal\n */\n sync(runtime: TextRuntime, i18n: I18nService | null, screenX: number, screenY: number, inFront: boolean): void {\n this.#runtime = runtime;\n const change = this.syncBlock(i18n);\n const block = this.block;\n if (block === null) {\n this.#dropLayer();\n return;\n }\n if (change === \"created\" || this.#layer === null) {\n this.#dropLayer();\n const layer = createPixelTextLayer(block, this.order, this.opacity);\n this.#layer = layer;\n runtime.addLayer(layer);\n }\n const layer = this.#layer;\n layer.opacity = this.opacity;\n layer.order = this.order;\n layer.visible = this.isEnabledInHierarchy && (inFront || !this.hideWhenBehindCamera);\n const metrics = this.metrics;\n computePivotPlacement(\n this.pivot,\n screenX + this.screenOffset.x,\n screenY + this.screenOffset.y,\n metrics.width,\n metrics.height,\n this.fontSize,\n this.#placement,\n );\n if (layer.positionPx.x !== this.#placement.x || layer.positionPx.y !== this.#placement.y) {\n movePixelTextLayer(layer, this.#placement.x, this.#placement.y);\n }\n }\n\n /** Removes the layer from the renderer, if it has one. */\n #dropLayer(): void {\n const layer = this.#layer;\n if (layer === null) {\n return;\n }\n this.#runtime?.removeLayer(layer);\n this.#layer = null;\n }\n}\n\n/**\n * The `WorldText2D` schema.\n *\n * @returns The schema, built fresh so no module holds state (`CONSTITUTION.md` §3.5).\n */\nfunction worldText2DSchema(): Schema {\n return defineSchema({\n ...textSchemaFields(),\n offset: vec3({ x: 0, y: 0, z: 0 }, { tooltip: \"A world-space offset added before projecting, in metres.\" }),\n screenOffset: vec2({ x: 0, y: 0 }, { tooltip: \"A screen-space offset added after projecting, in pixels.\" }),\n pivot: enumOf(HUD_ANCHORS, \"center\", { tooltip: \"Which point of the block sits on the projected position.\" }),\n hideWhenBehindCamera: bool(true, { tooltip: \"Hide the label when the anchor is behind the camera.\" }),\n order: i32(0, { tooltip: \"Sort order within the text renderer; lower draws first.\" }),\n });\n}\n","import { bool, createDefaults, defineSchema, f32, Quat, vec3, Vec3 } from \"@ignifx/core\";\nimport { UiErrorCode } from \"../errors.js\";\nimport {\n attachSceneText,\n createSceneText,\n destroySceneText,\n detachSceneText,\n moveSceneText,\n rotateSceneText,\n scaleSceneText,\n} from \"../lite/text.js\";\nimport { TextComponent, textSchemaFields } from \"./text-component.js\";\nimport type { I18nService } from \"../i18n/i18n-service.js\";\nimport type { LiteTextRenderable } from \"../lite/text.js\";\nimport type { ComponentHooks, LiteScene, MutableQuat, MutableVec3, QuatLike, Schema, Vec3Like } from \"@ignifx/core\";\n\n/**\n * `WorldText` (`docs/architecture/13-ui.md` §2): text that is part of the world — a sign, a\n * banner, a floating label that is hidden by the wall in front of it — drawn as a Babylon Lite\n * `TextRenderable` inside the render scene.\n *\n * ## Blocks are laid out in pixels, so the renderable is scaled down\n *\n * `createDefaultTextData` shapes in pixels: at `fontSize` 32 a capital letter is about 32 units\n * tall. A renderable at scale 1 would therefore be tens of metres high. {@link WorldText.pixelsPerUnit}\n * is the divisor, defaulting to 100 to match `@ignifx/2d`'s own default, so a 32-pixel block is\n * 0.32 m tall.\n *\n * ## It has to exist before `app.start()`\n *\n * `addTextRenderable` (`index.d.ts` 208) pushes a **deferred builder** onto the scene\n * (`lib/text/text-renderable.js` 242-249), and the only thing that drains those builders is\n * `buildScene`, which `registerScene` calls once (`lib/scene/scene-core.js` 228-241 and 246-262).\n * `rebuildSceneRenderables` — the one public rebuild — explicitly does not: it rebuilds *groups*\n * and returns early on an unbuilt scene, and Lite's runtime-build machinery is for meshes only. So\n * a renderable added after `app.start()` has registered the scene never materialises, and there is\n * no public call that would make it.\n *\n * A `WorldText` whose font and text are both present before the app starts therefore draws; one\n * that first gets its text mid-game does not, and says so once with `IGX-1308`. Until Lite exposes\n * a way to drain a late deferred renderable, the answers are to author signs in the scene file the\n * game starts with, or to use {@link WorldText2D}, which owns a text *layer* and can be added at\n * any time.\n *\n * ## Removal is one-way\n *\n * Babylon Lite 1.27.0 has `addTextRenderable` (`index.d.ts` 208) and **no inverse**:\n * `removeFromScene` (9613) accepts meshes, lights, cameras, shadow generators, transform nodes and\n * asset containers, and a `TextRenderable` is none of them. A destroyed `WorldText` therefore\n * empties its block and zeroes the renderable's opacity — it draws nothing and holds no GPU\n * buffers — but the record itself stays in the scene's renderable list until the scene is disposed.\n * A game that spawns and destroys thousands of signs should pool the components rather than the\n * entities. This is recorded as a Lite gap rather than worked around.\n */\n\n/**\n * World-space 3D text.\n *\n * @example\n * ```ts\n * const sign = app.world.createEntity(\"sign\").addComponent(WorldText);\n * sign.font = app.assets.load<FontAsset>(\"ui/Inter-Regular.ttf\");\n * sign.text = \"Danger\";\n * sign.billboard = true;\n * ```\n *\n * @public\n */\nexport class WorldText extends TextComponent implements ComponentHooks {\n /** The registration id the serializer writes into scene files. */\n static typeId = \"ignifx/WorldText\";\n\n /** One sign per entity. */\n static allowMultiple = false;\n\n /** The declarative fields (ADR-0004). */\n static schema: Schema = worldTextSchema();\n\n /** A local offset added to the entity's world position, in metres. */\n declare offset: Vec3Like;\n\n /** How many pixels of laid-out text span one world metre. */\n declare pixelsPerUnit: number;\n\n /** Whether the text turns to face the camera instead of following the entity's rotation. */\n declare billboard: boolean;\n\n /** Whether the text draws through geometry in front of it. */\n declare alwaysOnTop: boolean;\n\n #renderable: LiteTextRenderable | null = null;\n\n #scene: LiteScene | null = null;\n\n readonly #position: MutableVec3 = new Vec3();\n\n readonly #rotation: MutableQuat = new Quat();\n\n /** Builds a sign with the schema's defaults. */\n constructor() {\n super();\n Object.assign(this, createDefaults(WorldText.schema));\n }\n\n /**\n * The Babylon Lite objects the component owns. Unstable escape hatch.\n *\n * @returns The renderable, or `null` before the first frame that had a font and a string.\n */\n get lite(): { readonly renderable: LiteTextRenderable | null } {\n return { renderable: this.#renderable };\n }\n\n /** Silences and releases the renderable when the component goes away. */\n onDetach(): void {\n const renderable = this.#renderable;\n if (renderable !== null) {\n detachSceneText(renderable);\n destroySceneText(renderable);\n this.#renderable = null;\n }\n this.releaseBlock();\n }\n\n /**\n * Brings the renderable in line with the component's fields and the entity's transform.\n *\n * @param scene - The Lite scene the renderable is added to, from `app.lite.scene`.\n * @param i18n - The localization service, or `null`.\n * @param cameraRotation - The main camera's world rotation, for billboarding, or `null` when the\n * world has no camera.\n *\n * @internal\n */\n sync(scene: LiteScene, i18n: I18nService | null, cameraRotation: QuatLike | null): void {\n const change = this.syncBlock(i18n);\n const block = this.block;\n if (block === null) {\n const existing = this.#renderable;\n if (existing !== null) {\n detachSceneText(existing);\n destroySceneText(existing);\n this.#renderable = null;\n }\n return;\n }\n if (change === \"created\" || this.#renderable === null) {\n const previous = this.#renderable;\n if (previous !== null) {\n detachSceneText(previous);\n destroySceneText(previous);\n }\n const renderable = createSceneText(block, this.opacity);\n renderable.ignoreDepth = this.alwaysOnTop;\n attachSceneText(scene, renderable);\n this.#renderable = renderable;\n this.#scene = scene;\n this.#warnIfLate();\n }\n const renderable = this.#renderable;\n renderable.opacity = this.isEnabledInHierarchy ? this.opacity : 0;\n renderable.ignoreDepth = this.alwaysOnTop;\n const transform = this.transform;\n transform.positionToRef(this.#position);\n moveSceneText(\n renderable,\n this.#position.x + this.offset.x,\n this.#position.y + this.offset.y,\n this.#position.z + this.offset.z,\n );\n const rotation =\n this.billboard && cameraRotation !== null ? cameraRotation : transform.rotationToRef(this.#rotation);\n rotateSceneText(renderable, rotation.x, rotation.y, rotation.z, rotation.w);\n const divisor = this.pixelsPerUnit > 0 ? this.pixelsPerUnit : 1;\n scaleSceneText(renderable, 1 / divisor);\n }\n\n /**\n * Reports `IGX-1308` once when the renderable was built too late for Lite to draw it. See the\n * module's own remarks.\n */\n #warnIfLate(): void {\n const app = this.app;\n if (!app.isRunning || app.isHeadless) {\n return;\n }\n app.log.warnOnce(\n \"ignifx/ui/world-text-late\",\n `${WorldText.typeId} was given its text after app.start(), so Babylon Lite will not draw it ` +\n `(${UiErrorCode.sceneAlreadyBuilt}). Author the sign before starting, or use WorldText2D.`,\n );\n }\n\n /**\n * The scene the renderable was added to, for diagnostics.\n *\n * @returns The scene, or `null` when nothing has been added yet.\n *\n * @internal\n */\n get scene(): LiteScene | null {\n return this.#scene;\n }\n}\n\n/**\n * The `WorldText` schema.\n *\n * @returns The schema, built fresh so no module holds state (`CONSTITUTION.md` §3.5).\n */\nfunction worldTextSchema(): Schema {\n return defineSchema({\n ...textSchemaFields(),\n offset: vec3({ x: 0, y: 0, z: 0 }, { tooltip: \"A local offset added to the entity's position, in metres.\" }),\n pixelsPerUnit: f32(100, { min: 1, tooltip: \"How many pixels of laid-out text span one metre.\" }),\n billboard: bool(false, { tooltip: \"Turn the text to face the camera.\" }),\n alwaysOnTop: bool(false, { tooltip: \"Draw through geometry in front of the text.\" }),\n });\n}\n","// The build replaces this with the version in `package.json` (`define` in `tsdown.config.ts`).\ndeclare const IGNIFX_BUILD_VERSION: string | undefined;\n\n/**\n * The `@ignifx/ui` version this build was cut from, reported as `Extension.version`\n * (`docs/architecture/04-extensions.md` §1).\n *\n * @remarks\n * The build stamps it from `package.json`; code run from source, such as this repository's tests,\n * sees `\"0.0.0\"`.\n *\n * @public\n */\nexport const VERSION: string = typeof IGNIFX_BUILD_VERSION === \"string\" ? IGNIFX_BUILD_VERSION : \"0.0.0\";\n","import { clamp } from \"@ignifx/core\";\nimport type { UiPixelMapping } from \"../dom/scaling.js\";\n\n/**\n * Convert camera backing-store pixels to overlay units through `UiPixelMapping`.\n * Behind-camera projections are mirrored: hide them, or reflect before clamping to the viewport\n * edge. Keep the arithmetic independent of the DOM for headless tests.\n */\n\n/**\n * Everything {@link computeAnchorPlacement} reads.\n *\n * @public\n */\nexport interface AnchorInput {\n /** The projected x, in render-target pixels. */\n readonly screenX: number;\n /** The projected y, in render-target pixels. */\n readonly screenY: number;\n /** Whether the point is in front of the camera. */\n readonly inFront: boolean;\n /** How far the point is from the camera, in metres. */\n readonly distance: number;\n /** The overlay root's width, in UI units. */\n readonly viewWidth: number;\n /** The overlay root's height, in UI units. */\n readonly viewHeight: number;\n /** The render-target-pixel to UI-unit conversion. */\n readonly mapping: UiPixelMapping;\n /** Whether the element is hidden when the point is behind the camera. */\n readonly hideWhenBehindCamera: boolean;\n /** Whether the element is kept inside the overlay's bounds. */\n readonly clampToScreen: boolean;\n /** Whether the element shrinks with distance. */\n readonly scaleWithDistance: boolean;\n /** The distance at which {@link AnchorInput.scaleWithDistance} produces a scale of `1`. */\n readonly referenceDistance: number;\n /** The smallest scale distance scaling may produce. */\n readonly minScale: number;\n /** The largest scale distance scaling may produce. */\n readonly maxScale: number;\n}\n\n/**\n * Where the element goes, written in place so the per-frame path allocates nothing.\n *\n * @public\n */\nexport interface AnchorPlacement {\n /** Whether the element is shown at all. */\n visible: boolean;\n /** The x, in UI units from the overlay root's left edge. */\n x: number;\n /** The y, in UI units from the overlay root's top edge. */\n y: number;\n /** The uniform scale to draw the element at. */\n scale: number;\n}\n\n/**\n * Builds a zeroed placement, for a component to reuse every frame.\n *\n * @returns The placement.\n *\n * @internal\n */\nexport function createAnchorPlacement(): AnchorPlacement {\n return { visible: false, x: 0, y: 0, scale: 1 };\n}\n\n/**\n * The smallest distance the scale divisor accepts, so an anchor sitting on the camera does not\n * produce an infinite scale.\n */\nconst MIN_DISTANCE = 0.001;\n\n/**\n * Computes where an anchored element goes this frame.\n *\n * @param input - The projection, the flags, and the conversion.\n * @param out - Receives the placement.\n * @returns `out`, for chaining.\n *\n * @example\n * ```ts\n * const out = createAnchorPlacement();\n * computeAnchorPlacement(\n * {\n * screenX: 400,\n * screenY: 300,\n * inFront: true,\n * distance: 10,\n * viewWidth: 800,\n * viewHeight: 600,\n * mapping: { scaleX: 1, originX: 0, scaleY: 1, originY: 0 },\n * hideWhenBehindCamera: true,\n * clampToScreen: false,\n * scaleWithDistance: false,\n * referenceDistance: 10,\n * minScale: 0.5,\n * maxScale: 2,\n * },\n * out,\n * );\n * out.x; // 400\n * ```\n *\n * @public\n */\nexport function computeAnchorPlacement(input: AnchorInput, out: AnchorPlacement): AnchorPlacement {\n let x = input.screenX * input.mapping.scaleX - input.mapping.originX;\n let y = input.screenY * input.mapping.scaleY - input.mapping.originY;\n if (!input.inFront) {\n if (input.hideWhenBehindCamera || !input.clampToScreen) {\n out.visible = false;\n out.x = x;\n out.y = y;\n out.scale = 1;\n return out;\n }\n x = input.viewWidth - x;\n y = input.viewHeight - y;\n }\n if (input.clampToScreen) {\n x = clamp(x, 0, input.viewWidth);\n y = clamp(y, 0, input.viewHeight);\n }\n out.visible = input.clampToScreen || (x >= 0 && x <= input.viewWidth && y >= 0 && y <= input.viewHeight);\n out.x = x;\n out.y = y;\n out.scale = input.scaleWithDistance\n ? clamp(input.referenceDistance / Math.max(input.distance, MIN_DISTANCE), input.minScale, input.maxScale)\n : 1;\n return out;\n}\n","import { bool, Component, createDefaults, defineSchema, f32, vec3 } from \"@ignifx/core\";\nimport { computeAnchorPlacement, createAnchorPlacement } from \"./anchor-math.js\";\nimport type { AnchorPlacement } from \"./anchor-math.js\";\nimport type { UiPixelMapping } from \"../dom/scaling.js\";\nimport type { ComponentHooks, Schema, Vec3Like } from \"@ignifx/core\";\n\n/**\n * Position a game-owned DOM element without changing its contents or ownership.\n * Cache pose and camera state to avoid redundant style writes; changing a CSS transform still\n * requires a string allocation.\n */\n\n/**\n * An entity-to-element anchor.\n *\n * @example\n * ```ts\n * const tag = document.createElement(\"div\");\n * tag.textContent = \"Boss\";\n * app.ui.layer(\"hud\").element?.append(tag);\n *\n * const anchor = enemy.addComponent(WorldAnchor);\n * anchor.element = tag;\n * anchor.offset = { x: 0, y: 2, z: 0 };\n * ```\n *\n * @public\n */\nexport class WorldAnchor extends Component implements ComponentHooks {\n /** The registration id the serializer writes into scene files. */\n static typeId = \"ignifx/WorldAnchor\";\n\n /** One anchored element per entity. */\n static allowMultiple = false;\n\n /** The declarative fields (ADR-0004). */\n static schema: Schema = worldAnchorSchema();\n\n /** A world-space offset added to the entity's position before projecting, in metres. */\n declare offset: Vec3Like;\n\n /** Whether the element is hidden when the anchor point is behind the camera. */\n declare hideWhenBehindCamera: boolean;\n\n /** Whether the element is kept inside the overlay's bounds instead of being hidden off-screen. */\n declare clampToScreen: boolean;\n\n /** Whether the element shrinks with distance. */\n declare scaleWithDistance: boolean;\n\n /** The distance at which {@link WorldAnchor.scaleWithDistance} produces a scale of `1`, in metres. */\n declare referenceDistance: number;\n\n /** The smallest scale distance scaling may produce. */\n declare minScale: number;\n\n /** The largest scale distance scaling may produce. */\n declare maxScale: number;\n\n /**\n * The element to position. Not serialised — a DOM node cannot be — so a scene file carries the\n * flags and the game assigns the element in `awake`.\n */\n element: HTMLElement | null = null;\n\n readonly #placement: AnchorPlacement = createAnchorPlacement();\n\n #prepared: HTMLElement | null = null;\n\n #lastX = Number.NaN;\n\n #lastY = Number.NaN;\n\n #lastScale = Number.NaN;\n\n #lastVisible: boolean | null = null;\n\n /** Builds an anchor with the schema's defaults. */\n constructor() {\n super();\n Object.assign(this, createDefaults(WorldAnchor.schema));\n }\n\n /**\n * Where the element was placed on the last synchronised frame.\n *\n * @returns The placement; `visible` is `false` before the first sync.\n */\n get placement(): Readonly<AnchorPlacement> {\n return this.#placement;\n }\n\n /** Hides the element when the component goes away, so an orphaned tag does not linger. */\n onDetach(): void {\n const element = this.element;\n if (element !== null) {\n element.style.setProperty(\"display\", \"none\");\n }\n this.#prepared = null;\n }\n\n /**\n * Places the element for this frame.\n *\n * @param screenX - The anchor point's projected x, in render-target pixels.\n * @param screenY - The anchor point's projected y, in render-target pixels.\n * @param inFront - Whether the point is in front of the camera.\n * @param distance - How far the point is from the camera, in metres.\n * @param viewWidth - The overlay root's width, in UI units.\n * @param viewHeight - The overlay root's height, in UI units.\n * @param mapping - The render-target-pixel to UI-unit conversion.\n *\n * @internal\n */\n place(\n screenX: number,\n screenY: number,\n inFront: boolean,\n distance: number,\n viewWidth: number,\n viewHeight: number,\n mapping: UiPixelMapping,\n ): void {\n const element = this.element;\n if (element === null) {\n return;\n }\n computeAnchorPlacement(\n {\n screenX,\n screenY,\n inFront,\n distance,\n viewWidth,\n viewHeight,\n mapping,\n hideWhenBehindCamera: this.hideWhenBehindCamera,\n clampToScreen: this.clampToScreen,\n scaleWithDistance: this.scaleWithDistance,\n referenceDistance: this.referenceDistance,\n minScale: this.minScale,\n maxScale: this.maxScale,\n },\n this.#placement,\n );\n this.#write(element);\n }\n\n /**\n * Writes the placement onto the element, skipping every property that did not change.\n *\n * @param element - The element to write.\n */\n #write(element: HTMLElement): void {\n if (this.#prepared !== element) {\n const style = element.style;\n style.setProperty(\"position\", \"absolute\");\n style.setProperty(\"left\", \"0px\");\n style.setProperty(\"top\", \"0px\");\n this.#prepared = element;\n this.#lastVisible = null;\n this.#lastX = Number.NaN;\n }\n const visible = this.#placement.visible && this.isEnabledInHierarchy;\n if (this.#lastVisible !== visible) {\n element.style.setProperty(\"display\", visible ? \"block\" : \"none\");\n this.#lastVisible = visible;\n }\n if (!visible) {\n return;\n }\n const { x, y, scale } = this.#placement;\n if (this.#lastX === x && this.#lastY === y && this.#lastScale === scale) {\n return;\n }\n this.#lastX = x;\n this.#lastY = y;\n this.#lastScale = scale;\n element.style.setProperty(\n \"transform\",\n `translate(${String(x)}px, ${String(y)}px) translate(-50%, -50%) scale(${String(scale)})`,\n );\n }\n}\n\n/**\n * The `WorldAnchor` schema.\n *\n * @returns The schema, built fresh so no module holds state (`CONSTITUTION.md` §3.5).\n */\nfunction worldAnchorSchema(): Schema {\n return defineSchema({\n offset: vec3({ x: 0, y: 0, z: 0 }, { tooltip: \"A world-space offset added before projecting, in metres.\" }),\n hideWhenBehindCamera: bool(true, { tooltip: \"Hide the element when the anchor is behind the camera.\" }),\n clampToScreen: bool(false, { tooltip: \"Keep the element inside the overlay instead of hiding it.\" }),\n scaleWithDistance: bool(false, { tooltip: \"Shrink the element as the anchor gets further away.\" }),\n referenceDistance: f32(10, { min: 0.001, tooltip: \"The distance at which the scale is 1, in metres.\" }),\n minScale: f32(0.25, { min: 0, tooltip: \"The smallest scale distance scaling may produce.\" }),\n maxScale: f32(2, { min: 0, tooltip: \"The largest scale distance scaling may produce.\" }),\n });\n}\n","import { Quat, Vec3 } from \"@ignifx/core\";\nimport { HudText } from \"../text/hud-text.js\";\nimport { WorldText2D } from \"../text/world-text-2d.js\";\nimport { WorldText } from \"../text/world-text.js\";\nimport { WorldAnchor } from \"./world-anchor.js\";\nimport type { UiHost } from \"../dom/host.js\";\nimport type { I18nService } from \"../i18n/i18n-service.js\";\nimport type { TextRuntime } from \"../text/text-runtime.js\";\nimport type {\n App,\n Camera,\n MutableQuat,\n MutableVec3,\n System,\n SystemContext,\n Transform,\n Vec3Like,\n World,\n} from \"@ignifx/core\";\n\n/**\n * Run after core's camera sync so projections use the current pose and render-target size.\n * With no main camera, hide anchored elements. Text shaping only repeats when content changes.\n */\n\n/**\n * The `PreRender` order the UI system runs at.\n *\n * @remarks\n * After `RENDER_SYNC_ORDER` (900), which is the frame's camera synchronisation, and inside the\n * extension band. See the module's own remarks.\n *\n * @public\n */\nexport const UI_SYNC_ORDER = 1100;\n\n/**\n * What the system is built with. Only `uiExtension` builds one, through `UiSystem`'s `@internal`\n * constructor.\n *\n * @internal\n */\nexport interface UiSystemOptions {\n /** The app, for the render surface's size and the Lite scene. */\n readonly app: App;\n /** The overlay host, for the layout the anchors are placed in. */\n readonly host: UiHost;\n /** The text renderer's life. */\n readonly runtime: TextRuntime;\n /** The localization service `i18nKey` is resolved through. */\n readonly i18n: I18nService;\n}\n\n/**\n * Projects world anchors and re-shapes text once per frame.\n *\n * @public\n */\nexport class UiSystem implements System {\n /** The name diagnostics and error reports use. */\n readonly name = \"ignifx/ui-sync\";\n\n readonly #options: UiSystemOptions;\n\n readonly #point: MutableVec3 = new Vec3();\n\n readonly #screen: MutableVec3 = new Vec3();\n\n readonly #cameraPosition: MutableVec3 = new Vec3();\n\n readonly #cameraRotation: MutableQuat = new Quat();\n\n readonly #targetSize = { width: 1, height: 1 };\n\n /**\n * Builds the system. The extension does this; a game never constructs one.\n *\n * @param options - The app, the host, the text runtime, and the localization service.\n *\n * @internal\n */\n constructor(options: UiSystemOptions) {\n this.#options = options;\n }\n\n /**\n * Builds the overlay, now that the engine and its canvas exist.\n *\n * @remarks\n * This is the only hook that fires inside `createApp` **after** the Lite engine was created:\n * `register` runs before it, and `onStart` runs only when a game calls `app.start()`, which a\n * headless tool never does. `@ignifx/2d` uses the same hook for the same reason.\n *\n * @param _world - The new world, which the overlay does not need.\n */\n onWorldCreated(_world: World): void {\n this.#options.host.mount();\n }\n\n /**\n * Runs one frame's synchronisation.\n *\n * @param ctx - The world, clock, phase, and delta.\n */\n update(ctx: SystemContext): void {\n const { app, host, runtime, i18n } = this.#options;\n runtime.ensureRenderer();\n this.#readTargetSize(app);\n const camera = ctx.world.mainCamera;\n const hasCamera = camera !== null;\n if (hasCamera) {\n camera.transform.positionToRef(this.#cameraPosition);\n camera.transform.rotationToRef(this.#cameraRotation);\n }\n this.#syncAnchors(ctx.world, camera, host);\n this.#syncWorldText2D(ctx.world, camera, runtime, i18n);\n this.#syncHudText(ctx.world, runtime, i18n);\n this.#syncWorldText(ctx.world, app, i18n, hasCamera);\n }\n\n /**\n * Reads the render target's size, in device pixels; a headless app reports 1x1.\n *\n * @param app - The app, for its render surface.\n */\n #readTargetSize(app: App): void {\n const surface = app.renderer.surface;\n this.#targetSize.width = surface === null ? 1 : Math.max(1, surface.width);\n this.#targetSize.height = surface === null ? 1 : Math.max(1, surface.height);\n }\n\n /**\n * Projects and places every anchored element.\n *\n * @param world - The world.\n * @param camera - The main camera, or `null`.\n * @param host - The overlay host.\n */\n #syncAnchors(world: World, camera: Camera | null, host: UiHost): void {\n const anchors = world.components(WorldAnchor);\n if (anchors.length === 0) {\n return;\n }\n const layout = host.layout;\n const mapping = host.pixelMapping;\n for (let index = 0; index < anchors.length; index += 1) {\n const anchor = anchors[index];\n if (anchor === undefined || anchor.element === null) {\n continue;\n }\n if (camera === null) {\n anchor.place(0, 0, false, 0, layout.width, layout.height, mapping);\n continue;\n }\n const inFront = this.#project(camera, anchor.transform, anchor.offset);\n anchor.place(\n this.#screen.x,\n this.#screen.y,\n inFront,\n this.#distanceToCamera(),\n layout.width,\n layout.height,\n mapping,\n );\n }\n }\n\n /**\n * Projects and re-shapes every world-anchored pixel label.\n *\n * @param world - The world.\n * @param camera - The main camera, or `null`.\n * @param runtime - The text renderer's life.\n * @param i18n - The localization service.\n */\n #syncWorldText2D(world: World, camera: Camera | null, runtime: TextRuntime, i18n: I18nService): void {\n const labels = world.components(WorldText2D);\n for (let index = 0; index < labels.length; index += 1) {\n const label = labels[index];\n if (label === undefined) {\n continue;\n }\n if (camera === null) {\n label.sync(runtime, i18n, 0, 0, false);\n continue;\n }\n const inFront = this.#project(camera, label.transform, label.offset);\n label.sync(runtime, i18n, this.#screen.x, this.#screen.y, inFront);\n }\n }\n\n /**\n * Re-shapes and places every screen-anchored pixel label.\n *\n * @param world - The world.\n * @param runtime - The text renderer's life.\n * @param i18n - The localization service.\n */\n #syncHudText(world: World, runtime: TextRuntime, i18n: I18nService): void {\n const labels = world.components(HudText);\n for (let index = 0; index < labels.length; index += 1) {\n labels[index]?.sync(runtime, i18n, this.#targetSize.width, this.#targetSize.height);\n }\n }\n\n /**\n * Re-shapes and places every world-space sign.\n *\n * @param world - The world.\n * @param app - The app, for the Lite scene.\n * @param i18n - The localization service.\n * @param hasCamera - Whether a billboard has a rotation to copy.\n */\n #syncWorldText(world: World, app: App, i18n: I18nService, hasCamera: boolean): void {\n const signs = world.components(WorldText);\n if (signs.length === 0) {\n return;\n }\n const scene = app.lite.scene;\n const rotation = hasCamera ? this.#cameraRotation : null;\n for (let index = 0; index < signs.length; index += 1) {\n signs[index]?.sync(scene, i18n, rotation);\n }\n }\n\n /**\n * Projects an entity's offset position onto the render target.\n *\n * @param camera - The main camera.\n * @param transform - The entity's transform.\n * @param offset - The world-space offset to add first.\n * @returns `true` when the point is in front of the camera.\n */\n #project(camera: Camera, transform: Transform, offset: Vec3Like): boolean {\n transform.positionToRef(this.#point);\n this.#point.x += offset.x;\n this.#point.y += offset.y;\n this.#point.z += offset.z;\n return camera.worldToScreen(this.#point, this.#screen);\n }\n\n /**\n * How far the point last projected is from the camera.\n *\n * @returns The distance, in metres.\n */\n #distanceToCamera(): number {\n const dx = this.#point.x - this.#cameraPosition.x;\n const dy = this.#point.y - this.#cameraPosition.y;\n const dz = this.#point.z - this.#cameraPosition.z;\n return Math.sqrt(dx * dx + dy * dy + dz * dz);\n }\n}\n","import { defineExtension, Phase } from \"@ignifx/core\";\nimport { defineI18nAppProperty, defineUiAppProperty } from \"./augmentation.js\";\nimport { resolveDomTarget } from \"./dom/dom-target.js\";\nimport { UiHost } from \"./dom/host.js\";\nimport { uiError, UI_ERROR_MESSAGES, UiErrorCode } from \"./errors.js\";\nimport { I18nService } from \"./i18n/i18n-service.js\";\nimport { createLocaleLoader } from \"./i18n/loader.js\";\nimport {\n attachTextLayer,\n createRegisteredTextRenderer,\n destroyTextRenderer,\n detachTextLayer,\n enableTextDeviceLostRecovery,\n} from \"./lite/gpu/text-renderer.js\";\nimport { defaultUiSettings, UI_SETTINGS_SECTION, uiSettingsSchema } from \"./settings.js\";\nimport { HudText } from \"./text/hud-text.js\";\nimport { TextRuntime } from \"./text/text-runtime.js\";\nimport { WorldText2D } from \"./text/world-text-2d.js\";\nimport { WorldText } from \"./text/world-text.js\";\nimport { VERSION } from \"./version.js\";\nimport { UI_SYNC_ORDER, UiSystem } from \"./world/ui-system.js\";\nimport { WorldAnchor } from \"./world/world-anchor.js\";\nimport type { UiDomTarget } from \"./dom/dom-target.js\";\nimport type { LocaleAsset } from \"./i18n/locale-file.js\";\nimport type { LiteTextRenderer } from \"./lite/text.js\";\nimport type { UiScalingMode, UiSettings } from \"./settings.js\";\nimport type { App, AssetHandle, Extension, ExtensionContext } from \"@ignifx/core\";\n\n/**\n * The `@ignifx/ui` extension (`docs/architecture/04-extensions.md` §1, `13-ui.md`).\n * Registering it is the whole installation: `ui()` gives a game `app.ui`, `app.i18n`, four\n * components, the `i18n` asset type, the `ui` settings section, and the one `PreRender` system that\n * projects anchors and re-shapes text.\n *\n * ## What it needs, and what it does not\n *\n * `@ignifx/input` is an **optional** peer. The overlay host, the text components, and the\n * localization service work without it; only `VirtualJoystick` and `VirtualButton` need it, and\n * they say so with `IGX-1305`. The extension never imports it — it reaches\n * `app.input.uiHasFocus` structurally, for the reason `src/widgets/virtual-device.ts` records.\n *\n * ## Headless\n *\n * Everything registers headlessly. With no DOM canvas the host is inert (`13-ui.md` §1's\n * \"the host hides itself in headless mode\"*, read through `07-rendering.md` §6's rule that a\n * headless member is a documented no-op rather than a throw), no text renderer is created, and the\n * `PreRender` system still runs — so `WorldText` keeps its state and a test asserts on it.\n */\n\n/**\n * What `ui()` accepts. Every field that names a settings value overrides the matching `ui` section\n * value, which is the shape `04-extensions.md` §1 shows for `physics()`.\n *\n * @public\n */\nexport interface UiOptions {\n /** How the overlay's coordinate system relates to the canvas. */\n readonly scaling?: UiScalingMode;\n /** The `[width, height]` the `\"fit\"` mode scales to. */\n readonly referenceResolution?: readonly number[];\n /** The layers created up front, back to front. */\n readonly layers?: readonly string[];\n /** Whether the overlay starts shown. */\n readonly visible?: boolean;\n /**\n * The address of a `.i18n.json` document to load into `app.i18n` at start-up. Empty loads\n * nothing; a game that ships one file per locale calls `app.i18n.load` itself.\n */\n readonly strings?: string;\n /** The locale the app starts in, before any document is loaded. Defaults to `\"en\"`. */\n readonly locale?: string;\n}\n\n/**\n * Merges the extension's options over the resolved settings section.\n *\n * @param settings - The resolved `ui` section.\n * @param options - What the game passed to `ui(...)`.\n * @returns The effective settings.\n */\nfunction mergeSettings(settings: UiSettings, options: UiOptions): UiSettings {\n return {\n scaling: options.scaling ?? settings.scaling,\n referenceResolution: options.referenceResolution ?? settings.referenceResolution,\n layers: options.layers ?? settings.layers,\n visible: options.visible ?? settings.visible,\n };\n}\n\n/**\n * Builds the setter that writes `app.input.uiHasFocus`, or a no-op when `@ignifx/input` is not\n * registered.\n *\n * @remarks\n * `InputService.uiHasFocus` is a plain settable property whose own documentation says\n * \"`@ignifx/ui` assigns it\"* (`packages/input/src/service/input-service.ts` 340-349). This is that\n * assignment. It is looked up once, at registration, because `app.input` cannot appear later:\n * extensions all register before the first frame.\n *\n * @param app - The app being built.\n * @returns The setter.\n */\nfunction inputFocusSetter(app: App): (value: boolean) => void {\n return inputFlagSetter(app, \"uiHasFocus\");\n}\n\n/**\n * Builds the setter for one of `@ignifx/input`'s two UI flags, or a no-op when the extension is\n * absent or predates the flag.\n * @param app - The app being built.\n * @param flag - `uiHasFocus` (a text field owns the keyboard) or `uiHasPointer` (a pointer is\n * pressed on the overlay).\n * @returns The setter.\n */\nfunction inputFlagSetter(app: App, flag: \"uiHasFocus\" | \"uiHasPointer\"): (value: boolean) => void {\n const input: unknown = Reflect.get(app, \"input\");\n if (input === null || typeof input !== \"object\" || !(flag in input)) {\n return (): void => {\n // No input extension, or one without this flag: nothing consumes it, so nothing is written.\n };\n }\n return (value: boolean): void => {\n Reflect.set(input, flag, value);\n };\n}\n\n/**\n * The components the extension registers, in the order the API report lists them.\n *\n * @returns The classes.\n */\nfunction components(): readonly [typeof WorldAnchor, typeof HudText, typeof WorldText, typeof WorldText2D] {\n return [WorldAnchor, HudText, WorldText, WorldText2D];\n}\n\n/**\n * Registers everything the package contributes.\n *\n * @param ctx - The registration surface.\n * @param options - What the game passed to `ui(...)`.\n * @throws IgnifxError with code `IGX-1301` when a second `ui()` is registered on one app.\n */\nfunction registerUi(ctx: ExtensionContext, options: UiOptions): void {\n const app = ctx.app;\n // `Reflect.has` rather than `\"ui\" in app`: the augmentation in `./augmentation.js` declares the\n // property on `App`, so an `in` check narrows the negative branch to `never` and every later use\n // of `app` in this function stops type-checking.\n if (Reflect.has(app, \"ui\")) {\n throw uiError(UiErrorCode.duplicateExtension, \"The ui() extension is already registered on this app.\", {\n hint: \"Register ui() once; pass its options to that one call.\",\n });\n }\n ctx.registerErrorCodes(UI_ERROR_MESSAGES);\n ctx.registerSettings<UiSettings>(UI_SETTINGS_SECTION, uiSettingsSchema(), defaultUiSettings());\n const settings = mergeSettings(ctx.settings<UiSettings>(UI_SETTINGS_SECTION), options);\n const host = new UiHost({\n // A thunk, not a value: `AppImpl.initialize` registers every extension before it creates the\n // Lite engine, so `app.renderer.surface` throws `IGX-0107` here. `UiSystem.onWorldCreated`\n // calls `mount()` once the engine exists, still inside this `createApp` call.\n resolveTarget: (): UiDomTarget | null => (app.isHeadless ? null : resolveDomTarget(app.renderer.surface)),\n settings,\n log: ctx.log,\n setInputFocus: inputFocusSetter(app),\n setInputPointer: inputFlagSetter(app, \"uiHasPointer\"),\n });\n const i18n = new I18nService({ log: ctx.log, locale: options.locale ?? \"en\" });\n const runtime = new TextRuntime({\n createRenderer: app.isHeadless ? null : (): LiteTextRenderer => createRegisteredTextRenderer(app.lite.engine),\n attachLayer: attachTextLayer,\n detachLayer: detachTextLayer,\n destroyRenderer: destroyTextRenderer,\n });\n ctx.registerService(UiHost, host);\n ctx.registerService(I18nService, i18n);\n defineUiAppProperty(ctx, host);\n defineI18nAppProperty(ctx, i18n);\n ctx.registerAssetLoader(createLocaleLoader());\n ctx.registerComponents(components());\n ctx.registerSystem(new UiSystem({ app, host, runtime, i18n }), {\n phase: Phase.PreRender,\n order: UI_SYNC_ORDER,\n });\n let strings: AssetHandle<LocaleAsset> | null = null;\n if (options.strings !== undefined && options.strings !== \"\") {\n strings = app.assets.load<LocaleAsset>(options.strings);\n // Not awaited: delivery needs a frame and `register` runs before the first one\n // (`05-assets-and-loading.md` §4). Text that names an `i18nKey` shows the key until then.\n const handle = strings;\n void i18n.load(handle).catch((error: unknown): void => {\n app.onError.emit({ error, source: \"extension\", phase: null, entity: null, component: null });\n });\n }\n ctx.onDispose((): void => {\n runtime.dispose();\n host.dispose();\n i18n.dispose();\n strings?.release();\n });\n}\n\n/**\n * Turns on device-lost recovery for the text renderer.\n *\n * @param app - The app being started.\n */\nfunction startUi(app: App): void {\n if (app.isHeadless || !app.renderer.features.deviceLostRecovery) {\n return;\n }\n enableTextDeviceLostRecovery(\n app.lite.engine,\n (): void => {\n app.log.info(\"UI text resources recovered after device loss.\");\n },\n (error: unknown): void => {\n app.onError.emit({ error, source: \"extension\", phase: null, entity: null, component: null });\n },\n );\n}\n\n/**\n * The `@ignifx/ui` extension factory.\n *\n * @param options - Overrides for the `ui` settings section, plus the start-up translation document.\n * @returns The extension descriptor to pass to `createApp`.\n *\n * @example\n * ```ts\n * const app = await createApp({\n * canvas,\n * extensions: [ui({ scaling: \"fit\", referenceResolution: [640, 360] })],\n * });\n * ```\n *\n * @public\n */\nexport const ui: (options?: UiOptions) => Extension = defineExtension<UiOptions | undefined>((raw) => {\n // `defineExtension` hands the factory whatever the caller passed, which is `undefined` when the\n // game wrote `ui()`; the typed signature cannot express that, so the default lands here.\n const options: UiOptions = raw ?? {};\n return {\n name: \"@ignifx/ui\",\n version: VERSION,\n engine: \">=0.0.0 <1.0.0\",\n requires: [\"@ignifx/core\"],\n register(ctx: ExtensionContext): void {\n registerUi(ctx, options);\n },\n onStart(app: App): void {\n startUi(app);\n },\n };\n});\n","import { describeSchema } from \"@ignifx/core\";\nimport { describeLocaleFileFormat } from \"./i18n/locale-file.js\";\nimport { HudText } from \"./text/hud-text.js\";\nimport { WorldText2D } from \"./text/world-text-2d.js\";\nimport { WorldText } from \"./text/world-text.js\";\nimport { WorldAnchor } from \"./world/world-anchor.js\";\nimport type { SchemaDescription } from \"@ignifx/core\";\n\n/**\n * The documentation harness's view of everything `@ignifx/ui` declares\n * (`docs/architecture/16-docs-harness-and-skill.md` §3, `scripts/README.md`).\n *\n * `pnpm docs:schemas` imports the built entry point, calls {@link describeSchemas}, and renders\n * `skills/ignifx/references/formats/<format>.md` plus `ignifx.schemas.json` from the result. The\n * **function** form is what a package exports rather than a `schemas` object: building the record\n * means calling `describeSchema` for every component, and module scope holds declarations only\n * (`CONSTITUTION.md` §3.5).\n *\n * The translation document is keyed `ignifx/i18n-file` rather than `ignifx.i18n`: the harness\n * rejects a key with no `/` (`scripts/lib/schema-source.ts`), and it is the entry's `format` — not\n * its key — that decides which page it lands on. `@ignifx/core` and `@ignifx/audio` key their file\n * formats the same way.\n */\n\n/**\n * Describes every component and file format this package declares, for the documentation harness.\n *\n * @returns The records, keyed by namespaced type id.\n *\n * @example\n * ```ts\n * describeSchemas()[\"ignifx/HudText\"].fields[\"fontSize\"].default; // 32\n * ```\n *\n * @public\n */\nexport function describeSchemas(): Readonly<Record<string, SchemaDescription>> {\n return {\n \"ignifx/WorldAnchor\": describeSchema(\"ignifx/WorldAnchor\", WorldAnchor.schema, {\n description: \"Keeps a DOM element at an entity's screen position, with clamping and distance scaling.\",\n }),\n \"ignifx/HudText\": describeSchema(\"ignifx/HudText\", HudText.schema, {\n description: \"Pixel-space text drawn by Babylon Lite, anchored to a corner of the render target.\",\n }),\n \"ignifx/WorldText\": describeSchema(\"ignifx/WorldText\", WorldText.schema, {\n description: \"3D text in the render scene: signs and banners, optionally billboarded.\",\n }),\n \"ignifx/WorldText2D\": describeSchema(\"ignifx/WorldText2D\", WorldText2D.schema, {\n description: \"Pixel-space text placed at an entity's projected position: damage numbers and name tags.\",\n }),\n \"ignifx/i18n-file\": describeLocaleFileFormat(),\n };\n}\n","import { Signal } from \"@ignifx/core\";\nimport { UI_CLASS_NAMES } from \"../dom/styles.js\";\nimport type { UiHost } from \"../dom/host.js\";\nimport type { SignalLike } from \"@ignifx/core\";\n\n/**\n * Modal dialogs use a higher stacking level than menus so their panels and backdrops stay above\n * other layer content. Without a DOM overlay, methods are no-ops and `element` is `null`.\n */\n\n/**\n * One button in a dialog.\n *\n * @public\n */\nexport interface DialogButton {\n /** The identifier `onChosen` reports. */\n readonly id: string;\n /** The text drawn on the button. */\n readonly label: string;\n}\n\n/**\n * What `new Dialog(app.ui, options)` accepts.\n *\n * @public\n */\nexport interface DialogOptions {\n /** The heading. Omit for a dialog with no title. */\n readonly title?: string;\n /** The body text. Omit for a dialog with no message. */\n readonly message?: string;\n /** The buttons, left to right. */\n readonly buttons?: readonly DialogButton[];\n /** The layer to mount into. Defaults to `\"menu\"`. */\n readonly layer?: string;\n /** Whether the dialog starts shown. Defaults to `false`. */\n readonly visible?: boolean;\n /** Whether a click on the backdrop dismisses the dialog. Defaults to `false`. */\n readonly dismissOnBackdrop?: boolean;\n /** The stacking order inside the layer. Defaults to `UI_DIALOG_Z_INDEX`, from the stylesheet. */\n readonly zIndex?: number;\n}\n\n/**\n * A modal panel with a title, a message, and buttons.\n *\n * @public\n */\nexport class Dialog {\n readonly #root: HTMLDivElement | null;\n\n readonly #title: HTMLHeadingElement | null = null;\n\n readonly #message: HTMLParagraphElement | null = null;\n\n readonly #buttonRow: HTMLDivElement | null = null;\n\n readonly #buttonCleanups: (() => void)[] = [];\n\n readonly #chosen = new Signal<string>();\n\n readonly #dismissed = new Signal();\n\n readonly #cleanups: (() => void)[] = [];\n\n #visible: boolean;\n\n #disposed = false;\n\n /**\n * Builds the dialog and mounts it hidden.\n *\n * @param host - The overlay host, normally `app.ui`.\n * @param options - The title, the message, the buttons, and the layer.\n */\n constructor(host: UiHost, options: DialogOptions = {}) {\n this.#visible = options.visible ?? false;\n const layerElement = host.layer(options.layer ?? \"menu\").element;\n if (layerElement === null) {\n this.#root = null;\n return;\n }\n const document = layerElement.ownerDocument;\n const root = document.createElement(\"div\");\n root.className = UI_CLASS_NAMES.dialog;\n root.setAttribute(\"role\", \"dialog\");\n root.setAttribute(\"aria-modal\", \"true\");\n const backdrop = document.createElement(\"div\");\n backdrop.className = UI_CLASS_NAMES.dialogBackdrop;\n root.append(backdrop);\n if (options.dismissOnBackdrop === true) {\n const onBackdrop = (): void => {\n this.hide();\n };\n backdrop.addEventListener(\"pointerdown\", onBackdrop);\n this.#cleanups.push((): void => {\n backdrop.removeEventListener(\"pointerdown\", onBackdrop);\n });\n }\n const panel = document.createElement(\"div\");\n panel.className = UI_CLASS_NAMES.dialogPanel;\n if (options.title !== undefined) {\n const heading = document.createElement(\"h2\");\n heading.className = UI_CLASS_NAMES.dialogTitle;\n heading.textContent = options.title;\n panel.append(heading);\n this.#title = heading;\n }\n if (options.message !== undefined) {\n const paragraph = document.createElement(\"p\");\n paragraph.className = UI_CLASS_NAMES.dialogMessage;\n paragraph.textContent = options.message;\n panel.append(paragraph);\n this.#message = paragraph;\n }\n const row = document.createElement(\"div\");\n row.className = UI_CLASS_NAMES.dialogButtons;\n panel.append(row);\n this.#buttonRow = row;\n root.append(panel);\n root.style.setProperty(\"display\", this.#visible ? \"flex\" : \"none\");\n if (options.zIndex !== undefined) {\n root.style.setProperty(\"z-index\", String(options.zIndex));\n }\n layerElement.append(root);\n this.#root = root;\n this.setButtons(options.buttons ?? []);\n }\n\n /**\n * The dialog's outermost element, so a template can restyle it or mount more into it.\n *\n * @returns The element, or `null` when the app has no DOM overlay.\n */\n get element(): HTMLDivElement | null {\n return this.#root;\n }\n\n /**\n * Whether the dialog is shown.\n *\n * @returns `true` while it is on screen.\n */\n get isVisible(): boolean {\n return this.#visible;\n }\n\n /**\n * Emitted with a button's `id` when it is pressed. The dialog does not hide itself; the game\n * decides, because \"Cancel\" and \"Delete everything\" want different follow-ups.\n *\n * @returns The signal.\n */\n get onChosen(): SignalLike<string> {\n return this.#chosen;\n }\n\n /**\n * Emitted after {@link Dialog.hide}, whatever caused it.\n *\n * @returns The signal.\n */\n get onDismissed(): SignalLike {\n return this.#dismissed;\n }\n\n /** Shows the dialog. */\n show(): void {\n if (this.#visible || this.#disposed) {\n return;\n }\n this.#visible = true;\n this.#root?.style.setProperty(\"display\", \"flex\");\n }\n\n /** Hides the dialog and emits {@link Dialog.onDismissed}. */\n hide(): void {\n if (!this.#visible || this.#disposed) {\n return;\n }\n this.#visible = false;\n this.#root?.style.setProperty(\"display\", \"none\");\n this.#dismissed.emit();\n }\n\n /**\n * Replaces the heading, if the dialog was built with one.\n *\n * @param text - The new heading.\n */\n setTitle(text: string): void {\n if (this.#title !== null) {\n this.#title.textContent = text;\n }\n }\n\n /**\n * Replaces the body text, if the dialog was built with one.\n *\n * @param text - The new message.\n */\n setMessage(text: string): void {\n if (this.#message !== null) {\n this.#message.textContent = text;\n }\n }\n\n /**\n * Replaces the buttons.\n *\n * @remarks\n * One dialog re-used for every question is cheaper than one dialog per question and keeps the\n * stacking predictable, so the buttons have to be able to change: a confirmation asks\n * \"Yes\"/\"No\", a save error offers \"Retry\"/\"Cancel\", and a locale change relabels both.\n *\n * @param buttons - The buttons, left to right. An empty list leaves the row empty.\n *\n * @example\n * ```ts ignore-check\n * dialog.setMessage(\"Delete this save?\");\n * dialog.setButtons([{ id: \"no\", label: \"No\" }, { id: \"yes\", label: \"Yes\" }]);\n * ```\n */\n setButtons(buttons: readonly DialogButton[]): void {\n const row = this.#buttonRow;\n if (row === null || this.#disposed) {\n return;\n }\n for (const cleanup of this.#buttonCleanups) {\n cleanup();\n }\n this.#buttonCleanups.length = 0;\n row.replaceChildren();\n const document = row.ownerDocument;\n for (const button of buttons) {\n row.append(this.#createButton(document, button));\n }\n }\n\n /** Removes the dialog and unsubscribes. */\n dispose(): void {\n if (this.#disposed) {\n return;\n }\n this.#disposed = true;\n for (const cleanup of [...this.#cleanups, ...this.#buttonCleanups]) {\n cleanup();\n }\n this.#cleanups.length = 0;\n this.#buttonCleanups.length = 0;\n this.#root?.remove();\n this.#chosen.clear();\n this.#dismissed.clear();\n }\n\n /**\n * Builds one button and wires it to {@link Dialog.onChosen}.\n *\n * @param document - The document to create in.\n * @param button - The button's id and label.\n * @returns The element.\n */\n #createButton(document: Document, button: DialogButton): HTMLButtonElement {\n const element = document.createElement(\"button\");\n element.type = \"button\";\n element.className = UI_CLASS_NAMES.dialogButton;\n element.textContent = button.label;\n element.dataset[\"ignifxDialogButton\"] = button.id;\n const onClick = (): void => {\n this.#chosen.emit(button.id);\n };\n element.addEventListener(\"click\", onClick);\n this.#buttonCleanups.push((): void => {\n element.removeEventListener(\"click\", onClick);\n });\n return element;\n }\n}\n","import { clamp01, Signal } from \"@ignifx/core\";\nimport { UI_CLASS_NAMES } from \"../dom/styles.js\";\nimport type { UiHost } from \"../dom/host.js\";\nimport type { AssetProgress, Assets, Disconnect, SignalLike } from \"@ignifx/core\";\n\n/**\n * Prefer byte-weighted progress, falling back to handle counts when sizes are unknown.\n * Boot loads can be awaited before `app.start`; running games deliver loads in `PreUpdate`.\n * Both paths update through asset signals, without polling.\n */\n\n/**\n * What `new LoadingScreen(app.ui, options)` accepts.\n *\n * @public\n */\nexport interface LoadingScreenOptions {\n /** The layer to mount into. Defaults to `\"overlay\"`. */\n readonly layer?: string;\n /** The initial label. Defaults to `\"Loading…\"`. */\n readonly label?: string;\n /** Whether the screen starts shown. Defaults to `true` — a boot screen is up before anything else. */\n readonly visible?: boolean;\n}\n\n/**\n * The fraction of an asset batch that is done.\n *\n * @remarks\n * Bytes when the build recorded sizes, handles otherwise, and `1` for an empty batch — a loading\n * screen that never reaches 100% because nothing was queued is worse than one that closes at once.\n *\n * @param progress - The payload of `app.assets.onProgress`.\n * @returns The fraction, in `[0, 1]`.\n *\n * @example\n * ```ts\n * progressFraction({ loaded: 1, total: 4, bytesLoaded: 0, bytesTotal: 0 }); // 0.25\n * ```\n *\n * @public\n */\nexport function progressFraction(progress: AssetProgress): number {\n if (progress.bytesTotal > 0) {\n return clamp01(progress.bytesLoaded / progress.bytesTotal);\n }\n if (progress.total > 0) {\n return clamp01(progress.loaded / progress.total);\n }\n return 1;\n}\n\n/**\n * A full-overlay loading panel.\n *\n * @example\n * ```ts\n * const screen = new LoadingScreen(app.ui, { label: \"Loading…\" });\n * screen.bindTo(app.assets);\n * await app.assets.preloadGroup(\"boot\").promise;\n * screen.hide();\n * ```\n *\n * @public\n */\nexport class LoadingScreen {\n readonly #root: HTMLDivElement | null;\n\n readonly #label: HTMLDivElement | null = null;\n\n readonly #bar: HTMLDivElement | null = null;\n\n readonly #dismissed = new Signal();\n\n #disconnect: Disconnect | null = null;\n\n #progress = 0;\n\n #visible: boolean;\n\n #disposed = false;\n\n /**\n * Builds the screen and mounts it.\n *\n * @param host - The overlay host, normally `app.ui`.\n * @param options - The layer, the label, and the initial visibility.\n */\n constructor(host: UiHost, options: LoadingScreenOptions = {}) {\n this.#visible = options.visible ?? true;\n const layerElement = host.layer(options.layer ?? \"overlay\").element;\n if (layerElement === null) {\n this.#root = null;\n return;\n }\n const document = layerElement.ownerDocument;\n const root = document.createElement(\"div\");\n root.className = UI_CLASS_NAMES.loading;\n root.setAttribute(\"role\", \"progressbar\");\n root.setAttribute(\"aria-valuemin\", \"0\");\n root.setAttribute(\"aria-valuemax\", \"1\");\n root.setAttribute(\"aria-valuenow\", \"0\");\n const label = document.createElement(\"div\");\n label.className = UI_CLASS_NAMES.loadingLabel;\n label.textContent = options.label ?? \"Loading…\";\n const track = document.createElement(\"div\");\n track.className = UI_CLASS_NAMES.loadingTrack;\n const bar = document.createElement(\"div\");\n bar.className = UI_CLASS_NAMES.loadingBar;\n track.append(bar);\n root.append(label, track);\n root.style.setProperty(\"display\", this.#visible ? \"flex\" : \"none\");\n layerElement.append(root);\n this.#root = root;\n this.#label = label;\n this.#bar = bar;\n }\n\n /**\n * The screen's outermost element, so a template can restyle it or add a logo.\n *\n * @returns The element, or `null` when the app has no DOM overlay.\n */\n get element(): HTMLDivElement | null {\n return this.#root;\n }\n\n /**\n * Whether the screen is shown.\n *\n * @returns `true` while it is on screen.\n */\n get isVisible(): boolean {\n return this.#visible;\n }\n\n /**\n * How far along the bar is, in `[0, 1]`. Writing it moves the bar; values outside the range are\n * clamped.\n *\n * @returns The fraction.\n */\n get progress(): number {\n return this.#progress;\n }\n\n // eslint-disable-next-line jsdoc/require-jsdoc -- the accessor pair is documented on the getter.\n set progress(value: number) {\n const fraction = clamp01(value);\n if (this.#progress === fraction) {\n return;\n }\n this.#progress = fraction;\n this.#bar?.style.setProperty(\"width\", `${String(fraction * 100)}%`);\n this.#root?.setAttribute(\"aria-valuenow\", String(fraction));\n }\n\n /**\n * Emitted after {@link LoadingScreen.hide}, whatever caused it.\n *\n * @returns The signal.\n */\n get onDismissed(): SignalLike {\n return this.#dismissed;\n }\n\n /**\n * Follows an asset service's aggregate progress until {@link LoadingScreen.dispose} or a second\n * call to this method.\n *\n * @param assets - The asset service, normally `app.assets`.\n * @returns A function that stops following.\n */\n bindTo(assets: Assets): Disconnect {\n this.#disconnect?.();\n const disconnect = assets.onProgress.connect((progress: AssetProgress): void => {\n this.progress = progressFraction(progress);\n });\n this.#disconnect = disconnect;\n return disconnect;\n }\n\n /**\n * Replaces the label.\n *\n * @param text - The new label.\n */\n setLabel(text: string): void {\n if (this.#label !== null) {\n this.#label.textContent = text;\n }\n }\n\n /** Shows the screen. */\n show(): void {\n if (this.#visible || this.#disposed) {\n return;\n }\n this.#visible = true;\n this.#root?.style.setProperty(\"display\", \"flex\");\n }\n\n /** Hides the screen and emits {@link LoadingScreen.onDismissed}. */\n hide(): void {\n if (!this.#visible || this.#disposed) {\n return;\n }\n this.#visible = false;\n this.#root?.style.setProperty(\"display\", \"none\");\n this.#dismissed.emit();\n }\n\n /** Removes the screen and stops following the asset service. */\n dispose(): void {\n if (this.#disposed) {\n return;\n }\n this.#disposed = true;\n this.#disconnect?.();\n this.#disconnect = null;\n this.#root?.remove();\n this.#dismissed.clear();\n }\n}\n","/**\n * Rows declare the values they edit through `get` and `set`. The menu handles rendering,\n * clamping, formatting, and input repeat so each settings screen can share that behaviour.\n */\n\n/**\n * Text that is either fixed or re-read on every refresh.\n *\n * @remarks\n * A function is what makes a menu localizable: `label: () => app.i18n.t(\"menu.resume\")` re-renders\n * itself when `app.i18n.locale` changes, because {@link Menu.refresh} calls it again.\n *\n * @public\n */\nexport type MenuLabel = string | (() => string);\n\n/**\n * The values a `\"choice\"` row cycles through: a fixed list, or one read per use.\n *\n * @public\n */\nexport type MenuChoiceValues = readonly string[] | (() => readonly string[]);\n\n/**\n * What every selectable row carries.\n *\n * @public\n */\nexport interface MenuRowBase {\n /** A stable id. It becomes the row's `data-row` attribute, which is what a test selects on. */\n readonly id: string;\n /** The left-hand text. */\n readonly label: MenuLabel;\n /** Whether the row can be selected. A row that answers `false` is drawn dimmed and skipped. */\n readonly enabled?: () => boolean;\n}\n\n/**\n * A row that runs something when it is activated.\n *\n * @public\n */\nexport interface MenuActionRow extends MenuRowBase {\n /** What kind of row this is. */\n readonly kind: \"action\";\n /** The right-hand text, when the row shows one. */\n readonly value?: MenuLabel;\n /** What Enter, the pad's south button and a click do. */\n readonly activate?: () => void;\n}\n\n/**\n * A row that flips a flag.\n *\n * @public\n */\nexport interface MenuToggleRow extends MenuRowBase {\n /** What kind of row this is. */\n readonly kind: \"toggle\";\n /** Reads the flag. */\n readonly get: () => boolean;\n /** Writes the flag. */\n readonly set: (value: boolean) => void;\n /** Renders the flag. Defaults to the menu's `text.on` / `text.off`. */\n readonly format?: (value: boolean) => string;\n}\n\n/**\n * A row that edits a number over a range.\n *\n * @remarks\n * Drawn as a native `<input type=\"range\">` plus the formatted value, because dragging a knob is\n * worth having and `@ignifx/ui`'s own focus policy deliberately does not count a slider as a text\n * field (`docs/architecture/13-ui.md` §1), so a slider under the pointer never suppresses gameplay\n * input.\n *\n * @public\n */\nexport interface MenuSliderRow extends MenuRowBase {\n /** What kind of row this is. */\n readonly kind: \"slider\";\n /** The lowest value the row may take. */\n readonly min: number;\n /** The highest value the row may take. */\n readonly max: number;\n /** How far one Left or Right press moves the value. */\n readonly step: number;\n /** Reads the current value. */\n readonly get: () => number;\n /** Writes a new value, already clamped and snapped to the step. */\n readonly set: (value: number) => void;\n /** Renders the value. Defaults to the number itself. */\n readonly format?: (value: number) => string;\n}\n\n/**\n * A row that cycles through a list of values.\n *\n * @public\n */\nexport interface MenuChoiceRow extends MenuRowBase {\n /** What kind of row this is. */\n readonly kind: \"choice\";\n /** The values to cycle through, in order. */\n readonly values: MenuChoiceValues;\n /** Reads the current value. */\n readonly get: () => string;\n /** Writes the new value. */\n readonly set: (value: string) => void;\n /** Renders a value for display. Defaults to the value itself. */\n readonly format?: (value: string) => string;\n}\n\n/**\n * A row that shows one input binding and starts a rebind when it is activated.\n *\n * @remarks\n * The row knows nothing about `@ignifx/input`: it is handed the binding's path as a string and a\n * callback that starts whatever rebinding flow the game uses. `@ignifx/input`'s\n * `performInteractiveRebind` is the usual one.\n *\n * @public\n */\nexport interface MenuBindingRow extends MenuRowBase {\n /** What kind of row this is. */\n readonly kind: \"binding\";\n /** Reads the binding path, such as `<Keyboard>/arrowUp`, or `\"\"` when nothing is bound. */\n readonly path: () => string;\n /** Starts the rebind. */\n readonly rebind?: () => void;\n /** Whether this row's rebind is listening right now, which changes what the row shows. */\n readonly listening?: () => boolean;\n}\n\n/**\n * A non-selectable label that groups the rows under it.\n *\n * @public\n */\nexport interface MenuHeadingRow {\n /** What kind of row this is. */\n readonly kind: \"heading\";\n /** A stable id, which becomes the row's `data-row` attribute. */\n readonly id: string;\n /** The heading text. */\n readonly label: MenuLabel;\n}\n\n/**\n * A non-selectable rule between groups of rows.\n *\n * @public\n */\nexport interface MenuSeparatorRow {\n /** What kind of row this is. */\n readonly kind: \"separator\";\n /** A stable id, which becomes the row's `data-row` attribute. */\n readonly id: string;\n}\n\n/**\n * One row of a {@link Menu}.\n *\n * @public\n */\nexport type MenuRow =\n | MenuActionRow\n | MenuBindingRow\n | MenuChoiceRow\n | MenuHeadingRow\n | MenuSeparatorRow\n | MenuSliderRow\n | MenuToggleRow;\n\n/**\n * The words a menu uses for the states its rows can be in, so a localized game sets them once per\n * menu rather than on every row.\n *\n * @public\n */\nexport interface MenuText {\n /** What a `\"toggle\"` row shows when it is on. Defaults to `\"On\"`. */\n readonly on?: MenuLabel;\n /** What a `\"toggle\"` row shows when it is off. Defaults to `\"Off\"`. */\n readonly off?: MenuLabel;\n /** What a `\"binding\"` row shows when nothing is bound. Defaults to `\"—\"`. */\n readonly unbound?: MenuLabel;\n /** What a `\"binding\"` row shows while it is listening. Defaults to `\"Press any key…\"`. */\n readonly listening?: MenuLabel;\n}\n\n/**\n * Reads a {@link MenuLabel}.\n *\n * @param label - The fixed string, the function, or nothing.\n * @param fallback - What to answer when `label` is `undefined`.\n * @returns The text to draw.\n *\n * @public\n */\nexport function resolveMenuLabel(label: MenuLabel | undefined, fallback: string): string {\n if (label === undefined) {\n return fallback;\n }\n return typeof label === \"string\" ? label : label();\n}\n\n/**\n * Reads a {@link MenuChoiceValues}.\n *\n * @param values - The fixed list or the function.\n * @returns The values, in order.\n *\n * @public\n */\nexport function resolveMenuChoices(values: MenuChoiceValues): readonly string[] {\n return typeof values === \"function\" ? values() : values;\n}\n\n/**\n * Clamps a number into a range and snaps it to the step.\n *\n * @remarks\n * Snapping rather than accumulating is what stops a slider from drifting by floating-point error\n * after a few hundred key presses: every value is recomputed from `min` and a whole number of\n * steps.\n *\n * @param value - The raw value.\n * @param min - The lowest allowed value.\n * @param max - The highest allowed value.\n * @param step - The grid the value is snapped to. A step of `0` or less disables snapping.\n * @returns The clamped, snapped value.\n *\n * @example\n * ```ts\n * snapToStep(0.37, 0, 1, 0.05); // 0.35\n * ```\n *\n * @public\n */\nexport function snapToStep(value: number, min: number, max: number, step: number): number {\n const clamped = Math.min(max, Math.max(min, value));\n if (step <= 0) {\n return clamped;\n }\n const steps = Math.round((clamped - min) / step);\n return Math.min(max, Math.max(min, min + steps * step));\n}\n\n/**\n * Renders an `@ignifx/input` binding path the way a player reads it.\n *\n * @param path - The binding path, such as `<Keyboard>/arrowUp`, or `\"\"` for none.\n * @param unbound - What to answer for an empty path.\n * @returns The label, such as `Keyboard: Arrow up`.\n *\n * @example\n * ```ts\n * formatBindingPath(\"<Keyboard>/arrowUp\", \"—\"); // \"Keyboard: Arrow up\"\n * formatBindingPath(\"\", \"—\"); // \"—\"\n * ```\n *\n * @public\n */\nexport function formatBindingPath(path: string, unbound: string): string {\n if (path === \"\") {\n return unbound;\n }\n const slash = path.indexOf(\"/\");\n const device = slash > 0 ? path.slice(1, slash - 1) : \"\";\n const control = slash > 0 ? path.slice(slash + 1) : path;\n const spaced = control.replaceAll(\"/\", \" \").replaceAll(/(?<lower>[a-z])(?<upper>[A-Z])/gu, \"$<lower> $<upper>\");\n const pretty = spaced.charAt(0).toUpperCase() + spaced.slice(1).toLowerCase();\n return device === \"\" ? pretty : `${device}: ${pretty}`;\n}\n","import { assertNever, Signal } from \"@ignifx/core\";\nimport { UI_CLASS_NAMES } from \"../dom/styles.js\";\nimport { formatBindingPath, resolveMenuChoices, resolveMenuLabel, snapToStep } from \"./menu-row.js\";\nimport type { MenuLabel, MenuRow, MenuSliderRow, MenuText } from \"./menu-row.js\";\nimport type { UiHost } from \"../dom/host.js\";\nimport type { SignalLike } from \"@ignifx/core\";\n\n/**\n * Share one selection model across keyboard, gamepad, and pointer input.\n * DOM focus stays on the list; `aria-activedescendant` identifies the selected row.\n * Toggle rows expose `aria-checked`. Sliders expose their value through the row's accessible name;\n * the range input is pointer-only, while Left/Right also adjust the value.\n * Without a DOM overlay, methods are no-ops and `element` is `null`.\n */\n\n/**\n * What `new Menu(app.ui, options)` accepts.\n *\n * @public\n */\nexport interface MenuOptions {\n /** A stable id; it becomes the panel's `data-menu` attribute. */\n readonly id: string;\n /** The panel's heading. Re-read on every {@link Menu.refresh}. */\n readonly title?: MenuLabel;\n /** A line of prose under the heading. */\n readonly subtitle?: MenuLabel;\n /** The overlay layer to mount into. Defaults to `\"menu\"`. */\n readonly layer?: string;\n /** The rows to start with. More usually arrive through {@link Menu.setRows}. */\n readonly rows?: readonly MenuRow[];\n /** Whether the menu starts shown. Defaults to `false`. */\n readonly visible?: boolean;\n /** Whether Escape and {@link Menu.cancel} back out of the menu. Defaults to `true`. */\n readonly cancelable?: boolean;\n /**\n * Whether the widget reads the keyboard itself. Defaults to `true`.\n *\n * @remarks\n * Turn it off when the game drives navigation from its own input actions, or every arrow press\n * moves the selection twice. A {@link MenuStack} built with a navigation\n * source does that for you.\n */\n readonly keyboard?: boolean;\n /** Whether the selection wraps at both ends. Defaults to `true`. */\n readonly wrap?: boolean;\n /** The words the rows use for their states. */\n readonly text?: MenuText;\n}\n\n/** The elements one row is drawn from. */\ninterface MenuRowElements {\n /** The row's outermost element. */\n readonly root: HTMLElement;\n /** The left-hand text. */\n readonly label: HTMLElement;\n /** The right-hand text, or `null` for a row that shows none. */\n readonly value: HTMLElement | null;\n /** The range input, or `null` for anything but a `\"slider\"` row. */\n readonly slider: HTMLInputElement | null;\n}\n\n/** The default words a menu uses when {@link MenuOptions.text} does not override them. */\nconst DEFAULT_TEXT = {\n /** What a `\"toggle\"` row shows when it is on. */\n on: \"On\",\n /** What a `\"toggle\"` row shows when it is off. */\n off: \"Off\",\n /** What a `\"binding\"` row shows when nothing is bound. */\n unbound: \"—\",\n /** What a `\"binding\"` row shows while it is listening. */\n listening: \"Press any key…\",\n} as const;\n\n/**\n * A panel of selectable rows in an overlay layer.\n *\n * @example\n * ```ts ignore-check\n * const pause = new Menu(app.ui, { id: \"pause\", title: \"Paused\" });\n * pause.setRows([\n * { kind: \"action\", id: \"resume\", label: \"Resume\", activate: () => pause.hide() },\n * { kind: \"slider\", id: \"music\", label: \"Music\", min: 0, max: 1, step: 0.05,\n * get: () => music.volume, set: (v) => { music.volume = v; },\n * format: (v) => `${String(Math.round(v * 100))}%` },\n * ]);\n * pause.show();\n * ```\n *\n * @public\n */\nexport class Menu {\n /** The id the menu was built with. */\n readonly id: string;\n\n readonly #options: MenuOptions;\n\n readonly #panel: HTMLDivElement | null;\n\n readonly #heading: HTMLElement | null;\n\n readonly #subtitle: HTMLElement | null;\n\n readonly #list: HTMLElement | null;\n\n readonly #cleanups: (() => void)[] = [];\n\n /** Every range input this menu drew, so the key handler can leave their own keys alone. */\n readonly #sliders = new Set<EventTarget>();\n\n readonly #selectionChanged = new Signal<MenuRow>();\n\n readonly #activated = new Signal<MenuRow>();\n\n readonly #back = new Signal();\n\n #rows: readonly MenuRow[] = [];\n\n #elements: readonly MenuRowElements[] = [];\n\n #index = 0;\n\n #visible: boolean;\n\n #cancelable: boolean;\n\n #keyboard: boolean;\n\n #disposed = false;\n\n /**\n * Builds the panel and mounts it, hidden unless `options.visible` says otherwise.\n *\n * @param host - The overlay host, normally `app.ui`.\n * @param options - The id, the heading, the layer, and the starting rows.\n */\n constructor(host: UiHost, options: MenuOptions) {\n this.id = options.id;\n this.#options = options;\n this.#visible = options.visible ?? false;\n this.#cancelable = options.cancelable ?? true;\n this.#keyboard = options.keyboard ?? true;\n const layerElement = host.layer(options.layer ?? \"menu\").element;\n if (layerElement === null) {\n this.#panel = null;\n this.#heading = null;\n this.#subtitle = null;\n this.#list = null;\n this.setRows(options.rows ?? []);\n return;\n }\n const document = layerElement.ownerDocument;\n const panel = document.createElement(\"div\");\n panel.className = UI_CLASS_NAMES.menu;\n panel.dataset[\"menu\"] = options.id;\n panel.setAttribute(\"role\", \"dialog\");\n panel.setAttribute(\"aria-modal\", \"true\");\n panel.hidden = !this.#visible;\n\n const heading = document.createElement(\"h2\");\n heading.className = UI_CLASS_NAMES.menuTitle;\n panel.append(heading);\n\n let subtitle: HTMLElement | null = null;\n if (options.subtitle !== undefined) {\n subtitle = document.createElement(\"p\");\n subtitle.className = UI_CLASS_NAMES.menuSubtitle;\n panel.append(subtitle);\n }\n\n const list = document.createElement(\"div\");\n list.className = UI_CLASS_NAMES.menuRows;\n list.setAttribute(\"role\", \"menu\");\n list.tabIndex = -1;\n panel.append(list);\n const onKeyDown = (event: KeyboardEvent): void => {\n this.#onKeyDown(event);\n };\n list.addEventListener(\"keydown\", onKeyDown);\n this.#cleanups.push((): void => {\n list.removeEventListener(\"keydown\", onKeyDown);\n });\n layerElement.append(panel);\n\n this.#panel = panel;\n this.#heading = heading;\n this.#subtitle = subtitle;\n this.#list = list;\n this.setRows(options.rows ?? []);\n }\n\n /**\n * The panel element, so a game can restyle it or a test can read it.\n *\n * @returns The element, or `null` under an app with no DOM overlay.\n */\n get element(): HTMLDivElement | null {\n return this.#panel;\n }\n\n /**\n * Whether the panel is on screen.\n *\n * @returns `true` between {@link Menu.show} and {@link Menu.hide}.\n */\n get isVisible(): boolean {\n return this.#visible;\n }\n\n /**\n * The rows the menu is drawing.\n *\n * @returns The rows, in draw order.\n */\n get rows(): readonly MenuRow[] {\n return this.#rows;\n }\n\n /**\n * The selected row.\n *\n * @returns The row under the selection, or `null` when nothing can be selected.\n */\n get selected(): MenuRow | null {\n return this.#rows[this.#index] ?? null;\n }\n\n /**\n * Where the selection sits.\n *\n * @returns The index into {@link Menu.rows}.\n */\n get selectedIndex(): number {\n return this.#index;\n }\n\n /**\n * Whether Escape and {@link Menu.cancel} back out of this menu. A title screen sets it `false`.\n *\n * @returns `true` when the menu can be dismissed.\n */\n get cancelable(): boolean {\n return this.#cancelable;\n }\n\n // eslint-disable-next-line jsdoc/require-jsdoc -- the accessor pair is documented on the getter.\n set cancelable(value: boolean) {\n this.#cancelable = value;\n }\n\n /**\n * Whether the widget reads the keyboard itself.\n *\n * @returns `true` while its own `keydown` handler acts.\n */\n get keyboardEnabled(): boolean {\n return this.#keyboard;\n }\n\n // eslint-disable-next-line jsdoc/require-jsdoc -- the accessor pair is documented on the getter.\n set keyboardEnabled(value: boolean) {\n this.#keyboard = value;\n }\n\n /**\n * Emitted with the newly selected row whenever the selection moves, from any device. A game\n * connects a click sound to it.\n *\n * @returns The signal.\n */\n get onSelectionChanged(): SignalLike<MenuRow> {\n return this.#selectionChanged;\n }\n\n /**\n * Emitted with the row that was activated, after its own handler ran.\n *\n * @returns The signal.\n */\n get onActivated(): SignalLike<MenuRow> {\n return this.#activated;\n }\n\n /**\n * Emitted by {@link Menu.cancel} — Escape, the pad's east button, or a call — when the menu is\n * {@link Menu.cancelable}. A {@link MenuStack} connects `pop` to it.\n *\n * @returns The signal.\n */\n get onBack(): SignalLike {\n return this.#back;\n }\n\n /**\n * Replaces the rows and rebuilds the panel.\n *\n * @remarks\n * Rebuilding rather than diffing is deliberate: the row list changes when a save appears, when a\n * control scheme changes and when the locale changes, and a menu of at most a few dozen rows is\n * not worth a reconciler. The selection stays on the same row id when that id is still present.\n *\n * @param rows - The rows, in draw order.\n */\n setRows(rows: readonly MenuRow[]): void {\n const previous = this.#rows[this.#index]?.id ?? \"\";\n this.#rows = rows;\n this.#buildRows();\n const restored = rows.findIndex((row: MenuRow): boolean => row.id === previous);\n this.#index = restored >= 0 ? restored : this.#firstSelectable();\n this.refresh();\n }\n\n /** Re-reads every label and value and redraws the selection. */\n refresh(): void {\n const title = resolveMenuLabel(this.#options.title, \"\");\n if (this.#heading !== null) {\n this.#heading.textContent = title;\n }\n this.#panel?.setAttribute(\"aria-label\", title);\n this.#list?.setAttribute(\"aria-label\", title);\n if (this.#subtitle !== null) {\n this.#subtitle.textContent = resolveMenuLabel(this.#options.subtitle, \"\");\n }\n for (let index = 0; index < this.#rows.length; index += 1) {\n const row = this.#rows[index];\n const elements = this.#elements[index];\n if (row !== undefined && elements !== undefined) {\n this.#refreshRow(row, elements, index);\n }\n }\n this.#applyActiveDescendant();\n }\n\n /** Shows the panel, puts the selection on the first row that can take it, and focuses the list. */\n show(): void {\n if (this.#disposed) {\n return;\n }\n this.#visible = true;\n this.#index = this.#firstSelectable();\n if (this.#panel !== null) {\n this.#panel.hidden = false;\n }\n this.refresh();\n this.#list?.focus({ preventScroll: true });\n }\n\n /** Hides the panel. */\n hide(): void {\n if (this.#disposed) {\n return;\n }\n this.#visible = false;\n if (this.#panel !== null) {\n this.#panel.hidden = true;\n }\n this.refresh();\n }\n\n /**\n * Moves the selection, skipping headings, separators and disabled rows.\n *\n * @param delta - `-1` for up, `1` for down.\n */\n moveSelection(delta: -1 | 1): void {\n const count = this.#rows.length;\n if (count === 0) {\n return;\n }\n const wrap = this.#options.wrap ?? true;\n for (let step = 1; step <= count; step += 1) {\n const raw = this.#index + delta * step;\n if (!wrap && (raw < 0 || raw >= count)) {\n return;\n }\n const candidate = (raw + count * step) % count;\n if (this.#isSelectable(candidate)) {\n this.#select(candidate);\n return;\n }\n }\n }\n\n /**\n * Puts the selection on a row by id.\n *\n * @param id - The row's {@link MenuRowBase.id}.\n * @returns `true` when a selectable row with that id was found.\n */\n select(id: string): boolean {\n const index = this.#rows.findIndex((row: MenuRow): boolean => row.id === id);\n if (index < 0 || !this.#isSelectable(index)) {\n return false;\n }\n this.#select(index);\n return true;\n }\n\n /**\n * Runs the selected row's Left or Right behaviour: a slider moves by one step, a toggle flips,\n * and a choice advances.\n *\n * @param direction - `-1` for left, `1` for right.\n */\n adjustSelection(direction: -1 | 1): void {\n const row = this.#rows[this.#index];\n if (row === undefined || !this.#isSelectable(this.#index)) {\n return;\n }\n switch (row.kind) {\n case \"slider\": {\n row.set(snapToStep(row.get() + direction * row.step, row.min, row.max, row.step));\n break;\n }\n case \"toggle\": {\n row.set(!row.get());\n break;\n }\n case \"choice\": {\n const values = resolveMenuChoices(row.values);\n const here = values.indexOf(row.get());\n const next = values[(Math.max(here, 0) + direction + values.length) % values.length];\n if (next !== undefined && next !== row.get()) {\n row.set(next);\n }\n break;\n }\n case \"action\":\n case \"binding\":\n case \"heading\":\n case \"separator\": {\n break;\n }\n }\n this.refresh();\n }\n\n /** Runs the selected row's activate behaviour. */\n activateSelection(): void {\n const row = this.#rows[this.#index];\n if (row === undefined || !this.#isSelectable(this.#index)) {\n return;\n }\n switch (row.kind) {\n case \"action\": {\n row.activate?.();\n break;\n }\n case \"binding\": {\n row.rebind?.();\n break;\n }\n // A slider, a toggle and a choice all move on by one: Enter on a row whose only content is a\n // value is what a player expects to change that value.\n case \"choice\":\n case \"slider\":\n case \"toggle\": {\n this.adjustSelection(1);\n break;\n }\n // Unreachable: `#isSelectable` already turned these away.\n case \"heading\":\n case \"separator\": {\n break;\n }\n }\n this.refresh();\n this.#activated.emit(row);\n }\n\n /**\n * Backs out of the menu, if it is {@link Menu.cancelable}.\n *\n * @returns `true` when {@link Menu.onBack} was emitted, so the caller knows the press was used.\n */\n cancel(): boolean {\n if (!this.#cancelable || this.#disposed) {\n return false;\n }\n this.#back.emit();\n return true;\n }\n\n /** Removes the panel from the overlay and unsubscribes everything. */\n dispose(): void {\n if (this.#disposed) {\n return;\n }\n this.#disposed = true;\n for (const cleanup of this.#cleanups) {\n cleanup();\n }\n this.#cleanups.length = 0;\n this.#sliders.clear();\n this.#panel?.remove();\n this.#selectionChanged.clear();\n this.#activated.clear();\n this.#back.clear();\n }\n\n /**\n * Moves the selection and tells everyone.\n *\n * @param index - The row to select.\n */\n #select(index: number): void {\n if (index === this.#index) {\n return;\n }\n this.#index = index;\n this.refresh();\n this.#scrollIntoView();\n const row = this.#rows[index];\n if (row !== undefined) {\n this.#selectionChanged.emit(row);\n }\n }\n\n /**\n * Handles the keys the widget owns while the list has DOM focus.\n *\n * @param event - The key event.\n */\n #onKeyDown(event: KeyboardEvent): void {\n // A pointer press focuses a range input in most browsers even at `tabindex=\"-1\"`; while it has\n // focus its own arrow keys are the right behaviour, and the `input` event carries the change\n // back here.\n if (!this.#keyboard || (event.target !== null && this.#sliders.has(event.target))) {\n return;\n }\n switch (event.key) {\n case \"ArrowUp\": {\n this.moveSelection(-1);\n break;\n }\n case \"ArrowDown\": {\n this.moveSelection(1);\n break;\n }\n case \"ArrowLeft\": {\n this.adjustSelection(-1);\n break;\n }\n case \"ArrowRight\": {\n this.adjustSelection(1);\n break;\n }\n case \" \":\n case \"Enter\": {\n this.activateSelection();\n break;\n }\n case \"Escape\": {\n if (!this.cancel()) {\n return;\n }\n break;\n }\n default: {\n return;\n }\n }\n // Only for a key the menu acted on: an arrow that scrolled the page, or a space that scrolled\n // it, would otherwise move the panel out from under the player.\n event.preventDefault();\n }\n\n /** Rebuilds every row element from {@link Menu.setRows}'s list. */\n #buildRows(): void {\n const list = this.#list;\n if (list === null) {\n this.#elements = [];\n return;\n }\n const document = list.ownerDocument;\n list.replaceChildren();\n this.#sliders.clear();\n const built: MenuRowElements[] = [];\n for (let index = 0; index < this.#rows.length; index += 1) {\n const row = this.#rows[index];\n if (row !== undefined) {\n built.push(this.#buildRow(document, list, row, index));\n }\n }\n this.#elements = built;\n }\n\n /**\n * Builds one row's elements and connects its pointer handlers.\n *\n * @param document - The overlay's document.\n * @param list - The element to append to.\n * @param row - The row being drawn.\n * @param index - The row's position, captured by the pointer handlers.\n * @returns The row's elements.\n */\n #buildRow(document: Document, list: HTMLElement, row: MenuRow, index: number): MenuRowElements {\n const selectable = row.kind !== \"heading\" && row.kind !== \"separator\";\n const root = document.createElement(selectable ? \"button\" : \"div\");\n root.className = selectable ? UI_CLASS_NAMES.menuRow : rowClassName(row.kind);\n root.id = `${UI_CLASS_NAMES.menu}-${this.id}-${row.id}`;\n root.dataset[\"row\"] = row.id;\n root.dataset[\"kind\"] = row.kind;\n root.setAttribute(\"role\", rowRole(row.kind));\n root.tabIndex = -1;\n if (selectable) {\n root.setAttribute(\"type\", \"button\");\n }\n\n const label = document.createElement(\"span\");\n label.className = UI_CLASS_NAMES.menuRowLabel;\n root.append(label);\n\n let slider: HTMLInputElement | null = null;\n if (row.kind === \"slider\") {\n slider = document.createElement(\"input\");\n slider.type = \"range\";\n slider.className = UI_CLASS_NAMES.menuRowSlider;\n slider.tabIndex = -1;\n // Not in the accessibility tree: the row is a `menuitem`, which may not own an interactive\n // element, and the value is announced through the row's own name. See this file's header.\n slider.setAttribute(\"aria-hidden\", \"true\");\n slider.min = String(row.min);\n slider.max = String(row.max);\n slider.step = String(row.step);\n root.append(slider);\n this.#sliders.add(slider);\n }\n\n let value: HTMLElement | null = null;\n if (row.kind !== \"heading\" && row.kind !== \"separator\") {\n value = document.createElement(\"span\");\n value.className = UI_CLASS_NAMES.menuRowValue;\n root.append(value);\n }\n\n if (selectable) {\n this.#connectRowPointer(root, index);\n }\n if (slider !== null && row.kind === \"slider\") {\n this.#connectSlider(slider, row, index);\n }\n list.append(root);\n return { root, label, value, slider };\n }\n\n /**\n * Wires hover and click on a selectable row.\n *\n * @param root - The row element.\n * @param index - The row's position.\n */\n #connectRowPointer(root: HTMLElement, index: number): void {\n const onEnter = (): void => {\n if (this.#isSelectable(index)) {\n this.#select(index);\n }\n };\n const onClick = (): void => {\n if (!this.#isSelectable(index)) {\n return;\n }\n this.#select(index);\n this.activateSelection();\n };\n root.addEventListener(\"pointerenter\", onEnter);\n root.addEventListener(\"click\", onClick);\n this.#cleanups.push((): void => {\n root.removeEventListener(\"pointerenter\", onEnter);\n root.removeEventListener(\"click\", onClick);\n });\n }\n\n /**\n * Wires a range input to its row.\n *\n * @param slider - The input element.\n * @param row - The row it belongs to.\n * @param index - The row's position.\n */\n #connectSlider(slider: HTMLInputElement, row: MenuSliderRow, index: number): void {\n const onInput = (): void => {\n this.#index = index;\n row.set(snapToStep(Number(slider.value), row.min, row.max, row.step));\n this.refresh();\n };\n slider.addEventListener(\"input\", onInput);\n // A drag on the knob is a click on the row; without `stopSliderClick` the row would activate —\n // and a menu built out of one slider would advance a step — as soon as the player let go.\n slider.addEventListener(\"click\", stopSliderClick);\n this.#cleanups.push((): void => {\n slider.removeEventListener(\"input\", onInput);\n slider.removeEventListener(\"click\", stopSliderClick);\n });\n }\n\n /**\n * Re-reads one row and writes it onto its elements.\n *\n * @param row - The row.\n * @param elements - Its elements.\n * @param index - Its position, compared against the selection.\n */\n #refreshRow(row: MenuRow, elements: MenuRowElements, index: number): void {\n elements.label.textContent = row.kind === \"separator\" ? \"\" : resolveMenuLabel(row.label, \"\");\n if (elements.value !== null) {\n elements.value.textContent = this.#rowValueText(row);\n }\n if (elements.slider !== null && row.kind === \"slider\") {\n elements.slider.value = String(row.get());\n }\n if (row.kind === \"toggle\") {\n elements.root.setAttribute(\"aria-checked\", row.get() ? \"true\" : \"false\");\n }\n const enabled = this.#isSelectable(index);\n const selectable = row.kind !== \"heading\" && row.kind !== \"separator\";\n elements.root.toggleAttribute(\"data-disabled\", selectable && !enabled);\n if (selectable) {\n elements.root.setAttribute(\"aria-disabled\", enabled ? \"false\" : \"true\");\n }\n elements.root.toggleAttribute(\"data-focused\", enabled && index === this.#index && this.#visible);\n }\n\n /**\n * The right-hand text of one row.\n *\n * @param row - The row.\n * @returns The text, or `\"\"` when the row shows none.\n */\n #rowValueText(row: MenuRow): string {\n const text = this.#options.text ?? {};\n switch (row.kind) {\n case \"action\": {\n return resolveMenuLabel(row.value, \"\");\n }\n case \"toggle\": {\n const on = row.get();\n return row.format?.(on) ?? resolveMenuLabel(on ? text.on : text.off, on ? DEFAULT_TEXT.on : DEFAULT_TEXT.off);\n }\n case \"slider\": {\n const value = row.get();\n return row.format?.(value) ?? String(value);\n }\n case \"choice\": {\n const value = row.get();\n return row.format?.(value) ?? value;\n }\n case \"binding\": {\n if (row.listening?.() === true) {\n return resolveMenuLabel(text.listening, DEFAULT_TEXT.listening);\n }\n return formatBindingPath(row.path(), resolveMenuLabel(text.unbound, DEFAULT_TEXT.unbound));\n }\n case \"heading\":\n case \"separator\": {\n return \"\";\n }\n default: {\n return assertNever(row, \"menu row kind\");\n }\n }\n }\n\n /** Points `aria-activedescendant` at the selected row, or clears it. */\n #applyActiveDescendant(): void {\n const list = this.#list;\n if (list === null) {\n return;\n }\n const active = this.#isSelectable(this.#index) ? this.#elements[this.#index]?.root : undefined;\n if (active === undefined) {\n list.removeAttribute(\"aria-activedescendant\");\n return;\n }\n list.setAttribute(\"aria-activedescendant\", active.id);\n }\n\n /**\n * Whether a row can take the selection.\n *\n * @param index - The row's position.\n * @returns `true` when the row exists, is selectable, and is enabled.\n */\n #isSelectable(index: number): boolean {\n const row = this.#rows[index];\n if (row === undefined || row.kind === \"heading\" || row.kind === \"separator\") {\n return false;\n }\n return row.enabled?.() ?? true;\n }\n\n /**\n * The first row that can take the selection.\n *\n * @returns Its index, or `0` when there is none.\n */\n #firstSelectable(): number {\n for (let index = 0; index < this.#rows.length; index += 1) {\n if (this.#isSelectable(index)) {\n return index;\n }\n }\n return 0;\n }\n\n /** Brings the selected row into view in a scrolling list. */\n #scrollIntoView(): void {\n this.#elements[this.#index]?.root.scrollIntoView({ block: \"nearest\" });\n }\n}\n\n/**\n * Keeps the click that ends a slider drag from reaching the row and activating it.\n *\n * @param event - The click.\n */\nfunction stopSliderClick(event: Event): void {\n event.stopPropagation();\n}\n\n/**\n * The ARIA role one row kind is drawn with.\n *\n * @param kind - The row kind.\n * @returns The role attribute value.\n */\nfunction rowRole(kind: MenuRow[\"kind\"]): string {\n switch (kind) {\n case \"toggle\": {\n return \"menuitemcheckbox\";\n }\n case \"heading\":\n case \"separator\": {\n return \"separator\";\n }\n case \"action\":\n case \"binding\":\n case \"choice\":\n case \"slider\": {\n return \"menuitem\";\n }\n default: {\n return assertNever(kind, \"menu row kind\");\n }\n }\n}\n\n/**\n * The class name a non-selectable row kind is drawn with.\n *\n * @param kind - The row kind.\n * @returns The class name.\n */\nfunction rowClassName(kind: MenuRow[\"kind\"]): string {\n return kind === \"heading\" ? UI_CLASS_NAMES.menuHeading : UI_CLASS_NAMES.menuSeparator;\n}\n","import { Signal } from \"@ignifx/core\";\nimport type { MenuRow } from \"./menu-row.js\";\nimport type { Menu } from \"./menu.js\";\nimport type { Disconnect, SignalLike, Vec2Like } from \"@ignifx/core\";\n\n/**\n * Show one menu at a time and unwind one level per back action. Use unscaled time for input repeat\n * so navigation works while paused. Navigation accepts action-shaped objects without importing input.\n * When a navigation source is supplied, disable each stacked menu's keyboard handling to avoid\n * processing the same key twice; restore it on removal.\n */\n\n/**\n * Anything with a two-dimensional value, which `@ignifx/input`'s `InputAction` is.\n *\n * @public\n */\nexport interface MenuVectorSource {\n /** The direction, `-1` to `1` on each axis. Positive `y` is up. */\n readonly vector: Vec2Like;\n}\n\n/**\n * Anything with a press edge, which `@ignifx/input`'s `InputAction` is.\n *\n * @public\n */\nexport interface MenuButtonSource {\n /** Whether the control went down this frame. */\n readonly wasPressedThisFrame: boolean;\n}\n\n/**\n * The three controls a menu stack reads.\n *\n * @public\n */\nexport interface MenuNavigation {\n /** Moves the selection (`y`) and adjusts the selected row (`x`). */\n readonly move?: MenuVectorSource | null;\n /** Activates the selected row. */\n readonly submit?: MenuButtonSource | null;\n /** Backs out one screen. */\n readonly back?: MenuButtonSource | null;\n}\n\n/**\n * What `new MenuStack(options)` accepts.\n *\n * @public\n */\nexport interface MenuStackOptions {\n /** The controls to read in {@link MenuStack.update}. Omit to drive the stack by hand. */\n readonly navigation?: MenuNavigation;\n /** How long the first repeat of a held direction waits, in seconds. Defaults to `0.35`. */\n readonly repeatDelay?: number;\n /** How long each following repeat waits, in seconds. Defaults to `0.12`. */\n readonly repeatInterval?: number;\n /** How far an axis must move before it counts as a direction. Defaults to `0.5`. */\n readonly threshold?: number;\n}\n\n/** What the stack remembers about one menu it pushed. */\ninterface StackEntry {\n /** The menu. */\n readonly menu: Menu;\n /** The subscriptions to drop when it is popped. */\n readonly disconnects: readonly Disconnect[];\n /** What the menu's `keyboardEnabled` was before the stack turned it off. */\n readonly keyboard: boolean;\n}\n\n/**\n * A stack of {@link Menu} screens, innermost last.\n *\n * @example\n * ```ts ignore-check\n * const stack = new MenuStack({ navigation });\n * stack.push(title);\n * // in a script that runs while paused:\n * stack.update(app.time.unscaledDeltaTime);\n * ```\n *\n * @public\n */\nexport class MenuStack {\n readonly #entries: StackEntry[] = [];\n\n readonly #navigation: MenuNavigation | null;\n\n readonly #repeatDelay: number;\n\n readonly #repeatInterval: number;\n\n readonly #threshold: number;\n\n readonly #changed = new Signal<Menu | null>();\n\n readonly #selectionChanged = new Signal<MenuRow>();\n\n readonly #activated = new Signal<MenuRow>();\n\n #heldX: -1 | 0 | 1 = 0;\n\n #heldY: -1 | 0 | 1 = 0;\n\n #repeatIn = 0;\n\n #suspended = false;\n\n /**\n * Builds an empty stack.\n *\n * @param options - The controls to read, and the repeat timings.\n */\n constructor(options: MenuStackOptions = {}) {\n this.#navigation = options.navigation ?? null;\n this.#repeatDelay = options.repeatDelay ?? 0.35;\n this.#repeatInterval = options.repeatInterval ?? 0.12;\n this.#threshold = options.threshold ?? 0.5;\n }\n\n /**\n * The menus on the stack, outermost first.\n *\n * @returns The menus, in push order.\n */\n get menus(): readonly Menu[] {\n return this.#entries.map((entry: StackEntry): Menu => entry.menu);\n }\n\n /**\n * The menu on top, which is the visible one.\n *\n * @returns The top menu, or `null` when the stack is empty.\n */\n get top(): Menu | null {\n return this.#entries.at(-1)?.menu ?? null;\n }\n\n /**\n * The menu at the bottom, which is the one the stack was opened with.\n *\n * @returns The first menu pushed, or `null` when the stack is empty.\n */\n get bottom(): Menu | null {\n return this.#entries[0]?.menu ?? null;\n }\n\n /**\n * How deep the stack is.\n *\n * @returns The number of menus on it.\n */\n get depth(): number {\n return this.#entries.length;\n }\n\n /**\n * Whether any menu is open.\n *\n * @returns `true` while the stack is not empty.\n */\n get isOpen(): boolean {\n return this.#entries.length > 0;\n }\n\n /**\n * Whether {@link MenuStack.update} is reading its controls.\n *\n * @remarks\n * Set it while something modal is on top of the menu — a confirmation `Dialog`, or a rebind that\n * is listening for the next key — so that the same press does not reach both.\n *\n * @returns `true` while navigation is suspended.\n */\n get suspended(): boolean {\n return this.#suspended;\n }\n\n // eslint-disable-next-line jsdoc/require-jsdoc -- the accessor pair is documented on the getter.\n set suspended(value: boolean) {\n this.#suspended = value;\n if (value) {\n this.#releaseHeld();\n }\n }\n\n /**\n * Emitted with the new top menu — `null` when the stack empties — whenever the stack changes. A\n * game connects its audio ducking and its pause state to it.\n *\n * @returns The signal.\n */\n get onChanged(): SignalLike<Menu | null> {\n return this.#changed;\n }\n\n /**\n * Emitted with the newly selected row whenever the selection moves on the top menu.\n *\n * @returns The signal.\n */\n get onSelectionChanged(): SignalLike<MenuRow> {\n return this.#selectionChanged;\n }\n\n /**\n * Emitted with the row that was activated on the top menu.\n *\n * @returns The signal.\n */\n get onActivated(): SignalLike<MenuRow> {\n return this.#activated;\n }\n\n /**\n * Hides whatever is on top and shows `menu` over it.\n *\n * @param menu - The menu to open.\n */\n push(menu: Menu): void {\n this.top?.hide();\n const keyboard = menu.keyboardEnabled;\n if (this.#navigation !== null) {\n menu.keyboardEnabled = false;\n }\n this.#entries.push({\n menu,\n keyboard,\n disconnects: [\n menu.onBack.connect((): void => {\n this.pop();\n }),\n menu.onSelectionChanged.connect((row: MenuRow): void => {\n this.#selectionChanged.emit(row);\n }),\n menu.onActivated.connect((row: MenuRow): void => {\n this.#activated.emit(row);\n }),\n ],\n });\n menu.show();\n this.#releaseHeld();\n this.#changed.emit(menu);\n }\n\n /**\n * Closes the top menu and shows the one underneath.\n *\n * @returns The menu that was closed, or `null` when the stack was already empty.\n */\n pop(): Menu | null {\n const entry = this.#entries.pop();\n if (entry === undefined) {\n return null;\n }\n this.#release(entry);\n entry.menu.hide();\n this.top?.show();\n this.#releaseHeld();\n this.#changed.emit(this.top);\n return entry.menu;\n }\n\n /** Closes every menu on the stack. */\n closeAll(): void {\n if (this.#entries.length === 0) {\n return;\n }\n for (let index = this.#entries.length - 1; index >= 0; index -= 1) {\n const entry = this.#entries[index];\n if (entry !== undefined) {\n this.#release(entry);\n entry.menu.hide();\n }\n }\n this.#entries.length = 0;\n this.#releaseHeld();\n this.#changed.emit(null);\n }\n\n /** Re-reads every label on every menu on the stack, for a locale change. */\n refresh(): void {\n for (const entry of this.#entries) {\n entry.menu.refresh();\n }\n }\n\n /**\n * Reads the navigation controls and applies them to the top menu.\n *\n * @remarks\n * Call it from a script that declares `static updateWhenPaused = true`, with\n * `app.time.unscaledDeltaTime`: a menu that repeats a held direction has to keep time while the\n * game is stopped, and scaled time is pinned at zero while it is.\n *\n * @param unscaledDelta - Seconds since the last call, on the unscaled clock.\n */\n update(unscaledDelta: number): void {\n const top = this.top;\n const navigation = this.#navigation;\n if (top === null || navigation === null || this.#suspended) {\n this.#releaseHeld();\n return;\n }\n const move = navigation.move ?? null;\n const x = this.#direction(move === null ? 0 : move.vector.x);\n const y = this.#direction(move === null ? 0 : move.vector.y);\n if (x !== this.#heldX || y !== this.#heldY) {\n this.#heldX = x;\n this.#heldY = y;\n this.#repeatIn = this.#repeatDelay;\n this.#applyDirection(top, x, y);\n } else if (x !== 0 || y !== 0) {\n this.#repeatIn -= unscaledDelta;\n if (this.#repeatIn <= 0) {\n this.#repeatIn = this.#repeatInterval;\n this.#applyDirection(top, x, y);\n }\n }\n if (navigation.submit?.wasPressedThisFrame === true) {\n top.activateSelection();\n return;\n }\n if (navigation.back?.wasPressedThisFrame === true) {\n top.cancel();\n }\n }\n\n /** Drops every subscription. The menus themselves belong to the game and are not disposed. */\n dispose(): void {\n for (const entry of this.#entries) {\n this.#release(entry);\n }\n this.#entries.length = 0;\n this.#changed.clear();\n this.#selectionChanged.clear();\n this.#activated.clear();\n }\n\n /**\n * Applies one direction to the top menu.\n *\n * @param top - The menu on top.\n * @param x - `-1`, `0` or `1` on the horizontal axis.\n * @param y - `-1`, `0` or `1` on the vertical axis, positive up.\n */\n #applyDirection(top: Menu, x: -1 | 0 | 1, y: -1 | 0 | 1): void {\n if (y !== 0) {\n top.moveSelection(y > 0 ? -1 : 1);\n }\n if (x !== 0) {\n top.adjustSelection(x);\n }\n }\n\n /**\n * Turns an axis into a direction, so a stick and a keyboard composite read the same.\n *\n * @param value - The axis value.\n * @returns `-1`, `0` or `1`.\n */\n #direction(value: number): -1 | 0 | 1 {\n if (value >= this.#threshold) {\n return 1;\n }\n return value <= -this.#threshold ? -1 : 0;\n }\n\n /** Forgets the held direction, so the next frame starts a fresh press. */\n #releaseHeld(): void {\n this.#heldX = 0;\n this.#heldY = 0;\n this.#repeatIn = 0;\n }\n\n /**\n * Drops one entry's subscriptions and gives its menu its keyboard handling back.\n *\n * @param entry - The entry being removed.\n */\n #release(entry: StackEntry): void {\n for (const disconnect of entry.disconnects) {\n disconnect();\n }\n entry.menu.keyboardEnabled = entry.keyboard;\n }\n}\n","import { Signal } from \"@ignifx/core\";\nimport { UI_CLASS_NAMES } from \"../dom/styles.js\";\nimport type { UiHost } from \"../dom/host.js\";\nimport type { SignalLike } from \"@ignifx/core\";\n\n/**\n * The caller advances toast lifetime; no browser timer can outlive the app.\n * For messages that expire while paused, call `advance(app.time.unscaledDeltaTime)` from a script\n * with `updateWhenPaused = true`. The UI system does not advance toasts automatically.\n */\n\n/**\n * What `new Toast(app.ui, options)` accepts.\n *\n * @public\n */\nexport interface ToastOptions {\n /** The layer to mount the stack into. Defaults to `\"overlay\"`. */\n readonly layer?: string;\n /** How long a message stays up, in seconds, unless {@link Toast.show} overrides it. */\n readonly duration?: number;\n /** How many messages are stacked before the oldest is dropped. Defaults to `4`. */\n readonly maxVisible?: number;\n}\n\n/** One message on screen, and how much of its life is left. */\ninterface LiveToast {\n /** The element, or `null` under a headless app. */\n readonly element: HTMLDivElement | null;\n /** The text, so a headless test can assert on it. */\n readonly text: string;\n /** Seconds left before it is removed. */\n remaining: number;\n}\n\n/**\n * A stack of transient messages.\n *\n * @example\n * ```ts\n * const toasts = new Toast(app.ui);\n * toasts.show(\"Checkpoint reached\");\n * // in the update of a script that declares `static updateWhenPaused = true`:\n * toasts.advance(app.time.unscaledDeltaTime);\n * ```\n *\n * @public\n */\nexport class Toast {\n readonly #stack: HTMLDivElement | null;\n\n readonly #live: LiveToast[] = [];\n\n readonly #duration: number;\n\n readonly #maxVisible: number;\n\n readonly #expired = new Signal<string>();\n\n #disposed = false;\n\n /**\n * Builds the stack and mounts it.\n *\n * @param host - The overlay host, normally `app.ui`.\n * @param options - The layer, the default duration, and the stack depth.\n */\n constructor(host: UiHost, options: ToastOptions = {}) {\n this.#duration = options.duration ?? 3;\n this.#maxVisible = Math.max(1, options.maxVisible ?? 4);\n const layerElement = host.layer(options.layer ?? \"overlay\").element;\n if (layerElement === null) {\n this.#stack = null;\n return;\n }\n const stack = layerElement.ownerDocument.createElement(\"div\");\n stack.className = UI_CLASS_NAMES.toastStack;\n stack.setAttribute(\"role\", \"status\");\n stack.setAttribute(\"aria-live\", \"polite\");\n layerElement.append(stack);\n this.#stack = stack;\n }\n\n /**\n * The stack element, so a template can reposition it.\n *\n * @returns The element, or `null` when the app has no DOM overlay.\n */\n get element(): HTMLDivElement | null {\n return this.#stack;\n }\n\n /**\n * The messages currently on screen, oldest first.\n *\n * @returns The texts.\n */\n get messages(): readonly string[] {\n return this.#live.map((entry: LiveToast): string => entry.text);\n }\n\n /**\n * Emitted with a message's text when it times out or is pushed off the stack.\n *\n * @returns The signal.\n */\n get onDismissed(): SignalLike<string> {\n return this.#expired;\n }\n\n /**\n * Shows a message.\n *\n * @param text - The message.\n * @param duration - How long it stays up, in seconds; defaults to the stack's own duration.\n */\n show(text: string, duration?: number): void {\n if (this.#disposed) {\n return;\n }\n const stack = this.#stack;\n let element: HTMLDivElement | null = null;\n if (stack !== null) {\n element = stack.ownerDocument.createElement(\"div\");\n element.className = UI_CLASS_NAMES.toast;\n element.textContent = text;\n stack.append(element);\n }\n this.#live.push({ element, text, remaining: duration ?? this.#duration });\n while (this.#live.length > this.#maxVisible) {\n this.#remove(0);\n }\n }\n\n /**\n * Advances every message's timer.\n *\n * @remarks\n * Nothing calls this for you. The script that does must declare `static updateWhenPaused = true`\n * if toasts are to expire while the game is paused — a menu's \"Saved\" message is shown from a\n * paused game, and an ordinary script gets no `update` there.\n *\n * @param deltaSeconds - Seconds elapsed since the previous call; `dt` from a script's `update`, or\n * `app.time.unscaledDeltaTime` when the toast has to expire while the game is paused.\n */\n advance(deltaSeconds: number): void {\n for (let index = this.#live.length - 1; index >= 0; index -= 1) {\n const entry = this.#live[index];\n if (entry === undefined) {\n continue;\n }\n entry.remaining -= deltaSeconds;\n if (entry.remaining <= 0) {\n this.#remove(index);\n }\n }\n }\n\n /** Removes every message at once. */\n clear(): void {\n while (this.#live.length > 0) {\n this.#remove(this.#live.length - 1);\n }\n }\n\n /** Removes the stack and unsubscribes. */\n dispose(): void {\n if (this.#disposed) {\n return;\n }\n this.#disposed = true;\n this.#live.length = 0;\n this.#stack?.remove();\n this.#expired.clear();\n }\n\n /**\n * Removes one message and reports it.\n *\n * @param index - Its position in the stack.\n */\n #remove(index: number): void {\n const entry = this.#live[index];\n if (entry === undefined) {\n return;\n }\n this.#live.splice(index, 1);\n entry.element?.remove();\n this.#expired.emit(entry.text);\n }\n}\n","import { uiError, UiErrorCode } from \"../errors.js\";\nimport type { App } from \"@ignifx/core\";\n\n/**\n * Reach virtual input through its two-method shape. Importing the optional input peer, even for\n * types, would augment core and expose `app.input` to games that have not installed it.\n */\n\n/**\n * The part of `@ignifx/input`'s virtual device the touch widgets use.\n *\n * @remarks\n * Structural on purpose. A test passes a recording double; a game passes\n * `app.input.devices.virtual`.\n *\n * @public\n */\nexport interface VirtualDeviceLike {\n /**\n * Writes a scalar control, creating it when it does not exist.\n *\n * @param name - The control name, as it appears after `<Virtual>/`.\n * @param value - The new value.\n */\n set(name: string, value: number): void;\n /**\n * Writes a vector control, creating it when it does not exist.\n *\n * @param name - The control name.\n * @param x - The new x component.\n * @param y - The new y component.\n */\n setVector(name: string, x: number, y: number): void;\n}\n\n/**\n * Whether a value has the two methods {@link VirtualDeviceLike} declares.\n *\n * @param value - The candidate.\n * @returns `true` when both methods are functions.\n */\nfunction isVirtualDevice(value: unknown): value is VirtualDeviceLike {\n if (value === null || typeof value !== \"object\") {\n return false;\n }\n return typeof Reflect.get(value, \"set\") === \"function\" && typeof Reflect.get(value, \"setVector\") === \"function\";\n}\n\n/**\n * Finds `app.input.devices.virtual`, if `@ignifx/input` is registered.\n *\n * @param app - The running app.\n * @returns The device, or `null` when the input extension is not installed.\n *\n * @example\n * ```ts\n * const device = findVirtualDevice(app);\n * device?.setVector(\"joystick\", 0, 1);\n * ```\n *\n * @public\n */\nexport function findVirtualDevice(app: App): VirtualDeviceLike | null {\n const input: unknown = Reflect.get(app, \"input\");\n if (input === null || typeof input !== \"object\") {\n return null;\n }\n const devices: unknown = Reflect.get(input, \"devices\");\n if (devices === null || typeof devices !== \"object\") {\n return null;\n }\n const virtual: unknown = Reflect.get(devices, \"virtual\");\n return isVirtualDevice(virtual) ? virtual : null;\n}\n\n/**\n * Finds the virtual device, or explains why the widget cannot work.\n *\n * @param app - The running app.\n * @param widget - The widget's name, for the error's context.\n * @returns The device.\n * @throws IgnifxError with code `IGX-1305` when `@ignifx/input` is not registered.\n *\n * @internal\n */\nexport function requireVirtualDevice(app: App, widget: string): VirtualDeviceLike {\n const device = findVirtualDevice(app);\n if (device === null) {\n throw uiError(UiErrorCode.inputExtensionMissing, `${widget} needs the @ignifx/input extension.`, {\n context: { widget },\n hint: \"Add input() to createApp({ extensions }) before constructing the widget.\",\n });\n }\n return device;\n}\n\n/**\n * Claims a pointer for an element, best effort.\n *\n * @remarks\n * `setPointerCapture` throws `NotFoundError` when the id names no *active* pointer — a pointer that\n * was already released, or a synthetic `PointerEvent` dispatched by a test. Capture is an\n * improvement, not a requirement: without it a drag that leaves the widget stops updating, and the\n * `pointerup` still arrives. Losing the frame over it would be worse than losing the capture.\n *\n * @param element - The element to capture on.\n * @param pointerId - The pointer to claim.\n *\n * @internal\n */\nexport function capturePointer(element: Element, pointerId: number): void {\n try {\n element.setPointerCapture(pointerId);\n } catch {\n // See the remarks: capture is best effort.\n }\n}\n","import { UI_CLASS_NAMES } from \"../dom/styles.js\";\nimport { capturePointer, requireVirtualDevice } from \"./virtual-device.js\";\nimport type { VirtualDeviceLike } from \"./virtual-device.js\";\nimport type { App } from \"@ignifx/core\";\n\n/**\n * `VirtualButton` (`docs/architecture/13-ui.md` §3): an on-screen button that writes a\n * `<Virtual>/…` button control, so `jump` is one action bound to a key, a gamepad face button, and\n * this widget at the same time.\n *\n * A real `<button>` element rather than a `<div>`, so it is focusable, announced by a screen\n * reader, and reachable by keyboard. That has one consequence worth knowing: pressing it with the\n * keyboard fires a `click`, not a `pointerdown`, so the button also releases on `blur` — otherwise a\n * `Tab` away mid-press would stick.\n */\n\n/**\n * What `new VirtualButton(app, options)` accepts.\n *\n * @public\n */\nexport interface VirtualButtonOptions {\n /** The `<Virtual>/…` control to write. */\n readonly control: string;\n /** The glyph or word drawn on the button. Defaults to the control name. */\n readonly label?: string;\n /** The layer to mount into. Defaults to `\"hud\"`. */\n readonly layer?: string;\n /** Inline styles applied to the button, for placement. */\n readonly style?: Readonly<Record<string, string>>;\n /** An accessible label. Defaults to the control name. */\n readonly ariaLabel?: string;\n}\n\n/**\n * An on-screen button.\n *\n * @example\n * ```ts\n * const jump = new VirtualButton(app, { control: \"jump\", label: \"A\" });\n * ```\n *\n * @public\n */\nexport class VirtualButton {\n readonly #device: VirtualDeviceLike;\n\n readonly #control: string;\n\n readonly #element: HTMLButtonElement | null;\n\n #pressed = false;\n\n #disposed = false;\n\n readonly #onPress = (event: PointerEvent): void => {\n this.#set(true);\n const element = this.#element;\n if (element !== null) {\n capturePointer(element, event.pointerId);\n }\n event.preventDefault();\n };\n\n readonly #onRelease = (event: PointerEvent): void => {\n this.#set(false);\n event.preventDefault();\n };\n\n readonly #onBlur = (): void => {\n this.#set(false);\n };\n\n /**\n * Builds the widget and mounts it.\n *\n * @param app - The running app; `app.ui` and `app.input.devices.virtual` are the parts used.\n * @param options - The control name, the label, the layer, and the placement styles.\n * @throws IgnifxError with code `IGX-1305` when `@ignifx/input` is not registered.\n */\n constructor(app: App, options: VirtualButtonOptions) {\n this.#control = options.control;\n this.#device = requireVirtualDevice(app, \"VirtualButton\");\n const host = app.ui.layer(options.layer ?? \"hud\").element;\n if (host === null) {\n this.#element = null;\n return;\n }\n const element = host.ownerDocument.createElement(\"button\");\n element.type = \"button\";\n element.className = UI_CLASS_NAMES.button;\n element.textContent = options.label ?? options.control;\n element.setAttribute(\"aria-label\", options.ariaLabel ?? options.control);\n // The button takes DOM focus when tapped, and a focused `<button>` is not a text field, so\n // `isEditableElement` leaves `app.input.uiHasFocus` alone and the keyboard keeps driving the\n // game while a thumb is on the screen.\n for (const [name, value] of Object.entries(options.style ?? {})) {\n element.style.setProperty(name, value);\n }\n host.append(element);\n this.#element = element;\n element.addEventListener(\"pointerdown\", this.#onPress);\n element.addEventListener(\"pointerup\", this.#onRelease);\n element.addEventListener(\"pointercancel\", this.#onRelease);\n element.addEventListener(\"blur\", this.#onBlur);\n this.#device.set(this.#control, 0);\n }\n\n /**\n * The button element, so a template can restyle or reposition it.\n *\n * @returns The element, or `null` when the app has no DOM overlay.\n */\n get element(): HTMLButtonElement | null {\n return this.#element;\n }\n\n /**\n * The control this button writes.\n *\n * @returns The name, as it appears after `<Virtual>/`.\n */\n get control(): string {\n return this.#control;\n }\n\n /**\n * Whether the button is currently held.\n *\n * @returns `true` while it is pressed.\n */\n get isPressed(): boolean {\n return this.#pressed;\n }\n\n /** Removes the widget, unsubscribes, and releases the control. */\n dispose(): void {\n if (this.#disposed) {\n return;\n }\n this.#disposed = true;\n const element = this.#element;\n if (element !== null) {\n element.removeEventListener(\"pointerdown\", this.#onPress);\n element.removeEventListener(\"pointerup\", this.#onRelease);\n element.removeEventListener(\"pointercancel\", this.#onRelease);\n element.removeEventListener(\"blur\", this.#onBlur);\n element.remove();\n }\n this.#device.set(this.#control, 0);\n }\n\n /**\n * Writes the control, if the state changed.\n *\n * @param pressed - Whether the button is held.\n */\n #set(pressed: boolean): void {\n if (this.#pressed === pressed) {\n return;\n }\n this.#pressed = pressed;\n this.#device.set(this.#control, pressed ? 1 : 0);\n }\n}\n","import { clamp } from \"@ignifx/core\";\nimport { UI_CLASS_NAMES } from \"../dom/styles.js\";\nimport { capturePointer, requireVirtualDevice } from \"./virtual-device.js\";\nimport type { VirtualDeviceLike } from \"./virtual-device.js\";\nimport type { UiLayer } from \"../dom/layer.js\";\nimport type { App } from \"@ignifx/core\";\n\n/**\n * Write a virtual vector control with Y up, converting screen Y-down motion here.\n * Claim one pointer at a time so the stick and buttons support separate touches.\n * Clear the control on both release and cancellation to prevent stuck movement.\n */\n\n/**\n * What `new VirtualJoystick(app, options)` accepts.\n *\n * @public\n */\nexport interface VirtualJoystickOptions {\n /** The `<Virtual>/…` control to write. Defaults to `\"joystick\"`. */\n readonly control?: string;\n /** The layer to mount into. Defaults to `\"hud\"`. */\n readonly layer?: string;\n /** How far the knob travels, in UI units, before the stick reads as fully deflected. */\n readonly radius?: number;\n /** Deflections shorter than this fraction of the radius read as zero. Defaults to `0.15`. */\n readonly deadZone?: number;\n /** Inline styles applied to the pad, for placement. */\n readonly style?: Readonly<Record<string, string>>;\n /** An accessible label for the pad. Defaults to the control name. */\n readonly ariaLabel?: string;\n}\n\n/**\n * Converts a raw deflection into the value written to the control.\n *\n * @param delta - The deflection along one axis, in UI units.\n * @param length - The deflection's length, in UI units.\n * @param radius - The radius at which the stick is fully deflected.\n * @param deadZone - The fraction of the radius below which the stick reads as centred.\n * @returns The axis value, in `-1` to `1`.\n *\n * @example\n * ```ts\n * stickAxis(0, 0, 44, 0.15); // 0\n * stickAxis(44, 44, 44, 0.15); // 1\n * ```\n *\n * @public\n */\nexport function stickAxis(delta: number, length: number, radius: number, deadZone: number): number {\n if (radius <= 0 || length <= 0) {\n return 0;\n }\n const magnitude = Math.min(length, radius) / radius;\n if (magnitude <= deadZone) {\n return 0;\n }\n // Rescaled so the value leaves the dead zone at 0 rather than jumping to `deadZone`, which is\n // what makes a slow walk possible on a touch screen.\n const scaled = (magnitude - deadZone) / (1 - deadZone);\n return clamp((delta / length) * scaled, -1, 1);\n}\n\n/**\n * An on-screen thumbstick.\n *\n * @example\n * ```ts\n * const stick = new VirtualJoystick(app, { control: \"joystick\" });\n * // later\n * stick.dispose();\n * ```\n *\n * @public\n */\nexport class VirtualJoystick {\n readonly #device: VirtualDeviceLike;\n\n readonly #control: string;\n\n readonly #radius: number;\n\n readonly #deadZone: number;\n\n readonly #pad: HTMLDivElement | null;\n\n readonly #knob: HTMLDivElement | null;\n\n #pointerId: number | null = null;\n\n #originX = 0;\n\n #originY = 0;\n\n #disposed = false;\n\n readonly #onPointerDown = (event: PointerEvent): void => {\n if (this.#pointerId !== null || this.#pad === null) {\n return;\n }\n this.#pointerId = event.pointerId;\n const box = this.#pad.getBoundingClientRect();\n this.#originX = box.left + box.width / 2;\n this.#originY = box.top + box.height / 2;\n capturePointer(this.#pad, event.pointerId);\n this.#move(event);\n event.preventDefault();\n };\n\n readonly #onPointerMove = (event: PointerEvent): void => {\n if (event.pointerId === this.#pointerId) {\n this.#move(event);\n event.preventDefault();\n }\n };\n\n readonly #onPointerUp = (event: PointerEvent): void => {\n if (event.pointerId === this.#pointerId) {\n this.#release();\n event.preventDefault();\n }\n };\n\n /**\n * Builds the widget and mounts it.\n *\n * @param app - The running app; `app.ui` and `app.input.devices.virtual` are the parts used.\n * @param options - The control name, the layer, the geometry, and the placement styles.\n * @throws IgnifxError with code `IGX-1305` when `@ignifx/input` is not registered.\n */\n constructor(app: App, options: VirtualJoystickOptions = {}) {\n this.#control = options.control ?? \"joystick\";\n this.#device = requireVirtualDevice(app, \"VirtualJoystick\");\n this.#radius = options.radius ?? 44;\n this.#deadZone = clamp(options.deadZone ?? 0.15, 0, 0.9);\n const layer: UiLayer = app.ui.layer(options.layer ?? \"hud\");\n const host = layer.element;\n if (host === null) {\n this.#pad = null;\n this.#knob = null;\n return;\n }\n const document = host.ownerDocument;\n const pad = document.createElement(\"div\");\n pad.className = UI_CLASS_NAMES.joystick;\n pad.setAttribute(\"role\", \"application\");\n pad.setAttribute(\"aria-label\", options.ariaLabel ?? this.#control);\n for (const [name, value] of Object.entries(options.style ?? {})) {\n pad.style.setProperty(name, value);\n }\n const knob = document.createElement(\"div\");\n knob.className = UI_CLASS_NAMES.joystickKnob;\n pad.append(knob);\n host.append(pad);\n this.#pad = pad;\n this.#knob = knob;\n pad.addEventListener(\"pointerdown\", this.#onPointerDown);\n pad.addEventListener(\"pointermove\", this.#onPointerMove);\n pad.addEventListener(\"pointerup\", this.#onPointerUp);\n pad.addEventListener(\"pointercancel\", this.#onPointerUp);\n this.#device.setVector(this.#control, 0, 0);\n }\n\n /**\n * The pad element, so a template can restyle or reposition it.\n *\n * @returns The element, or `null` when the app has no DOM overlay.\n */\n get element(): HTMLDivElement | null {\n return this.#pad;\n }\n\n /**\n * The control this stick writes.\n *\n * @returns The name, as it appears after `<Virtual>/`.\n */\n get control(): string {\n return this.#control;\n }\n\n /**\n * Whether a pointer currently holds the stick.\n *\n * @returns `true` while the stick is being dragged.\n */\n get isActive(): boolean {\n return this.#pointerId !== null;\n }\n\n /** Removes the widget, unsubscribes, and centres the control. */\n dispose(): void {\n if (this.#disposed) {\n return;\n }\n this.#disposed = true;\n const pad = this.#pad;\n if (pad !== null) {\n pad.removeEventListener(\"pointerdown\", this.#onPointerDown);\n pad.removeEventListener(\"pointermove\", this.#onPointerMove);\n pad.removeEventListener(\"pointerup\", this.#onPointerUp);\n pad.removeEventListener(\"pointercancel\", this.#onPointerUp);\n pad.remove();\n }\n this.#device.setVector(this.#control, 0, 0);\n }\n\n /**\n * Reads one pointer position and writes the control.\n *\n * @param event - The pointer event.\n */\n #move(event: PointerEvent): void {\n const dx = event.clientX - this.#originX;\n // Screen `+Y` points down and the world's points up, so the vertical axis is negated here and\n // nowhere else — the same convention the templates' own widget used.\n const dy = this.#originY - event.clientY;\n const length = Math.hypot(dx, dy);\n const scale = length > this.#radius ? this.#radius / length : 1;\n this.#knob?.style.setProperty(\"transform\", `translate(${String(dx * scale)}px, ${String(-dy * scale)}px)`);\n this.#device.setVector(\n this.#control,\n stickAxis(dx, length, this.#radius, this.#deadZone),\n stickAxis(dy, length, this.#radius, this.#deadZone),\n );\n }\n\n /** Centres the knob and the control. */\n #release(): void {\n this.#pointerId = null;\n this.#knob?.style.setProperty(\"transform\", \"translate(0px, 0px)\");\n this.#device.setVector(this.#control, 0, 0);\n }\n}\n"],"mappings":";;;;;;;;;;;;AAkCA,SAAgB,oBAAoB,KAAuB,MAAoB;CA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