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(ui): per-axis anchor edits that never move the widget + viewport polish

esenginef350fbb28744
diff --git a/desktop/src/engine/SceneCommands.ts b/desktop/src/engine/SceneCommands.ts
index ce199af1d..4d3b8bad2 100644
--- a/desktop/src/engine/SceneCommands.ts
+++ b/desktop/src/engine/SceneCommands.ts
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import type { SceneData, PrefabData, ControllerState, UIControllerData, GearBinding, GearTween, UIGearData } from 'esengine';
-import { TilemapAPI, TilemapLiveSync, UIPositionType, DimensionUnit, anchorPresetFields, writeFieldPath, type AnchorPreset } from 'esengine';
+import { TilemapAPI, TilemapLiveSync, UIPositionType, DimensionUnit, AnchorAxis, writeFieldPath, type AnchorPreset } from 'esengine';
import type { EntityId, InspectorFieldType, InspectorFieldValue } from '@/types';
import { EditorHistory, EditorHistoryImpl } from './EditorHistory';
import { SceneModel, SceneModelImpl } from './SceneModel';
@@ -478,29 +478,84 @@ export class SceneCommandsImpl {
}
/**
- * Apply an anchor preset (Start / Center / End / Stretch per axis) to each
- * UINode as one undo step. A preset is a VIEW over the box fields, not stored
- * state, so this simply writes `position` Absolute + the insets/margins (+ size
- * for a Stretch axis) that express it — {@link detectAnchor} reads them back.
+ * Apply an anchor preset (Start / Center / End / Stretch, PER AXIS — an absent
+ * axis is left untouched) to each UINode as one undo step. A preset is a VIEW
+ * over the box fields, not stored state; the node's current resolved box is
+ * baked into the pinned insets so changing an anchor never moves the widget on
+ * screen (Center excepted — auto-margin centring has no offset to express), and
+ * leaving Stretch freezes the resolved size so the box doesn't collapse to its
+ * content. {@link detectAnchorAxes} reads the result back.
*/
- setUINodeAnchor(sourceIds: EntityId[], preset: AnchorPreset): void {
- const f = anchorPresetFields(preset);
- const dims: Array<[string, { value: number; unit: number }]> = [
- ['insetLeft', f.insetLeft], ['insetRight', f.insetRight],
- ['insetTop', f.insetTop], ['insetBottom', f.insetBottom],
- ['marginLeft', f.marginLeft], ['marginRight', f.marginRight],
- ['marginTop', f.marginTop], ['marginBottom', f.marginBottom],
- ];
- if (f.width) dims.push(['width', f.width]);
- if (f.height) dims.push(['height', f.height]);
+ setUINodeAnchor(sourceIds: EntityId[], preset: Partial<AnchorPreset>): void {
this.beginGesture('Anchor');
for (const id of sourceIds) {
- this.setField(id, 'UINode', 'position', 'enum', f.position);
- for (const [key, dim] of dims) this.setField(id, 'UINode', key, 'dimension', dim);
+ // Live boxes for the offset bake, read BEFORE any writes (world px == layout
+ // px in the UI world). Null without a live layout → preset zero offsets.
+ const rt = this.model.runtimeFor(id);
+ const parentSrc = this.model.entityBySource(id)?.parent;
+ const parentRt = parentSrc != null ? this.model.runtimeFor(parentSrc) : undefined;
+ const node = rt !== undefined ? ViewportController.uiEntityWorldOBB(rt) : null;
+ const parent = parentRt !== undefined ? ViewportController.uiEntityWorldOBB(parentRt) : null;
+ this.setField(id, 'UINode', 'position', 'enum', UIPositionType.Absolute);
+ for (const axis of ['h', 'v'] as const) {
+ const mode = preset[axis];
+ if (mode === undefined) continue;
+ // Edge gaps in layout space (y-down): near = left/top, far = right/bottom.
+ const gaps = node && parent
+ ? axis === 'h'
+ ? { near: (node.cx - node.hw) - (parent.cx - parent.hw), far: (parent.cx + parent.hw) - (node.cx + node.hw), size: node.hw * 2 }
+ : { near: (parent.cy + parent.hh) - (node.cy + node.hh), far: (node.cy - node.hh) - (parent.cy - parent.hh), size: node.hh * 2 }
+ : null;
+ this.applyAnchorAxis_(id, axis, mode, gaps);
+ }
}
this.endGesture();
}
+ /** One axis of {@link setUINodeAnchor}: writes the inset/margin (+ size) fields
+ * that express `mode`, pinning at the baked `gaps` when available. */
+ private applyAnchorAxis_(
+ sourceId: EntityId, axis: 'h' | 'v', mode: AnchorAxis,
+ gaps: { near: number; far: number; size: number } | null,
+ ): void {
+ const keys = axis === 'h'
+ ? { near: 'insetLeft', far: 'insetRight', mNear: 'marginLeft', mFar: 'marginRight', size: 'width' }
+ : { near: 'insetTop', far: 'insetBottom', mNear: 'marginTop', mFar: 'marginBottom', size: 'height' };
+ const px = (v: number) => ({ value: Math.round(v), unit: DimensionUnit.Px });
+ const autoDim = () => ({ value: 0, unit: DimensionUnit.Auto });
+ const write = (key: string, dim: { value: number; unit: number }): void =>
+ this.setField(sourceId, 'UINode', key, 'dimension', dim);
+ switch (mode) {
+ case AnchorAxis.Start:
+ write(keys.near, px(gaps?.near ?? 0));
+ write(keys.far, autoDim());
+ break;
+ case AnchorAxis.End:
+ write(keys.near, autoDim());
+ write(keys.far, px(gaps?.far ?? 0));
+ break;
+ case AnchorAxis.Center:
+ write(keys.near, autoDim());
+ write(keys.far, autoDim());
+ break;
+ case AnchorAxis.Stretch:
+ write(keys.near, px(gaps?.near ?? 0));
+ write(keys.far, px(gaps?.far ?? 0));
+ write(keys.size, autoDim());
+ break;
+ }
+ // Center centres via auto margins; every other mode pins with 0 so the inset
+ // alone drives the position.
+ const m = mode === AnchorAxis.Center ? autoDim() : px(0);
+ write(keys.mNear, m);
+ write(keys.mFar, m);
+ // Leaving Stretch: freeze an auto (inset-driven) size at its resolved value.
+ if (mode !== AnchorAxis.Stretch && gaps) {
+ const cur = this.modelFieldValue(sourceId, 'UINode', keys.size) as { unit: number } | undefined;
+ if ((cur?.unit ?? DimensionUnit.Auto) === DimensionUnit.Auto) write(keys.size, px(gaps.size));
+ }
+ }
+
// — Undoable entity lifecycle (model ops; the Reconciler re-spawns/-despawns) —
/** Spawn a new empty entity (with a Transform). Returns its source id. */
diff --git a/desktop/src/engine/entitySources.ts b/desktop/src/engine/entitySources.ts
index 388d57e8f..caa8344ee 100644
--- a/desktop/src/engine/entitySources.ts
+++ b/desktop/src/engine/entitySources.ts
@@ -11,7 +11,7 @@
* UI. (REARCH_ENTITY_CREATION E2.)
*/
import type { LucideIcon } from 'lucide-react';
-import { CircleDot, LayoutPanelTop, ToggleLeft, SlidersHorizontal, List, ChevronDown, SquareMousePointer, RectangleHorizontal, Box, Type, Image as ImageIcon, SquareDashed, ScrollText } from 'lucide-react';
+import { CircleDot, LayoutPanelTop, ToggleLeft, SlidersHorizontal, List, ChevronDown, SquareMousePointer, RectangleHorizontal, Box, Type, Image as ImageIcon, SquareDashed, ScrollText, AppWindow, TextCursorInput } from 'lucide-react';
import { BUILTIN_UI_PREFABS, BUILTIN_UI_WIDGET_NAMES, PREFAB_FORMAT_VERSION, getUserComponents, type PrefabData } from 'esengine';
import type { EntityId } from '@/types';
import { componentByName, componentDefaults, prettyLabel, componentCategory } from './schema';
@@ -181,6 +181,8 @@ const UI_WIDGET_ICON: Record<string, LucideIcon> = {
Button: SquareMousePointer,
Toggle: ToggleLeft,
Slider: SlidersHorizontal,
+ Dialog: AppWindow,
+ TextInput: TextCursorInput,
Progress: RectangleHorizontal,
Dropdown: ChevronDown,
ListView: List,
diff --git a/desktop/src/panels/Details.tsx b/desktop/src/panels/Details.tsx
index 145c3171b..dfaa13fed 100644
--- a/desktop/src/panels/Details.tsx
+++ b/desktop/src/panels/Details.tsx
@@ -52,7 +52,7 @@ import { InspectorClipboard } from '@/engine/inspectorClipboard';
import { SceneCommands, toModelValue } from '@/engine/SceneCommands';
import { ENTITY_SOURCES, createFromSource } from '@/engine/entitySources';
import { PlayInspect } from '@/engine/PlayInspect';
-import { DimensionUnit, AnchorAxis, detectAnchor, UIPositionType, parseLocaleTable, EasingType } from 'esengine';
+import { DimensionUnit, AnchorAxis, detectAnchorAxes, UIPositionType, parseLocaleTable, EasingType } from 'esengine';
import type { SceneData, InputMapAsset, ActionType, Binding, LocaleTableAsset, PluralCategory, GearValue, GearTween } from 'esengine';
import { modelAddableComponentEntries, subscribeSchemas, getSchemaRevision, prettyLabel, hexToRgba, dynamicEnumOptions, boxGroupsFor, isRequiredEmpty, type BoxGroupDef } from '@/engine/schema';
import * as imap from '@/project/inputMapDoc';
@@ -1371,8 +1371,8 @@ function uiLayoutOwnedFields(absolute: boolean): ReadonlySet<string> {
/** The anchor 9-preset picker for an ABSOLUTE UINode: a live preview + two labelled
* Horizontal/Vertical pickers (Left/Center/Right/Stretch × Top/Middle/Bottom/Stretch).
- * Each axis is an independent named choice; writing either applies the combined
- * preset, read back via detectAnchor. */
+ * Each axis is an independent choice, written alone so the other axis keeps its
+ * state, read back per-axis via detectAnchorAxes. */
function AnchorPicker({ entities, comp }: { entities: EntityId[]; comp: InspectorComponent }) {
const dim = (key: string) => {
const v = comp.fields.find((f) => f.key === key)?.value as { value: number; unit: number } | undefined;
@@ -1385,21 +1385,20 @@ function AnchorPicker({ entities, comp }: { entities: EntityId[]; comp: Inspecto
marginLeft: dim('marginLeft'), marginRight: dim('marginRight'),
marginTop: dim('marginTop'), marginBottom: dim('marginBottom'),
width: dim('width'), height: dim('height'),
- } as Parameters<typeof detectAnchor>[0];
- const active = detectAnchor(node);
- // Custom (non-preset) box → the pickers show nothing selected; changing one axis
- // falls back to Center on the other so the result is still a clean preset.
- const curH = active?.h ?? AnchorAxis.Center;
- const curV = active?.v ?? AnchorAxis.Center;
- const r = anchorWidgetRect(curH, curV);
+ } as Parameters<typeof detectAnchorAxes>[0];
+ // Each axis classifies independently, so a box with one hand-tuned axis still
+ // shows (and keeps) the clean one; writing an axis touches ONLY that axis.
+ const axes = detectAnchorAxes(node);
+ const clean = axes.h !== null && axes.v !== null;
+ const r = anchorWidgetRect(axes.h ?? AnchorAxis.Center, axes.v ?? AnchorAxis.Center);
return (
<>
<div className="anchor-head">
<span className="anchor-t">{t('det.anchor')}</span>
- <em className="anchor-cur">{active ? anchorTitle(active.h, active.v) : t('det.anchorCustom')}</em>
+ <em className="anchor-cur">{clean ? anchorTitle(axes.h!, axes.v!) : t('det.anchorCustom')}</em>
</div>
<div className="anchor-body">
- <div className={`anchor-preview${active ? '' : ' custom'}`} aria-hidden="true">
+ <div className={`anchor-preview${clean ? '' : ' custom'}`} aria-hidden="true">
<svg viewBox="0 0 24 24">
<rect className="anchor-frame" x="2.5" y="2.5" width="19" height="19" rx="3" ry="3" />
<rect className="anchor-widget" x={r.x} y={r.y} width={r.w} height={r.h} rx="2" ry="2" />
@@ -1411,9 +1410,9 @@ function AnchorPicker({ entities, comp }: { entities: EntityId[]; comp: Inspecto
<Segmented
grow
ariaLabel={t('det.horizontalAnchorAria')}
- value={active ? String(active.h) : ''}
+ value={axes.h !== null ? String(axes.h) : ''}
options={H_ANCHOR_OPTS}
- onChange={(val) => SceneCommands.setUINodeAnchor(entities, { h: Number(val), v: curV })}
+ onChange={(val) => SceneCommands.setUINodeAnchor(entities, { h: Number(val) })}
/>
</label>
<label className="anchor-axis">
@@ -1421,9 +1420,9 @@ function AnchorPicker({ entities, comp }: { entities: EntityId[]; comp: Inspecto
<Segmented
grow
ariaLabel={t('det.verticalAnchorAria')}
- value={active ? String(active.v) : ''}
+ value={axes.v !== null ? String(axes.v) : ''}
options={V_ANCHOR_OPTS}
- onChange={(val) => SceneCommands.setUINodeAnchor(entities, { h: curH, v: Number(val) })}
+ onChange={(val) => SceneCommands.setUINodeAnchor(entities, { v: Number(val) })}
/>
</label>
</div>
diff --git a/desktop/src/panels/Viewport.tsx b/desktop/src/panels/Viewport.tsx
index 1ed2d388d..1ab52d899 100644
--- a/desktop/src/panels/Viewport.tsx
+++ b/desktop/src/panels/Viewport.tsx
@@ -1044,11 +1044,16 @@ export function Viewport() {
safe.style.opacity = '0';
}
}
- // The authored resolution, pinned to the frame's top-left corner.
+ // The authored resolution, pinned to the frame's top-left corner but clamped
+ // into the viewport — when the frame corner pans off-screen the label sticks
+ // to the nearest edge instead of getting clipped away.
const dlabel = designLabelRef.current;
if (dlabel) {
dlabel.textContent = `${ci.designResolution.x} × ${ci.designResolution.y}`;
- dlabel.style.transform = `translate(${des.x + 4}px, ${des.y + 4}px)`;
+ // Top clamp clears the .ov-tl floating toolbar (top:10 + ~34px tall).
+ const lx = Math.min(Math.max(des.x + 4, 4), Math.max(dsvg.clientWidth - dlabel.offsetWidth - 4, 4));
+ const ly = Math.min(Math.max(des.y + 4, 48), Math.max(dsvg.clientHeight - dlabel.offsetHeight - 4, 48));
+ dlabel.style.transform = `translate(${lx}px, ${ly}px)`;
dlabel.style.opacity = '1';
}
} else {
@@ -1821,7 +1826,24 @@ export function Viewport() {
>
<div className="ovmenu-lbl">{t('vp.device')}</div>
{RESOLUTION_PRESETS.map((p) => (
- <DdRadio key={p.id} on={device === p.id} label={p.label} onClick={() => useEditorMode.getState().setDevice(p.id)} />
+ <DdRadio
+ key={p.id}
+ on={device === p.id}
+ label={p.label}
+ onClick={() => {
+ const ms = useEditorMode.getState();
+ ms.setDevice(p.id);
+ // Picking a real device snaps the orientation to the design's own
+ // (a landscape design previews on a landscape phone); the explicit
+ // orientation radios below still override.
+ if (p.w > 0) {
+ const dw = sceneCanvas ? sceneCanvas.x : projectDesign.width;
+ const dh = sceneCanvas ? sceneCanvas.y : projectDesign.height;
+ const want = dw >= dh ? 'landscape' : 'portrait';
+ if (ms.orientation !== want) ms.toggleOrientation();
+ }
+ }}
+ />
))}
<div className="ovmenu-lbl">{t('vp.orientation')}</div>
<DdRadio
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index db7d8b464..ed614ac4a 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1242 stable · 17 beta · 1 deprecated
+Symbols: 1243 stable · 17 beta · 1 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -8115,6 +8115,11 @@ PluralSelector
(node: UINodeData): AnchorPreset | null
```
+## detectAnchorAxes — function
+```
+(node: UINodeData): { h: AnchorAxis | null; v: AnchorAxis | null; }
+```
+
## diffAgainstSource — function
```
(source: PrefabData, instance: readonly ProcessedEntity[], options?: DiffOptions): { overrides: PrefabOverride[]; untracked: ProcessedEntity[]; orphanedSourceIds: PrefabEntityId[]; }
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 4a5238e39..a01b5febc 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1241 stable · 19 beta · 1 deprecated
+Symbols: 1242 stable · 19 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -8110,6 +8110,11 @@ PluralSelector
(node: UINodeData): AnchorPreset | null
```
+## detectAnchorAxes — function
+```
+(node: UINodeData): { h: AnchorAxis | null; v: AnchorAxis | null; }
+```
+
## diffAgainstSource — function
```
(source: PrefabData, instance: readonly ProcessedEntity[], options?: DiffOptions): { overrides: PrefabOverride[]; untracked: ProcessedEntity[]; orphanedSourceIds: PrefabEntityId[]; }
diff --git a/sdk/src/core-ui.ts b/sdk/src/core-ui.ts
index 4f644ccf6..5ba61094f 100644
--- a/sdk/src/core-ui.ts
+++ b/sdk/src/core-ui.ts
@@ -158,6 +158,7 @@ export {
ANCHOR_AXES,
anchorPresetFields,
detectAnchor,
+ detectAnchorAxes,
type AnchorPreset,
type AnchorFields,
// Builders
diff --git a/sdk/src/ui/index.ts b/sdk/src/ui/index.ts
index 5f818ef58..db083ead2 100644
--- a/sdk/src/ui/index.ts
+++ b/sdk/src/ui/index.ts
@@ -81,6 +81,7 @@ export {
ANCHOR_AXES,
anchorPresetFields,
detectAnchor,
+ detectAnchorAxes,
type AnchorPreset,
type AnchorFields,
} from './layout/anchor';
diff --git a/sdk/src/ui/layout/anchor.ts b/sdk/src/ui/layout/anchor.ts
index c67fbc385..6d431c54a 100644
--- a/sdk/src/ui/layout/anchor.ts
+++ b/sdk/src/ui/layout/anchor.ts
@@ -123,13 +123,22 @@ function axisMode(near: Dimension, far: Dimension, mNear: Dimension, mFar: Dimen
return null;
}
+/** Per-axis classification of a UINode's box: each axis resolves independently
+ * to its {@link AnchorAxis}, or null when that axis isn't a clean preset — so a
+ * box with one hand-tuned axis still reads (and can keep) the other. */
+export function detectAnchorAxes(node: UINodeData): { h: AnchorAxis | null; v: AnchorAxis | null } {
+ if (node.position !== UIPositionType.Absolute) return { h: null, v: null };
+ return {
+ h: axisMode(node.insetLeft, node.insetRight, node.marginLeft, node.marginRight, node.width),
+ v: axisMode(node.insetTop, node.insetBottom, node.marginTop, node.marginBottom, node.height),
+ };
+}
+
/** 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);
+ const { h, v } = detectAnchorAxes(node);
if (h === null || v === null) return null;
return { h, v };
}