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): a packaging target's settings are edited on its own page

esenginef0c9eb52d3f3
diff --git a/desktop/src/commands/editorCommands.ts b/desktop/src/commands/editorCommands.ts
index bab027d4b..d79334a6a 100644
--- a/desktop/src/commands/editorCommands.ts
+++ b/desktop/src/commands/editorCommands.ts
@@ -116,7 +116,10 @@ commands.register({
category: t('cat.build'),
keybinding: 'mod+shift+b',
isEnabled: () => !!ProjectStore.getSnapshot(),
- run: () => editor().setBuildOpen(true),
+ // No target named: the dialog resumes where the project left off. Going through
+ // openBuild rather than setBuildOpen is what CLEARS a target another entry point
+ // asked for, so one trip through settings search does not pin every later build.
+ run: () => editor().openBuild(),
});
commands.register({
id: 'project.close',
diff --git a/desktop/src/components/BuildDialog.tsx b/desktop/src/components/BuildDialog.tsx
index 09169dd7f..977a79598 100644
--- a/desktop/src/components/BuildDialog.tsx
+++ b/desktop/src/components/BuildDialog.tsx
@@ -22,6 +22,11 @@
* authored per asset in the Inspector's Import Settings; the build only
* chooses whether to HONOR those settings (`assetCompression: 'auto'`) or
* skip them for fast iteration (`'skip'`). Every target is live.
+ *
+ * What a TARGET is configured with (a WeChat appid, the desktop channel,
+ * Steam's ids) is declared in the settings registry with a `platform` and
+ * rendered here by the same row renderer the settings window uses — which
+ * omits those rows, so each value has exactly one editor.
*/
import { useState, useEffect, useSyncExternalStore, type ReactNode } from 'react';
import {
@@ -29,6 +34,7 @@ import {
Globe, Monitor, MessageSquare, ChevronRight, Smartphone, Apple, Package, TriangleAlert, Plus,
} from 'lucide-react';
import type { ExportPlatform, NativeToolchain, PlatformPrereq } from '@/project/platforms';
+import { platformLabel } from '@/project/platformLabels';
import type { PlayableNetworkOption } from '../../electron/platformCatalog';
import type { BuildSizeReport } from '../../electron/sizeReport';
import { formatBytes } from '@/project/sizeBudget';
@@ -37,6 +43,8 @@ import { Modal } from '@/components/Modal';
import { Segmented } from '@/components/Segmented';
import { Select } from '@/components/Select';
import { Button } from '@/components/Button';
+import { Group as SettingsGroup, groupByGroup } from '@/components/SettingsRow';
+import { settingsRegistry } from '@/settings/registry';
import { ProjectStore } from '@/project/ProjectStore';
import { AssetRegistry } from '@/project/AssetRegistry';
import { useEditorStore } from '@/store/editorStore';
@@ -124,25 +132,25 @@ interface PlatformDef {
* inlines the WEB runtime, not a `-t playable` one. */
const BUILTIN_PLATFORMS: PlatformDef[] = [
{
- id: 'web', label: t('build.plat.web'), ready: true, category: 'general', icon: <Globe size={17} />,
+ id: 'web', label: platformLabel('web'), ready: true, category: 'general', icon: <Globe size={17} />,
blurb: t('build.blurb.web'),
defaultOut: 'dist-web', sourceMaps: true, httpPreview: true,
next: (o) => t('build.next.web', { out: o }),
},
{
- id: 'desktop', label: t('build.plat.desktop'), ready: true, category: 'general', icon: <Monitor size={17} />,
+ id: 'desktop', label: platformLabel('desktop'), ready: true, category: 'general', icon: <Monitor size={17} />,
blurb: t('build.blurb.desktop'),
defaultOut: 'dist-desktop', sourceMaps: true,
next: (o) => t('build.next.desktop', { out: o }),
},
{
- id: 'wechat', label: t('build.plat.wechat'), ready: true, category: 'minigame', icon: <MessageSquare size={17} />,
+ id: 'wechat', label: platformLabel('wechat'), ready: true, category: 'minigame', icon: <MessageSquare size={17} />,
blurb: t('build.blurb.wechat'),
defaultOut: 'dist-wechat', sourceMaps: false,
next: (o) => t('build.next.wechat', { out: o }),
},
{
- id: 'playable', label: t('build.plat.playable'), ready: true, category: 'general', icon: <Play size={16} />,
+ id: 'playable', label: platformLabel('playable'), ready: true, category: 'general', icon: <Play size={16} />,
blurb: t('build.blurb.playable'),
defaultOut: 'dist-playable', sourceMaps: false, httpPreview: true,
next: () => t('build.next.playable'),
@@ -152,13 +160,13 @@ const BUILTIN_PLATFORMS: PlatformDef[] = [
// everything AROUND that differs: the toolchain, whether this machine has it,
// and the command that turns the content into an installable app.
{
- id: 'android', label: t('build.plat.android'), ready: true, category: 'mobile', icon: <Smartphone size={17} />,
+ id: 'android', label: platformLabel('android'), ready: true, category: 'mobile', icon: <Smartphone size={17} />,
blurb: t('build.blurb.android'),
defaultOut: 'dist-android', sourceMaps: false,
next: (o) => t('build.next.android', { out: o }),
},
{
- id: 'ios', label: t('build.plat.ios'), ready: true, category: 'mobile', icon: <Apple size={17} />,
+ id: 'ios', label: platformLabel('ios'), ready: true, category: 'mobile', icon: <Apple size={17} />,
blurb: t('build.blurb.ios'),
defaultOut: 'dist-ios', sourceMaps: false,
next: (o) => t('build.next.ios', { out: o }),
@@ -223,7 +231,9 @@ export function BuildDialog() {
// Restore the project's persisted Package Project settings (project.esproject).
const [saved] = useState(() => ProjectStore.packagingSettings());
- const initialPlatform: Platform = saved.platform ?? 'web';
+ // Something elsewhere may mean a specific target's page (settings search landing
+ // on a row that is edited here); otherwise resume where the project left off.
+ const initialPlatform: Platform = useEditorStore.getState().buildPlatform ?? saved.platform ?? 'web';
const initialDef = BUILTIN_PLATFORMS.find((p) => p.id === initialPlatform) ?? BUILTIN_PLATFORMS[0];
// The built-ins are what we can draw immediately; readiness and the project's
@@ -248,11 +258,6 @@ export function BuildDialog() {
// that is a per-build decision, not a property of the project. The list arrives from
// the main process, since it includes the networks the PROJECT defines.
const [adNetwork, setAdNetwork] = useState<string>(saved.platforms?.playable?.network ?? 'generic');
- // The Play upload format, beside the installable APK. A per-build decision that
- // the project remembers, like the ad network above.
- const [appBundle, setAppBundle] = useState(saved.platforms?.android?.appBundle ?? false);
- const [androidOutput, setAndroidOutput] = useState<'package' | 'project'>(
- saved.platforms?.android?.output ?? 'package');
const [adNetworks, setAdNetworks] = useState<PlayableNetworkOption[]>([]);
const [advOpen, setAdvOpen] = useState(false);
const [copiedFix, setCopiedFix] = useState(false);
@@ -275,6 +280,10 @@ export function BuildDialog() {
const [cdnRoot, setCdnRoot] = useState(() => ProjectStore.activeProfileRemoteRoot());
const def = platforms.find((p) => p.id === platform) ?? platforms[0];
+ // Re-derived per render rather than memoized: `visibleWhen` reads the project
+ // (a Steam depot id exists only on a Steam channel), and `project` above is what
+ // re-renders this dialog when that answer changes.
+ const platformSettings = groupByGroup(settingsRegistry.settingsForPlatform(platform));
const running = phase === 'running';
// Bumped when something the probes read changes on disk (a runtime template is
// installed), so the rows re-probe instead of the dialog having to be reopened.
@@ -511,8 +520,6 @@ export function BuildDialog() {
// Awaited, not fired-and-forgotten: the export resolves the network from the
// manifest, so a race here would package for the previous one.
if (platform === 'playable') await ProjectStore.setPlatformPackaging('playable', { network: adNetwork });
- // Same reason: the export reads the bundle choice from the manifest.
- if (platform === 'android') await ProjectStore.setPlatformPackaging('android', { appBundle, output: androidOutput });
// 'auto' → honor each asset's Import Settings (the cook then reads per-asset
// texture/audio compression + Max Size); 'skip' → ship everything raw.
const compress = assetCompression === 'auto';
@@ -766,31 +773,22 @@ export function BuildDialog() {
</div>
)}
+ {/* What this TARGET is — its identifier, its channel, the ids a store knows
+ it by. Declared in the settings registry with a `platform` and rendered
+ by the settings row renderer, so the row a developer edits here is the
+ same row, with the same reset and the same persistence, as every other
+ project setting. */}
+ {platformSettings.length > 0 && (
+ <Group title={t('build.secTarget', { platform: def.label })}>
+ <div className="build__settings">
+ {platformSettings.map((g) => (
+ <SettingsGroup key={g.label} label={g.label} settings={g.settings} />
+ ))}
+ </div>
+ </Group>
+ )}
+
<Group title={t('build.secBuild')}>
- {platform === 'android' && (
- <>
- <div className="build__row">
- <span className="build__label" title={t('build.androidOutputTip')}>{t('build.androidOutput')}</span>
- <Select
- ariaLabel={t('build.androidOutput')}
- value={androidOutput}
- options={[
- { value: 'package', label: t('build.androidOutput.package') },
- { value: 'project', label: t('build.androidOutput.project') },
- ]}
- onChange={(v) => setAndroidOutput(v as 'package' | 'project')}
- />
- </div>
- {/* An App Bundle is a second FORMAT of the package; a project builds
- whichever format its own Gradle build is asked for. */}
- {androidOutput === 'package' && (
- <label className="build__opt" title={t('build.appBundleTip')}>
- <input type="checkbox" checked={appBundle} onChange={(e) => setAppBundle(e.target.checked)} />
- {t('build.appBundle')}
- </label>
- )}
- </>
- )}
{platform === 'playable' && (
<>
<div className="build__row">
diff --git a/desktop/src/components/SettingsDialog.tsx b/desktop/src/components/SettingsDialog.tsx
index 083996dc1..ffa89dadc 100644
--- a/desktop/src/components/SettingsDialog.tsx
+++ b/desktop/src/components/SettingsDialog.tsx
@@ -4,756 +4,31 @@
* @file SettingsDialog.tsx — the settings window (the design's `.set-*`), driven
* entirely by the settings registry + store. The dialog knows nothing about
* individual settings: it renders nav from registered sections and rows from
- * registered descriptors, picking a control by `type`. Search filters across
- * sections; a reset arrow shows when a value differs from its default.
+ * registered descriptors (SettingsRow.tsx). Search filters across sections.
+ *
+ * A setting belonging to a packaging target is edited on that target's page
+ * in Package Project instead; `settingsForSection` leaves those out, so this
+ * file needs no list of which ones they are.
*/
-import { useEffect, useRef, useState, useSyncExternalStore } from 'react';
-import type { PointerEvent as ReactPointerEvent } from 'react';
+import { useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
-import { useShallow } from 'zustand/react/shallow';
-import { Settings as SettingsIcon, X, RotateCcw, FolderSearch, Plus, Trash2, ChevronRight, Check, KeyRound } from 'lucide-react';
+import { Settings as SettingsIcon, X, ExternalLink } from 'lucide-react';
import { useEditorStore } from '@/store/editorStore';
-import { useSettings } from '@/store/settingsStore';
import { settingsRegistry } from '@/settings/registry';
-import { eventToChord, formatKeybinding } from '@/commands/keybinding';
-import { commands } from '@/commands';
-import { Toasts } from '@/store/Toasts';
+import { platformLabel } from '@/project/platformLabels';
import { useDialogFocus } from '@/components/dialogFocus';
import { IconButton } from '@/components/IconButton';
import { SearchField } from '@/components/SearchField';
-import { Segmented } from '@/components/Segmented';
-import { Select } from '@/components/Select';
-import { ColorControl } from '@/components/ColorControl';
-import { refreshSecret, secretStatus, storeSecret, forgetSecret, subscribeSecrets } from '@/store/SecretStore';
-import type { Setting, NumberSetting, KeybindingSetting, StringListSetting, PathSetting, SecretSetting, MatrixSetting, FlagListSetting, ObjectListSetting, ObjectListColumn } from '@/settings/types';
+import { Group, groupByGroup } from '@/components/SettingsRow';
+import type { Setting } from '@/settings/types';
import { t } from '@/i18n';
-// A bound list setting's getter returns a fresh array each call; useShallow below
-// keeps the read referentially stable (else useSyncExternalStore loops). A shared
-// empty fallback avoids a fresh `[]` when a value is unset.
-const EMPTY_LIST: readonly string[] = [];
-
const CATEGORY_LABEL: Record<string, string> = {
editor: t('set.cat.editor'),
project: t('set.cat.project'),
plugin: t('set.cat.plugin'),
};
-const clamp = (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, v));
-
-function Slider({
- value, min, max, step, onChange,
-}: {
- value: number; min: number; max: number; step: number; onChange: (v: number) => void;
-}) {
- const ref = useRef<HTMLSpanElement>(null);
- const pct = max > min ? clamp(((value - min) / (max - min)) * 100, 0, 100) : 0;
- const fromClient = (clientX: number) => {
- const el = ref.current;
- if (!el) return;
- const r = el.getBoundingClientRect();
- const t = clamp((clientX - r.left) / r.width, 0, 1);
- const raw = min + t * (max - min);
- onChange(clamp(Math.round(raw / step) * step, min, max));
- };
- return (
- <span
- ref={ref}
- className="slider set-slider"
- onPointerDown={(e: ReactPointerEvent) => {
- (e.target as HTMLElement).setPointerCapture(e.pointerId);
- fromClient(e.clientX);
- }}
- onPointerMove={(e: ReactPointerEvent) => {
- if (e.buttons & 1) fromClient(e.clientX);
- }}
- >
- <span className="fill" style={{ width: `${pct}%` }} />
- <span className="thumb" style={{ left: `${pct}%` }} />
- </span>
- );
-}
-
-function NumberControl({ setting }: { setting: NumberSetting }) {
- const setValue = useSettings((s) => s.setValue);
- const value = Number(useSettings((s) => s.getValue<number>(setting.id)));
- // An absent max means unbounded for the numeric field (a design width is not a
- // percentage); only the slider needs a finite range, so it falls back to 100.
- const { min = 0, max = Infinity, step = 1, slider, suffix } = setting;
- return (
- <>
- {slider && (
- <Slider value={value} min={min} max={Number.isFinite(max) ? max : 100} step={step} onChange={(v) => setValue(setting.id, v)} />
- )}
- <input
- className="set-num"
- defaultValue={`${value}${suffix ?? ''}`}
- key={value}
- onBlur={(e) => {
- const n = parseFloat(e.target.value);
- if (!Number.isNaN(n)) setValue(setting.id, clamp(n, min, max));
- }}
- onKeyDown={(e) => {
- if (e.key === 'Enter') (e.target as HTMLInputElement).blur();
- }}
- />
- </>
- );
-}
-
-// Click to capture the next chord (Esc cancels). Bound to the command registry,
-// so the new binding persists and takes effect immediately.
-function KeybindCapture({ setting }: { setting: KeybindingSetting }) {
- const setValue = useSettings((s) => s.setValue);
- const chord = useSettings((s) => s.getValue<string>(setting.id));
- const [capturing, setCapturing] = useState(false);
- useEffect(() => {
- if (!capturing) return;
- const onKey = (e: KeyboardEvent) => {
- e.preventDefault();
- e.stopPropagation();
- if (e.key === 'Escape') {
- setCapturing(false);
- return;
- }
- if (['Control', 'Shift', 'Alt', 'Meta'].includes(e.key)) return; // wait for the real key
- const chord = eventToChord(e);
- setValue(setting.id, chord);
- setCapturing(false);
- // Warn (don't block) if the chord already drives another command — some
- // overlaps are intentional (context-gated keys), but a SILENT shadow is the
- // real bug, so name the clash and let the user decide.
- const clash = commands.conflictsFor(chord, setting.commandId);
- if (clash.length) {
- Toasts.push(
- t('set.rebindConflict', { keys: formatKeybinding(chord), cmd: commands.get(clash[0])?.label ?? clash[0] }),
- 'warn',
- );
- }
- };
- // Capture phase + stopPropagation so neither commands nor the dialog Esc fire.
- window.addEventListener('keydown', onKey, true);
- return () => window.removeEventListener('keydown', onKey, true);
- }, [capturing, setting.id, setValue]);
- return (
- <button
- type="button"
- className={`set-key${capturing ? ' capturing' : ''}`}
- title={t('set.rebindHint')}
- onClick={() => setCapturing((c) => !c)}
- >
- {capturing ? t('set.pressKeys') : formatKeybinding(chord) || t('set.unbound')}
- </button>
- );
-}
-
-/**
- * A machine-local path: type it, or browse for it. The clear button is not a
- * reset — clearing means "use the system default", which for these is a real and
- * often preferable answer, so it stays visible rather than hiding behind the
- * row's changed-from-default arrow.
- */
-function PathControl({ setting }: { setting: PathSetting }) {
- const setValue = useSettings((s) => s.setValue);
- const value = useSettings((s) => s.getValue<string>(setting.id) ?? '');
- const [found, setFound] = useState<{ id: string; label: string; path: string }[]>([]);
- // Detection is an fs walk in main; do it when the page is looked at, not at boot.
- useEffect(() => {
- if (!setting.detect) return;
- void window.estella?.shell?.detectEditors?.().then((list) => setFound(list ?? []));
- }, [setting.detect]);
-
- const browse = async () => {
- const title = setting.pickTitle ?? setting.label;
- const shell = window.estella?.shell;
- const picked = setting.pick === 'directory'
- ? await shell?.pickDirectory?.(title)
- : await shell?.pickProgram?.(title);
- if (picked) setValue(setting.id, picked);
- };
-
- // '' is AUTO, not "nothing": it names what the editor would actually do, so the
- // row answers "what happens if I leave this alone?" without the user guessing.
- const auto = found[0]
- ? t('set.externalTools.autoNamed', { program: found[0].label })
- : t('set.externalTools.placeholder');
- const options = [
- { value: '', label: auto },
- ...found.map((f) => ({ value: f.path, label: f.label })),
- // A path the user browsed to is not in the catalog; keep it selectable so the
- // dropdown never silently drops the very thing that is in effect.
- ...(value && !found.some((f) => f.path === value) ? [{ value, label: basename(value) }] : []),
- ];
-
- return (
- <div className="set-path">
- {setting.detect ? (
- <Select value={value} options={options} onChange={(v) => setValue(setting.id, v)} />
- ) : (
- <input
- className="set-str"
- value={value}
- placeholder={setting.placeholder ?? ''}
- spellCheck={false}
- onChange={(e) => setValue(setting.id, e.target.value)}
- />
- )}
- {value && (
- <IconButton title={t('ui.clear')} ariaLabel={t('ui.clear')} onClick={() => setValue(setting.id, '')}>
- <X size={13} />
- </IconButton>
- )}
- <IconButton title={t('ui.browse')} ariaLabel={t('ui.browse')} onClick={() => void browse()}>
- <FolderSearch size={13} />
- </IconButton>
- </div>
- );
-}
-
-const basename = (p: string): string => p.split(/[\\/]/).pop() || p;
-
-/**
- * A credential: type it once, and from then on the row can only say that one is
- * held, or forget it. There is no reveal affordance because there is nothing to
- * reveal — main never hands the value back (see settings/types.ts) — and a row
- * that could show it would have to keep it here, which is the thing being
- * avoided. The draft survives a refused store so a paste is never lost.
- */
-function SecretControl({ setting }: { setting: SecretSetting }) {
- const status = useSyncExternalStore(subscribeSecrets, () => secretStatus(setting.id));
- const [draft, setDraft] = useState('');
- useEffect(() => {
- void refreshSecret(setting.id);
- }, [setting.id]);
-
- // Main has not answered yet. Rendering either state would be a guess, and one
- // of the two guesses reads as "your key is gone".
- if (!status) return null;
-
- if (status.configured) {
- return (
- <div className="set-secret">
- <span className="set-secret-on">
- <Check size={12} strokeWidth={2} />
- {t('set.secret.stored')}
- </span>
- <IconButton title={t('set.secret.forget')} onClick={() => void forgetSecret(setting.id)}>
- <Trash2 size={13} />
- </IconButton>
- </div>
- );
- }
-
- // Nothing can be sealed on this machine, so the field is shown refused rather
- // than accepting a key it would have to drop. The row's status line says why.
- const blocked = status.storage === 'unavailable';
- const submit = () => {
- if (!draft.trim() || blocked) return;
- void storeSecret(setting.id, draft).then((s) => {
- if (s?.configured) setDraft('');
- });
- };
- return (
- <div className="set-secret">
- <input
- className="set-str"
- type="password"
- value={draft}
- disabled={blocked}
- placeholder={setting.placeholder ?? ''}
- spellCheck={false}
- autoComplete="off"
- onChange={(e) => setDraft(e.target.value)}
- onKeyDown={(e) => {
- if (e.key === 'Enter') submit();
- }}
- />
- <IconButton title={t('set.secret.store')} disabled={blocked || !draft.trim()} onClick={submit}>
- <Check size={13} />
- </IconButton>
- </div>
- );
-}
-
-function StringListControl({ setting }: { setting: StringListSetting }) {
- const setValue = useSettings((s) => s.setValue);
- const value = useSettings(useShallow((s) => s.getValue<string[]>(setting.id) ?? (EMPTY_LIST as string[])));
- return (
- <div className="set-list">
- {Array.from({ length: setting.count }, (_, i) => (
- <input
- key={i}
- className="set-list-item"
- value={value[i] ?? ''}
- placeholder={setting.placeholder?.(i) ?? String(i)}
- spellCheck={false}
- onChange={(e) => {
- const next = Array.from({ length: setting.count }, (_, j) => value[j] ?? '');
- next[i] = e.target.value;
- setValue(setting.id, next);
- }}
- />
- ))}
- </div>
- );
-}
-
-const EMPTY_MASKS: readonly number[] = [];
-
-function MatrixControl({ setting }: { setting: MatrixSetting }) {
- const setValue = useSettings((s) => s.setValue);
- const value = useSettings(useShallow((s) => s.getValue<number[]>(setting.id) ?? (EMPTY_MASKS as number[])));
- // `labels` reads a DIFFERENT setting (the layer names), which this control does
- // not subscribe to — so also watch the store identity, bumped on every set.
- // Without it, naming a layer left the matrix showing the names it booted with.
- useSettings((s) => s.values);
- const labels = setting.labels();
- const masks = Array.from({ length: setting.count }, (_, i) => value[i] ?? 0xffff);
- // Show layer 0 (Default) + any named layer — the matrix stays readable.
- const shown = Array.from({ length: setting.count }, (_, i) => i).filter((i) => i === 0 || (labels[i] ?? '') !== '');
- const collides = (i: number, j: number) => ((masks[i] >> j) & 1) === 1;
- const toggle = (i: number, j: number) => {
- const on = !collides(i, j);
- const setBit = (m: number, b: number) => (on ? m | (1 << b) : m & ~(1 << b)) & 0xffff;
- const next = masks.slice();
- next[i] = setBit(next[i], j);
- next[j] = setBit(next[j], i); // keep the matrix symmetric
- setValue(setting.id, next);
- };
- return (
- <table className="set-matrix">
- <thead>
- <tr>
- <th />
- {shown.map((j) => <th key={j} className="set-matrix-col"><span>{labels[j] || t('set.layerN', { i: j })}</span></th>)}
- </tr>
- </thead>
- <tbody>
- {shown.map((i) => (
- <tr key={i}>
- <th className="set-matrix-row">{labels[i] || t('set.layerN', { i })}</th>
- {shown.map((j) => (
- <td key={j}>
- <input type="checkbox" checked={collides(i, j)} onChange={() => toggle(i, j)} />
- </td>
- ))}
- </tr>
- ))}
- </tbody>
- </table>
- );
-}
-
-function FlagListControl({ setting }: { setting: FlagListSetting }) {
- const setValue = useSettings((s) => s.setValue);
- const value = useSettings(useShallow((s) => s.getValue<number[]>(setting.id) ?? (EMPTY_MASKS as number[])));
- // Same as MatrixControl: the names come from another setting, so a rename has
- // to reach this list — otherwise a layer you just named never becomes tickable.
- useSettings((s) => s.values);
- const labels = setting.labels();
- const shown = Array.from({ length: setting.count }, (_, i) => i).filter((i) => i === 0 || (labels[i] ?? '') !== '');
- const isOn = (i: number) => value.includes(i);
- const toggle = (i: number) => {
- const next = isOn(i) ? value.filter((v) => v !== i) : [...value, i].sort((a, b) => a - b);
- setValue(setting.id, next);
- };
- return (
- <div className="set-flaglist">
- {shown.map((i) => (
- <label key={i} className="set-flaglist-item">
- <input type="checkbox" checked={isOn(i)} onChange={() => toggle(i)} />
- <span>{labels[i] || t('set.layerN', { i })}</span>
- </label>
- ))}
- </div>
- );
-}
-
-/**
- * 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>[] = [];
-
-/** 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) };
-}
-
-/**
- * A credential belonging to one row of a list.
- *
- * The same bargain as {@link SecretControl} — typed once, never read back — in
- * the width of a table cell. The unset state is a labelled button rather than a
- * blank field: a missing key is the likeliest reason a configured-looking row
- * does nothing, so the cell says what is absent instead of looking empty.
- */
-function ObjectListSecret({ id }: { id: string }) {
- const status = useSyncExternalStore(subscribeSecrets, () => secretStatus(id));
- const [entering, setEntering] = useState(false);
- const [draft, setDraft] = useState('');
- useEffect(() => {
- void refreshSecret(id);
- }, [id]);
-
- if (status?.configured) {
- return (
- <span className="set-objlist-secret on">
- <Check size={11} strokeWidth={2.4} />
- {t('set.secret.stored')}
- <IconButton title={t('set.secret.forget')} onClick={() => void forgetSecret(id)}>
- <Trash2 size={12} />
- </IconButton>
- </span>
- );
- }
-
- const blocked = status?.storage === 'unavailable';
- if (!entering) {
- return (
- <button
- type="button"
- className="set-objlist-secret"
- disabled={blocked}
- onClick={() => setEntering(true)}
- >
- <KeyRound size={11} strokeWidth={2} />
- {t('set.secret.needed')}
- </button>
- );
- }
- const submit = () => {
- if (!draft.trim()) return;
- void storeSecret(id, draft).then((s) => {
- if (!s?.configured) return;
- setDraft('');
- setEntering(false);
- });
- };
- return (
- <input
- className="set-str"
- type="password"
- autoFocus
- value={draft}
- placeholder="sk-…"
- spellCheck={false}
- autoComplete="off"
- onChange={(e) => setDraft(e.target.value)}
- onBlur={() => { if (!draft.trim()) setEntering(false); }}
- onKeyDown={(e) => {
- if (e.key === 'Enter') submit();
- if (e.key === 'Escape') { setDraft(''); setEntering(false); }
- }}
- />
- );
-}
-
-function ObjectListField({
- col, row, onChange,
-}: {
- col: ObjectListColumn;
- row: Record<string, unknown>;
- onChange: (v: unknown) => void;
-}) {
- if (col.type === 'secret') return <ObjectListSecret id={col.secretId?.(row) ?? ''} />;
- if (col.type === 'enum') {
- return (
- <Select
- ariaLabel={col.label}
- value={String(readPath(row, col.key) ?? col.options?.[0]?.value ?? '')}
- options={col.options ?? []}
- onChange={onChange}
- />
- );
- }
- if (col.type === 'boolean') {
- const on = readPath(row, col.key) === true;
- return (
- <span
- className={`toggle${on ? ' on' : ''}`}
- role="switch"
- aria-checked={on}
- aria-label={col.label}
- tabIndex={0}
- onClick={() => onChange(!on)}
- onKeyDown={(e) => {
- if (e.key === ' ' || e.key === 'Enter') {
- e.preventDefault();
- onChange(!on);
- }
- }}
- />
- );
- }
- return (
- <input
- className={`set-str${col.mono === false ? ' prose' : ''}`}
- type={col.type === 'number' ? 'number' : 'text'}
- min={col.min}
- spellCheck={false}
- placeholder={col.placeholder}
- value={String(readPath(row, col.key) ?? '')}
- // A cleared number field is EMPTY, not zero, so the placeholder keeps
- // saying what the column falls back to.
- onChange={(e) => onChange(
- col.type !== 'number' ? e.target.value : (e.target.value === '' ? undefined : Number(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 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 ? 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">
- {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>)}
- {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) => (
- <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));
- setting.onRowRemoved?.(row);
- 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>
- );
- })}
- <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
- // otherwise make this snapshot change every render and loop.
- const value = useSettings(useShallow((s) => s.getValue(setting.id)));
- switch (setting.type) {
- case 'boolean':
- return (
- <span
- className={`toggle${value ? ' on' : ''}`}
- role="switch"
- aria-checked={Boolean(value)}
- tabIndex={0}
- onClick={() => setValue(setting.id, !value)}
- onKeyDown={(e) => {
- if (e.key === ' ' || e.key === 'Enter') {
- e.preventDefault();
- setValue(setting.id, !value);
- }
- }}
- />
- );
- case 'enum': {
- const options = setting.options.map((o) => ({ value: o.value, label: o.label }));
- if (setting.segmented) {
- return (
- <Segmented
- value={String(value)}
- onChange={(v) => setValue(setting.id, v)}
- ariaLabel={setting.label}
- options={options}
- />
- );
- }
- return (
- <Select
- ariaLabel={setting.label}
- value={String(value)}
- options={options}
- onChange={(v) => setValue(setting.id, v)}
- />
- );
- }
- case 'number':
- return <NumberControl setting={setting} />;
- case 'color':
- return (
- <div className="set-swatches">
- {setting.swatches.map((c) => (
- <span
- key={c}
- className={`set-swatch${value === c ? ' on' : ''}`}
- style={{ background: c }}
- title={c}
- onClick={() => setValue(setting.id, c)}
- />
- ))}
- </div>
- );
- case 'colorpicker': {
- const hex = String(value ?? '');
- return (
- <div className={`set-colorpicker${hex ? '' : ' inherited'}`}>
- <ColorControl
- value={hex || setting.placeholderColor?.() || '#00000000'}
- onChange={(v) => setValue(setting.id, v)}
- />
- {!hex && <span className="set-inherit">{t('set.inherited')}</span>}
- </div>
- );
- }
- case 'keybinding':
- return <KeybindCapture setting={setting} />;
- case 'string':
- return (
- <input
- className="set-str"
- value={String(value ?? '')}
- placeholder={setting.placeholder ?? ''}
- spellCheck={false}
- onChange={(e) => setValue(setting.id, e.target.value)}
- />
- );
- case 'path':
- return <PathControl setting={setting} />;
- case 'secret':
- return <SecretControl setting={setting} />;
- case 'stringList':
- return <StringListControl setting={setting} />;
- case 'matrix':
- return <MatrixControl setting={setting} />;
- case 'flagList':
- return <FlagListControl setting={setting} />;
- case 'objectList':
- return <ObjectListControl setting={setting} />;
- }
-}
-
-// What the setting's backing is actually doing right now, under the description.
-// Subscribed rather than read once: the state it reports (a port that opened, an
-// error that came back) lands after the click that asked for it.
-const NEVER_CHANGES = () => () => {};
-
-function StatusLine({ status }: { status: NonNullable<Setting['status']> }) {
- const text = useSyncExternalStore(status.subscribe ?? NEVER_CHANGES, status.read, status.read);
- return text ? <div className="sd set-status">{text}</div> : null;
-}
-
-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' : ''}${setting.layout === 'block' ? ' set-row--block' : ''}`}>
- <div>
- <div className="sn">{setting.label}</div>
- {setting.description && <div className="sd">{setting.description}</div>}
- {setting.status && <StatusLine status={setting.status} />}
- </div>
- <div className="set-ctrl">
- <Control setting={setting} />
- </div>
- <span
- className={`set-reset${isChanged ? ' show' : ''}`}
- title={t('set.resetDefault')}
- onClick={() => isChanged && reset(setting.id)}
- >
- {isChanged && <RotateCcw size={11} strokeWidth={2} />}
- </span>
- </div>
- );
-}
-
-// A content group: a header + its rows.
-function Group({ label, settings }: { label: string; settings: Setting[] }) {
- return (
- <>
- <div className="set-group">{label}</div>
- {settings.map((s) => (
- <Row key={s.id} setting={s} />
- ))}
- </>
- );
-}
-
export function SettingsDialog() {
const close = () => useEditorStore.getState().setSettingsOpen(false);
const winRef = useRef<HTMLDivElement>(null);
@@ -797,6 +72,14 @@ export function SettingsDialog() {
.filter((g) => g.settings.length > 0)
: groupByGroup(settingsRegistry.settingsForSection(active));
+ // Search must still find a row this window does not edit. It reports WHERE that
+ // row is rather than repeating its control, which would put the value back to
+ // having two editors.
+ const elsewhere = q
+ ? settingsRegistry.all().filter((s) => s.platform && matches(s))
+ : [];
+ const activeSection = sections.find((s) => s.id === active);
+
return createPortal(
<div className={`set-scrim${open ? ' open' : ''}`} onMouseDown={close}>
<div
@@ -843,11 +126,38 @@ export function SettingsDialog() {
</nav>
<div className="set-content">
- {content.length === 0 ? (
+ {!q && activeSection?.hint && <div className="set-hint">{activeSection.hint}</div>}
+ {content.length === 0 && elsewhere.length === 0 ? (
<div className="empty-line">{t('set.noMatch', { query })}</div>
) : (
content.map((g) => <Group key={g.label} label={g.label} settings={g.settings} />)
)}
+ {elsewhere.length > 0 && (
+ <>
+ <div className="set-group">{t('set.inBuildDialog')}</div>
+ {elsewhere.map((s) => (
+ <div key={s.id} className="set-row">
+ <div>
+ <div className="sn">{s.label}</div>
+ <div className="sd">{t('set.inBuildDialog.where', { platform: platformLabel(s.platform!) })}</div>
+ </div>
+ <div className="set-ctrl">
+ <button
+ type="button"
+ className="set-goto"
+ onClick={() => {
+ close();
+ useEditorStore.getState().openBuild(s.platform!);
+ }}
+ >
+ <ExternalLink size={12} /> {t('set.openBuildDialog')}
+ </button>
+ </div>
+ <span className="set-reset" />
+ </div>
+ ))}
+ </>
+ )}
</div>
</div>
</div>
@@ -855,18 +165,3 @@ export function SettingsDialog() {
document.body,
);
}
-
-// Group a section's settings by their `group` field, preserving first-seen order.
-function groupByGroup(settings: Setting[]): { label: string; settings: Setting[] }[] {
- const order: string[] = [];
- const map = new Map<string, Setting[]>();
- for (const s of settings) {
- const g = s.group ?? '';
- if (!map.has(g)) {
- map.set(g, []);
- order.push(g);
- }
- map.get(g)!.push(s);
- }
- return order.map((label) => ({ label, settings: map.get(label)! }));
-}
diff --git a/desktop/src/components/SettingsRow.tsx b/desktop/src/components/SettingsRow.tsx
new file mode 100644
index 000000000..549cd9104
--- /dev/null
+++ b/desktop/src/components/SettingsRow.tsx
@@ -0,0 +1,767 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file SettingsRow.tsx — one registered setting, rendered. The control picked
+ * by `type`, the label, the description, the live status line and the
+ * reset affordance.
+ *
+ * Its own file because a setting is edited in more than one window: the
+ * settings dialog renders whole sections of them, and the Package Project
+ * dialog renders the rows a packaging target declares (`Setting.platform`)
+ * on that target's page. One renderer, so a row cannot look or behave like
+ * two different things depending on which dialog you opened.
+ */
+import { useEffect, useRef, useState, useSyncExternalStore } from 'react';
+import type { PointerEvent as ReactPointerEvent } from 'react';
+import { useShallow } from 'zustand/react/shallow';
+import { RotateCcw, FolderSearch, Plus, Trash2, ChevronRight, Check, KeyRound, X } from 'lucide-react';
+import { useSettings } from '@/store/settingsStore';
+import { eventToChord, formatKeybinding } from '@/commands/keybinding';
+import { commands } from '@/commands';
+import { Toasts } from '@/store/Toasts';
+import { IconButton } from '@/components/IconButton';
+import { Segmented } from '@/components/Segmented';
+import { Select } from '@/components/Select';
+import { ColorControl } from '@/components/ColorControl';
+import { refreshSecret, secretStatus, storeSecret, forgetSecret, subscribeSecrets } from '@/store/SecretStore';
+import type { Setting, NumberSetting, KeybindingSetting, StringListSetting, PathSetting, SecretSetting, 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
+// keeps the read referentially stable (else useSyncExternalStore loops). A shared
+// empty fallback avoids a fresh `[]` when a value is unset.
+const EMPTY_LIST: readonly string[] = [];
+
+const clamp = (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, v));
+
+function Slider({
+ value, min, max, step, onChange,
+}: {
+ value: number; min: number; max: number; step: number; onChange: (v: number) => void;
+}) {
+ const ref = useRef<HTMLSpanElement>(null);
+ const pct = max > min ? clamp(((value - min) / (max - min)) * 100, 0, 100) : 0;
+ const fromClient = (clientX: number) => {
+ const el = ref.current;
+ if (!el) return;
+ const r = el.getBoundingClientRect();
+ const t = clamp((clientX - r.left) / r.width, 0, 1);
+ const raw = min + t * (max - min);
+ onChange(clamp(Math.round(raw / step) * step, min, max));
+ };
+ return (
+ <span
+ ref={ref}
+ className="slider set-slider"
+ onPointerDown={(e: ReactPointerEvent) => {
+ (e.target as HTMLElement).setPointerCapture(e.pointerId);
+ fromClient(e.clientX);
+ }}
+ onPointerMove={(e: ReactPointerEvent) => {
+ if (e.buttons & 1) fromClient(e.clientX);
+ }}
+ >
+ <span className="fill" style={{ width: `${pct}%` }} />
+ <span className="thumb" style={{ left: `${pct}%` }} />
+ </span>
+ );
+}
+
+function NumberControl({ setting }: { setting: NumberSetting }) {
+ const setValue = useSettings((s) => s.setValue);
+ const value = Number(useSettings((s) => s.getValue<number>(setting.id)));
+ // An absent max means unbounded for the numeric field (a design width is not a
+ // percentage); only the slider needs a finite range, so it falls back to 100.
+ const { min = 0, max = Infinity, step = 1, slider, suffix } = setting;
+ return (
+ <>
+ {slider && (
+ <Slider value={value} min={min} max={Number.isFinite(max) ? max : 100} step={step} onChange={(v) => setValue(setting.id, v)} />
+ )}
+ <input
+ className="set-num"
+ defaultValue={`${value}${suffix ?? ''}`}
+ key={value}
+ onBlur={(e) => {
+ const n = parseFloat(e.target.value);
+ if (!Number.isNaN(n)) setValue(setting.id, clamp(n, min, max));
+ }}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') (e.target as HTMLInputElement).blur();
+ }}
+ />
+ </>
+ );
+}
+
+// Click to capture the next chord (Esc cancels). Bound to the command registry,
+// so the new binding persists and takes effect immediately.
+function KeybindCapture({ setting }: { setting: KeybindingSetting }) {
+ const setValue = useSettings((s) => s.setValue);
+ const chord = useSettings((s) => s.getValue<string>(setting.id));
+ const [capturing, setCapturing] = useState(false);
+ useEffect(() => {
+ if (!capturing) return;
+ const onKey = (e: KeyboardEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ if (e.key === 'Escape') {
+ setCapturing(false);
+ return;
+ }
+ if (['Control', 'Shift', 'Alt', 'Meta'].includes(e.key)) return; // wait for the real key
+ const chord = eventToChord(e);
+ setValue(setting.id, chord);
+ setCapturing(false);
+ // Warn (don't block) if the chord already drives another command — some
+ // overlaps are intentional (context-gated keys), but a SILENT shadow is the
+ // real bug, so name the clash and let the user decide.
+ const clash = commands.conflictsFor(chord, setting.commandId);
+ if (clash.length) {
+ Toasts.push(
+ t('set.rebindConflict', { keys: formatKeybinding(chord), cmd: commands.get(clash[0])?.label ?? clash[0] }),
+ 'warn',
+ );
+ }
+ };
+ // Capture phase + stopPropagation so neither commands nor the dialog Esc fire.
+ window.addEventListener('keydown', onKey, true);
+ return () => window.removeEventListener('keydown', onKey, true);
+ }, [capturing, setting.id, setValue]);
+ return (
+ <button
+ type="button"
+ className={`set-key${capturing ? ' capturing' : ''}`}
+ title={t('set.rebindHint')}
+ onClick={() => setCapturing((c) => !c)}
+ >
+ {capturing ? t('set.pressKeys') : formatKeybinding(chord) || t('set.unbound')}
+ </button>
+ );
+}
+
+/**
+ * A machine-local path: type it, or browse for it. The clear button is not a
+ * reset — clearing means "use the system default", which for these is a real and
+ * often preferable answer, so it stays visible rather than hiding behind the
+ * row's changed-from-default arrow.
+ */
+function PathControl({ setting }: { setting: PathSetting }) {
+ const setValue = useSettings((s) => s.setValue);
+ const value = useSettings((s) => s.getValue<string>(setting.id) ?? '');
+ const [found, setFound] = useState<{ id: string; label: string; path: string }[]>([]);
+ // Detection is an fs walk in main; do it when the page is looked at, not at boot.
+ useEffect(() => {
+ if (!setting.detect) return;
+ void window.estella?.shell?.detectEditors?.().then((list) => setFound(list ?? []));
+ }, [setting.detect]);
+
+ const browse = async () => {
+ const title = setting.pickTitle ?? setting.label;
+ const shell = window.estella?.shell;
+ const picked = setting.pick === 'directory'
+ ? await shell?.pickDirectory?.(title)
+ : await shell?.pickProgram?.(title);
+ if (picked) setValue(setting.id, picked);
+ };
+
+ // '' is AUTO, not "nothing": it names what the editor would actually do, so the
+ // row answers "what happens if I leave this alone?" without the user guessing.
+ const auto = found[0]
+ ? t('set.externalTools.autoNamed', { program: found[0].label })
+ : t('set.externalTools.placeholder');
+ const options = [
+ { value: '', label: auto },
+ ...found.map((f) => ({ value: f.path, label: f.label })),
+ // A path the user browsed to is not in the catalog; keep it selectable so the
+ // dropdown never silently drops the very thing that is in effect.
+ ...(value && !found.some((f) => f.path === value) ? [{ value, label: basename(value) }] : []),
+ ];
+
+ return (
+ <div className="set-path">
+ {setting.detect ? (
+ <Select value={value} options={options} onChange={(v) => setValue(setting.id, v)} />
+ ) : (
+ <input
+ className="set-str"
+ value={value}
+ placeholder={setting.placeholder ?? ''}
+ spellCheck={false}
+ onChange={(e) => setValue(setting.id, e.target.value)}
+ />
+ )}
+ {value && (
+ <IconButton title={t('ui.clear')} ariaLabel={t('ui.clear')} onClick={() => setValue(setting.id, '')}>
+ <X size={13} />
+ </IconButton>
+ )}
+ <IconButton title={t('ui.browse')} ariaLabel={t('ui.browse')} onClick={() => void browse()}>
+ <FolderSearch size={13} />
+ </IconButton>
+ </div>
+ );
+}
+
+const basename = (p: string): string => p.split(/[\\/]/).pop() || p;
+
+/**
+ * A credential: type it once; from then on the row can only say one is held, or
+ * forget it. No reveal affordance, because main never hands the value back (see
+ * settings/types.ts) and a row that could show it would have to keep it here. The
+ * draft survives a refused store so a paste is never lost.
+ */
+function SecretControl({ setting }: { setting: SecretSetting }) {
+ const status = useSyncExternalStore(subscribeSecrets, () => secretStatus(setting.id));
+ const [draft, setDraft] = useState('');
+ useEffect(() => {
+ void refreshSecret(setting.id);
+ }, [setting.id]);
+
+ // Main has not answered yet. Rendering either state would be a guess, and one
+ // of the two guesses reads as "your key is gone".
+ if (!status) return null;
+
+ if (status.configured) {
+ return (
+ <div className="set-secret">
+ <span className="set-secret-on">
+ <Check size={12} strokeWidth={2} />
+ {t('set.secret.stored')}
+ </span>
+ <IconButton title={t('set.secret.forget')} onClick={() => void forgetSecret(setting.id)}>
+ <Trash2 size={13} />
+ </IconButton>
+ </div>
+ );
+ }
+
+ // Nothing can be sealed on this machine, so the field is shown refused rather
+ // than accepting a key it would have to drop. The row's status line says why.
+ const blocked = status.storage === 'unavailable';
+ const submit = () => {
+ if (!draft.trim() || blocked) return;
+ void storeSecret(setting.id, draft).then((s) => {
+ if (s?.configured) setDraft('');
+ });
+ };
+ return (
+ <div className="set-secret">
+ <input
+ className="set-str"
+ type="password"
+ value={draft}
+ disabled={blocked}
+ placeholder={setting.placeholder ?? ''}
+ spellCheck={false}
+ autoComplete="off"
+ onChange={(e) => setDraft(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') submit();
+ }}
+ />
+ <IconButton title={t('set.secret.store')} disabled={blocked || !draft.trim()} onClick={submit}>
+ <Check size={13} />
+ </IconButton>
+ </div>
+ );
+}
+
+function StringListControl({ setting }: { setting: StringListSetting }) {
+ const setValue = useSettings((s) => s.setValue);
+ const value = useSettings(useShallow((s) => s.getValue<string[]>(setting.id) ?? (EMPTY_LIST as string[])));
+ return (
+ <div className="set-list">
+ {Array.from({ length: setting.count }, (_, i) => (
+ <input
+ key={i}
+ className="set-list-item"
+ value={value[i] ?? ''}
+ placeholder={setting.placeholder?.(i) ?? String(i)}
+ spellCheck={false}
+ onChange={(e) => {
+ const next = Array.from({ length: setting.count }, (_, j) => value[j] ?? '');
+ next[i] = e.target.value;
+ setValue(setting.id, next);
+ }}
+ />
+ ))}
+ </div>
+ );
+}
+
+const EMPTY_MASKS: readonly number[] = [];
+
+function MatrixControl({ setting }: { setting: MatrixSetting }) {
+ const setValue = useSettings((s) => s.setValue);
+ const value = useSettings(useShallow((s) => s.getValue<number[]>(setting.id) ?? (EMPTY_MASKS as number[])));
+ // `labels` reads a DIFFERENT setting (the layer names), which this control does
+ // not subscribe to — so also watch the store identity, bumped on every set.
+ // Without it, naming a layer left the matrix showing the names it booted with.
+ useSettings((s) => s.values);
+ const labels = setting.labels();
+ const masks = Array.from({ length: setting.count }, (_, i) => value[i] ?? 0xffff);
+ // Show layer 0 (Default) + any named layer — the matrix stays readable.
+ const shown = Array.from({ length: setting.count }, (_, i) => i).filter((i) => i === 0 || (labels[i] ?? '') !== '');
+ const collides = (i: number, j: number) => ((masks[i] >> j) & 1) === 1;
+ const toggle = (i: number, j: number) => {
+ const on = !collides(i, j);
+ const setBit = (m: number, b: number) => (on ? m | (1 << b) : m & ~(1 << b)) & 0xffff;
+ const next = masks.slice();
+ next[i] = setBit(next[i], j);
+ next[j] = setBit(next[j], i); // keep the matrix symmetric
+ setValue(setting.id, next);
+ };
+ return (
+ <table className="set-matrix">
+ <thead>
+ <tr>
+ <th />
+ {shown.map((j) => <th key={j} className="set-matrix-col"><span>{labels[j] || t('set.layerN', { i: j })}</span></th>)}
+ </tr>
+ </thead>
+ <tbody>
+ {shown.map((i) => (
+ <tr key={i}>
+ <th className="set-matrix-row">{labels[i] || t('set.layerN', { i })}</th>
+ {shown.map((j) => (
+ <td key={j}>
+ <input type="checkbox" checked={collides(i, j)} onChange={() => toggle(i, j)} />
+ </td>
+ ))}
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ );
+}
+
+function FlagListControl({ setting }: { setting: FlagListSetting }) {
+ const setValue = useSettings((s) => s.setValue);
+ const value = useSettings(useShallow((s) => s.getValue<number[]>(setting.id) ?? (EMPTY_MASKS as number[])));
+ // Same as MatrixControl: the names come from another setting, so a rename has
+ // to reach this list — otherwise a layer you just named never becomes tickable.
+ useSettings((s) => s.values);
+ const labels = setting.labels();
+ const shown = Array.from({ length: setting.count }, (_, i) => i).filter((i) => i === 0 || (labels[i] ?? '') !== '');
+ const isOn = (i: number) => value.includes(i);
+ const toggle = (i: number) => {
+ const next = isOn(i) ? value.filter((v) => v !== i) : [...value, i].sort((a, b) => a - b);
+ setValue(setting.id, next);
+ };
+ return (
+ <div className="set-flaglist">
+ {shown.map((i) => (
+ <label key={i} className="set-flaglist-item">
+ <input type="checkbox" checked={isOn(i)} onChange={() => toggle(i)} />
+ <span>{labels[i] || t('set.layerN', { i })}</span>
+ </label>
+ ))}
+ </div>
+ );
+}
+
+/**
+ * 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>[] = [];
+
+/** 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) };
+}
+
+/**
+ * A credential belonging to one row of a list.
+ *
+ * The same bargain as {@link SecretControl} — typed once, never read back — in
+ * the width of a table cell. Unset shows a labelled button, not a blank field: a
+ * missing key is the likeliest reason a configured-looking row does nothing.
+ */
+function ObjectListSecret({ id }: { id: string }) {
+ const status = useSyncExternalStore(subscribeSecrets, () => secretStatus(id));
+ const [entering, setEntering] = useState(false);
+ const [draft, setDraft] = useState('');
+ useEffect(() => {
+ void refreshSecret(id);
+ }, [id]);
+
+ if (status?.configured) {
+ return (
+ <span className="set-objlist-secret on">
+ <Check size={11} strokeWidth={2.4} />
+ {t('set.secret.stored')}
+ <IconButton title={t('set.secret.forget')} onClick={() => void forgetSecret(id)}>
+ <Trash2 size={12} />
+ </IconButton>
+ </span>
+ );
+ }
+
+ const blocked = status?.storage === 'unavailable';
+ if (!entering) {
+ return (
+ <button
+ type="button"
+ className="set-objlist-secret"
+ disabled={blocked}
+ onClick={() => setEntering(true)}
+ >
+ <KeyRound size={11} strokeWidth={2} />
+ {t('set.secret.needed')}
+ </button>
+ );
+ }
+ const submit = () => {
+ if (!draft.trim()) return;
+ void storeSecret(id, draft).then((s) => {
+ if (!s?.configured) return;
+ setDraft('');
+ setEntering(false);
+ });
+ };
+ return (
+ <input
+ className="set-str"
+ type="password"
+ autoFocus
+ value={draft}
+ placeholder="sk-…"
+ spellCheck={false}
+ autoComplete="off"
+ onChange={(e) => setDraft(e.target.value)}
+ onBlur={() => { if (!draft.trim()) setEntering(false); }}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') submit();
+ if (e.key === 'Escape') { setDraft(''); setEntering(false); }
+ }}
+ />
+ );
+}
+
+function ObjectListField({
+ col, row, onChange,
+}: {
+ col: ObjectListColumn;
+ row: Record<string, unknown>;
+ onChange: (v: unknown) => void;
+}) {
+ if (col.type === 'secret') return <ObjectListSecret id={col.secretId?.(row) ?? ''} />;
+ if (col.type === 'enum') {
+ return (
+ <Select
+ ariaLabel={col.label}
+ value={String(readPath(row, col.key) ?? col.options?.[0]?.value ?? '')}
+ options={col.options ?? []}
+ onChange={onChange}
+ />
+ );
+ }
+ if (col.type === 'boolean') {
+ const on = readPath(row, col.key) === true;
+ return (
+ <span
+ className={`toggle${on ? ' on' : ''}`}
+ role="switch"
+ aria-checked={on}
+ aria-label={col.label}
+ tabIndex={0}
+ onClick={() => onChange(!on)}
+ onKeyDown={(e) => {
+ if (e.key === ' ' || e.key === 'Enter') {
+ e.preventDefault();
+ onChange(!on);
+ }
+ }}
+ />
+ );
+ }
+ return (
+ <input
+ className={`set-str${col.mono === false ? ' prose' : ''}`}
+ type={col.type === 'number' ? 'number' : 'text'}
+ min={col.min}
+ spellCheck={false}
+ placeholder={col.placeholder}
+ value={String(readPath(row, col.key) ?? '')}
+ // A cleared number field is EMPTY, not zero, so the placeholder keeps
+ // saying what the column falls back to.
+ onChange={(e) => onChange(
+ col.type !== 'number' ? e.target.value : (e.target.value === '' ? undefined : Number(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 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 ? 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">
+ {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>)}
+ {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) => (
+ <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));
+ setting.onRowRemoved?.(row);
+ 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>
+ );
+ })}
+ <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
+ // otherwise make this snapshot change every render and loop.
+ const value = useSettings(useShallow((s) => s.getValue(setting.id)));
+ switch (setting.type) {
+ case 'boolean':
+ return (
+ <span
+ className={`toggle${value ? ' on' : ''}`}
+ role="switch"
+ aria-checked={Boolean(value)}
+ tabIndex={0}
+ onClick={() => setValue(setting.id, !value)}
+ onKeyDown={(e) => {
+ if (e.key === ' ' || e.key === 'Enter') {
+ e.preventDefault();
+ setValue(setting.id, !value);
+ }
+ }}
+ />
+ );
+ case 'enum': {
+ const options = setting.options.map((o) => ({ value: o.value, label: o.label }));
+ if (setting.segmented) {
+ return (
+ <Segmented
+ value={String(value)}
+ onChange={(v) => setValue(setting.id, v)}
+ ariaLabel={setting.label}
+ options={options}
+ />
+ );
+ }
+ return (
+ <Select
+ ariaLabel={setting.label}
+ value={String(value)}
+ options={options}
+ onChange={(v) => setValue(setting.id, v)}
+ />
+ );
+ }
+ case 'number':
+ return <NumberControl setting={setting} />;
+ case 'color':
+ return (
+ <div className="set-swatches">
+ {setting.swatches.map((c) => (
+ <span
+ key={c}
+ className={`set-swatch${value === c ? ' on' : ''}`}
+ style={{ background: c }}
+ title={c}
+ onClick={() => setValue(setting.id, c)}
+ />
+ ))}
+ </div>
+ );
+ case 'colorpicker': {
+ const hex = String(value ?? '');
+ return (
+ <div className={`set-colorpicker${hex ? '' : ' inherited'}`}>
+ <ColorControl
+ value={hex || setting.placeholderColor?.() || '#00000000'}
+ onChange={(v) => setValue(setting.id, v)}
+ />
+ {!hex && <span className="set-inherit">{t('set.inherited')}</span>}
+ </div>
+ );
+ }
+ case 'keybinding':
+ return <KeybindCapture setting={setting} />;
+ case 'string':
+ return (
+ <input
+ className="set-str"
+ value={String(value ?? '')}
+ placeholder={setting.placeholder ?? ''}
+ spellCheck={false}
+ onChange={(e) => setValue(setting.id, e.target.value)}
+ />
+ );
+ case 'path':
+ return <PathControl setting={setting} />;
+ case 'secret':
+ return <SecretControl setting={setting} />;
+ case 'stringList':
+ return <StringListControl setting={setting} />;
+ case 'matrix':
+ return <MatrixControl setting={setting} />;
+ case 'flagList':
+ return <FlagListControl setting={setting} />;
+ case 'objectList':
+ return <ObjectListControl setting={setting} />;
+ }
+}
+
+// What the setting's backing is actually doing right now, under the description.
+// Subscribed rather than read once: the state it reports (a port that opened, an
+// error that came back) lands after the click that asked for it.
+const NEVER_CHANGES = () => () => {};
+
+function StatusLine({ status }: { status: NonNullable<Setting['status']> }) {
+ const text = useSyncExternalStore(status.subscribe ?? NEVER_CHANGES, status.read, status.read);
+ return text ? <div className="sd set-status">{text}</div> : null;
+}
+
+export 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' : ''}${setting.layout === 'block' ? ' set-row--block' : ''}`}>
+ <div>
+ <div className="sn">{setting.label}</div>
+ {setting.description && <div className="sd">{setting.description}</div>}
+ {setting.status && <StatusLine status={setting.status} />}
+ </div>
+ <div className="set-ctrl">
+ <Control setting={setting} />
+ </div>
+ <span
+ className={`set-reset${isChanged ? ' show' : ''}`}
+ title={t('set.resetDefault')}
+ onClick={() => isChanged && reset(setting.id)}
+ >
+ {isChanged && <RotateCcw size={11} strokeWidth={2} />}
+ </span>
+ </div>
+ );
+}
+
+/**
+ * A content group: a header + its rows. Conditional rows are filtered here rather
+ * than inside {@link Row} — a row that renders nothing still runs its hooks, and a
+ * group with every row hidden must take its header with it.
+ */
+export function Group({ label, settings }: { label: string; settings: Setting[] }) {
+ const visible = settings.filter((s) => s.visibleWhen?.() !== false);
+ if (visible.length === 0) return null;
+ return (
+ <>
+ <div className="set-group">{label}</div>
+ {visible.map((s) => (
+ <Row key={s.id} setting={s} />
+ ))}
+ </>
+ );
+}
+
+// Group a section's settings by their `group` field, preserving first-seen order.
+export function groupByGroup(settings: Setting[]): { label: string; settings: Setting[] }[] {
+ const order: string[] = [];
+ const map = new Map<string, Setting[]>();
+ for (const s of settings) {
+ const g = s.group ?? '';
+ if (!map.has(g)) {
+ map.set(g, []);
+ order.push(g);
+ }
+ map.get(g)!.push(s);
+ }
+ return order.map((label) => ({ label, settings: map.get(label)! }));
+}
diff --git a/desktop/src/i18n/messages/project.ts b/desktop/src/i18n/messages/project.ts
index deb388c7c..2988cc2a0 100644
--- a/desktop/src/i18n/messages/project.ts
+++ b/desktop/src/i18n/messages/project.ts
@@ -226,6 +226,7 @@ export const projectMessages = defineMessages({
// — Section headers + asset-optimization mode (per-asset compression lives in
// the Inspector's Import Settings; the build only picks honor-vs-skip) —
'build.secBuild': { en: 'Build', zh: '构建' },
+ 'build.secTarget': { en: '{platform} settings', zh: '{platform}设置' },
'build.advanced': { en: 'Advanced', zh: '高级' },
'build.assetCompression': { en: 'Compression', zh: '资源压缩' },
'build.assetAuto': { en: 'By import settings', zh: '按导入设置' },
diff --git a/desktop/src/i18n/messages/settings.ts b/desktop/src/i18n/messages/settings.ts
index 78c853c69..6e9f895b3 100644
--- a/desktop/src/i18n/messages/settings.ts
+++ b/desktop/src/i18n/messages/settings.ts
@@ -85,6 +85,19 @@ export const settingsMessages = defineMessages({
},
'set.inherited': { en: 'inherited', zh: '继承' },
'set.section.packaging': { en: 'Packaging', zh: '打包' },
+ 'set.section.packaging.hint': {
+ en: 'What is true of this project whatever it ships to. What one target is '
+ + 'called, where it goes and the ids a store knows it by are edited on that '
+ + "target's page in Package Project.",
+ zh: '这里是无论发往哪里都成立的部分。某个目标叫什么、发往哪里、商店用什么 id 认它,'
+ + '在「打包项目」里那个目标自己的页面上编辑。',
+ },
+ 'set.inBuildDialog': { en: 'Edited in Package Project', zh: '在「打包项目」里编辑' },
+ 'set.inBuildDialog.where': {
+ en: 'A {platform} packaging setting — it lives on that target\'s page.',
+ zh: '{platform}的打包设置——它在该目标自己的页面上。',
+ },
+ 'set.openBuildDialog': { en: 'Open', zh: '打开' },
// — Group headers —
'set.group.appearance': { en: 'Appearance', zh: '外观' },
@@ -209,8 +222,8 @@ export const settingsMessages = defineMessages({
'set.group.collisionLayers': { en: 'Collision Layers', zh: '碰撞层' },
'set.group.solver': { en: 'Solver', zh: '求解器' },
'set.group.application': { en: 'Application', zh: '应用' },
- 'set.group.wechat': { en: 'WeChat', zh: '微信' },
- 'set.group.desktop': { en: 'Desktop', zh: '桌面' },
+ 'set.group.distribution': { en: 'Distribution', zh: '发行' },
+ 'set.group.output': { en: 'Output', zh: '输出' },
// — Editor settings —
'set.appearance.language': { en: 'Language', zh: '语言' },
diff --git a/desktop/src/project/platformLabels.ts b/desktop/src/project/platformLabels.ts
new file mode 100644
index 000000000..f9cfbf917
--- /dev/null
+++ b/desktop/src/project/platformLabels.ts
@@ -0,0 +1,38 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file What a packaging target is CALLED, in the reader's language.
+ *
+ * Separate from platforms.ts, which is deliberately free of i18n so the
+ * electron main process and the tests can read it — and separate from the
+ * build dialog, which is no longer the only surface that has to name a
+ * target: settings search reports which target a row belongs to, and it
+ * should say "Desktop", not `desktop`.
+ *
+ * A project's own platform is not here (only the project knows its name);
+ * callers pass the label the profile declared, and the id is the floor.
+ */
+import { BUILTIN_PLATFORMS, type ExportPlatform } from '@/project/platforms';
+import { t } from '@/i18n';
+
+const BUILTIN_LABEL: Record<string, string> = {
+ web: t('build.plat.web'),
+ desktop: t('build.plat.desktop'),
+ wechat: t('build.plat.wechat'),
+ playable: t('build.plat.playable'),
+ android: t('build.plat.android'),
+ ios: t('build.plat.ios'),
+};
+
+/** The display name for a target. Falls back to the id, which is what a project
+ * platform without a declared label is known by anyway. */
+export function platformLabel(id: ExportPlatform): string {
+ return BUILTIN_LABEL[id] ?? id;
+}
+
+/** The built-ins that have no label — empty, and asserted so by the tests. A
+ * target added to {@link BUILTIN_PLATFORMS} without one would otherwise appear
+ * under its raw id in a dialog nobody reopens after adding it. */
+export function unlabeledBuiltins(): string[] {
+ return BUILTIN_PLATFORMS.filter((id) => !BUILTIN_LABEL[id]);
+}
diff --git a/desktop/src/settings/projectSettings.ts b/desktop/src/settings/projectSettings.ts
index c142a73ea..4e082f273 100644
--- a/desktop/src/settings/projectSettings.ts
+++ b/desktop/src/settings/projectSettings.ts
@@ -370,20 +370,15 @@ for (const role of THEME_COLOR_ROLES) {
});
}
-settingsRegistry.registerSection({ id: 'packaging', label: t('set.section.packaging'), category: 'project', order: 4 });
-
-settingsRegistry.register({
- id: 'project.packaging.wechat.appid',
- type: 'string', scope: 'project', section: 'packaging', group: t('set.group.wechat'),
- label: t('set.project.packaging.wechat.appid'),
- description: t('set.project.packaging.wechat.appid.desc'),
- placeholder: 'wx0123456789abcdef', default: '',
- bind: {
- get: () => ProjectStore.platformPackaging().wechat?.appid ?? '',
- set: (v) => void ProjectStore.setPlatformPackaging('wechat', { appid: v }),
- },
+settingsRegistry.registerSection({
+ id: 'packaging', label: t('set.section.packaging'), category: 'project', order: 4,
+ hint: t('set.section.packaging.hint'),
});
+/** What this project's desktop build is being shipped through, for the rows that
+ * only exist on one of those answers. */
+const desktopChannel = (): string => ProjectStore.platformPackaging().desktop?.channel ?? 'standalone';
+
// The application identifier every installable target needs. One project ships as
// one application, so it is declared once; a target that genuinely differs
// overrides it below. Absent ⇒ derived from the project name, so a build always
@@ -415,9 +410,59 @@ settingsRegistry.register({
},
});
+// The ids this game unlocks. Platform-NEUTRAL and therefore not under Steam: every
+// store keeps this same list under a different name. Declared so that an unlock of
+// an id no backend has is refused here rather than accepted and dropped there.
+settingsRegistry.register({
+ id: 'project.packaging.achievements',
+ type: 'objectList', scope: 'project', section: 'packaging', group: t('set.group.achievements'),
+ label: t('set.project.packaging.achievements'),
+ description: t('set.project.packaging.achievements.desc'),
+ layout: 'block',
+ default: [],
+ columns: [
+ { key: 'id', label: t('set.achievement.id'), type: 'text', width: '1fr', placeholder: 'FIRST_BLOOD' },
+ ],
+ addLabel: t('set.achievement.add'),
+ emptyHint: t('set.achievement.empty'),
+ newRow: () => ({ id: '' }),
+ rowError: (row, all) => {
+ const id = String(row.id ?? '').trim();
+ if (!id) return t('set.achievement.errId');
+ // A store keys achievements by this exact string, so two rows differing only
+ // in whitespace are one achievement and one that never fires.
+ if (all.filter((r) => String(r.id ?? '').trim() === id).length > 1) return t('set.achievement.errDup');
+ return null;
+ },
+ bind: {
+ get: () => (ProjectStore.packagingSettings().achievements ?? []).map((id) => ({ id })),
+ set: (v) => void ProjectStore.setPackaging({
+ achievements: v.map((r) => String(r.id ?? '').trim()).filter(Boolean),
+ }),
+ },
+});
+
+// ── Per-target packaging ──────────────────────────────────────────────────────
+// A row naming a `platform` is edited on that target's page in Package Project;
+// `section` still applies, and settings search reports it from there.
+
+settingsRegistry.register({
+ id: 'project.packaging.wechat.appid',
+ type: 'string', scope: 'project', section: 'packaging', platform: 'wechat',
+ group: t('set.group.application'),
+ label: t('set.project.packaging.wechat.appid'),
+ description: t('set.project.packaging.wechat.appid.desc'),
+ placeholder: 'wx0123456789abcdef', default: '',
+ bind: {
+ get: () => ProjectStore.platformPackaging().wechat?.appid ?? '',
+ set: (v) => void ProjectStore.setPlatformPackaging('wechat', { appid: v }),
+ },
+});
+
settingsRegistry.register({
id: 'project.packaging.android.versionCode',
- type: 'number', scope: 'project', section: 'packaging', group: t('set.group.application'),
+ type: 'number', scope: 'project', section: 'packaging', platform: 'android',
+ group: t('set.group.application'),
label: t('set.project.packaging.android.versionCode'),
description: t('set.project.packaging.android.versionCode.desc'),
default: 1, min: 1, step: 1,
@@ -427,9 +472,46 @@ settingsRegistry.register({
},
});
+// Whether the build ends at an installable package or at the Gradle project one is
+// assembled from — the choice a project makes once and keeps, which is why it is
+// declared here rather than re-answered in the dialog on every build.
+settingsRegistry.register({
+ id: 'project.packaging.android.output',
+ type: 'enum', scope: 'project', section: 'packaging', platform: 'android',
+ group: t('set.group.output'),
+ label: t('build.androidOutput'),
+ description: t('build.androidOutputTip'),
+ default: 'package',
+ options: [
+ { value: 'package', label: t('build.androidOutput.package') },
+ { value: 'project', label: t('build.androidOutput.project') },
+ ],
+ bind: {
+ get: () => ProjectStore.platformPackaging().android?.output ?? 'package',
+ set: (v) => void ProjectStore.setPlatformPackaging('android', { output: v as 'package' | 'project' }),
+ },
+});
+
+// An App Bundle is a second FORMAT of the package, so it is a question only when
+// a package is what the build produces.
+settingsRegistry.register({
+ id: 'project.packaging.android.appBundle',
+ type: 'boolean', scope: 'project', section: 'packaging', platform: 'android',
+ group: t('set.group.output'),
+ label: t('build.appBundle'),
+ description: t('build.appBundleTip'),
+ default: false,
+ visibleWhen: () => (ProjectStore.platformPackaging().android?.output ?? 'package') === 'package',
+ bind: {
+ get: () => ProjectStore.platformPackaging().android?.appBundle ?? false,
+ set: (v) => void ProjectStore.setPlatformPackaging('android', { appBundle: v }),
+ },
+});
+
settingsRegistry.register({
id: 'project.packaging.desktop.appId',
- type: 'string', scope: 'project', section: 'packaging', group: t('set.group.desktop'),
+ type: 'string', scope: 'project', section: 'packaging', platform: 'desktop',
+ group: t('set.group.application'),
label: t('set.project.packaging.desktop.appId'),
description: t('set.project.packaging.desktop.appId.desc'),
placeholder: 'com.studio.game', default: '',
@@ -441,7 +523,8 @@ settingsRegistry.register({
settingsRegistry.register({
id: 'project.packaging.desktop.productName',
- type: 'string', scope: 'project', section: 'packaging', group: t('set.group.desktop'),
+ type: 'string', scope: 'project', section: 'packaging', platform: 'desktop',
+ group: t('set.group.application'),
label: t('set.project.packaging.desktop.productName'),
description: t('set.project.packaging.desktop.productName.desc'),
placeholder: '(project name)', default: '',
@@ -453,12 +536,13 @@ settingsRegistry.register({
settingsRegistry.register({
id: 'project.packaging.desktop.channel',
- type: 'enum', scope: 'project', section: 'packaging', group: t('set.group.desktop'),
+ type: 'enum', scope: 'project', section: 'packaging', platform: 'desktop',
+ group: t('set.group.distribution'),
label: t('set.project.packaging.desktop.channel'),
description: t('set.project.packaging.desktop.channel.desc'),
options: DESKTOP_CHANNEL, segmented: true, default: 'standalone',
bind: {
- get: () => ProjectStore.platformPackaging().desktop?.channel ?? 'standalone',
+ get: () => desktopChannel(),
set: (v) => void ProjectStore.setPlatformPackaging('desktop', {
channel: v as 'standalone' | 'steam',
}),
@@ -467,10 +551,12 @@ settingsRegistry.register({
settingsRegistry.register({
id: 'project.packaging.desktop.steam.appId',
- type: 'number', scope: 'project', section: 'packaging', group: t('set.group.steam'),
+ type: 'number', scope: 'project', section: 'packaging', platform: 'desktop',
+ group: t('set.group.steam'),
label: t('set.project.packaging.desktop.steam.appId'),
description: t('set.project.packaging.desktop.steam.appId.desc'),
default: 0, min: 0, step: 1,
+ visibleWhen: () => desktopChannel() === 'steam',
bind: {
get: () => ProjectStore.platformPackaging().desktop?.steam?.appId ?? 0,
// 0 clears it rather than shipping a scripts-for-game-zero build: the export
@@ -481,49 +567,19 @@ settingsRegistry.register({
},
});
-// The ids this game unlocks. Platform-NEUTRAL and therefore not under Steam: every
-// store keeps this same list under a different name. Declared so that an unlock of
-// an id no backend has is refused here rather than accepted and dropped there.
-settingsRegistry.register({
- id: 'project.packaging.achievements',
- type: 'objectList', scope: 'project', section: 'packaging', group: t('set.group.achievements'),
- label: t('set.project.packaging.achievements'),
- description: t('set.project.packaging.achievements.desc'),
- layout: 'block',
- default: [],
- columns: [
- { key: 'id', label: t('set.achievement.id'), type: 'text', width: '1fr', placeholder: 'FIRST_BLOOD' },
- ],
- addLabel: t('set.achievement.add'),
- emptyHint: t('set.achievement.empty'),
- newRow: () => ({ id: '' }),
- rowError: (row, all) => {
- const id = String(row.id ?? '').trim();
- if (!id) return t('set.achievement.errId');
- // A store keys achievements by this exact string, so two rows differing only
- // in whitespace are one achievement and one that never fires.
- if (all.filter((r) => String(r.id ?? '').trim() === id).length > 1) return t('set.achievement.errDup');
- return null;
- },
- bind: {
- get: () => (ProjectStore.packagingSettings().achievements ?? []).map((id) => ({ id })),
- set: (v) => void ProjectStore.setPackaging({
- achievements: v.map((r) => String(r.id ?? '').trim()).filter(Boolean),
- }),
- },
-});
-
// Where Steam's own library comes from. A path rather than a checkbox because the
// engine has no copy to switch on: the SDK is the developer's download, and the
// assembler takes exactly one file out of it.
settingsRegistry.register({
id: 'project.packaging.desktop.steam.sdkPath',
type: 'path', pick: 'directory',
- scope: 'project', section: 'packaging', group: t('set.group.steam'),
+ scope: 'project', section: 'packaging', platform: 'desktop',
+ group: t('set.group.steam'),
label: t('set.project.packaging.desktop.steam.sdkPath'),
description: t('set.project.packaging.desktop.steam.sdkPath.desc'),
pickTitle: t('set.project.packaging.desktop.steam.sdkPath.pick'),
default: '',
+ visibleWhen: () => desktopChannel() === 'steam',
bind: {
get: () => ProjectStore.platformPackaging().desktop?.steam?.sdkPath ?? '',
set: (v) => void ProjectStore.setSteamPackaging({ sdkPath: v.trim() || undefined }),
@@ -536,10 +592,12 @@ settingsRegistry.register({
for (const os of ['macos', 'windows', 'linux'] as const) {
settingsRegistry.register({
id: `project.packaging.desktop.steam.depot.${os}`,
- type: 'number', scope: 'project', section: 'packaging', group: t('set.group.steam'),
+ type: 'number', scope: 'project', section: 'packaging', platform: 'desktop',
+ group: t('set.group.steam'),
label: t(`set.project.packaging.desktop.steam.depot.${os}`),
description: t('set.project.packaging.desktop.steam.depot.desc'),
default: 0, min: 0, step: 1,
+ visibleWhen: () => desktopChannel() === 'steam',
bind: {
get: () => ProjectStore.platformPackaging().desktop?.steam?.depots?.[os] ?? 0,
set: (v) => void ProjectStore.setSteamDepot(os, v > 0 ? Math.round(v) : undefined),
diff --git a/desktop/src/settings/registry.ts b/desktop/src/settings/registry.ts
index 10401b839..ac672b8ae 100644
--- a/desktop/src/settings/registry.ts
+++ b/desktop/src/settings/registry.ts
@@ -53,9 +53,21 @@ class SettingsRegistry {
.filter((g) => g.sections.length > 0);
}
- /** Settings in a section, in declared registration order. */
+ /**
+ * Settings in a section, in declared registration order.
+ *
+ * A setting that names a packaging target is NOT here: it is edited on that
+ * target's page in the Package Project dialog (see {@link Setting.platform}),
+ * and a value with two editors is a value with two answers.
+ */
settingsForSection(sectionId: string): Setting[] {
- return this.all().filter((s) => s.section === sectionId);
+ return this.all().filter((s) => s.section === sectionId && !s.platform);
+ }
+
+ /** The settings one packaging target declares, in registration order. Open to
+ * a project's own platform id, since that is what a platform id is. */
+ settingsForPlatform(platform: string): Setting[] {
+ return this.all().filter((s) => s.platform === platform);
}
/** Retract every section + setting of one owner (plugin unload / disable). */
diff --git a/desktop/src/settings/types.ts b/desktop/src/settings/types.ts
index c6d0c7f61..30e2c2765 100644
--- a/desktop/src/settings/types.ts
+++ b/desktop/src/settings/types.ts
@@ -11,6 +11,7 @@
* - `effect` — for store-owned settings, push the value to runtime on set + on
* hydrate (CSS variable, engine resource, …). Persisted by the store.
*/
+import type { ExportPlatform } from '@/project/platforms';
/** Where a setting lives / persists. editor → per-user (localStorage). */
export type SettingScope = 'editor' | 'project';
@@ -23,6 +24,9 @@ export interface SettingsSection {
label: string;
category: SettingCategory;
order?: number;
+ /** A line above the section's rows, for a section whose contents are only half
+ * the story — where the rest is edited says so rather than being folklore. */
+ hint?: string;
}
interface BaseSetting<T> {
@@ -33,6 +37,19 @@ interface BaseSetting<T> {
section: string;
/** Group header within the section content. */
group?: string;
+ /**
+ * The packaging target this setting BELONGS to — a Steam depot id, a WeChat
+ * appid. Edited on that target's page in Package Project and nowhere else;
+ * unmarked ⇒ it holds whatever the project ships to. {@link section} still
+ * applies, so settings search finds it either way.
+ */
+ platform?: ExportPlatform;
+ /**
+ * Whether this row applies right now, read at render time — a depot id on a
+ * build that is not going to Steam is not a blank to fill in. A hidden row
+ * keeps its stored value.
+ */
+ visibleWhen?: () => boolean;
label: string;
description?: string;
default: T;
diff --git a/desktop/src/store/editorStore.ts b/desktop/src/store/editorStore.ts
index c15bd041d..17561155a 100644
--- a/desktop/src/store/editorStore.ts
+++ b/desktop/src/store/editorStore.ts
@@ -105,6 +105,11 @@ interface EditorState {
// Package/Build dialog (File → Build) — the UE5-style export modal.
buildOpen: boolean;
setBuildOpen: (open: boolean) => void;
+ /** Target to open the build dialog on; null = the one the project last packaged
+ * for. Set when something elsewhere means a SPECIFIC target's page — settings
+ * search landing on a row that is edited there. */
+ buildPlatform: string | null;
+ openBuild: (platform?: string | null) => void;
// Settings window (the registry-driven preferences dialog).
settingsOpen: boolean;
@@ -223,6 +228,8 @@ export const useEditorStore = create<EditorState>((set) => ({
buildOpen: false,
setBuildOpen: (buildOpen) => set({ buildOpen }),
+ buildPlatform: null,
+ openBuild: (platform = null) => set({ buildOpen: true, buildPlatform: platform }),
settingsOpen: false,
setSettingsOpen: (settingsOpen) => set({ settingsOpen }),
diff --git a/desktop/src/theme/menus.css b/desktop/src/theme/menus.css
index a55d5d725..aaabaac97 100644
--- a/desktop/src/theme/menus.css
+++ b/desktop/src/theme/menus.css
@@ -385,6 +385,15 @@
.build__group-body .build__row { gap: 10px; }
.build__group-body .build__label { width: 118px; }
+/* A target's own settings, rendered by the settings row renderer (SettingsRow.tsx)
+ so a packaging setting is the same row in both windows. Only the widths differ:
+ this dialog is narrower than the settings window, and the first group here sits
+ directly under the section head rather than needing its own top margin. */
+.build__settings .set-row { grid-template-columns: 1fr 190px 14px; gap: 10px; padding: 7px 0; }
+.build__settings .set-row:last-child { border-bottom: none; padding-bottom: 0; }
+.build__settings .set-group { font-size: var(--fs-xs); margin: 0 0 6px; padding-bottom: 5px; }
+.build__settings .set-group:not(:first-child) { margin-top: 14px; }
+
/* Progressive disclosure: advanced (hot-update CDN / source maps / open folder). */
.build__adv { display: flex; align-items: center; gap: 6px; font-size: var(--fs-xs); color: var(--text-dim); background: none; border: none; cursor: pointer; padding: 2px 0; }
.build__adv:hover { color: var(--text); }
diff --git a/desktop/src/theme/settings.css b/desktop/src/theme/settings.css
index 0e3a3f19c..fe3fe20e9 100644
--- a/desktop/src/theme/settings.css
+++ b/desktop/src/theme/settings.css
@@ -101,6 +101,35 @@
from { opacity: 0; transform: translateY(8px); }
to { opacity: 1; transform: translateY(0); }
}
+/* A section whose contents are only half the story says where the rest is. */
+.set-hint {
+ font-size: var(--fs-xs);
+ color: var(--text-mute);
+ line-height: 1.5;
+ padding: 8px 10px;
+ margin-bottom: 10px;
+ background: var(--srf-3);
+ border: 1px solid var(--border-soft);
+ border-radius: var(--r-sm);
+}
+
+/* A search hit this window does not edit: the control column holds the way to
+ where it IS edited, not a second copy of the control. */
+.set-goto {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ height: 24px;
+ padding: 0 10px;
+ font-size: var(--fs-xs);
+ color: var(--text);
+ background: var(--srf-4);
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ cursor: pointer;
+}
+.set-goto:hover { border-color: var(--acc); color: var(--acc); }
+
.set-group {
font-size: var(--fs-md);
font-weight: 700;
diff --git a/desktop/tests/packaging-settings-home.test.ts b/desktop/tests/packaging-settings-home.test.ts
new file mode 100644
index 000000000..b9d432af6
--- /dev/null
+++ b/desktop/tests/packaging-settings-home.test.ts
@@ -0,0 +1,119 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Where a packaging setting is edited — and that it is edited in exactly
+ * one place.
+ *
+ * `Setting.platform` puts a target's own values (a WeChat appid, the
+ * desktop channel, Steam's ids) on that target's page in Package Project
+ * and takes them out of the settings window. What is guarded is not that
+ * they render but that there is one editor per value, and it is reachable.
+ */
+import { describe, it, expect, afterEach } from 'vitest';
+import '@/settings';
+import { settingsRegistry } from '@/settings/registry';
+import { ProjectStore } from '@/project/ProjectStore';
+import { BUILTIN_PLATFORMS } from '@/project/platforms';
+import { platformLabel, unlabeledBuiltins } from '@/project/platformLabels';
+
+/** Every registered setting that claims a packaging target. */
+const targetOwned = () => settingsRegistry.all().filter((s) => s.platform);
+
+describe('a packaging setting has one home', () => {
+ it('names a target the editor actually offers', () => {
+ // A typo reports nothing: the row leaves the settings window AND matches no
+ // platform page, so the value becomes uneditable while every manifest-level
+ // test still passes. Custom platform ids are open, so the guard is built-ins.
+ const known = new Set<string>(BUILTIN_PLATFORMS);
+ for (const s of targetOwned()) expect(known.has(s.platform!)).toBe(true);
+ });
+
+ it('has a name to be reported under', () => {
+ // Settings search names the target a row belongs to. A built-in without a
+ // label is reported by its raw id there — and nowhere else, since every other
+ // surface builds its own row and would look right.
+ expect(unlabeledBuiltins()).toEqual([]);
+ for (const s of targetOwned()) expect(platformLabel(s.platform!)).not.toBe(s.platform);
+ });
+
+ it('is not also offered by the settings window', () => {
+ const inSections = new Set(
+ settingsRegistry.allSections().flatMap((sec) => settingsRegistry.settingsForSection(sec.id).map((s) => s.id)),
+ );
+ for (const s of targetOwned()) expect(inSections.has(s.id)).toBe(false);
+ });
+
+ it('leaves no setting with neither home', () => {
+ // `section` stays declared on a target-owned row (settings search reports
+ // where it lives), so the two queries must partition the registry.
+ const sectioned = settingsRegistry.allSections()
+ .flatMap((sec) => settingsRegistry.settingsForSection(sec.id));
+ const total = sectioned.length + targetOwned().length;
+ expect(total).toBe(settingsRegistry.all().length);
+ });
+
+ it('puts the desktop channel, Steam and the store ids on their target pages', () => {
+ const desktop = settingsRegistry.settingsForPlatform('desktop').map((s) => s.id);
+ expect(desktop).toEqual(expect.arrayContaining([
+ 'project.packaging.desktop.channel',
+ 'project.packaging.desktop.steam.appId',
+ 'project.packaging.desktop.steam.sdkPath',
+ 'project.packaging.desktop.steam.depot.macos',
+ 'project.packaging.desktop.steam.depot.windows',
+ 'project.packaging.desktop.steam.depot.linux',
+ ]));
+ expect(settingsRegistry.settingsForPlatform('wechat').map((s) => s.id))
+ .toContain('project.packaging.wechat.appid');
+ expect(settingsRegistry.settingsForPlatform('android').map((s) => s.id))
+ .toEqual(expect.arrayContaining([
+ 'project.packaging.android.versionCode',
+ 'project.packaging.android.output',
+ 'project.packaging.android.appBundle',
+ ]));
+ });
+
+ it('keeps the platform-neutral rows in the settings window', () => {
+ // One project ships as one application, and every store keeps the same list of
+ // achievement ids under a different name — so these answer for the project,
+ // not for a target, and a target page is the wrong place to ask.
+ for (const id of ['project.packaging.appId', 'project.packaging.icon', 'project.packaging.achievements']) {
+ expect(settingsRegistry.get(id)?.platform).toBeUndefined();
+ }
+ expect(settingsRegistry.settingsForSection('packaging').map((s) => s.id))
+ .toEqual(expect.arrayContaining(['project.packaging.appId', 'project.packaging.achievements']));
+ });
+});
+
+describe('rows that only apply on one answer', () => {
+ const visible = (id: string) => settingsRegistry.get(id)!.visibleWhen?.() !== false;
+ // The predicates read the live project, so the packaging accessor is stood in
+ // for — and put back, since the registry these tests share outlives the block.
+ const real = ProjectStore.platformPackaging;
+ afterEach(() => { ProjectStore.platformPackaging = real; });
+
+ it('asks for Steam ids only on the Steam channel', () => {
+ // Not a styling detail: a depot id on a standalone build is not a blank to
+ // fill in, it is a question nobody asked — and showing it is exactly the
+ // "every target's answers at once" list this split removes.
+ ProjectStore.platformPackaging = () => ({ desktop: { channel: 'standalone' } });
+ expect(visible('project.packaging.desktop.steam.appId')).toBe(false);
+ expect(visible('project.packaging.desktop.steam.depot.macos')).toBe(false);
+ // The channel itself is always the question.
+ expect(visible('project.packaging.desktop.channel')).toBe(true);
+
+ ProjectStore.platformPackaging = () => ({ desktop: { channel: 'steam' } });
+ expect(visible('project.packaging.desktop.steam.appId')).toBe(true);
+ expect(visible('project.packaging.desktop.steam.sdkPath')).toBe(true);
+ expect(visible('project.packaging.desktop.steam.depot.linux')).toBe(true);
+ });
+
+ it('asks for an App Bundle only when the build produces a package', () => {
+ ProjectStore.platformPackaging = () => ({ android: { output: 'project' } });
+ expect(visible('project.packaging.android.appBundle')).toBe(false);
+ ProjectStore.platformPackaging = () => ({ android: { output: 'package' } });
+ expect(visible('project.packaging.android.appBundle')).toBe(true);
+ // Absent output means the default, which is a package.
+ ProjectStore.platformPackaging = () => ({});
+ expect(visible('project.packaging.android.appBundle')).toBe(true);
+ });
+});