Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(sdk): UI runtime modernization — anchor presets, theme system, data binding

esengine269cf5cab2b7
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 50cfc2fc5..83b6350d2 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,13 +1,18 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1063 stable · 44 beta · 1 deprecated
+Symbols: 1084 stable · 44 beta · 1 deprecated
## ABI_LAYOUT_HASH — const
```
"89ad72a9b853289f"
```
+## ANCHOR_AXES — const
+```
+readonly AnchorAxis[]
+```
+
## ActionDef — interface
```
bindings: Binding[]
@@ -144,6 +149,35 @@ Start = 1
Stretch = 4
```
+## AnchorAxis — enum
+```
+Center = 1
+End = 2
+Start = 0
+Stretch = 3
+```
+
+## AnchorFields — interface
+```
+height: Dimension | undefined
+insetBottom: Dimension
+insetLeft: Dimension
+insetRight: Dimension
+insetTop: Dimension
+marginBottom: Dimension
+marginLeft: Dimension
+marginRight: Dimension
+marginTop: Dimension
+position: number
+width: Dimension | undefined
+```
+
+## AnchorPreset — interface
+```
+h: AnchorAxis
+v: AnchorAxis
+```
+
## And — function
```
(...filters: FilterExpr[]): FilterExpr
@@ -971,7 +1005,7 @@ fadeDuration: number | undefined
node: UINodeInit | undefined
onClick: ((entity: Entity) => void) | undefined
parent: number | undefined
-states: Record<string, ButtonStateVisual>
+states: Record<string, ButtonStateVisual> | undefined
text: string | TextInit | undefined
transitionFlags: number | undefined
world: World
@@ -1285,6 +1319,11 @@ g: number
r: number
```
+## ColorRole — type
+```
+keyof ThemeColors
+```
+
## Commands — function
```
(): CommandsDescriptor
@@ -2968,6 +3007,11 @@ static new (opts?: KineticScrollOptions): KineticScroll
static prototype: KineticScroll
```
+## LIGHT_TOKENS — const
+```
+ThemeTokens
+```
+
## LayoutProvider — interface
```
getContentSize: (count: number) => Vec2
@@ -4487,6 +4531,12 @@ static prototype: QueryInstance<any>
1
```
+## ReadonlySignal — interface
+```
+get: () => T
+subscribe: (fn: (value: T) => void) => () => void
+```
+
## Removed — function
```
<T extends AnyComponentDef>(component: T): RemovedQueryDescriptor<T>
@@ -5188,6 +5238,14 @@ acquire: (id: SideModuleId) => Promise<SideModule | null>
'physics' | 'basis' | `spine:${SpineVersion}`
```
+## Signal — interface
+```
+get: () => T
+set: (value: T) => void
+subscribe: (fn: (value: T) => void) => () => void
+update: (fn: (prev: T) => T) => void
+```
+
## SimulationSpace — enum
```
Local = 1
@@ -5869,12 +5927,33 @@ primaryActive: Color
primaryHover: Color
surface: Color
surfaceElevated: Color
+text: Color
track: Color
```
+## ThemeStyle — const
+```
+ComponentDef<ThemeStyleData>
+```
+
+## ThemeStyleData — interface
+```
+states: Record<string, keyof ThemeColors> | undefined
+text: keyof ThemeColors | undefined
+visual: keyof ThemeColors | undefined
+```
+
## ThemeTokens — interface
```
colors: ThemeColors
+type: ThemeType
+```
+
+## ThemeType — interface
+```
+body: number
+label: number
+title: number
```
## TileFlags — interface
@@ -6860,6 +6939,11 @@ TransformData
AiRegistry<AiContext>
```
+## anchorPresetFields — function
+```
+(preset: AnchorPreset): AnchorFields
+```
+
## animationPlugin — const
```
AnimationPlugin
@@ -6885,6 +6969,11 @@ AnimationPlugin
(components: { Text?: { _default: Record<string, unknown>; }; TextInput?: { _default: Record<string, unknown>; }; Canvas?: { _default: Record<string, unknown>; }; }): void
```
+## applyThemeToWorld — function
+```
+(world: World): void
+```
+
## applyWrapMode — function
```
(time: number, duration: number, mode: WrapMode): { time: number; stopped: boolean; }
@@ -6915,6 +7004,11 @@ AudioPlugin
() => Dimension
```
+## bind — function
+```
+<C extends object, K extends keyof C>(world: World, entity: Entity, component: ComponentDef<C>, field: K, source: ReadonlySignal<C[K]>): () => void
+```
+
## btEdges — function
```
(def: BtDefinition): BtEdge[]
@@ -7245,6 +7339,16 @@ PluralSelector
(name: string): ComponentDef<{}>
```
+## derived — function
+```
+<T>(sources: ReadonlySignal<unknown>[], compute: () => T): ReadonlySignal<T>
+```
+
+## detectAnchor — function
+```
+(node: UINodeData): AnchorPreset | null
+```
+
## diffAgainstSource — function
```
(source: PrefabData, instance: readonly ProcessedEntity[], options?: DiffOptions): { overrides: PrefabOverride[]; untracked: ProcessedEntity[]; orphanedSourceIds: PrefabEntityId[]; }
@@ -7815,6 +7919,11 @@ Logger
(physics: Physics): LosCheck
```
+## markThemed — function
+```
+(world: World, entity: Entity, style: ThemeStyleData): void
+```
+
## maxChildren — function
```
(type: BtNodeType): number
@@ -8410,6 +8519,11 @@ Plugin
(): void
```
+## signal — function
+```
+<T>(initial: T): Signal<T>
+```
+
## singleStamp — function
```
(raw: number): TileStamp
@@ -8445,6 +8559,11 @@ StatsPlugin
(world: World, entity: Entity): void
```
+## switchTheme — function
+```
+(world: World, tokens: ThemeTokens): void
+```
+
## textInputPlugin — const
```
TextInputPlugin
@@ -8455,11 +8574,21 @@ TextInputPlugin
TextPlugin
```
+## themeButtonStates — function
+```
+(): Record<string, ButtonStateVisual>
+```
+
## themeColors — function
```
(): ThemeColors
```
+## themeType — function
+```
+(): ThemeType
+```
+
## tickBt — function
```
<Ctx>(def: BtDefinition, ctx: Ctx, bb: Blackboard, registry: AiRegistry<Ctx>, rs: BtRunState, dt: number): Status
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index bc13236ab..34b347cf2 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,12 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1062 stable · 46 beta · 1 deprecated
+Symbols: 1083 stable · 46 beta · 1 deprecated
+
+## ANCHOR_AXES — const
+```
+readonly AnchorAxis[]
+```
## ActionDef — interface
```
@@ -139,6 +144,35 @@ Start = 1
Stretch = 4
```
+## AnchorAxis — enum
+```
+Center = 1
+End = 2
+Start = 0
+Stretch = 3
+```
+
+## AnchorFields — interface
+```
+height: Dimension | undefined
+insetBottom: Dimension
+insetLeft: Dimension
+insetRight: Dimension
+insetTop: Dimension
+marginBottom: Dimension
+marginLeft: Dimension
+marginRight: Dimension
+marginTop: Dimension
+position: number
+width: Dimension | undefined
+```
+
+## AnchorPreset — interface
+```
+h: AnchorAxis
+v: AnchorAxis
+```
+
## And — function
```
(...filters: FilterExpr[]): FilterExpr
@@ -966,7 +1000,7 @@ fadeDuration: number | undefined
node: UINodeInit | undefined
onClick: ((entity: Entity) => void) | undefined
parent: number | undefined
-states: Record<string, ButtonStateVisual>
+states: Record<string, ButtonStateVisual> | undefined
text: string | TextInit | undefined
transitionFlags: number | undefined
world: World
@@ -1280,6 +1314,11 @@ g: number
r: number
```
+## ColorRole — type
+```
+keyof ThemeColors
+```
+
## Commands — function
```
(): CommandsDescriptor
@@ -2963,6 +3002,11 @@ static new (opts?: KineticScrollOptions): KineticScroll
static prototype: KineticScroll
```
+## LIGHT_TOKENS — const
+```
+ThemeTokens
+```
+
## LayoutProvider — interface
```
getContentSize: (count: number) => Vec2
@@ -4482,6 +4526,12 @@ static prototype: QueryInstance<any>
1
```
+## ReadonlySignal — interface
+```
+get: () => T
+subscribe: (fn: (value: T) => void) => () => void
+```
+
## Removed — function
```
<T extends AnyComponentDef>(component: T): RemovedQueryDescriptor<T>
@@ -5183,6 +5233,14 @@ acquire: (id: SideModuleId) => Promise<SideModule | null>
'physics' | 'basis' | `spine:${SpineVersion}`
```
+## Signal — interface
+```
+get: () => T
+set: (value: T) => void
+subscribe: (fn: (value: T) => void) => () => void
+update: (fn: (prev: T) => T) => void
+```
+
## SimulationSpace — enum
```
Local = 1
@@ -5864,12 +5922,33 @@ primaryActive: Color
primaryHover: Color
surface: Color
surfaceElevated: Color
+text: Color
track: Color
```
+## ThemeStyle — const
+```
+ComponentDef<ThemeStyleData>
+```
+
+## ThemeStyleData — interface
+```
+states: Record<string, keyof ThemeColors> | undefined
+text: keyof ThemeColors | undefined
+visual: keyof ThemeColors | undefined
+```
+
## ThemeTokens — interface
```
colors: ThemeColors
+type: ThemeType
+```
+
+## ThemeType — interface
+```
+body: number
+label: number
+title: number
```
## TileFlags — interface
@@ -6855,6 +6934,11 @@ TransformData
AiRegistry<AiContext>
```
+## anchorPresetFields — function
+```
+(preset: AnchorPreset): AnchorFields
+```
+
## animationPlugin — const
```
AnimationPlugin
@@ -6880,6 +6964,11 @@ AnimationPlugin
(components: { Text?: { _default: Record<string, unknown>; }; TextInput?: { _default: Record<string, unknown>; }; Canvas?: { _default: Record<string, unknown>; }; }): void
```
+## applyThemeToWorld — function
+```
+(world: World): void
+```
+
## applyWrapMode — function
```
(time: number, duration: number, mode: WrapMode): { time: number; stopped: boolean; }
@@ -6910,6 +6999,11 @@ AudioPlugin
() => Dimension
```
+## bind — function
+```
+<C extends object, K extends keyof C>(world: World, entity: Entity, component: ComponentDef<C>, field: K, source: ReadonlySignal<C[K]>): () => void
+```
+
## btEdges — function
```
(def: BtDefinition): BtEdge[]
@@ -7240,6 +7334,16 @@ PluralSelector
(name: string): ComponentDef<{}>
```
+## derived — function
+```
+<T>(sources: ReadonlySignal<unknown>[], compute: () => T): ReadonlySignal<T>
+```
+
+## detectAnchor — function
+```
+(node: UINodeData): AnchorPreset | null
+```
+
## diffAgainstSource — function
```
(source: PrefabData, instance: readonly ProcessedEntity[], options?: DiffOptions): { overrides: PrefabOverride[]; untracked: ProcessedEntity[]; orphanedSourceIds: PrefabEntityId[]; }
@@ -7815,6 +7919,11 @@ Logger
(physics: Physics): LosCheck
```
+## markThemed — function
+```
+(world: World, entity: Entity, style: ThemeStyleData): void
+```
+
## maxChildren — function
```
(type: BtNodeType): number
@@ -8415,6 +8524,11 @@ Plugin
(): void
```
+## signal — function
+```
+<T>(initial: T): Signal<T>
+```
+
## singleStamp — function
```
(raw: number): TileStamp
@@ -8450,6 +8564,11 @@ StatsPlugin
(world: World, entity: Entity): void
```
+## switchTheme — function
+```
+(world: World, tokens: ThemeTokens): void
+```
+
## textInputPlugin — const
```
TextInputPlugin
@@ -8460,11 +8579,21 @@ TextInputPlugin
TextPlugin
```
+## themeButtonStates — function
+```
+(): Record<string, ButtonStateVisual>
+```
+
## themeColors — function
```
(): ThemeColors
```
+## themeType — function
+```
+(): ThemeType
+```
+
## tickBt — function
```
<Ctx>(def: BtDefinition, ctx: Ctx, bb: Blackboard, registry: AiRegistry<Ctx>, rs: BtRunState, dt: number): Status
diff --git a/sdk/src/core-ui.ts b/sdk/src/core-ui.ts
index ce24af353..9eaf196f6 100644
--- a/sdk/src/core-ui.ts
+++ b/sdk/src/core-ui.ts
@@ -84,11 +84,27 @@ export {
type SafeAreaData,
// Theme design tokens
DARK_TOKENS,
+ LIGHT_TOKENS,
getTheme,
setTheme,
themeColors,
+ themeType,
type ThemeTokens,
type ThemeColors,
+ type ThemeType,
+ // Live re-theming
+ ThemeStyle,
+ markThemed,
+ applyThemeToWorld,
+ switchTheme,
+ type ThemeStyleData,
+ type ColorRole,
+ // Reactive data binding
+ signal,
+ derived,
+ bind,
+ type Signal,
+ type ReadonlySignal,
} from './ui';
// ─── UI code-composition surface ─────────────────────────────────────────────
@@ -114,6 +130,13 @@ export {
AlignItems,
AlignContent,
type FlexContainerData,
+ // Anchor presets (authoring shortcuts over the box fields)
+ AnchorAxis,
+ ANCHOR_AXES,
+ anchorPresetFields,
+ detectAnchor,
+ type AnchorPreset,
+ type AnchorFields,
// Builders
buildUINode,
buildUIVisual,
@@ -129,6 +152,7 @@ export {
// Widget factories
createButton,
setButtonState,
+ themeButtonStates,
type ButtonOptions,
type ButtonStateVisual,
createToggle,
diff --git a/sdk/src/ui/behavior/theme-apply.ts b/sdk/src/ui/behavior/theme-apply.ts
new file mode 100644
index 000000000..a64405132
--- /dev/null
+++ b/sdk/src/ui/behavior/theme-apply.ts
@@ -0,0 +1,59 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ui/behavior/theme-apply.ts
+ * @brief Live re-theming: re-resolve every {@link ThemeStyle}-tagged entity's
+ * role bindings against the active theme.
+ *
+ * This is what makes {@link switchTheme} restyle already-constructed widgets, not
+ * just future ones — the piece a colors-baked-at-construction model otherwise
+ * can't express. Lives here (not in `theme/`) because it touches `StateVisuals`
+ * (this layer) plus `UIVisual`/`Text` (core); `theme/` is cross-cutting and may
+ * not import up into behaviors.
+ */
+import type { World } from '../../world';
+import { ThemeStyle, type ThemeStyleData } from '../theme/theme-style';
+import { setTheme, themeColors, type ThemeTokens } from '../theme/tokens';
+import { UIVisual, type UIVisualData } from '../core/ui-visual';
+import { Text, type TextData } from '../core/text';
+import { StateVisuals, type StateVisualsData } from './state-visuals';
+
+/**
+ * Re-resolve every {@link ThemeStyle} entity's role bindings and write the active
+ * theme's colors into its `UIVisual`/`Text`/`StateVisuals`. The existing **alpha
+ * is preserved** — only the hue re-themes — so a dimmed `disabled` state keeps its
+ * transparency, and a caller's translucency survives a swap.
+ */
+export function applyThemeToWorld(world: World): void {
+ const colors = themeColors();
+ for (const e of world.getEntitiesWithComponents([ThemeStyle])) {
+ const s = world.get(e, ThemeStyle) as ThemeStyleData;
+
+ if (s.visual && world.has(e, UIVisual)) {
+ const v = world.get(e, UIVisual) as UIVisualData;
+ const c = colors[s.visual];
+ world.insert(e, UIVisual, { ...v, color: { r: c.r, g: c.g, b: c.b, a: v.color.a } });
+ }
+ if (s.text && world.has(e, Text)) {
+ const t = world.get(e, Text) as TextData;
+ const c = colors[s.text];
+ world.insert(e, Text, { ...t, color: { r: c.r, g: c.g, b: c.b, a: t.color.a } });
+ }
+ if (s.states && world.has(e, StateVisuals)) {
+ const sv = world.get(e, StateVisuals) as StateVisualsData;
+ const states = sv.states.map((st) => {
+ const role = s.states![st.name];
+ if (!role) return st;
+ const c = colors[role];
+ return { ...st, r: c.r, g: c.g, b: c.b }; // keep st.a
+ });
+ world.insert(e, StateVisuals, { ...sv, states });
+ }
+ }
+}
+
+/** Set the active theme AND live-restyle every already-constructed themed widget. */
+export function switchTheme(world: World, tokens: ThemeTokens): void {
+ setTheme(tokens);
+ applyThemeToWorld(world);
+}
diff --git a/sdk/src/ui/binding/bind.ts b/sdk/src/ui/binding/bind.ts
new file mode 100644
index 000000000..b7b7cb3b1
--- /dev/null
+++ b/sdk/src/ui/binding/bind.ts
@@ -0,0 +1,52 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ui/binding/bind.ts
+ * @brief bind — drive a component field from a {@link ReadonlySignal}.
+ *
+ * The declarative replacement for the imperative "read the component, mutate the
+ * field, insert it back" every UI-from-state update used to be. The field is set
+ * immediately, then tracks the signal; the binding auto-disposes when the entity
+ * despawns (and returns a manual dispose).
+ */
+import type { World } from '../../world';
+import type { Entity } from '../../types';
+import type { ComponentDef } from '../../component';
+import type { ReadonlySignal } from './signal';
+
+/**
+ * Bind `source` to `entity`'s `component.field`: applied now and on every change.
+ * Writes are guarded (skipped if the entity is gone or lacks the component), and
+ * the binding tears itself down when the entity despawns. Returns a dispose to
+ * unbind early.
+ */
+export function bind<C extends object, K extends keyof C>(
+ world: World,
+ entity: Entity,
+ component: ComponentDef<C>,
+ field: K,
+ source: ReadonlySignal<C[K]>,
+): () => void {
+ let disposed = false;
+
+ const apply = (value: C[K]): void => {
+ if (disposed || !world.valid(entity) || !world.has(entity, component)) return;
+ const data = world.get(entity, component) as C;
+ world.insert(entity, component, { ...data, [field]: value });
+ };
+
+ apply(source.get()); // seed the field with the current value
+
+ const unsub = source.subscribe(apply);
+ const dispose = (): void => {
+ if (disposed) return;
+ disposed = true;
+ unsub();
+ offDespawn();
+ };
+ const offDespawn = world.onDespawn((e) => {
+ if (e === entity) dispose();
+ });
+
+ return dispose;
+}
diff --git a/sdk/src/ui/binding/signal.ts b/sdk/src/ui/binding/signal.ts
new file mode 100644
index 000000000..209fed80c
--- /dev/null
+++ b/sdk/src/ui/binding/signal.ts
@@ -0,0 +1,67 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ui/binding/signal.ts
+ * @brief Signal — a minimal reactive value, the source side of data binding.
+ *
+ * A signal holds a value and notifies subscribers when it changes; `bind` (see
+ * `bind.ts`) drives a component field from one, replacing the imperative
+ * get→mutate→insert loop that updating UI from game state used to require.
+ * Push-based (subscribers run on `set`), so there is no per-frame polling.
+ */
+
+/** A read-only reactive value. */
+export interface ReadonlySignal<T> {
+ get(): T;
+ /** Subscribe to changes; returns an unsubscribe. */
+ subscribe(fn: (value: T) => void): () => void;
+}
+
+/** A writable reactive value. */
+export interface Signal<T> extends ReadonlySignal<T> {
+ set(value: T): void;
+ update(fn: (prev: T) => T): void;
+}
+
+/** A reactive value seeded with `initial`. `set` notifies subscribers only when
+ * the value actually changes (`Object.is`), so an unchanged write is free. */
+export function signal<T>(initial: T): Signal<T> {
+ let value = initial;
+ const subs = new Set<(v: T) => void>();
+ const set = (next: T): void => {
+ if (Object.is(next, value)) return;
+ value = next;
+ for (const fn of [...subs]) fn(value); // snapshot: a subscriber may unsubscribe mid-notify
+ };
+ return {
+ get: () => value,
+ set,
+ update: (fn) => set(fn(value)),
+ subscribe: (fn) => {
+ subs.add(fn);
+ return () => subs.delete(fn);
+ },
+ };
+}
+
+/** A read-only signal computed from `sources`; recomputes (and notifies) whenever
+ * any source changes. Its subscriptions live for the process — use for
+ * app-lifetime derivations (e.g. `health / maxHealth`). */
+export function derived<T>(sources: ReadonlySignal<unknown>[], compute: () => T): ReadonlySignal<T> {
+ let value = compute();
+ const subs = new Set<(v: T) => void>();
+ const recompute = (): void => {
+ const next = compute();
+ if (Object.is(next, value)) return;
+ value = next;
+ for (const fn of [...subs]) fn(value);
+ };
+ for (const s of sources) s.subscribe(recompute);
+ return {
+ get: () => value,
+ subscribe: (fn) => {
+ subs.add(fn);
+ return () => subs.delete(fn);
+ },
+ };
+}
diff --git a/sdk/src/ui/index.ts b/sdk/src/ui/index.ts
index d8eedd021..581d6e8c5 100644
--- a/sdk/src/ui/index.ts
+++ b/sdk/src/ui/index.ts
@@ -94,6 +94,15 @@ export {
type FlexContainerData,
} from './layout/flex';
+export {
+ AnchorAxis,
+ ANCHOR_AXES,
+ anchorPresetFields,
+ detectAnchor,
+ type AnchorPreset,
+ type AnchorFields,
+} from './layout/anchor';
+
// ─── Layer 2: Behaviors ─────────────────────────────────────────────────────
export {
@@ -203,6 +212,7 @@ export {
export {
createButton,
setButtonState,
+ themeButtonStates,
type ButtonOptions,
type ButtonStateVisual,
} from './widgets/button';
@@ -315,13 +325,30 @@ export { UIRenderOrderPlugin, uiRenderOrderPlugin } from './render/render-order'
export {
DARK_TOKENS,
+ LIGHT_TOKENS,
getTheme,
setTheme,
themeColors,
+ themeType,
type ThemeTokens,
type ThemeColors,
+ type ThemeType,
} from './theme/tokens';
+export {
+ ThemeStyle,
+ markThemed,
+ type ThemeStyleData,
+ type ColorRole,
+} from './theme/theme-style';
+
+export { applyThemeToWorld, switchTheme } from './behavior/theme-apply';
+
+// ─── Binding (reactive data → component fields) ─────────────────────────────
+
+export { signal, derived, type Signal, type ReadonlySignal } from './binding/signal';
+export { bind } from './binding/bind';
+
// Property Path Utilities
export {
getNestedProperty,
diff --git a/sdk/src/ui/layout/anchor.ts b/sdk/src/ui/layout/anchor.ts
new file mode 100644
index 000000000..c67fbc385
--- /dev/null
+++ b/sdk/src/ui/layout/anchor.ts
@@ -0,0 +1,135 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ui/layout/anchor.ts
+ * @brief Anchor presets — authoring shortcuts over a UINode's CSS box fields.
+ *
+ * The box model is CSS (position + inset + margin), so an anchor is NOT stored
+ * state: a preset is a derived view that maps to/from the inset/margin/position
+ * fields. Keeping the box fields the single source of truth (rather than a
+ * redundant anchor enum, as RectTransform engines store) is what makes a preset
+ * and the live layout impossible to desync.
+ *
+ * Each axis resolves independently to one of {@link AnchorAxis}: Start pins the
+ * near edge, End the far edge, Stretch pins both edges with the size set to
+ * `auto` so the insets drive it, and Center leaves both insets AND both margins
+ * `auto` — the engine reads that combination as "centre this out-of-flow node in
+ * the parent box", the one anchor a pivot-less CSS box can't express through
+ * Yoga alone (Yoga's abspos centring keys off the parent's `justifyContent`, so
+ * it can't differ per sibling).
+ */
+import { auto, isAuto, px, type Dimension } from '../core/dimension';
+import { UIPositionType, type UINodeData } from '../core/ui-node';
+
+/** Per-axis anchor mode (a preset is one of these per axis). */
+export enum AnchorAxis {
+ /** Pin the near edge (left / top). */
+ Start = 0,
+ /** Centre via `auto` margins on both edges. */
+ Center = 1,
+ /** Pin the far edge (right / bottom). */
+ End = 2,
+ /** Pin both edges; the size becomes `auto` so the insets drive it. */
+ Stretch = 3,
+}
+
+/** A 2-D anchor: one {@link AnchorAxis} per axis. */
+export interface AnchorPreset {
+ h: AnchorAxis;
+ v: AnchorAxis;
+}
+
+/** The four axis modes in row/column order, for building a preset grid. */
+export const ANCHOR_AXES: readonly AnchorAxis[] = [
+ AnchorAxis.Start,
+ AnchorAxis.Center,
+ AnchorAxis.End,
+ AnchorAxis.Stretch,
+];
+
+/** The UINode box fields one axis of a preset writes. `size` is present only for
+ * Stretch — every other mode leaves the authored width/height untouched. */
+interface AxisFields {
+ near: Dimension;
+ far: Dimension;
+ marginNear: Dimension;
+ marginFar: Dimension;
+ size?: Dimension;
+}
+
+function axisFields(mode: AnchorAxis): AxisFields {
+ switch (mode) {
+ case AnchorAxis.Start:
+ return { near: px(0), far: auto(), marginNear: px(0), marginFar: px(0) };
+ case AnchorAxis.End:
+ return { near: auto(), far: px(0), marginNear: px(0), marginFar: px(0) };
+ case AnchorAxis.Center:
+ return { near: auto(), far: auto(), marginNear: auto(), marginFar: auto() };
+ case AnchorAxis.Stretch:
+ return { near: px(0), far: px(0), marginNear: px(0), marginFar: px(0), size: auto() };
+ }
+}
+
+/** The UINode fields a preset resolves to. Always sets `position` Absolute plus
+ * the two inset + two margin dimensions per axis; `width`/`height` appear only
+ * for a Stretch axis (so a non-stretch axis preserves the authored size). */
+export interface AnchorFields {
+ position: number;
+ insetLeft: Dimension;
+ insetRight: Dimension;
+ insetTop: Dimension;
+ insetBottom: Dimension;
+ marginLeft: Dimension;
+ marginRight: Dimension;
+ marginTop: Dimension;
+ marginBottom: Dimension;
+ width?: Dimension;
+ height?: Dimension;
+}
+
+/** Resolve a preset to the UINode box fields that express it. */
+export function anchorPresetFields(preset: AnchorPreset): AnchorFields {
+ const h = axisFields(preset.h);
+ const v = axisFields(preset.v);
+ const fields: AnchorFields = {
+ position: UIPositionType.Absolute,
+ insetLeft: h.near,
+ insetRight: h.far,
+ insetTop: v.near,
+ insetBottom: v.far,
+ marginLeft: h.marginNear,
+ marginRight: h.marginFar,
+ marginTop: v.marginNear,
+ marginBottom: v.marginFar,
+ };
+ if (h.size) fields.width = h.size;
+ if (v.size) fields.height = v.size;
+ return fields;
+}
+
+/** Classify one axis back to its {@link AnchorAxis}, or null when the field
+ * combination isn't a clean preset (a hand-tuned / over-constrained box). */
+function axisMode(near: Dimension, far: Dimension, mNear: Dimension, mFar: Dimension, size: Dimension): AnchorAxis | null {
+ const nearAuto = isAuto(near);
+ const farAuto = isAuto(far);
+ if (nearAuto && farAuto) {
+ return isAuto(mNear) && isAuto(mFar) ? AnchorAxis.Center : null;
+ }
+ if (!nearAuto && !farAuto) {
+ return isAuto(size) ? AnchorAxis.Stretch : null; // pinned both + definite size = over-constrained
+ }
+ if (!nearAuto && !isAuto(mNear)) return AnchorAxis.Start; // near pinned, far auto
+ if (!farAuto && !isAuto(mFar)) return AnchorAxis.End; // far pinned, near auto
+ return null;
+}
+
+/** The preset a UINode currently matches, or null (Relative flow, or a custom
+ * box that isn't a clean preset). `detectAnchor(node with anchorPresetFields(p))`
+ * round-trips back to `p`. */
+export function detectAnchor(node: UINodeData): AnchorPreset | null {
+ if (node.position !== UIPositionType.Absolute) return null;
+ const h = axisMode(node.insetLeft, node.insetRight, node.marginLeft, node.marginRight, node.width);
+ const v = axisMode(node.insetTop, node.insetBottom, node.marginTop, node.marginBottom, node.height);
+ if (h === null || v === null) return null;
+ return { h, v };
+}
diff --git a/sdk/src/ui/theme/theme-style.ts b/sdk/src/ui/theme/theme-style.ts
new file mode 100644
index 000000000..2c979d09a
--- /dev/null
+++ b/sdk/src/ui/theme/theme-style.ts
@@ -0,0 +1,40 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ui/theme/theme-style.ts
+ * @brief ThemeStyle — a runtime-only tag that records which semantic color
+ * {@link ThemeColors} role each of an entity's themeable properties uses.
+ *
+ * It is the missing link for live re-theming: widgets bake a theme's colors into
+ * `UIVisual`/`Text`/`StateVisuals` at construction, so without recording the
+ * *role* there is no way to re-resolve them when the theme changes. A widget tags
+ * the entities it themes (via {@link markThemed}); `applyThemeToWorld` re-resolves
+ * the tags against the active theme. Not serialized — it lives only on
+ * code-constructed widgets.
+ */
+import { defineComponent } from '../../component';
+import type { World } from '../../world';
+import type { Entity } from '../../types';
+import type { ThemeColors } from './tokens';
+
+/** A semantic color role (a key of {@link ThemeColors}). */
+export type ColorRole = keyof ThemeColors;
+
+export interface ThemeStyleData {
+ /** Role that drives this entity's `UIVisual.color`. */
+ visual?: ColorRole;
+ /** Role that drives this entity's `Text.color`. */
+ text?: ColorRole;
+ /** State-name → role, for each `StateVisuals` state color. */
+ states?: Record<string, ColorRole>;
+}
+
+// Runtime-only: a widget's theme-role tags are re-derived from code on every
+// construct, never persisted — so it stays out of scenes and prefabs.
+export const ThemeStyle = defineComponent<ThemeStyleData>('ThemeStyle', {}, { transient: true });
+
+/** Tag `entity` so the active theme's colors re-resolve onto it (see
+ * `applyThemeToWorld`). */
+export function markThemed(world: World, entity: Entity, style: ThemeStyleData): void {
+ world.insert(entity, ThemeStyle, style);
+}
diff --git a/sdk/src/ui/theme/tokens.ts b/sdk/src/ui/theme/tokens.ts
index d9323e358..38020e181 100644
--- a/sdk/src/ui/theme/tokens.ts
+++ b/sdk/src/ui/theme/tokens.ts
@@ -2,14 +2,14 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file ui/theme/tokens.ts
- * @brief ThemeTokens — semantic design tokens for the widget layer,
- * replacing the deleted per-widget UITheme god-object.
+ * @brief ThemeTokens — semantic design tokens for the widget layer.
*
- * Widgets read their default colors from the active theme via {@link getTheme}
- * instead of hard-coding RGBA ("去裸色"): one place defines the palette, and an
- * app can re-theme every widget by calling {@link setTheme} before constructing
- * them. Semantic names (surface/control/primary/…) decouple widgets from literal
- * colors. `DARK_TOKENS` is the built-in default.
+ * Widgets read their defaults from the active theme via {@link getTheme} instead
+ * of hard-coding values ("去裸色"): one place defines the palette + type scale, and
+ * an app re-themes every widget it constructs afterwards by calling {@link setTheme}
+ * first. Semantic roles (surface/control/primary/text/…) decouple widgets from
+ * literal values, so the same widget code renders correctly under {@link DARK_TOKENS}
+ * or {@link LIGHT_TOKENS}. `DARK_TOKENS` is the built-in default.
*/
import type { Color } from '../../types';
@@ -29,16 +29,32 @@ export interface ThemeColors {
primary: Color;
primaryHover: Color;
primaryActive: Color;
- /** Content/handle drawn on top of primary or controls. */
+ /** Content/handle drawn on top of `primary`. */
onPrimary: Color;
+ /** Default foreground (label text / icon) drawn on `surface`/`control`. */
+ text: Color;
/** Modal scrim. */
backdrop: Color;
}
+/** Typographic scale (font sizes in px) consumed by widget text. */
+export interface ThemeType {
+ /** Control / label text (buttons, options). */
+ label: number;
+ /** Body / default text. */
+ body: number;
+ /** Headings (dialog titles). */
+ title: number;
+}
+
export interface ThemeTokens {
colors: ThemeColors;
+ type: ThemeType;
}
+/** Shared type scale (the same across light/dark). */
+const TYPE_SCALE: ThemeType = { label: 14, body: 15, title: 20 };
+
/** Built-in dark palette (mirrors the values the widgets used to hard-code). */
export const DARK_TOKENS: ThemeTokens = {
colors: {
@@ -52,8 +68,29 @@ export const DARK_TOKENS: ThemeTokens = {
primaryHover: { r: 0.30, g: 0.50, b: 0.90, a: 1 },
primaryActive: { r: 0.20, g: 0.40, b: 0.75, a: 1 },
onPrimary: { r: 1, g: 1, b: 1, a: 1 },
+ text: { r: 0.92, g: 0.92, b: 0.94, a: 1 },
backdrop: { r: 0, g: 0, b: 0, a: 0.5 },
},
+ type: TYPE_SCALE,
+};
+
+/** Built-in light palette — the same roles on light surfaces with dark text. */
+export const LIGHT_TOKENS: ThemeTokens = {
+ colors: {
+ surface: { r: 0.96, g: 0.96, b: 0.97, a: 1 },
+ surfaceElevated:{ r: 1, g: 1, b: 1, a: 1 },
+ control: { r: 0.90, g: 0.90, b: 0.92, a: 1 },
+ controlHover: { r: 0.84, g: 0.84, b: 0.87, a: 1 },
+ controlActive: { r: 0.78, g: 0.78, b: 0.82, a: 1 },
+ track: { r: 0.86, g: 0.86, b: 0.88, a: 1 },
+ primary: { r: 0.20, g: 0.52, b: 0.92, a: 1 },
+ primaryHover: { r: 0.26, g: 0.58, b: 0.96, a: 1 },
+ primaryActive: { r: 0.16, g: 0.42, b: 0.80, a: 1 },
+ onPrimary: { r: 1, g: 1, b: 1, a: 1 },
+ text: { r: 0.12, g: 0.12, b: 0.14, a: 1 },
+ backdrop: { r: 0, g: 0, b: 0, a: 0.35 },
+ },
+ type: TYPE_SCALE,
};
let activeTheme: ThemeTokens = DARK_TOKENS;
@@ -72,3 +109,8 @@ export function setTheme(tokens: ThemeTokens): void {
export function themeColors(): ThemeColors {
return activeTheme.colors;
}
+
+/** Convenience: the active type scale. */
+export function themeType(): ThemeType {
+ return activeTheme.type;
+}
diff --git a/sdk/src/ui/widgets/button.ts b/sdk/src/ui/widgets/button.ts
index 244818e02..6e0bf4802 100644
--- a/sdk/src/ui/widgets/button.ts
+++ b/sdk/src/ui/widgets/button.ts
@@ -13,6 +13,8 @@ import {
type StateVisualsData,
} from '../behavior/state-visuals';
import { UIEventType, type UIEventQueue } from '../core/events';
+import { themeColors, themeType } from '../theme/tokens';
+import { markThemed } from '../theme/theme-style';
import {
spawnUIEntity,
@@ -45,9 +47,10 @@ export interface ButtonOptions {
* Map of state name (e.g. "normal", "hover", "pressed", "disabled")
* to its visual override. The Interactable driver writes the four
* canonical state names; callers may add more (e.g. "loading") and
- * flip them manually via `setState`.
+ * flip them manually via `setState`. Omit to default to the active
+ * theme's control roles ({@link themeButtonStates}).
*/
- states: Record<string, ButtonStateVisual>;
+ states?: Record<string, ButtonStateVisual>;
/** Combination of TransitionFlag values. Default: ColorTint. */
transitionFlags?: number;
/** Lerp time for ColorTint/Scale transitions. Default 0 (snap). */
@@ -64,6 +67,19 @@ function buildStates(states: Record<string, ButtonStateVisual>): VisualState[] {
{ sprite: v.sprite, scale: v.scale }));
}
+/** The canonical button state colors from the active theme's control roles —
+ * `createButton`'s default when the caller passes no `states`. `disabled` reuses
+ * the resting control fill at reduced alpha. */
+export function themeButtonStates(): Record<string, ButtonStateVisual> {
+ const c = themeColors();
+ return {
+ normal: { color: c.control },
+ hover: { color: c.controlHover },
+ pressed: { color: c.controlActive },
+ disabled: { color: { ...c.control, a: c.control.a * 0.5 } },
+ };
+}
+
/**
* Spawn a clickable button entity composed of Interactable +
* StateMachine + StateVisuals, optionally with a child Text label.
@@ -98,18 +114,28 @@ export function createButton(opts: ButtonOptions): Entity {
targetGraphic: 0 as Entity,
transitionFlags: opts.transitionFlags ?? TransitionFlag.ColorTint,
fadeDuration: opts.fadeDuration ?? 0,
- states: buildStates(opts.states),
+ states: buildStates(opts.states ?? themeButtonStates()),
};
world.insert(entity, StateVisuals, visuals);
+ // Only theme-managed default states re-resolve on a theme swap; caller-supplied
+ // colors are the caller's own.
+ if (opts.states === undefined) {
+ markThemed(world, entity, {
+ states: { normal: 'control', hover: 'controlHover', pressed: 'controlActive', disabled: 'control' },
+ });
+ }
if (opts.text !== undefined) {
- const textInit = typeof opts.text === 'string' ? { content: opts.text } : opts.text;
- spawnUIEntity({
+ const userText = typeof opts.text === 'string' ? { content: opts.text } : opts.text;
+ // Theme-default the label's color + size; the caller's fields win.
+ const textInit = { color: themeColors().text, fontSize: themeType().label, ...userText };
+ const label = spawnUIEntity({
world,
parent: entity,
node: { fill: true },
text: textInit,
});
+ if (userText.color === undefined) markThemed(world, label, { text: 'text' });
}
if (opts.onClick) {
diff --git a/sdk/src/ui/widgets/dialog.ts b/sdk/src/ui/widgets/dialog.ts
index 4ad02227f..d6772f730 100644
--- a/sdk/src/ui/widgets/dialog.ts
+++ b/sdk/src/ui/widgets/dialog.ts
@@ -8,6 +8,7 @@ import { Interactable, UIInteraction } from '../input/interactable';
import { spawnUIEntity, setUIVisible, type UINodeInit, type UIVisualInit } from './helpers';
import { px, percent } from '../core/dimension';
import { themeColors } from '../theme/tokens';
+import { markThemed } from '../theme/theme-style';
export interface DialogOptions {
world: World;
@@ -49,6 +50,7 @@ export function createDialog(opts: DialogOptions): DialogHandle {
node: opts.backdropNode ?? { fill: true },
visual: opts.backdropVisual ?? { color: c.backdrop },
});
+ if (!opts.backdropVisual) markThemed(world, backdrop, { visual: 'backdrop' });
// Blocks hit-test on the scene behind the dialog.
world.insert(backdrop, Interactable, {
@@ -75,6 +77,7 @@ export function createDialog(opts: DialogOptions): DialogHandle {
},
visual: opts.panelVisual ?? { color: c.surface },
});
+ if (!opts.panelVisual) markThemed(world, panel, { visual: 'surface' });
let open = !(opts.startHidden ?? true);
applyOpen(open);
diff --git a/sdk/src/ui/widgets/dropdown.ts b/sdk/src/ui/widgets/dropdown.ts
index 25f7b5009..e81016dcc 100644
--- a/sdk/src/ui/widgets/dropdown.ts
+++ b/sdk/src/ui/widgets/dropdown.ts
@@ -12,6 +12,7 @@ import { Text, type TextData } from '../core/text';
import { spawnUIEntity, type UINodeInit, type UIVisualInit } from './helpers';
import { px, percent } from '../core/dimension';
import { themeColors } from '../theme/tokens';
+import { markThemed } from '../theme/theme-style';
export interface DropdownOptions<T> {
world: World;
@@ -110,13 +111,17 @@ export function createDropdown<T>(opts: DropdownOptions<T>): DropdownHandle<T> {
world.insert(button, UIInteraction, INTERACTION_DEFAULT);
world.insert(button, StateMachine, { current: 'normal', previous: '' });
world.insert(button, StateVisuals, makeStatesSV(btnColors));
+ if (opts.buttonStates === undefined) {
+ markThemed(world, button, { states: { normal: 'control', hover: 'controlHover', pressed: 'controlActive' } });
+ }
const label = spawnUIEntity({
world,
parent: button,
node: { fill: true },
- text: { content: labelOf(opts.options[selectedIndex]!, selectedIndex) },
+ text: { content: labelOf(opts.options[selectedIndex]!, selectedIndex), color: themeColors().text },
});
+ markThemed(world, label, { text: 'text' });
let popupPanel: Entity | null = null;
const optionUnsubs: Array<() => void> = [];
diff --git a/sdk/src/ui/widgets/prefabs/Dropdown.esprefab b/sdk/src/ui/widgets/prefabs/Dropdown.esprefab
index 40f2e7b7b..a4b8607a8 100644
--- a/sdk/src/ui/widgets/prefabs/Dropdown.esprefab
+++ b/sdk/src/ui/widgets/prefabs/Dropdown.esprefab
@@ -336,9 +336,9 @@
"fontFamily": "Arial",
"fontSize": 14,
"color": {
- "r": 1,
- "g": 1,
- "b": 1,
+ "r": 0.92,
+ "g": 0.92,
+ "b": 0.94,
"a": 1
},
"align": 1,
diff --git a/sdk/src/ui/widgets/prefabs/generated.ts b/sdk/src/ui/widgets/prefabs/generated.ts
index 828a9076b..fdb11d418 100644
--- a/sdk/src/ui/widgets/prefabs/generated.ts
+++ b/sdk/src/ui/widgets/prefabs/generated.ts
@@ -1862,9 +1862,9 @@ export const BUILTIN_UI_PREFABS: Record<string, PrefabData> = {
"fontFamily": "Arial",
"fontSize": 14,
"color": {
- "r": 1,
- "g": 1,
- "b": 1,
+ "r": 0.92,
+ "g": 0.92,
+ "b": 0.94,
"a": 1
},
"align": 1,
diff --git a/sdk/src/ui/widgets/progress.ts b/sdk/src/ui/widgets/progress.ts
index 94ab1c6ff..cd75421a8 100644
--- a/sdk/src/ui/widgets/progress.ts
+++ b/sdk/src/ui/widgets/progress.ts
@@ -19,6 +19,7 @@ import {
type LinearFillDirection,
} from './helpers';
import { themeColors } from '../theme/tokens';
+import { markThemed } from '../theme/theme-style';
export interface ProgressOptions {
world: World;
@@ -66,6 +67,7 @@ export function createProgress(opts: ProgressOptions): ProgressHandle {
node: opts.node ?? { fill: true },
visual: opts.background ?? { color: c.track },
});
+ if (!opts.background) markThemed(world, track, { visual: 'track' });
const fill = spawnUIEntity({
world,
@@ -80,6 +82,7 @@ export function createProgress(opts: ProgressOptions): ProgressHandle {
fillAmount: value,
},
});
+ if (opts.fill?.color === undefined) markThemed(world, fill, { visual: 'primary' });
function setValue(v: number): void {
const next = clamp01(v);
diff --git a/sdk/src/ui/widgets/slider.ts b/sdk/src/ui/widgets/slider.ts
index 93a3306e0..cb5853e4f 100644
--- a/sdk/src/ui/widgets/slider.ts
+++ b/sdk/src/ui/widgets/slider.ts
@@ -9,6 +9,7 @@ import { UIVisual, UIVisualType, type UIVisualData } from '../core/ui-visual';
import { spawnUIEntity, FILL_AXIS, type UINodeInit, type UIVisualInit } from './helpers';
import { themeColors } from '../theme/tokens';
+import { markThemed } from '../theme/theme-style';
export interface SliderOptions {
world: World;
@@ -72,6 +73,7 @@ export function createSlider(opts: SliderOptions): SliderHandle {
node: opts.node ?? { fill: true },
visual: opts.trackVisual ?? { color: c.track },
});
+ if (!opts.trackVisual) markThemed(opts.world, track, { visual: 'track' });
const fill = spawnUIEntity({
world: opts.world,
@@ -85,6 +87,7 @@ export function createSlider(opts: SliderOptions): SliderHandle {
...(opts.fillVisual ?? { color: c.primary }),
},
});
+ if (!opts.fillVisual) markThemed(opts.world, fill, { visual: 'primary' });
const handle = spawnUIEntity({
world: opts.world,
@@ -92,6 +95,7 @@ export function createSlider(opts: SliderOptions): SliderHandle {
node: handleNodeAt(fraction(value, min, max), handleWidth),
visual: opts.handleVisual ?? { color: c.onPrimary },
});
+ if (!opts.handleVisual) markThemed(opts.world, handle, { visual: 'onPrimary' });
// Value -> visuals: the fill's Filled amount is the value fraction (a
// render-time crop, no relayout); the handle's left inset tracks it,
diff --git a/sdk/src/ui/widgets/toPrefab.ts b/sdk/src/ui/widgets/toPrefab.ts
index 638f5d03d..f23207d7a 100644
--- a/sdk/src/ui/widgets/toPrefab.ts
+++ b/sdk/src/ui/widgets/toPrefab.ts
@@ -34,9 +34,10 @@ class RecordingWorld {
return id;
}
- insert(entity: number, comp: { _name: string }, data: unknown): void {
+ insert(entity: number, comp: { _name: string; transient?: boolean }, data: unknown): void {
const ent = this.entities.get(entity);
if (!ent) return;
+ if (comp.transient) return; // runtime-only state never persists into a prefab
const clone = JSON.parse(JSON.stringify(data)) as unknown;
const existing = ent.components.find((c) => c.type === comp._name);
if (existing) existing.data = clone as ComponentData['data'];
diff --git a/sdk/tests/ui-anchor-preset.test.ts b/sdk/tests/ui-anchor-preset.test.ts
new file mode 100644
index 000000000..9a3b9b544
--- /dev/null
+++ b/sdk/tests/ui-anchor-preset.test.ts
@@ -0,0 +1,204 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ui-anchor-preset.test.ts
+ * @brief Anchor presets map to/from UINode box fields, and lay out through the
+ * real Yoga solver as pinned / centred / stretched.
+ *
+ * The integration half needs pre-built WASM at desktop/public/wasm/esengine.wasm
+ * (`node build-tools/cli.js build -t web`); the pure half always runs.
+ */
+import { describe, it, expect, beforeAll } from 'vitest';
+import {
+ AnchorAxis,
+ ANCHOR_AXES,
+ anchorPresetFields,
+ detectAnchor,
+ type AnchorPreset,
+} from '../src/ui/layout/anchor';
+import { UIPositionType, UINode, type UINodeData } from '../src/ui/core/ui-node';
+import { DimensionUnit, px, auto } from '../src/ui/core/dimension';
+import { App } from '../src/app';
+import { Canvas, Transform, Sprite } from '../src/component';
+import { UICameraInfo } from '../src/ui/core/ui-camera-info';
+import { uiLayoutPlugin } from '../src/ui/layout/layout';
+import type { ESEngineModule, CppRegistry } from '../src/wasm';
+import { loadWasmModule, HAS_WASM } from './helpers/loadWasm';
+
+function baseNode(over: Partial<UINodeData> = {}): UINodeData {
+ return {
+ position: 0,
+ width: auto(), height: auto(),
+ minWidth: auto(), minHeight: auto(),
+ maxWidth: auto(), maxHeight: auto(),
+ flexGrow: 0, flexShrink: 1, flexBasis: auto(),
+ alignSelf: 0,
+ marginLeft: px(0), marginTop: px(0), marginRight: px(0), marginBottom: px(0),
+ insetLeft: auto(), insetTop: auto(), insetRight: auto(), insetBottom: auto(),
+ ...over,
+ };
+}
+
+/** Overlay a preset onto a base node the way an author/editor would. */
+function applyPreset(base: UINodeData, preset: AnchorPreset): UINodeData {
+ return { ...base, ...anchorPresetFields(preset) };
+}
+
+describe('anchor presets (pure)', () => {
+ it('always resolves to an Absolute box', () => {
+ for (const h of ANCHOR_AXES) {
+ for (const v of ANCHOR_AXES) {
+ expect(anchorPresetFields({ h, v }).position).toBe(UIPositionType.Absolute);
+ }
+ }
+ });
+
+ it('Center leaves both insets and both margins auto; the size is untouched', () => {
+ const f = anchorPresetFields({ h: AnchorAxis.Center, v: AnchorAxis.Center });
+ for (const d of [f.insetLeft, f.insetRight, f.insetTop, f.insetBottom,
+ f.marginLeft, f.marginRight, f.marginTop, f.marginBottom]) {
+ expect(d.unit).toBe(DimensionUnit.Auto);
+ }
+ expect(f.width).toBeUndefined();
+ expect(f.height).toBeUndefined();
+ });
+
+ it('Stretch pins both edges and drives the size via auto', () => {
+ const f = anchorPresetFields({ h: AnchorAxis.Stretch, v: AnchorAxis.Stretch });
+ expect(f.insetLeft.unit).toBe(DimensionUnit.Px);
+ expect(f.insetRight.unit).toBe(DimensionUnit.Px);
+ expect(f.width?.unit).toBe(DimensionUnit.Auto);
+ expect(f.height?.unit).toBe(DimensionUnit.Auto);
+ });
+
+ it('detect ∘ apply round-trips for all 16 presets (from an auto-sized base)', () => {
+ for (const h of ANCHOR_AXES) {
+ for (const v of ANCHOR_AXES) {
+ const preset = { h, v };
+ expect(detectAnchor(applyPreset(baseNode(), preset))).toEqual(preset);
+ }
+ }
+ });
+
+ it('detect ∘ apply round-trips from a fixed-size base too', () => {
+ const sized = baseNode({ width: px(120), height: px(48) });
+ for (const h of ANCHOR_AXES) {
+ for (const v of ANCHOR_AXES) {
+ const preset = { h, v };
+ expect(detectAnchor(applyPreset(sized, preset))).toEqual(preset);
+ }
+ }
+ });
+
+ it('returns null for a Relative (flow) node and for a hand-tuned custom box', () => {
+ expect(detectAnchor(baseNode())).toBeNull(); // default = Relative
+ // Absolute, both edges pinned, definite size, fixed margins → over-constrained.
+ expect(detectAnchor(baseNode({
+ position: UIPositionType.Absolute,
+ insetLeft: px(0), insetRight: px(0), width: px(100),
+ insetTop: px(0), insetBottom: auto(),
+ }))).toBeNull();
+ });
+});
+
+describe.skipIf(!HAS_WASM)('anchor presets lay out via Yoga (WASM integration)', () => {
+ let module: ESEngineModule;
+ beforeAll(async () => { module = await loadWasmModule(); });
+
+ function createApp(): { app: App; registry: CppRegistry } {
+ const app = App.new();
+ const registry = new module.Registry() as unknown as CppRegistry;
+ app.connectCpp(registry, module);
+ app.insertResource(UICameraInfo, {
+ viewProjection: new Float32Array(16),
+ vpX: 0, vpY: 0, vpW: 0, vpH: 0, screenW: 0, screenH: 0,
+ worldLeft: -400, worldBottom: -300, worldRight: 400, worldTop: 300,
+ worldMouseX: 0, worldMouseY: 0, valid: true,
+ });
+ app.addPlugin(uiLayoutPlugin);
+ return { app, registry };
+ }
+
+ function dispose(app: App, registry: CppRegistry): void {
+ for (const e of app.world.getAllEntities()) { try { app.world.despawn(e); } catch (_) {} }
+ app.world.disconnectCpp();
+ (registry as unknown as { delete(): void }).delete();
+ }
+
+ const W = (r: CppRegistry, e: number) => module.getUINodeComputedWidth!(r, e);
+ const H = (r: CppRegistry, e: number) => module.getUINodeComputedHeight!(r, e);
+
+ /** Spawn an 800×600 canvas root with one preset-anchored 100×80 child; return
+ * the child's computed size + laid-out local position (canvas sits at origin,
+ * so local == world). */
+ async function layoutChild(preset: AnchorPreset) {
+ const { app, registry } = createApp();
+ const world = app.world;
+
+ const root = world.spawn();
+ world.insert(root, Canvas, {});
+ world.insert(root, UINode, baseNode({
+ position: UIPositionType.Absolute,
+ insetLeft: px(0), insetTop: px(0), insetRight: px(0), insetBottom: px(0),
+ }));
+ world.insert(root, Transform, {
+ position: { x: 0, y: 0, z: 0 },
+ rotation: { x: 0, y: 0, z: 0, w: 1 },
+ scale: { x: 1, y: 1, z: 1 },
+ });
+
+ const child = world.spawn();
+ world.setParent(child, root);
+ world.insert(child, UINode, applyPreset(baseNode({ width: px(100), height: px(80) }), preset));
+ world.insert(child, Transform, {
+ position: { x: 0, y: 0, z: 0 },
+ rotation: { x: 0, y: 0, z: 0, w: 1 },
+ scale: { x: 1, y: 1, z: 1 },
+ });
+ world.insert(child, Sprite, {
+ texture: 0, color: { r: 1, g: 1, b: 1, a: 1 }, size: { x: 100, y: 80 },
+ uvOffset: { x: 0, y: 0 }, uvScale: { x: 1, y: 1 }, layer: 0, flipX: false, flipY: false,
+ });
+
+ await app.tick(1 / 60);
+ const w = W(registry, child), h = H(registry, child);
+ const p = registry.getTransform(child).position;
+ dispose(app, registry);
+ return { w, h, x: p.x, y: p.y };
+ }
+
+ it('Center/Center sits at the canvas centre, keeping its fixed size', async () => {
+ const r = await layoutChild({ h: AnchorAxis.Center, v: AnchorAxis.Center });
+ expect(r.w).toBeCloseTo(100, 0);
+ expect(r.h).toBeCloseTo(80, 0);
+ expect(r.x).toBeCloseTo(0, 0);
+ expect(r.y).toBeCloseTo(0, 0);
+ });
+
+ it('Start/Start pins the top-left corner', async () => {
+ const r = await layoutChild({ h: AnchorAxis.Start, v: AnchorAxis.Start });
+ expect(r.w).toBeCloseTo(100, 0);
+ expect(r.x).toBeLessThan(-100); // toward the left edge
+ expect(r.y).toBeGreaterThan(100); // toward the top edge (world y-up)
+ });
+
+ it('End/End pins the bottom-right corner', async () => {
+ const r = await layoutChild({ h: AnchorAxis.End, v: AnchorAxis.End });
+ expect(r.x).toBeGreaterThan(100);
+ expect(r.y).toBeLessThan(-100);
+ });
+
+ it('Center-horizontal + Start-vertical centres X and pins the top', async () => {
+ const r = await layoutChild({ h: AnchorAxis.Center, v: AnchorAxis.Start });
+ expect(r.x).toBeCloseTo(0, 0);
+ expect(r.y).toBeGreaterThan(100);
+ });
+
+ it('Stretch/Stretch fills the canvas', async () => {
+ const r = await layoutChild({ h: AnchorAxis.Stretch, v: AnchorAxis.Stretch });
+ expect(r.w).toBeCloseTo(800, 0);
+ expect(r.h).toBeCloseTo(600, 0);
+ expect(r.x).toBeCloseTo(0, 0);
+ expect(r.y).toBeCloseTo(0, 0);
+ });
+});
diff --git a/sdk/tests/ui-binding.test.ts b/sdk/tests/ui-binding.test.ts
new file mode 100644
index 000000000..44fac2ea7
--- /dev/null
+++ b/sdk/tests/ui-binding.test.ts
@@ -0,0 +1,117 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Reactive data binding: signals notify, derived recomputes, and bind
+ * drives a component field from a signal (seed, track, auto-dispose).
+ */
+import { describe, it, expect } from 'vitest';
+import { signal, derived, bind, Text } from '../src/ui';
+import type { Entity } from '../src/types';
+import type { World } from '../src/world';
+
+function mockWorld() {
+ const comps = new Map<number, Map<object, unknown>>();
+ const despawnCbs: Array<(e: number) => void> = [];
+ let next = 1;
+ const w = {
+ spawn(): Entity { const e = next++; comps.set(e, new Map()); return e as Entity; },
+ despawn(e: Entity) { comps.delete(e as number); [...despawnCbs].forEach((cb) => cb(e as number)); },
+ valid(e: Entity) { return comps.has(e as number); },
+ has(e: Entity, c: object) { return comps.get(e as number)?.has(c) ?? false; },
+ get(e: Entity, c: object) { return comps.get(e as number)?.get(c); },
+ insert(e: Entity, c: object, d: unknown) { comps.get(e as number)?.set(c, d); },
+ onDespawn(cb: (e: number) => void) {
+ despawnCbs.push(cb);
+ return () => { const i = despawnCbs.indexOf(cb); if (i >= 0) despawnCbs.splice(i, 1); };
+ },
+ };
+ return w as unknown as World;
+}
+
+describe('signal', () => {
+ it('holds a value and notifies subscribers on change', () => {
+ const s = signal(1);
+ const seen: number[] = [];
+ s.subscribe((v) => seen.push(v));
+ expect(s.get()).toBe(1);
+ s.set(2);
+ s.update((p) => p + 10);
+ expect(s.get()).toBe(12);
+ expect(seen).toEqual([2, 12]);
+ });
+
+ it('an unchanged set is a no-op (no notification)', () => {
+ const s = signal('a');
+ let count = 0;
+ s.subscribe(() => count++);
+ s.set('a');
+ expect(count).toBe(0);
+ });
+
+ it('unsubscribe stops delivery', () => {
+ const s = signal(0);
+ let count = 0;
+ const off = s.subscribe(() => count++);
+ s.set(1);
+ off();
+ s.set(2);
+ expect(count).toBe(1);
+ });
+});
+
+describe('derived', () => {
+ it('recomputes from its sources', () => {
+ const hp = signal(50);
+ const max = signal(100);
+ const pct = derived([hp, max], () => hp.get() / max.get());
+ expect(pct.get()).toBe(0.5);
+ const seen: number[] = [];
+ pct.subscribe((v) => seen.push(v));
+ hp.set(75);
+ max.set(150);
+ expect(pct.get()).toBe(0.5);
+ expect(seen).toEqual([0.75, 0.5]);
+ });
+});
+
+describe('bind', () => {
+ it('seeds the field immediately and tracks the signal', () => {
+ const w = mockWorld();
+ const e = w.spawn();
+ w.insert(e, Text, { content: 'x' });
+ const label = signal('hello');
+ bind(w, e, Text, 'content', label);
+ expect((w.get(e, Text) as { content: string }).content).toBe('hello'); // seeded
+ label.set('world');
+ expect((w.get(e, Text) as { content: string }).content).toBe('world'); // tracks
+ });
+
+ it('dispose() stops further updates', () => {
+ const w = mockWorld();
+ const e = w.spawn();
+ w.insert(e, Text, { content: '' });
+ const label = signal('a');
+ const dispose = bind(w, e, Text, 'content', label);
+ dispose();
+ label.set('b');
+ expect((w.get(e, Text) as { content: string }).content).toBe('a');
+ });
+
+ it('auto-disposes when the entity despawns (no write, no throw)', () => {
+ const w = mockWorld();
+ const e = w.spawn();
+ w.insert(e, Text, { content: '' });
+ const label = signal('a');
+ bind(w, e, Text, 'content', label);
+ (w as unknown as { despawn(e: Entity): void }).despawn(e);
+ expect(() => label.set('b')).not.toThrow();
+ });
+
+ it('skips the write when the entity lacks the component', () => {
+ const w = mockWorld();
+ const e = w.spawn(); // no Text inserted
+ const label = signal('a');
+ expect(() => bind(w, e, Text, 'content', label)).not.toThrow();
+ expect(w.has(e, Text)).toBe(false); // never created it
+ });
+});
diff --git a/sdk/tests/ui-theme-swap.test.ts b/sdk/tests/ui-theme-swap.test.ts
new file mode 100644
index 000000000..2ae3fe204
--- /dev/null
+++ b/sdk/tests/ui-theme-swap.test.ts
@@ -0,0 +1,109 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Live re-theming: switchTheme re-resolves every ThemeStyle-tagged entity's
+ * role bindings onto its UIVisual / Text / StateVisuals, so already-built
+ * widgets restyle — not just future ones.
+ */
+import { describe, it, expect, afterEach } from 'vitest';
+import {
+ createButton,
+ switchTheme,
+ applyThemeToWorld,
+ markThemed,
+ ThemeStyle,
+ UIVisual,
+ UIVisualType,
+ Text,
+ StateVisuals,
+ DARK_TOKENS,
+ LIGHT_TOKENS,
+ setTheme,
+ themeColors,
+} from '../src/ui';
+import type { Entity } from '../src/types';
+import type { World } from '../src/world';
+
+// A generic mock world: stores any component def per entity + supports the
+// getEntitiesWithComponents query applyThemeToWorld needs.
+function mockWorld() {
+ const comps = new Map<number, Map<object, unknown>>();
+ let next = 1;
+ const w = {
+ spawn(): Entity { const e = next++; comps.set(e, new Map()); return e as Entity; },
+ valid(e: Entity) { return comps.has(e as number); },
+ setParent() {},
+ onDespawn() { return () => {}; },
+ has(e: Entity, c: object) { return comps.get(e as number)?.has(c) ?? false; },
+ get(e: Entity, c: object) { return comps.get(e as number)?.get(c); },
+ insert(e: Entity, c: object, data: unknown) { comps.get(e as number)?.set(c, data); },
+ getEntitiesWithComponents(cs: object[]): Entity[] {
+ const out: Entity[] = [];
+ for (const [e, m] of comps) if (cs.every((c) => m.has(c))) out.push(e as Entity);
+ return out;
+ },
+ };
+ return w as unknown as World;
+}
+
+const noEvents = { on: () => {} } as never;
+
+describe('live re-theming', () => {
+ afterEach(() => setTheme(DARK_TOKENS));
+
+ it('applyThemeToWorld recolors a UIVisual role, preserving alpha', () => {
+ const w = mockWorld();
+ const e = w.spawn();
+ w.insert(e, UIVisual, { visualType: UIVisualType.SolidColor, color: { r: 1, g: 1, b: 1, a: 0.3 } });
+ markThemed(w, e, { visual: 'primary' });
+
+ setTheme(LIGHT_TOKENS);
+ applyThemeToWorld(w);
+ const v = w.get(e, UIVisual) as { color: { r: number; g: number; b: number; a: number } };
+ expect(v.color).toMatchObject({ ...LIGHT_TOKENS.colors.primary, a: 0.3 }); // hue swaps, alpha kept
+ });
+
+ it('applyThemeToWorld recolors a Text role', () => {
+ const w = mockWorld();
+ const e = w.spawn();
+ w.insert(e, Text, { content: 'x', color: { r: 1, g: 1, b: 1, a: 1 } });
+ markThemed(w, e, { text: 'text' });
+
+ setTheme(LIGHT_TOKENS);
+ applyThemeToWorld(w);
+ const t = w.get(e, Text) as { color: { r: number } };
+ expect(t.color.r).toBeCloseTo(LIGHT_TOKENS.colors.text.r);
+ });
+
+ it('switchTheme restyles an already-built button (states + label)', () => {
+ const w = mockWorld();
+ const btn = createButton({ world: w, events: noEvents, text: 'OK' });
+ // Built under the default dark theme.
+ const svBefore = w.get(btn, StateVisuals) as { states: Array<{ name: string; r: number }> };
+ expect(svBefore.states.find((s) => s.name === 'normal')!.r).toBeCloseTo(DARK_TOKENS.colors.control.r);
+
+ switchTheme(w, LIGHT_TOKENS);
+
+ const sv = w.get(btn, StateVisuals) as { states: Array<{ name: string; r: number; g: number; b: number; a: number }> };
+ const normal = sv.states.find((s) => s.name === 'normal')!;
+ expect(normal).toMatchObject(LIGHT_TOKENS.colors.control);
+ const hover = sv.states.find((s) => s.name === 'hover')!;
+ expect(hover).toMatchObject(LIGHT_TOKENS.colors.controlHover);
+ // The dimmed 'disabled' state keeps its half alpha; only the hue re-themes.
+ const disabled = sv.states.find((s) => s.name === 'disabled')!;
+ expect(disabled.a).toBeCloseTo(DARK_TOKENS.colors.control.a * 0.5);
+ expect(disabled.r).toBeCloseTo(LIGHT_TOKENS.colors.control.r);
+ });
+
+ it('does not clobber a button whose states the caller supplied', () => {
+ const w = mockWorld();
+ const btn = createButton({
+ world: w, events: noEvents,
+ states: { normal: { color: { r: 0.5, g: 0.1, b: 0.9, a: 1 } } },
+ });
+ expect(w.has(btn, ThemeStyle)).toBe(false); // untagged → not theme-managed
+ switchTheme(w, LIGHT_TOKENS);
+ const sv = w.get(btn, StateVisuals) as { states: Array<{ r: number; g: number; b: number }> };
+ expect(sv.states[0]).toMatchObject({ r: 0.5, g: 0.1, b: 0.9 }); // caller's color survives
+ });
+});
diff --git a/sdk/tests/ui-theme.test.ts b/sdk/tests/ui-theme.test.ts
index 03a5d8408..ce297fa0e 100644
--- a/sdk/tests/ui-theme.test.ts
+++ b/sdk/tests/ui-theme.test.ts
@@ -1,33 +1,60 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
- * @file ThemeTokens — the design-token palette widgets resolve defaults from.
+ * @file ThemeTokens — the design-token palette + type scale widgets resolve
+ * defaults from, and the built-in dark/light themes.
*/
import { describe, it, expect, afterEach } from 'vitest';
import {
DARK_TOKENS,
+ LIGHT_TOKENS,
getTheme,
setTheme,
themeColors,
+ themeType,
type ThemeTokens,
} from '../src/ui/theme/tokens';
+import { themeButtonStates } from '../src/ui/widgets/button';
describe('ThemeTokens', () => {
afterEach(() => setTheme(DARK_TOKENS));
- it('defaults to the built-in dark palette', () => {
+ it('defaults to the built-in dark palette + type scale', () => {
expect(getTheme()).toBe(DARK_TOKENS);
expect(themeColors().primary).toEqual({ r: 0.25, g: 0.56, b: 0.96, a: 1 });
- expect(themeColors().backdrop).toEqual({ r: 0, g: 0, b: 0, a: 0.5 });
+ expect(themeType()).toEqual({ label: 14, body: 15, title: 20 });
});
- it('setTheme swaps the active palette for later widget construction', () => {
+ it('ships a light theme: light surfaces, dark text, same type scale', () => {
+ expect(LIGHT_TOKENS.colors.surface.r).toBeGreaterThan(0.8);
+ expect(DARK_TOKENS.colors.surface.r).toBeLessThan(0.3);
+ expect(LIGHT_TOKENS.colors.text.r).toBeLessThan(0.3);
+ expect(DARK_TOKENS.colors.text.r).toBeGreaterThan(0.8);
+ expect(LIGHT_TOKENS.type).toEqual(DARK_TOKENS.type);
+ });
+
+ it('every color role is defined in both themes (no missing role)', () => {
+ expect(Object.keys(LIGHT_TOKENS.colors).sort()).toEqual(Object.keys(DARK_TOKENS.colors).sort());
+ });
+
+ it('setTheme swaps the active palette + type for later widget construction', () => {
+ setTheme(LIGHT_TOKENS);
+ expect(themeColors().surface).toEqual(LIGHT_TOKENS.colors.surface);
const custom: ThemeTokens = {
colors: { ...DARK_TOKENS.colors, primary: { r: 1, g: 0, b: 0, a: 1 } },
+ type: DARK_TOKENS.type,
};
setTheme(custom);
expect(themeColors().primary).toEqual({ r: 1, g: 0, b: 0, a: 1 });
- // unrelated roles are preserved
- expect(themeColors().surface).toEqual(DARK_TOKENS.colors.surface);
+ expect(themeColors().surface).toEqual(DARK_TOKENS.colors.surface); // unrelated roles preserved
+ });
+
+ it('themeButtonStates derives the canonical states from the ACTIVE theme', () => {
+ expect(themeButtonStates().normal.color).toEqual(DARK_TOKENS.colors.control);
+ setTheme(LIGHT_TOKENS);
+ const s = themeButtonStates();
+ expect(s.normal.color).toEqual(LIGHT_TOKENS.colors.control);
+ expect(s.hover.color).toEqual(LIGHT_TOKENS.colors.controlHover);
+ expect(s.disabled.color).toMatchObject({ a: LIGHT_TOKENS.colors.control.a * 0.5 });
});
});
diff --git a/sdk/tests/ui-widgets.test.ts b/sdk/tests/ui-widgets.test.ts
index 3c73b0a19..e881e724f 100644
--- a/sdk/tests/ui-widgets.test.ts
+++ b/sdk/tests/ui-widgets.test.ts
@@ -18,6 +18,7 @@ import {
UIEventQueue,
UIEventType,
TransitionFlag,
+ themeColors,
} from '../src/ui';
import type { Entity } from '../src/types';
import type { World } from '../src/world';
@@ -137,6 +138,18 @@ describe('createButton', () => {
expect(sv.transitionFlags).toBe(TransitionFlag.ColorTint);
});
+ it('defaults its states to the active theme control roles (de-nude)', () => {
+ const btn = createButton({ world: world as unknown as World, events, text: 'OK' });
+ const sv = world.get(btn, StateVisuals) as {
+ states: Array<{ name: string; r: number; g: number; b: number; a: number }>;
+ };
+ const c = themeColors();
+ expect(sv.states.map(s => s.name)).toEqual(['normal', 'hover', 'pressed', 'disabled']);
+ expect(sv.states[0]).toMatchObject(c.control);
+ expect(sv.states[1]).toMatchObject(c.controlHover);
+ expect(sv.states[2]).toMatchObject(c.controlActive);
+ });
+
it('starts in "disabled" state when opts.disabled is true', () => {
const btn = createButton({
world: world as unknown as World,
diff --git a/src/esengine/ecs/UILayoutSystem.cpp b/src/esengine/ecs/UILayoutSystem.cpp
index f72ce7727..c2e559f37 100644
--- a/src/esengine/ecs/UILayoutSystem.cpp
+++ b/src/esengine/ecs/UILayoutSystem.cpp
@@ -237,6 +237,25 @@ void layoutUINodeSubtree(
}
f32 yl = YGNodeLayoutGetLeft(node);
f32 yt = YGNodeLayoutGetTop(node);
+
+ // An absolute child centres an axis when both its insets AND both its
+ // margins on that axis are `auto`. A pivot-less CSS box can't otherwise
+ // centre an out-of-flow node: Yoga's abspos centring keys off the
+ // parent's justifyContent, so it can't differ per sibling under one
+ // Canvas. Overriding the Yoga offset makes centring a self-contained
+ // per-node anchor, independent of the parent and of which axis is main.
+ if (k != begin && un.position == UIPositionType::Absolute) {
+ auto axisCentred = [](const Dimension& a, const Dimension& b,
+ const Dimension& m0, const Dimension& m1) {
+ return a.unit == DIM_AUTO && b.unit == DIM_AUTO &&
+ m0.unit == DIM_AUTO && m1.unit == DIM_AUTO;
+ };
+ if (axisCentred(un.insetLeft, un.insetRight, un.marginLeft, un.marginRight))
+ yl = 0.5f * (pw - fw);
+ if (axisCentred(un.insetTop, un.insetBottom, un.marginTop, un.marginBottom))
+ yt = 0.5f * (ph - fh);
+ }
+
// Center-based, y-up local position (implicit pivot 0.5).
f32 localX = -ppx * pw + yl + 0.5f * fw;
f32 localY = (1.0f - ppy) * ph - yt - 0.5f * fh;