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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(editor): screen presets are editable in Project Settings, and manifest writes stop racing
esengine2694c5a69bc3
diff --git a/desktop/src/components/SettingsDialog.tsx b/desktop/src/components/SettingsDialog.tsxindex 627b3b6dc..0677bf2fc 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 } from 'lucide-react';+import { Settings as SettingsIcon, X, RotateCcw, FolderSearch, Plus, Trash2 } 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 } from '@/settings/types';+import type { Setting, NumberSetting, KeybindingSetting, StringListSetting, PathSetting, MatrixSetting, FlagListSetting, ObjectListSetting } from '@/settings/types';import { t } from '@/i18n';// A bound list setting's getter returns a fresh array each call; useShallow below@@ -294,6 +294,81 @@ function FlagListControl({ setting }: { setting: FlagListSetting }) {);}+/**+ * 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.+ */+const EMPTY_ROWS: readonly Record<string, unknown>[] = [];++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 cols = setting.columns;+ const grid = { gridTemplateColumns: `${cols.map((c) => c.width ?? '1fr').join(' ')} 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)));+ };++ return (+ <div className="set-objlist">+ {rows.length === 0 && setting.emptyHint && <div className="set-objlist-empty">{setting.emptyHint}</div>}+ {rows.length > 0 && (+ <div className="set-objlist-head" style={grid}>+ {cols.map((c) => <span key={c.key}>{c.label}</span>)}+ <span />+ </div>+ )}+ {rows.map((row, i) => {+ const err = setting.rowError?.(row, rows) ?? null;+ 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)}+ />+ ))}+ <button+ type="button"+ className="set-objlist-del"+ title={t('set.objList.remove')}+ onClick={() => setValue(setting.id, rows.filter((_, j) => j !== i))}+ >+ <Trash2 size={12} strokeWidth={2} />+ </button>+ </div>+ {err && <div className="set-objlist-err">{err}</div>}+ </div>+ );+ })}+ <button+ type="button"+ className="set-objlist-add"+ onClick={() => setValue(setting.id, [...rows, setting.newRow()])}+ >+ <Plus size={12} strokeWidth={2.2} /> {setting.addLabel}+ </button>+ </div>+ );+}+function Control({ setting }: { setting: Setting }) {const setValue = useSettings((s) => s.setValue);// useShallow: a bound list setting returns a fresh array each read, which would@@ -385,6 +460,8 @@ function Control({ setting }: { setting: Setting }) {return <MatrixControl setting={setting} />;case 'flagList':return <FlagListControl setting={setting} />;+ case 'objectList':+ return <ObjectListControl setting={setting} />;}}@@ -392,7 +469,7 @@ function Row({ setting }: { setting: Setting }) {const isChanged = useSettings((s) => s.isChanged(setting.id));const reset = useSettings((s) => s.reset);return (- <div className={`set-row${isChanged ? ' changed' : ''}`}>+ <div className={`set-row${isChanged ? ' changed' : ''}${setting.layout === 'block' ? ' set-row--block' : ''}`}><div><div className="sn">{setting.label}</div>{setting.description && <div className="sd">{setting.description}</div>}diff --git a/desktop/src/i18n/messages/project.ts b/desktop/src/i18n/messages/project.tsindex 513d9d528..ce6cd7ce3 100644--- a/desktop/src/i18n/messages/project.ts+++ b/desktop/src/i18n/messages/project.ts@@ -314,6 +314,7 @@ export const projectMessages = defineMessages({zh: '{instances} 个预制体实例上的 {overrides} 处覆盖已与预制体不符,已被丢弃',},'proj.saveSortingLayersFailed': { en: 'Failed to save sorting layers', zh: '保存排序层失败' },+ 'proj.saveScreenPresetsFailed': { en: 'Failed to save screen presets', zh: '保存屏幕预设失败' },'proj.saveDesignResolutionFailed': { en: 'Failed to save design resolution', zh: '保存设计分辨率失败' },'proj.savePackagingFailed': { en: 'Failed to save packaging settings', zh: '保存打包设置失败' },'proj.saveAssetGroupsFailed': { en: 'Failed to save asset delivery config', zh: '保存资产交付配置失败' },diff --git a/desktop/src/i18n/messages/settings.ts b/desktop/src/i18n/messages/settings.tsindex 67be7d7d4..8d4e9f4ab 100644--- a/desktop/src/i18n/messages/settings.ts+++ b/desktop/src/i18n/messages/settings.ts@@ -88,6 +88,24 @@ export const settingsMessages = defineMessages({'set.group.background': { en: 'Background', zh: '后台' },'set.group.console': { en: 'Console', zh: '控制台' },'set.group.renderer': { en: 'Renderer', zh: '渲染器' },+ 'set.project.display.screenPresets': { en: 'Screen presets', zh: '屏幕预设' },+ 'set.project.display.screenPresets.desc': {+ en: 'Extra screens the viewport and Game view can simulate, on top of the built-in devices. Reusing a built-in id (iphone, ipad, 1080p, 720p) replaces it.',+ zh: '视口与游戏视图可模拟的额外屏幕,叠加在内置设备之上。使用与内置相同的 id(iphone、ipad、1080p、720p)即可替换它。',+ },+ 'set.screenPreset.id': { en: 'Id', zh: '标识' },+ 'set.screenPreset.label': { en: 'Name', zh: '名称' },+ 'set.screenPreset.width': { en: 'Width', zh: '宽' },+ 'set.screenPreset.height': { en: 'Height', zh: '高' },+ 'set.screenPreset.add': { en: 'Add screen', zh: '添加屏幕' },+ 'set.screenPreset.empty': {+ en: 'No project screens — the dropdown shows the built-in devices only.',+ zh: '尚无项目屏幕——下拉中只显示内置设备。',+ },+ 'set.screenPreset.errId': { en: 'An id is required (it is what a saved selection refers to)', zh: '必须填写标识(已保存的选择依据它解析)' },+ 'set.screenPreset.errDup': { en: 'This id is used by another row', zh: '该标识与其它行重复' },+ 'set.screenPreset.errSize': { en: 'Width and height must both be above zero', zh: '宽和高都必须大于 0' },+ 'set.objList.remove': { en: 'Remove', zh: '移除' },'set.group.designResolution': { en: 'Design Resolution', zh: '设计分辨率' },'set.group.sortingLayers': { en: 'Sorting Layers', zh: '排序层' },'set.group.ySort': { en: 'Y-Sort', zh: 'Y 轴排序' },diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.tsindex 0b9f47ac6..285b8a38d 100644--- a/desktop/src/project/ProjectStore.ts+++ b/desktop/src/project/ProjectStore.ts@@ -113,6 +113,8 @@ interface PreloadResult {fontHandles: Map<string, number>;}+const NO_SCREEN_PRESETS: ScreenPreset[] = [];+interface ProjectState {root: string;name: string;@@ -1642,17 +1644,12 @@ class ProjectStoreImpl {else delete features.ui;this.store.setState({ project: { ...st, features } });applyWidgetTheme(this.uiTheme(), this.uiThemeOverrides());- try {- const raw = JSON.parse(await window.estella.fs.read(PROJECT_MANIFEST_FILE)) as Record<string, unknown>;- const rf = { ...(raw.features as Record<string, unknown> ?? {}) };- if (ui) rf.ui = ui;- else delete rf.ui;- raw.features = rf;- await window.estella.fs.write(PROJECT_MANIFEST_FILE, JSON.stringify(raw, null, 2) + '\n');- } catch (e) {- Toasts.push(t('proj.saveUiThemeFailed'), 'error');- console.error('[project] patchUiFeature write failed', e);- }+ await this.patchManifest((raw) => {+ const rf = { ...(raw.features as Record<string, unknown> ?? {}) };+ if (ui) rf.ui = ui;+ else delete rf.ui;+ raw.features = rf;+ }, t('proj.saveUiThemeFailed'));}/**@@ -1665,14 +1662,9 @@ class ProjectStoreImpl {if (!st) return;const features: ProjectFeatures = { ...st.features, audio: config };this.store.setState({ project: { ...st, features } });- try {- const raw = JSON.parse(await window.estella.fs.read(PROJECT_MANIFEST_FILE)) as Record<string, unknown>;- raw.features = { ...(raw.features as Record<string, unknown> ?? {}), audio: config };- await window.estella.fs.write(PROJECT_MANIFEST_FILE, JSON.stringify(raw, null, 2) + '\n');- } catch (e) {- Toasts.push(t('proj.saveAudioFailed'), 'error');- console.error('[project] setAudio write failed', e);- }+ await this.patchManifest((raw) => {+ raw.features = { ...(raw.features as Record<string, unknown> ?? {}), audio: config };+ }, t('proj.saveAudioFailed'));}/** The project's declared physics feature, with defaults (for Project Settings). The@@ -1765,14 +1757,9 @@ class ProjectStoreImpl {const features: ProjectFeatures = { ...st.features, rendering };this.store.setState({ project: { ...st, features } });Renderer.setYSortLayers(this.ySortMask());- try {- const raw = JSON.parse(await window.estella.fs.read(PROJECT_MANIFEST_FILE)) as Record<string, unknown>;- raw.features = { ...((raw.features as Record<string, unknown>) ?? {}), rendering };- await window.estella.fs.write(PROJECT_MANIFEST_FILE, JSON.stringify(raw, null, 2) + '\n');- } catch (e) {- Toasts.push(t('proj.saveSortingLayersFailed'), 'error');- console.error('[project] setRendering write failed', e);- }+ await this.patchManifest((raw) => {+ raw.features = { ...((raw.features as Record<string, unknown>) ?? {}), rendering };+ }, t('proj.saveSortingLayersFailed'));}/** Project reference resolution — the seed for new Canvas entities. Falls back to@@ -1788,14 +1775,61 @@ class ProjectStoreImpl {if (!st) return;const designResolution: DesignResolution = { ...this.designResolution(), ...patch };this.store.setState({ project: { ...st, designResolution } });- try {- const raw = JSON.parse(await window.estella.fs.read(PROJECT_MANIFEST_FILE)) as Record<string, unknown>;- raw.designResolution = designResolution;- await window.estella.fs.write(PROJECT_MANIFEST_FILE, JSON.stringify(raw, null, 2) + '\n');- } catch (e) {- Toasts.push(t('proj.saveDesignResolutionFailed'), 'error');- console.error('[project] setDisplay write failed', e);- }+ await this.patchManifest((raw) => { raw.designResolution = designResolution; },+ t('proj.saveDesignResolutionFailed'));+ }++ /**+ * Read-modify-write the project manifest, SERIALLY.+ *+ * Every writer here is a read-modify-write, and they used to race: two edits+ * in flight at once both read the pre-edit file, and the second write lands on+ * top of the first — losing it, or, when the writes interleave, leaving the+ * file with trailing garbage that no longer parses. That is not hypothetical;+ * typing across the fields of one settings row produced exactly it.+ *+ * Patches queue on one chain, so each sees what the previous one wrote.+ */+ private manifestWrites: Promise<void> = Promise.resolve();++ private patchManifest(apply: (raw: Record<string, unknown>) => void, failMessage: string): Promise<boolean> {+ const done = this.manifestWrites.then(async () => {+ try {+ const raw = JSON.parse(await window.estella.fs.read(PROJECT_MANIFEST_FILE)) as Record<string, unknown>;+ apply(raw);+ await window.estella.fs.write(PROJECT_MANIFEST_FILE, JSON.stringify(raw, null, 2) + '\n');+ return true;+ } catch (e) {+ Toasts.push(failMessage, 'error');+ console.error('[project] manifest write failed', e);+ return false;+ }+ });+ // The chain carries no value, so one failed patch cannot stall the next.+ this.manifestWrites = done.then(() => undefined);+ return done;+ }++ /** The project's declared screens (empty when it declares none). The empty+ * case is ONE array, not a fresh one per call: callers select on it, and a+ * new reference every read is an infinite re-render. */+ screenPresets(): ScreenPreset[] {+ return this.state?.screenPresets ?? NO_SCREEN_PRESETS;+ }++ /**+ * Replace the declared screens. Entries are written verbatim so a half-typed+ * row survives a dialog round-trip; `parseManifest` is what decides which of+ * them a LOAD accepts, keeping one validator rather than two that drift.+ */+ async setScreenPresets(presets: ScreenPreset[]): Promise<void> {+ const st = this.state;+ if (!st) return;+ this.store.setState({ project: { ...st, screenPresets: presets } });+ await this.patchManifest((raw) => {+ if (presets.length > 0) raw.screenPresets = presets;+ else delete raw.screenPresets;+ }, t('proj.saveScreenPresetsFailed'));}/** Persisted Package Project settings (last target/config/output), or {}. */@@ -1814,14 +1848,9 @@ class ProjectStoreImpl {outDir: { ...st.packaging?.outDir, ...patch.outDir },};this.store.setState({ project: { ...st, packaging } });- try {- const raw = JSON.parse(await window.estella.fs.read(PROJECT_MANIFEST_FILE)) as Record<string, unknown>;- raw.packaging = packaging;- await window.estella.fs.write(PROJECT_MANIFEST_FILE, JSON.stringify(raw, null, 2) + '\n');- } catch (e) {- Toasts.push(t('proj.savePackagingFailed'), 'error');- console.error('[project] setPackaging write failed', e);- }+ await this.patchManifest((raw) => {+ raw.packaging = packaging;+ }, t('proj.savePackagingFailed'));}// ── Asset delivery groups (.esengine/asset-groups.json) ──────────────────────@@ -1901,14 +1930,9 @@ class ProjectStoreImpl {const platforms = { ...prev, [platform]: { ...prev[platform], ...patch } } as NonNullable<ProjectPackaging['platforms']>;const packaging: ProjectPackaging = { ...st.packaging, platforms };this.store.setState({ project: { ...st, packaging } });- try {- const raw = JSON.parse(await window.estella.fs.read(PROJECT_MANIFEST_FILE)) as Record<string, unknown>;- raw.packaging = packaging;- await window.estella.fs.write(PROJECT_MANIFEST_FILE, JSON.stringify(raw, null, 2) + '\n');- } catch (e) {- Toasts.push(t('proj.savePlatformFailed'), 'error');- console.error('[project] setPlatformPackaging write failed', e);- }+ await this.patchManifest((raw) => {+ raw.packaging = packaging;+ }, t('proj.savePlatformFailed'));}/**@@ -1924,14 +1948,9 @@ class ProjectStoreImpl {const physics: NonNullable<ProjectFeatures['physics']> = { ...st.features?.physics, ...patch };const features: ProjectFeatures = { ...st.features, physics };this.store.setState({ project: { ...st, features } });- try {- const raw = JSON.parse(await window.estella.fs.read(PROJECT_MANIFEST_FILE)) as Record<string, unknown>;- raw.features = { ...(raw.features as Record<string, unknown> ?? {}), physics };- await window.estella.fs.write(PROJECT_MANIFEST_FILE, JSON.stringify(raw, null, 2) + '\n');- } catch (e) {- Toasts.push(t('proj.savePhysicsFailed'), 'error');- console.error('[project] setPhysics write failed', e);- }+ await this.patchManifest((raw) => {+ raw.features = { ...(raw.features as Record<string, unknown> ?? {}), physics };+ }, t('proj.savePhysicsFailed'));}/**@@ -1946,22 +1965,19 @@ class ProjectStoreImpl {// The startup scene always ships — becoming it lifts any export exclusion.const packaging = this.packagingWithoutExclusion_(st.packaging, path);this.store.setState({ project: { ...st, defaultScene: path, packaging } });- try {- const raw = JSON.parse(await window.estella.fs.read(PROJECT_MANIFEST_FILE)) as Record<string, unknown>;- raw.defaultScene = path;- if (packaging !== st.packaging) {- // Merge into the RAW packaging so fields the editor parser doesn't- // model survive the rewrite.- const rawPkg = { ...((raw.packaging as Record<string, unknown>) ?? {}) };- if (packaging?.excludeScenes) rawPkg.excludeScenes = packaging.excludeScenes;- else delete rawPkg.excludeScenes;- raw.packaging = rawPkg;- }- await window.estella.fs.write(PROJECT_MANIFEST_FILE, JSON.stringify(raw, null, 2) + '\n');- Toasts.push(t('proj.startupScene', { name: path.split('/').pop() ?? path }), 'info');- } catch (e) {- Toasts.push(t('proj.saveStartupSceneFailed'), 'error');- console.error('[project] setDefaultScene write failed', e);+ const ok = await this.patchManifest((raw) => {+ raw.defaultScene = path;+ if (packaging !== st.packaging) {+ // Merge into the RAW packaging so fields the editor parser doesn't+ // model survive the rewrite.+ const rawPkg = { ...((raw.packaging as Record<string, unknown>) ?? {}) };+ if (packaging?.excludeScenes) rawPkg.excludeScenes = packaging.excludeScenes;+ else delete rawPkg.excludeScenes;+ raw.packaging = rawPkg;+ }+ }, t('proj.saveStartupSceneFailed'));+ if (ok) {+ Toasts.push(t('proj.startupScene', { name: path.split('/').pop() ?? path }), 'info');}}@@ -1990,20 +2006,17 @@ class ProjectStoreImpl {if (cur.size > 0) packaging.excludeScenes = [...cur].sort();else delete packaging.excludeScenes;this.store.setState({ project: { ...st, packaging } });- try {- const raw = JSON.parse(await window.estella.fs.read(PROJECT_MANIFEST_FILE)) as Record<string, unknown>;- // Merge into the RAW packaging so fields the editor parser doesn't model- // survive the rewrite.- const rawPkg = { ...((raw.packaging as Record<string, unknown>) ?? {}) };- if (packaging.excludeScenes) rawPkg.excludeScenes = packaging.excludeScenes;- else delete rawPkg.excludeScenes;- raw.packaging = rawPkg;- await window.estella.fs.write(PROJECT_MANIFEST_FILE, JSON.stringify(raw, null, 2) + '\n');- const leaf = path.split('/').pop() ?? path;- Toasts.push(t(excluded ? 'proj.excludedFromExport' : 'proj.includedInExport', { name: leaf }), 'info');- } catch (e) {- Toasts.push(t('proj.saveExclusionFailed'), 'error');- console.error('[project] setSceneExcluded write failed', e);+ const ok = await this.patchManifest((raw) => {+ // Merge into the RAW packaging so fields the editor parser doesn't model+ // survive the rewrite.+ const rawPkg = { ...((raw.packaging as Record<string, unknown>) ?? {}) };+ if (packaging.excludeScenes) rawPkg.excludeScenes = packaging.excludeScenes;+ else delete rawPkg.excludeScenes;+ raw.packaging = rawPkg;+ }, t('proj.saveExclusionFailed'));+ if (ok) {+ const leaf = path.split('/').pop() ?? path;+ Toasts.push(t(excluded ? 'proj.excludedFromExport' : 'proj.includedInExport', { name: leaf }), 'info');}}diff --git a/desktop/src/settings/projectSettings.ts b/desktop/src/settings/projectSettings.tsindex 8da25eb98..ec2a0301b 100644--- a/desktop/src/settings/projectSettings.ts+++ b/desktop/src/settings/projectSettings.ts@@ -14,7 +14,7 @@ import { rgbaToHex8 } from '@/components/ColorControl';import { EngineHost } from '@/engine/EngineHost';import { Toasts } from '@/store/Toasts';import { useEditorMode } from '@/store/editorModeStore';-import type { ScreenOrientation, CameraScaleMode } from '@/project/format';+import type { ScreenOrientation, CameraScaleMode, ScreenPreset } from '@/project/format';import { t } from '@/i18n';const ORIENTATION = [@@ -57,6 +57,40 @@ settingsRegistry.register({},});+// 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.+settingsRegistry.register({+ id: 'project.display.screenPresets',+ type: 'objectList', scope: 'project', section: 'display', group: t('set.group.designResolution'),+ label: t('set.project.display.screenPresets'),+ description: t('set.project.display.screenPresets.desc'),+ layout: 'block',+ default: [],+ columns: [+ { key: 'id', label: t('set.screenPreset.id'), type: 'text', width: '120px', placeholder: 'my-device' },+ { key: 'label', label: t('set.screenPreset.label'), type: 'text', width: '1fr', placeholder: 'My Device' },+ { 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 },+ ],+ addLabel: t('set.screenPreset.add'),+ emptyHint: t('set.screenPreset.empty'),+ // Portrait storage keeps one meaning for the orientation toggle across the+ // built-ins and a project's own, so a swap is always the same operation.+ newRow: () => ({ id: '', label: '', width: 1080, height: 1920 }),+ rowError: (row, all) => {+ const id = String(row.id ?? '').trim();+ if (!id) return t('set.screenPreset.errId');+ if (all.filter((r) => String(r.id ?? '').trim() === id).length > 1) return t('set.screenPreset.errDup');+ if (!(Number(row.width) > 0) || !(Number(row.height) > 0)) return t('set.screenPreset.errSize');+ return null;+ },+ bind: {+ get: () => ProjectStore.screenPresets() as unknown as Record<string, unknown>[],+ set: (v) => void ProjectStore.setScreenPresets(v as unknown as ScreenPreset[]),+ },+});+// Project-wide screen orientation — one value every export target reads (WeChat// game.json, the web/playable rotate hint, the desktop window aspect). Shown as the// resolved value (explicit, else derived from the design resolution's aspect); thediff --git a/desktop/src/settings/types.ts b/desktop/src/settings/types.tsindex b25ae5db0..72dec72a1 100644--- a/desktop/src/settings/types.ts+++ b/desktop/src/settings/types.ts@@ -36,6 +36,13 @@ interface BaseSetting<T> {label: string;description?: string;default: T;+ /**+ * Row layout. `inline` (default) puts the control in the fixed right-hand+ * column beside the label; `block` stacks it under the label at full width,+ * for controls a 230px column cannot hold — a table, a list that grows.+ * Orthogonal to `type`, so a wide control does not need its own row plumbing.+ */+ layout?: 'inline' | 'block';/** Two-way delegation to a live store; when present the store owns the value. */bind?: { get: () => T; set: (value: T) => void };/** One-way push to runtime for store-owned settings (on set + on hydrate). */@@ -135,6 +142,39 @@ export interface FlagListSetting extends BaseSetting<number[]> {labels: () => string[];}+/** One editable field of an {@link ObjectListSetting} row. */+export interface ObjectListColumn {+ key: string;+ label: string;+ type: 'text' | 'number';+ /** Grid track for this column (CSS), e.g. '1fr' or '68px'. Defaults to 1fr. */+ width?: string;+ placeholder?: string;+ min?: number;+}++/**+ * A list of structured rows the user can add to, edit and remove — unlike+ * {@link StringListSetting} and {@link MatrixSetting}, whose length is fixed by+ * the schema. The first user is the project's screen presets; the shape is+ * general because "a table of things this project declares" is not.+ *+ * Rows are plain objects keyed by {@link columns}. `rowError` is checked per+ * row and shown inline rather than blocking the edit — a half-typed row is a+ * normal state, and refusing the keystroke is how a form becomes unusable.+ */+export interface ObjectListSetting extends BaseSetting<Record<string, unknown>[]> {+ type: 'objectList';+ columns: ObjectListColumn[];+ /** Values a freshly added row starts with. */+ newRow: () => Record<string, unknown>;+ /** Per-row validation → message, or null when the row is fine. */+ rowError?: (row: Record<string, unknown>, all: Record<string, unknown>[]) => string | null;+ addLabel: string;+ /** Shown in place of the table when the list is empty. */+ emptyHint?: string;+}+export type Setting =| BooleanSetting| NumberSetting@@ -146,6 +186,7 @@ export type Setting =| KeybindingSetting| StringListSetting| MatrixSetting- | FlagListSetting;+ | FlagListSetting+ | ObjectListSetting;-export type SettingValue = boolean | number | string | string[] | number[];+export type SettingValue = boolean | number | string | string[] | number[] | Record<string, unknown>[];diff --git a/desktop/src/theme/settings.css b/desktop/src/theme/settings.cssindex c2c3fbc4e..6e51d66b9 100644--- a/desktop/src/theme/settings.css+++ b/desktop/src/theme/settings.css@@ -276,3 +276,31 @@padding: 8px 12px; cursor: pointer; font: inherit;}.mix-add:hover { color: var(--text); border-color: var(--line-strong); }++/* Block row: the control stacks under its label at full width, for anything a+ 230px column cannot hold. Set by `layout: 'block'` on the descriptor. */+.set-row--block { grid-template-columns: 1fr 18px; }+.set-row--block .set-ctrl { grid-column: 1 / -1; justify-content: stretch; }++/* Editable table of project-declared rows (screen presets today). */+.set-objlist { display: flex; flex-direction: column; gap: 4px; width: 100%; }+.set-objlist-head,+.set-objlist-fields { display: grid; gap: 6px; align-items: center; }+.set-objlist-head { font-size: var(--fs-2xs); color: var(--text-mute); padding: 0 2px; }+.set-objlist .set-str { width: 100%; font-family: var(--mono); }+.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-add {+ display: inline-flex;+ align-items: center;+ gap: 5px;+ color: var(--text-mute);+ border-radius: var(--r-sm);+ transition: color var(--t-fast), background var(--t-fast);+}+.set-objlist-del { justify-content: center; width: 24px; height: 24px; }+.set-objlist-del:hover { color: var(--error); background: color-mix(in srgb, var(--error) 14%, transparent); }+.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; }diff --git a/desktop/tests/screen-preset-setting.test.ts b/desktop/tests/screen-preset-setting.test.tsnew file mode 100644index 000000000..db1e656c7--- /dev/null+++ b/desktop/tests/screen-preset-setting.test.ts@@ -0,0 +1,83 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The screen-preset editor, as a settings descriptor.+ *+ * The settings system is declarative — "new setting = new descriptor, the UI+ * needs no change" — so what is worth pinning is the DESCRIPTOR: its columns,+ * the row it seeds, and above all its validation. An id is what a saved device+ * selection resolves through, so a blank or duplicated one has to be caught+ * where the user can still see it, not silently at load.+ */+import { describe, it, expect, vi } from 'vitest';++vi.mock('@/project/ProjectStore', () => ({+ ProjectStore: {+ screenPresets: () => [],+ setScreenPresets: vi.fn(),+ designResolution: () => ({ width: 1920, height: 1080 }),+ resolvedOrientation: () => 'landscape',+ setDisplay: vi.fn(),+ setPackaging: vi.fn(),+ setFeatures: vi.fn(),+ features: () => ({}),+ subscribe: () => () => {},+ getSnapshot: () => null,+ },+}));++await import('@/settings/projectSettings');+const { settingsRegistry } = await import('@/settings/registry');++const setting = settingsRegistry.get('project.display.screenPresets') as never as {+ type: string;+ layout?: string;+ columns: { key: string; type: string }[];+ newRow: () => Record<string, unknown>;+ rowError: (row: Record<string, unknown>, all: Record<string, unknown>[]) => string | null;+};++describe('screen-preset setting descriptor', () => {+ it('is registered as a full-width object list', () => {+ expect(setting).toBeDefined();+ expect(setting.type).toBe('objectList');+ // A four-column table does not fit the dialog's fixed control column.+ expect(setting.layout).toBe('block');+ expect(setting.columns.map((c) => c.key)).toEqual(['id', 'label', 'width', 'height']);+ });++ it('seeds a new row portrait, like the built-ins store theirs', () => {+ // One meaning for the orientation toggle across built-in and project screens:+ // a swap is always the same operation.+ const row = setting.newRow();+ expect(Number(row.height)).toBeGreaterThan(Number(row.width));+ });++ describe('row validation', () => {+ const ok = { id: 'deck', label: 'Steam Deck', width: 800, height: 1280 };++ it('accepts a complete row', () => {+ expect(setting.rowError(ok, [ok])).toBeNull();+ });++ it('requires an id — it is what a saved selection refers to', () => {+ expect(setting.rowError({ ...ok, id: '' }, [{ ...ok, id: '' }])).toBeTruthy();+ expect(setting.rowError({ ...ok, id: ' ' }, [{ ...ok, id: ' ' }])).toBeTruthy();+ });++ it('rejects a duplicate id rather than letting one row shadow another', () => {+ const dup = [ok, { ...ok, label: 'Other' }];+ expect(setting.rowError(ok, dup)).toBeTruthy();+ });++ it('rejects non-positive dimensions', () => {+ expect(setting.rowError({ ...ok, width: 0 }, [ok])).toBeTruthy();+ expect(setting.rowError({ ...ok, height: -5 }, [ok])).toBeTruthy();+ });++ it('reports the problem instead of blocking the keystroke', () => {+ // A half-typed row is a normal state; the message is what tells the user.+ expect(typeof setting.rowError({ ...ok, id: '' }, [])).toBe('string');+ });+ });+});