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(editor): mode-driven UINode layout — In-Layout vs Absolute

esenginee7888c048d44
diff --git a/desktop/src/engine/SceneCommands.ts b/desktop/src/engine/SceneCommands.ts
index b0f137f54..05f6645a2 100644
--- a/desktop/src/engine/SceneCommands.ts
+++ b/desktop/src/engine/SceneCommands.ts
@@ -268,6 +268,11 @@ export class SceneCommandsImpl {
const applySeed = (): void => {
if (seed?.insetLeft !== undefined) this.writeField_(sourceId, 'UINode', 'insetLeft', 'dimension', { value: seed.insetLeft, unit: DimensionUnit.Px });
if (seed?.insetTop !== undefined) this.writeField_(sourceId, 'UINode', 'insetTop', 'dimension', { value: seed.insetTop, unit: DimensionUnit.Px });
+ // Freeze the flex-resolved size too, so a stretched/auto-sized node keeps its
+ // dimensions when it leaves flow (an absolute node with only a top-left inset
+ // would otherwise collapse to its content size).
+ if (seed?.width !== undefined) this.writeField_(sourceId, 'UINode', 'width', 'dimension', { value: seed.width, unit: DimensionUnit.Px });
+ if (seed?.height !== undefined) this.writeField_(sourceId, 'UINode', 'height', 'dimension', { value: seed.height, unit: DimensionUnit.Px });
};
if (bakeAbsolute && !this.gesture) {
// One undo step for the flip + the seeded insets.
@@ -314,24 +319,29 @@ export class SceneCommandsImpl {
}
/**
- * The concrete px insets that pin a UINode's CURRENT resolved box to its parent's
- * top-left — captured while the node is still in its old (pre-flip) layout so the
- * box is live. Only an axis with no explicit offset yet (both sides auto) is
- * seeded; an axis the user already positioned is left untouched (undefined).
- * Empty without live boxes. Applied after the flip to keep the node put + draggable.
+ * The concrete px inset + size that reproduce a UINode's CURRENT resolved box —
+ * captured while the node is still in its old (pre-flip) layout so the box is live.
+ * Pins the top-left inset and freezes an auto (flex/content-driven) width/height, so
+ * flipping to Absolute keeps the node exactly where and how big it was. Only an axis
+ * / dimension still at its auto default is seeded; one the user already set is left
+ * untouched (undefined). Empty without live boxes.
*/
- private absoluteInsetSeed_(sourceId: EntityId): { insetLeft?: number; insetTop?: number } {
+ private absoluteInsetSeed_(sourceId: EntityId): { insetLeft?: number; insetTop?: number; width?: number; height?: number } {
const rt = this.model.runtimeFor(sourceId);
const parentSrc = this.model.entityBySource(sourceId)?.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;
if (!node || !parent) return {};
- const autoAxis = (nearKey: string, farKey: string): boolean => {
- const near = this.modelFieldValue(sourceId, 'UINode', nearKey) as { unit: number } | undefined;
- const far = this.modelFieldValue(sourceId, 'UINode', farKey) as { unit: number } | undefined;
- return near?.unit === DimensionUnit.Auto && far?.unit === DimensionUnit.Auto;
- };
+ // A field absent from the model sits at its DEFAULT, which for inset/width/height
+ // is `auto` — so a missing value must read as auto, not "not auto". (A fresh flow
+ // node stores almost nothing, so without this the bake seeded nothing and the node
+ // collapsed to the top-left corner.)
+ const unitOf = (key: string): number =>
+ (this.modelFieldValue(sourceId, 'UINode', key) as { unit: number } | undefined)?.unit ?? DimensionUnit.Auto;
+ const autoAxis = (nearKey: string, farKey: string): boolean =>
+ unitOf(nearKey) === DimensionUnit.Auto && unitOf(farKey) === DimensionUnit.Auto;
+ const isAutoDim = (key: string): boolean => unitOf(key) === DimensionUnit.Auto;
// An absolute node's margin still offsets it on top of its inset, so the inset
// that reproduces the current position is (edge gap − own margin). Only px
// margins subtract cleanly; percent/auto margins are rare here and left as 0.
@@ -339,10 +349,14 @@ export class SceneCommandsImpl {
const m = this.modelFieldValue(sourceId, 'UINode', key) as { value: number; unit: number } | undefined;
return m?.unit === DimensionUnit.Px ? m.value : 0;
};
- const out: { insetLeft?: number; insetTop?: number } = {};
+ const out: { insetLeft?: number; insetTop?: number; width?: number; height?: number } = {};
if (autoAxis('insetLeft', 'insetRight')) out.insetLeft = Math.round((node.cx - node.hw) - (parent.cx - parent.hw) - marginPx('marginLeft'));
// Layout space is y-down: the top inset is the gap from the parent's top edge.
if (autoAxis('insetTop', 'insetBottom')) out.insetTop = Math.round((parent.cy + parent.hh) - (node.cy + node.hh) - marginPx('marginTop'));
+ // The OBB half-extents are the flex-resolved size (world px == layout px at the UI
+ // camera's unit scale); freeze it only where the size was auto (flex/content-driven).
+ if (isAutoDim('width')) out.width = Math.round(node.hw * 2);
+ if (isAutoDim('height')) out.height = Math.round(node.hh * 2);
return out;
}
diff --git a/desktop/src/panels/Details.tsx b/desktop/src/panels/Details.tsx
index bf22e0801..dc8e47bf3 100644
--- a/desktop/src/panels/Details.tsx
+++ b/desktop/src/panels/Details.tsx
@@ -44,7 +44,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 } from 'esengine';
+import { DimensionUnit, AnchorAxis, detectAnchor, UIPositionType } from 'esengine';
import type { SceneData, InputMapAsset, ActionType, Binding } from 'esengine';
import { modelAddableComponentEntries, subscribeSchemas, getSchemaRevision, prettyLabel, hexToRgba, dynamicEnumOptions, boxGroupsFor, type BoxGroupDef } from '@/engine/schema';
import * as imap from '@/project/inputMapDoc';
@@ -1179,18 +1179,40 @@ const V_ANCHOR_OPTS = [
{ value: String(AnchorAxis.Stretch), label: 'Stretch' },
];
-/** Anchor control for a UINode: a live preview of where the element sits in its
- * parent, plus two labelled Horizontal/Vertical pickers (Left/Center/Right/Stretch
- * × Top/Middle/Bottom/Stretch). Each axis is an independent, named choice — far
- * clearer than decoding a 16-cell icon grid — and writing either one applies the
- * combined preset (making the node Absolute), read back via detectAnchor. */
-function AnchorControl({ entities, comp }: { entities: EntityId[]; comp: InspectorComponent }) {
+const POSITION_MODE_OPTS = [
+ { value: String(UIPositionType.Relative), label: 'In Layout' },
+ { value: String(UIPositionType.Absolute), label: 'Absolute' },
+];
+// alignSelf enum: 0 Auto · 1 Start · 2 Center · 3 End · 4 Stretch (matches the SDK).
+const ALIGN_SELF_OPTS = [
+ { value: '0', label: 'Auto' },
+ { value: '1', label: 'Start' },
+ { value: '2', label: 'Center' },
+ { value: '3', label: 'End' },
+ { value: '4', label: 'Stretch' },
+];
+
+/** The UINode fields the Layout block owns, so the generic field flow skips them —
+ * which set depends on the positioning MODE (an anchor/inset belongs to Absolute,
+ * the flex knobs to flow). Mirrors how box cards claim their edge fields. */
+function uiLayoutOwnedFields(absolute: boolean): ReadonlySet<string> {
+ const base = ['position', 'alignSelf'];
+ // Flow: offsets are meaningless (inset only applies to Absolute). Absolute: the
+ // flex-item knobs don't participate (the node is out of flow).
+ return new Set(absolute ? [...base, 'flexGrow', 'flexShrink', 'flexBasis'] : [...base, 'insetLeft', 'insetRight', 'insetTop', 'insetBottom']);
+}
+
+/** 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. */
+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;
return v ?? { value: 0, unit: DimensionUnit.Auto };
};
const node = {
- position: Number(comp.fields.find((f) => f.key === 'position')?.value ?? 0),
+ position: UIPositionType.Absolute,
insetLeft: dim('insetLeft'), insetRight: dim('insetRight'),
insetTop: dim('insetTop'), insetBottom: dim('insetBottom'),
marginLeft: dim('marginLeft'), marginRight: dim('marginRight'),
@@ -1204,7 +1226,7 @@ function AnchorControl({ entities, comp }: { entities: EntityId[]; comp: Inspect
const curV = active?.v ?? AnchorAxis.Center;
const r = anchorWidgetRect(curH, curV);
return (
- <div className="anchor-block">
+ <>
<div className="anchor-head">
<span className="anchor-t">Anchor</span>
<em className="anchor-cur">{active ? anchorTitle(active.h, active.v) : 'Custom'}</em>
@@ -1239,6 +1261,64 @@ function AnchorControl({ entities, comp }: { entities: EntityId[]; comp: Inspect
</label>
</div>
</div>
+ </>
+ );
+}
+
+/** The flow-layout controls for a RELATIVE (In-Layout) UINode: its parent's flex
+ * layout decides the placement, so the only per-node control is the cross-axis
+ * Align Self (the flow analog of a 1-axis anchor). Grow/shrink/basis live in the
+ * field flow below. */
+function FlowLayoutControls({ entities, comp }: { entities: EntityId[]; comp: InspectorComponent }) {
+ const field = comp.fields.find((f) => f.key === 'alignSelf');
+ const value = field?.mixed ? '' : String(Number(field?.value ?? 0));
+ const set = (val: string) => {
+ SceneCommands.beginGesture('Align Self');
+ for (const id of entities) SceneCommands.setField(id, 'UINode', 'alignSelf', 'enum', Number(val));
+ SceneCommands.endGesture();
+ };
+ return (
+ <>
+ <div className="anchor-body">
+ <div className="anchor-axes">
+ <label className="anchor-axis">
+ <span>Align Self</span>
+ <Segmented grow ariaLabel="Align self" value={value} options={ALIGN_SELF_OPTS} onChange={set} />
+ </label>
+ </div>
+ </div>
+ <div className="anchor-hint">Placed by the parent’s layout · Align Self overrides the cross-axis.</div>
+ </>
+ );
+}
+
+/** The UINode positioning block: an explicit In-Layout ↔ Absolute mode switch, then
+ * the controls that actually apply in that mode — the anchor presets for Absolute,
+ * Align Self for flow. Anchors are an absolute-positioning concept, so a flow node
+ * never shows a meaningless "Custom" anchor; it shows how it sits in its parent's
+ * flex layout instead. The mode switch writes `position` (flipping to Absolute bakes
+ * the current on-screen box into px insets — see SceneCommands.setField). */
+function UILayoutControl({ entities, comp }: { entities: EntityId[]; comp: InspectorComponent }) {
+ const posField = comp.fields.find((f) => f.key === 'position');
+ const absolute = Number(posField?.value ?? 0) === UIPositionType.Absolute;
+ const setMode = (val: string) => {
+ SceneCommands.beginGesture('UI Position Mode');
+ for (const id of entities) SceneCommands.setField(id, 'UINode', 'position', 'enum', Number(val));
+ SceneCommands.endGesture();
+ };
+ return (
+ <div className="anchor-block">
+ <div className="ui-mode-row">
+ <span className="anchor-t">Position</span>
+ <Segmented
+ grow
+ ariaLabel="Position mode"
+ value={posField?.mixed ? '' : String(absolute ? UIPositionType.Absolute : UIPositionType.Relative)}
+ options={POSITION_MODE_OPTS}
+ onChange={setMode}
+ />
+ </div>
+ {absolute ? <AnchorPicker entities={entities} comp={comp} /> : <FlowLayoutControls entities={entities} comp={comp} />}
</div>
);
}
@@ -1348,6 +1428,7 @@ function ComponentSection({
write,
action,
extra,
+ hideFields,
}: {
entities: EntityId[];
comp: InspectorComponent;
@@ -1357,6 +1438,9 @@ function ComponentSection({
write?: FieldWrite;
action?: { label: string; title: string; run: () => void };
extra?: React.ReactNode;
+ /** Field keys the `extra` block owns (e.g. UINode's Layout section), skipped by
+ * the generic field flow so they aren't edited in two places. */
+ hideFields?: ReadonlySet<string>;
}) {
const Icon = componentIcon(comp.name);
const overridden = comp.fields.some(isModified);
@@ -1368,8 +1452,11 @@ function ComponentSection({
// Edge fields that fold into a spatial box (margin/offsets) are pulled out of the
// normal flow and rendered as a compound card below the plain rows — but only
// when all four sides are present in the reflection.
- const boxGroups = boxGroupsFor(comp.name).filter((g) =>
- [g.left, g.right, g.top, g.bottom].every((k) => comp.fields.some((f) => f.key === k)),
+ const boxGroups = boxGroupsFor(comp.name).filter(
+ (g) =>
+ [g.left, g.right, g.top, g.bottom].every((k) => comp.fields.some((f) => f.key === k)) &&
+ // A box card the extra block owns (all four sides hidden) drops out entirely.
+ ![g.left, g.right, g.top, g.bottom].every((k) => hideFields?.has(k)),
);
const boxKeys = new Set(boxGroups.flatMap((g) => [g.left, g.right, g.top, g.bottom]));
@@ -1379,6 +1466,7 @@ function ComponentSection({
const advancedFields: InspectorField[] = [];
const groups = new Map<string, InspectorField[]>();
for (const f of comp.fields) {
+ if (hideFields?.has(f.key)) continue; // owned by the extra block (UINode Layout)
if (boxKeys.has(f.key)) continue;
if (f.category) (groups.get(f.category) ?? groups.set(f.category, []).get(f.category)!).push(f);
else if (f.advanced) advancedFields.push(f);
@@ -2242,7 +2330,14 @@ function EditorDetails() {
onToggle={() => toggle(comp.name)}
onMore={(e, name) => setCompMenu({ x: e.clientX, y: e.clientY, comp: name })}
action={uiNodeCanvasAction(ids, comp)}
- extra={comp.name === 'UINode' ? <AnchorControl entities={ids} comp={comp} /> : undefined}
+ extra={comp.name === 'UINode' ? <UILayoutControl entities={ids} comp={comp} /> : undefined}
+ hideFields={
+ comp.name === 'UINode'
+ ? uiLayoutOwnedFields(
+ Number(comp.fields.find((f) => f.key === 'position')?.value ?? 0) === UIPositionType.Absolute,
+ )
+ : undefined
+ }
/>
))}
{query && visible.length === 0 && (
diff --git a/desktop/src/theme/inspector.css b/desktop/src/theme/inspector.css
index 5220b61b3..be722e2b2 100644
--- a/desktop/src/theme/inspector.css
+++ b/desktop/src/theme/inspector.css
@@ -81,6 +81,11 @@
choice (Left/Center/Right/Stretch × Top/Middle/Bottom/Stretch) — self-documenting,
unlike a 16-cell icon grid. The header names the active preset (or "Custom"). */
.anchor-block { padding: 7px 8px 9px; }
+/* Position mode switch (In Layout ↔ Absolute) — sits above the mode's controls. */
+.ui-mode-row { display: flex; align-items: center; gap: 9px; margin-bottom: 9px; }
+.ui-mode-row .anchor-t { font-size: var(--fs-2xs); text-transform: uppercase; letter-spacing: .5px; color: var(--text-mute); flex-shrink: 0; }
+.ui-mode-row .seg { flex: 1; min-width: 0; }
+.anchor-hint { margin-top: 8px; font-size: var(--fs-2xs); color: var(--text-mute); line-height: 1.4; }
.anchor-head { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; margin-bottom: 8px; }
.anchor-head .anchor-t { font-size: var(--fs-2xs); text-transform: uppercase; letter-spacing: .5px; color: var(--text-mute); }
.anchor-head .anchor-cur { font-style: normal; font-size: var(--fs-sm); font-weight: 600; color: var(--acc-hi); }