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): safe-area insets are editable, in an expander rather than four more columns

esenginea30cc0a5dff4
diff --git a/desktop/src/components/SettingsDialog.tsx b/desktop/src/components/SettingsDialog.tsx
index 0677bf2fc..f7d12301d 100644
--- a/desktop/src/components/SettingsDialog.tsx
+++ b/desktop/src/components/SettingsDialog.tsx
@@ -11,7 +11,7 @@ import { useEffect, useRef, useState } from 'react';
import type { PointerEvent as ReactPointerEvent } from 'react';
import { createPortal } from 'react-dom';
import { useShallow } from 'zustand/react/shallow';
-import { Settings as SettingsIcon, X, RotateCcw, FolderSearch, Plus, Trash2 } from 'lucide-react';
+import { Settings as SettingsIcon, X, RotateCcw, FolderSearch, Plus, Trash2, ChevronRight } from 'lucide-react';
import { useEditorStore } from '@/store/editorStore';
import { useSettings } from '@/store/settingsStore';
import { settingsRegistry } from '@/settings/registry';
@@ -24,7 +24,7 @@ import { SearchField } from '@/components/SearchField';
import { Segmented } from '@/components/Segmented';
import { Select } from '@/components/Select';
import { ColorControl } from '@/components/ColorControl';
-import type { Setting, NumberSetting, KeybindingSetting, StringListSetting, PathSetting, MatrixSetting, FlagListSetting, ObjectListSetting } from '@/settings/types';
+import type { Setting, NumberSetting, KeybindingSetting, StringListSetting, PathSetting, MatrixSetting, FlagListSetting, ObjectListSetting, ObjectListColumn } from '@/settings/types';
import { t } from '@/i18n';
// A bound list setting's getter returns a fresh array each call; useShallow below
@@ -301,22 +301,67 @@ function FlagListControl({ setting }: { setting: FlagListSetting }) {
*/
const EMPTY_ROWS: readonly Record<string, unknown>[] = [];
+/** Read `a.b.c` out of a row. */
+function readPath(row: Record<string, unknown>, path: string): unknown {
+ return path.split('.').reduce<unknown>((o, k) => (o as Record<string, unknown> | undefined)?.[k], row);
+}
+
+/** Immutably write `a.b.c` into a row, creating the intermediate objects. */
+function writePath(row: Record<string, unknown>, path: string, v: unknown): Record<string, unknown> {
+ const [head, ...rest] = path.split('.');
+ if (rest.length === 0) return { ...row, [head]: v };
+ const child = (row[head] as Record<string, unknown> | undefined) ?? {};
+ return { ...row, [head]: writePath(child, rest.join('.'), v) };
+}
+
+function ObjectListField({
+ col, row, onChange,
+}: {
+ col: ObjectListColumn;
+ row: Record<string, unknown>;
+ onChange: (v: unknown) => void;
+}) {
+ return (
+ <input
+ className="set-str"
+ type={col.type === 'number' ? 'number' : 'text'}
+ min={col.min}
+ spellCheck={false}
+ placeholder={col.placeholder}
+ value={String(readPath(row, col.key) ?? '')}
+ onChange={(e) => onChange(col.type === 'number' ? Number(e.target.value) : e.target.value)}
+ />
+ );
+}
+
+/**
+ * A table of rows the user can add to, edit and delete. Values are committed on
+ * every keystroke — the setting store is the working copy, and a row that is
+ * momentarily invalid shows its complaint inline instead of being refused.
+ */
function ObjectListControl({ setting }: { setting: ObjectListSetting }) {
const setValue = useSettings((s) => s.setValue);
// useShallow, not a bare selector: `getValue` hands back a fresh array each
// call, and Object.is on a new reference re-renders forever — the same reason
// FlagListControl below reads its value this way.
const rows = useSettings(useShallow((s) => s.getValue<Record<string, unknown>[]>(setting.id) ?? (EMPTY_ROWS as Record<string, unknown>[])));
+ const [expanded, setExpanded] = useState<ReadonlySet<number>>(() => new Set());
const cols = setting.columns;
- const grid = { gridTemplateColumns: `${cols.map((c) => c.width ?? '1fr').join(' ')} 24px` };
+ const details = setting.detailColumns ?? [];
+ const grid = { gridTemplateColumns: `${cols.map((c) => c.width ?? '1fr').join(' ')}${details.length > 0 ? ' 24px' : ''} 24px` };
// Read the CURRENT rows rather than the render's closure: editing two fields
// in quick succession would otherwise have the second patch built from the
// pre-first snapshot and silently drop the first edit.
const patch = (i: number, key: string, v: unknown) => {
const live = useSettings.getState().getValue<Record<string, unknown>[]>(setting.id) ?? rows;
- setValue(setting.id, live.map((r, j) => (j === i ? { ...r, [key]: v } : r)));
+ setValue(setting.id, live.map((r, j) => (j === i ? writePath(r, key, v) : r)));
};
+ const toggle = (i: number) => setExpanded((prev) => {
+ const next = new Set(prev);
+ if (!next.delete(i)) next.add(i);
+ return next;
+ });
return (
<div className="set-objlist">
@@ -324,37 +369,54 @@ function ObjectListControl({ setting }: { setting: ObjectListSetting }) {
{rows.length > 0 && (
<div className="set-objlist-head" style={grid}>
{cols.map((c) => <span key={c.key}>{c.label}</span>)}
+ {details.length > 0 && <span />}
<span />
</div>
)}
{rows.map((row, i) => {
const err = setting.rowError?.(row, rows) ?? null;
+ const open = expanded.has(i);
return (
<div key={i} className={`set-objlist-row${err ? ' invalid' : ''}`}>
<div className="set-objlist-fields" style={grid}>
{cols.map((c) => (
- <input
- key={c.key}
- className="set-str"
- type={c.type === 'number' ? 'number' : 'text'}
- min={c.min}
- spellCheck={false}
- placeholder={c.placeholder}
- value={String(row[c.key] ?? '')}
- onChange={(e) =>
- patch(i, c.key, c.type === 'number' ? Number(e.target.value) : e.target.value)}
- />
+ <ObjectListField key={c.key} col={c} row={row} onChange={(v) => patch(i, c.key, v)} />
))}
+ {details.length > 0 && (
+ <button
+ type="button"
+ className={`set-objlist-more${open ? ' open' : ''}`}
+ title={setting.detailLabel}
+ aria-expanded={open}
+ onClick={() => toggle(i)}
+ >
+ <ChevronRight size={12} strokeWidth={2} />
+ </button>
+ )}
<button
type="button"
className="set-objlist-del"
title={t('set.objList.remove')}
- onClick={() => setValue(setting.id, rows.filter((_, j) => j !== i))}
+ onClick={() => {
+ setValue(setting.id, rows.filter((_, j) => j !== i));
+ setExpanded(new Set());
+ }}
>
<Trash2 size={12} strokeWidth={2} />
</button>
</div>
{err && <div className="set-objlist-err">{err}</div>}
+ {open && (
+ <div className="set-objlist-detail">
+ {setting.detailLabel && <span className="set-objlist-detail-lbl">{setting.detailLabel}</span>}
+ {details.map((c) => (
+ <label key={c.key} className="set-objlist-detail-f">
+ <span>{c.label}</span>
+ <ObjectListField col={c} row={row} onChange={(v) => patch(i, c.key, v)} />
+ </label>
+ ))}
+ </div>
+ )}
</div>
);
})}
diff --git a/desktop/src/i18n/messages/settings.ts b/desktop/src/i18n/messages/settings.ts
index 8d4e9f4ab..3fe067620 100644
--- a/desktop/src/i18n/messages/settings.ts
+++ b/desktop/src/i18n/messages/settings.ts
@@ -97,6 +97,11 @@ export const settingsMessages = defineMessages({
'set.screenPreset.label': { en: 'Name', zh: '名称' },
'set.screenPreset.width': { en: 'Width', zh: '宽' },
'set.screenPreset.height': { en: 'Height', zh: '高' },
+ 'set.screenPreset.safeArea': { en: 'Safe area (px)', zh: '安全区域(像素)' },
+ 'set.screenPreset.safeTop': { en: 'Top', zh: '上' },
+ 'set.screenPreset.safeBottom': { en: 'Bottom', zh: '下' },
+ 'set.screenPreset.safeLeft': { en: 'Left', zh: '左' },
+ 'set.screenPreset.safeRight': { en: 'Right', zh: '右' },
'set.screenPreset.add': { en: 'Add screen', zh: '添加屏幕' },
'set.screenPreset.empty': {
en: 'No project screens — the dropdown shows the built-in devices only.',
diff --git a/desktop/src/settings/projectSettings.ts b/desktop/src/settings/projectSettings.ts
index ec2a0301b..5631a5aa8 100644
--- a/desktop/src/settings/projectSettings.ts
+++ b/desktop/src/settings/projectSettings.ts
@@ -57,6 +57,22 @@ settingsRegistry.register({
},
});
+/**
+ * What gets persisted for one row: an all-zero (or half-filled) inset is dropped
+ * rather than written, because "no safe area" and "a safe area of nothing" are
+ * the same screen, and only one of them should appear in the project file.
+ */
+function normalizeScreenPreset(p: ScreenPreset): ScreenPreset {
+ const s = p.safe;
+ const edges = s ? [s.top, s.bottom, s.left, s.right].map((n) => (Number.isFinite(n) ? Number(n) : 0)) : [];
+ if (edges.length === 0 || edges.every((n) => n <= 0)) {
+ const { safe: _drop, ...rest } = p;
+ return rest;
+ }
+ const [top, bottom, left, right] = edges.map((n) => Math.max(0, n));
+ return { ...p, safe: { top, bottom, left, right } };
+}
+
// The screens this project tests on. The built-in device list is a guess; a team
// that ships to specific hardware corrects it here, and an entry reusing a
// built-in id replaces that built-in rather than sitting beside it.
@@ -73,6 +89,15 @@ settingsRegistry.register({
{ key: 'width', label: t('set.screenPreset.width'), type: 'number', width: '84px', min: 1 },
{ key: 'height', label: t('set.screenPreset.height'), type: 'number', width: '84px', min: 1 },
],
+ // Safe-area insets ride in an expander: most screens have none, and four more
+ // columns would widen every row to serve the few that do.
+ detailColumns: [
+ { key: 'safe.top', label: t('set.screenPreset.safeTop'), type: 'number', width: '72px', min: 0 },
+ { key: 'safe.bottom', label: t('set.screenPreset.safeBottom'), type: 'number', width: '72px', min: 0 },
+ { key: 'safe.left', label: t('set.screenPreset.safeLeft'), type: 'number', width: '72px', min: 0 },
+ { key: 'safe.right', label: t('set.screenPreset.safeRight'), type: 'number', width: '72px', min: 0 },
+ ],
+ detailLabel: t('set.screenPreset.safeArea'),
addLabel: t('set.screenPreset.add'),
emptyHint: t('set.screenPreset.empty'),
// Portrait storage keeps one meaning for the orientation toggle across the
@@ -87,7 +112,7 @@ settingsRegistry.register({
},
bind: {
get: () => ProjectStore.screenPresets() as unknown as Record<string, unknown>[],
- set: (v) => void ProjectStore.setScreenPresets(v as unknown as ScreenPreset[]),
+ set: (v) => void ProjectStore.setScreenPresets((v as unknown as ScreenPreset[]).map(normalizeScreenPreset)),
},
});
diff --git a/desktop/src/settings/types.ts b/desktop/src/settings/types.ts
index 72dec72a1..630c9bf0d 100644
--- a/desktop/src/settings/types.ts
+++ b/desktop/src/settings/types.ts
@@ -142,7 +142,12 @@ export interface FlagListSetting extends BaseSetting<number[]> {
labels: () => string[];
}
-/** One editable field of an {@link ObjectListSetting} row. */
+/**
+ * One editable field of an {@link ObjectListSetting} row.
+ *
+ * `key` may be a dot path (`safe.top`), so a row's nested shape does not have to
+ * be flattened into the stored format just to be editable.
+ */
export interface ObjectListColumn {
key: string;
label: string;
@@ -166,6 +171,14 @@ export interface ObjectListColumn {
export interface ObjectListSetting extends BaseSetting<Record<string, unknown>[]> {
type: 'objectList';
columns: ObjectListColumn[];
+ /**
+ * Fields shown only when a row is expanded. For what most rows leave alone —
+ * putting them in the main table would widen every row to serve the few that
+ * need them, and a table wide enough to need scrolling is worse than a click.
+ */
+ detailColumns?: ObjectListColumn[];
+ /** Heading for the expanded area, and the expander's tooltip. */
+ detailLabel?: string;
/** Values a freshly added row starts with. */
newRow: () => Record<string, unknown>;
/** Per-row validation → message, or null when the row is fine. */
diff --git a/desktop/src/theme/settings.css b/desktop/src/theme/settings.css
index 6e51d66b9..d16aed8fc 100644
--- a/desktop/src/theme/settings.css
+++ b/desktop/src/theme/settings.css
@@ -291,6 +291,7 @@
.set-objlist-row.invalid .set-str { border-color: var(--error); }
.set-objlist-err { color: var(--error); font-size: var(--fs-2xs); padding: 2px 2px 0; }
.set-objlist-del,
+.set-objlist-more,
.set-objlist-add {
display: inline-flex;
align-items: center;
@@ -304,3 +305,20 @@
.set-objlist-add { align-self: flex-start; height: 26px; padding: 0 9px; font-size: var(--fs-xs); }
.set-objlist-add:hover { color: var(--text); background: rgba(255, 255, 255, 0.07); }
.set-objlist-empty { color: var(--text-mute); font-size: var(--fs-xs); padding: 2px 0 4px; }
+.set-objlist-more { justify-content: center; width: 24px; height: 24px; }
+.set-objlist-more:hover { color: var(--text); background: rgba(255, 255, 255, 0.07); }
+.set-objlist-more svg { transition: transform var(--t-fast); }
+.set-objlist-more.open svg { transform: rotate(90deg); }
+/* Expanded secondary fields: indented under their row so the grouping reads. */
+.set-objlist-detail {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 10px;
+ padding: 6px 0 6px 10px;
+ margin-left: 2px;
+ border-left: 1px solid var(--border-soft);
+}
+.set-objlist-detail-lbl { color: var(--text-mute); font-size: var(--fs-2xs); }
+.set-objlist-detail-f { display: flex; align-items: center; gap: 5px; color: var(--text-dim); font-size: var(--fs-2xs); }
+.set-objlist-detail-f .set-str { width: 66px; }
diff --git a/desktop/tests/screen-preset-setting.test.ts b/desktop/tests/screen-preset-setting.test.ts
index db1e656c7..360200a96 100644
--- a/desktop/tests/screen-preset-setting.test.ts
+++ b/desktop/tests/screen-preset-setting.test.ts
@@ -33,8 +33,10 @@ const setting = settingsRegistry.get('project.display.screenPresets') as never a
type: string;
layout?: string;
columns: { key: string; type: string }[];
+ detailColumns?: { key: string; type: string }[];
newRow: () => Record<string, unknown>;
rowError: (row: Record<string, unknown>, all: Record<string, unknown>[]) => string | null;
+ bind: { set: (v: Record<string, unknown>[]) => void };
};
describe('screen-preset setting descriptor', () => {
@@ -81,3 +83,39 @@ describe('screen-preset setting descriptor', () => {
});
});
});
+
+describe('safe-area insets', () => {
+ it('are edited in an expander, addressed by dot path', () => {
+ // Four more columns would widen every row to serve the few screens that
+ // have a notch, so they live behind the row's expander.
+ expect(setting.detailColumns?.map((c) => c.key))
+ .toEqual(['safe.top', 'safe.bottom', 'safe.left', 'safe.right']);
+ expect(setting.detailColumns?.every((c) => c.type === 'number')).toBe(true);
+ });
+
+ it('persist when any edge is set', async () => {
+ const { ProjectStore } = await import('@/project/ProjectStore');
+ setting.bind.set([{ id: 'a', label: 'A', width: 1170, height: 2532, safe: { top: 59, bottom: 34, left: 0, right: 0 } }]);
+ expect(ProjectStore.setScreenPresets).toHaveBeenCalledWith([
+ { id: 'a', label: 'A', width: 1170, height: 2532, safe: { top: 59, bottom: 34, left: 0, right: 0 } },
+ ]);
+ });
+
+ it('are dropped entirely when every edge is zero', async () => {
+ const { ProjectStore } = await import('@/project/ProjectStore');
+ // "No safe area" and "a safe area of nothing" are the same screen; only one
+ // of them belongs in the project file.
+ setting.bind.set([{ id: 'a', label: 'A', width: 8, height: 9, safe: { top: 0, bottom: 0, left: 0, right: 0 } }]);
+ expect(ProjectStore.setScreenPresets).toHaveBeenLastCalledWith([
+ { id: 'a', label: 'A', width: 8, height: 9 },
+ ]);
+ });
+
+ it('clamp a negative edge rather than shipping it', async () => {
+ const { ProjectStore } = await import('@/project/ProjectStore');
+ setting.bind.set([{ id: 'a', label: 'A', width: 8, height: 9, safe: { top: -5, bottom: 20, left: 0, right: 0 } }]);
+ expect(ProjectStore.setScreenPresets).toHaveBeenLastCalledWith([
+ { id: 'a', label: 'A', width: 8, height: 9, safe: { top: 0, bottom: 20, left: 0, right: 0 } },
+ ]);
+ });
+});