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): the audio mixer is a plugin, and the editor ships it

yhh96e94a18d8d2
diff --git a/desktop/electron-builder.yml b/desktop/electron-builder.yml
index 41180dc1c..592e55f02 100644
--- a/desktop/electron-builder.yml
+++ b/desktop/electron-builder.yml
@@ -63,6 +63,16 @@ extraResources:
to: sdk-types
filter:
- "**/*.d.ts"
+ # The plugins the editor ships with. They are ordinary plugins — the same
+ # manifest, the same contribution API a third party writes against — installed
+ # rather than built in, which is what keeps that API load-bearing. Staged as
+ # directories because the plugin host compiles their entry from disk.
+ - from: ../plugins
+ to: plugins
+ filter:
+ - "**/*"
+ - "!**/node_modules/**"
+ - "!**/tests/**"
# New-project templates: the bundled blank-slate starter(s) plus the sample
# projects, staged as real directories (createFromTemplate copies a template
# with fs.cp, which cannot source from inside the asar). The launcher reads
diff --git a/desktop/electron/main.ts b/desktop/electron/main.ts
index 662cfe947..39de28f7e 100644
--- a/desktop/electron/main.ts
+++ b/desktop/electron/main.ts
@@ -1403,19 +1403,33 @@ const userData = (): string => app.getPath('userData');
// also keeps the catalog unit-testable with no gate installed.
setPlatformTrustGate((id, file) => isTrusted(userData(), id, '0.0.0', file));
+/**
+ * Where the editor's own plugins ship — a resource in a packaged app, the
+ * monorepo's `plugins/` in a dev run, the same shape the templates take. Trusted
+ * because they arrived with the app: prompting for a feature of the editor you
+ * installed teaches people to click through prompts.
+ */
+const BUILTIN_PLUGIN_DIR = app.isPackaged
+ ? path.join(process.resourcesPath, 'plugins')
+ : path.join(process.env.APP_ROOT ?? '', '..', 'plugins');
+
+const allPlugins = () => discoverPlugins(projectRoot, userData(), BUILTIN_PLUGIN_DIR);
+const pluginTrusted = (p: { scope: string; id: string; dir: string; manifest?: { version: string } }) =>
+ p.scope === 'builtin' || isTrusted(userData(), p.id, p.manifest?.version ?? '0.0.0', p.dir);
+
ipcMain.handle('plugins:list', async () => {
- const found = await discoverPlugins(projectRoot, userData());
+ const found = await allPlugins();
return found.map((p) => ({ ...p, disabled: isDisabled(userData(), p.id) }));
});
ipcMain.handle('plugins:load', async (_e, id: string) => {
- const found = await discoverPlugins(projectRoot, userData());
+ const found = await allPlugins();
const plugin = found.find((p) => p.id === id && !p.shadowedBy);
if (!plugin) return { ok: false, errors: [`plugin "${id}" not found`], warnings: [] };
const entry = plugin.manifest?.main?.editor;
if (!entry) return { ok: false, errors: [`plugin "${id}" has no renderer entry`], warnings: [] };
const built = await compilePlugin(plugin.dir, entry);
- return { ...built, trusted: isTrusted(userData(), id, plugin.manifest!.version, plugin.dir) };
+ return { ...built, trusted: pluginTrusted(plugin) };
});
// The renderer says only "the user approved this id" — main resolves which version
@@ -1423,13 +1437,13 @@ ipcMain.handle('plugins:load', async (_e, id: string) => {
// Trust WITHOUT compiling — what a project platform profile needs, since it has no
// renderer entry to build and approving it only permits a main-process import.
ipcMain.handle('plugins:trustState', async (_e, id: string) => {
- const found = await discoverPlugins(projectRoot, userData());
+ const found = await allPlugins();
const entry = found.find((p) => p.id === id && p.manifest);
- return !!entry && isTrusted(userData(), id, entry.manifest!.version, entry.dir);
+ return !!entry && pluginTrusted(entry);
});
ipcMain.handle('plugins:trust', async (_e, id: string) => {
- const found = await discoverPlugins(projectRoot, userData());
+ const found = await allPlugins();
const plugin = found.find((p) => p.id === id && p.manifest);
if (plugin) trustPlugin(userData(), id, plugin.manifest!.version, plugin.dir);
});
@@ -1438,7 +1452,7 @@ ipcMain.handle('plugins:setEnabled', (_e, id: string, enabled: boolean) =>
setPluginEnabled(userData(), id, enabled),
);
ipcMain.handle('plugins:reveal', async (_e, id: string) => {
- const found = await discoverPlugins(projectRoot, userData());
+ const found = await allPlugins();
const dir = found.find((p) => p.id === id)?.dir;
if (dir) shell.openPath(dir);
});
@@ -1466,7 +1480,7 @@ ipcMain.handle('plugins:scaffold', async (_e, scope: 'project' | 'user', opts: S
// name carries the id and version, so a folder of these stays readable.
ipcMain.handle('plugins:export', async (_e, id: string) => {
if (!win) return { ok: false, error: 'no window' };
- const found = await discoverPlugins(projectRoot, userData());
+ const found = await allPlugins();
const entry = found.find((p) => p.id === id && p.kind === 'plugin');
if (!entry?.manifest) return { ok: false, error: `plugin "${id}" not found` };
diff --git a/desktop/electron/pluginHost.ts b/desktop/electron/pluginHost.ts
index 895881e9a..de847f7df 100644
--- a/desktop/electron/pluginHost.ts
+++ b/desktop/electron/pluginHost.ts
@@ -6,12 +6,13 @@
*
* Three things the renderer cannot do for itself:
*
- * 1. DISCOVERY. Plugins live on disk in three scopes — inside the project
+ * 1. DISCOVERY. Plugins live on disk in four scopes — inside the project
* (`.esengine/plugins/`, versioned with it, shared by the team), installed
- * from npm (a direct dependency shipping a `plugin.json`), and per-user
- * (`<userData>/plugins/`, personal tools across projects). On an id collision
- * the higher-priority scope wins and the shadowed one is REPORTED rather than
- * dropped.
+ * from npm (a direct dependency shipping a `plugin.json`), per-user
+ * (`<userData>/plugins/`, personal tools across projects), and the ones the
+ * editor ships with. On an id collision the higher-priority scope wins and
+ * the shadowed one is REPORTED rather than dropped — which is also how a
+ * project replaces a shipped plugin with its own build of it.
*
* 2. COMPILATION. Authors write ESM TypeScript with no build step; esbuild turns
* the entry into one CJS module through the same single door the project-script
@@ -43,8 +44,8 @@ export const PROJECT_PLUGIN_DIR = path.join(...PROJECT_PLUGIN_REL.split('/'));
export const USER_PLUGIN_DIR = 'plugins';
/** Which scope a plugin was found in. On an id collision the first of
- * project → package → user wins, and the others say who took it. */
-export type PluginScope = 'project' | 'package' | 'user';
+ * project → package → user → builtin wins, and the others say who took it. */
+export type PluginScope = 'project' | 'package' | 'user' | 'builtin';
/**
* What kind of project-supplied code an entry is.
@@ -90,10 +91,12 @@ const EDITOR_EXTERNALS = ['react', 'react-dom', 'react-dom/client', 'react/jsx-r
/** One plugin folder read into a record. `fallbackId` names it while the manifest
* cannot: an unreadable plugin still has to appear, carrying the reason. */
+const NO_MANIFEST = 'folder has no plugin.json';
+
async function readOnePlugin(pluginDir: string, scope: PluginScope, fallbackId: string): Promise<DiscoveredPlugin> {
const base = { kind: 'plugin' as const, scope, dir: pluginDir };
const manifestFile = path.join(pluginDir, 'plugin.json');
- if (!existsSync(manifestFile)) return { ...base, id: fallbackId, error: 'folder has no plugin.json' };
+ if (!existsSync(manifestFile)) return { ...base, id: fallbackId, error: NO_MANIFEST };
try {
const parsed: unknown = JSON.parse(await readFile(manifestFile, 'utf8'));
const result = validateManifest(parsed);
@@ -118,7 +121,11 @@ async function readPluginDir(dir: string, scope: PluginScope): Promise<Discovere
} catch {
return [];
}
- return Promise.all(names.map((name) => readOnePlugin(path.join(dir, name), scope, name)));
+ const found = await Promise.all(names.map((name) => readOnePlugin(path.join(dir, name), scope, name)));
+ // A folder someone put in a plugins directory and got wrong is worth naming.
+ // One the editor SHIPS is a package that may simply have no editor half — a
+ // runtime-only plugin is not a broken one.
+ return scope === 'builtin' ? found.filter((p) => p.error !== NO_MANIFEST) : found;
}
/**
@@ -192,11 +199,16 @@ async function readPlatformProfiles(root: string): Promise<DiscoveredPlugin[]> {
* personal one installed for every project. A shadowed plugin is listed carrying
* `shadowedBy` rather than dropped, so the UI can say why it isn't running.
*/
-export async function discoverPlugins(root: string | null, userDataDir: string): Promise<DiscoveredPlugin[]> {
+export async function discoverPlugins(
+ root: string | null,
+ userDataDir: string,
+ builtinDir?: string,
+): Promise<DiscoveredPlugin[]> {
const project = root ? await readPluginDir(path.join(root, PROJECT_PLUGIN_DIR), 'project') : [];
const platforms = root ? await readPlatformProfiles(root) : [];
const packages = root ? await readPackagePlugins(root) : [];
const user = await readPluginDir(path.join(userDataDir, USER_PLUGIN_DIR), 'user');
+ const builtin = builtinDir ? await readPluginDir(builtinDir, 'builtin') : [];
const claimed = new Map(project.map((p) => [p.id, p.scope]));
const resolve = (list: DiscoveredPlugin[]): DiscoveredPlugin[] =>
list.map((p) => {
@@ -205,7 +217,7 @@ export async function discoverPlugins(root: string | null, userDataDir: string):
claimed.set(p.id, p.scope);
return p;
});
- return [...project, ...platforms, ...resolve(packages), ...resolve(user)];
+ return [...project, ...platforms, ...resolve(packages), ...resolve(user), ...resolve(builtin)];
}
// =============================================================================
diff --git a/desktop/src/i18n/messages/index.ts b/desktop/src/i18n/messages/index.ts
index 9305198dd..08e72abdd 100644
--- a/desktop/src/i18n/messages/index.ts
+++ b/desktop/src/i18n/messages/index.ts
@@ -33,7 +33,6 @@ import { sequencerMessages } from './sequencer';
import { nodegraphMessages } from './nodegraph';
import { tileMessages } from './tile';
import { flipbookMessages } from './flipbook';
-import { mixerMessages } from './mixer';
import { materialMessages } from './material';
import { projectMessages } from './project';
import { controllerMessages } from './controllers';
@@ -60,7 +59,6 @@ export const messageModules = {
nodegraph: nodegraphMessages,
tile: tileMessages,
flipbook: flipbookMessages,
- mixer: mixerMessages,
material: materialMessages,
project: projectMessages,
controllers: controllerMessages,
@@ -87,7 +85,6 @@ export const editorMessages = {
...nodegraphMessages,
...tileMessages,
...flipbookMessages,
- ...mixerMessages,
...materialMessages,
...projectMessages,
...controllerMessages,
diff --git a/desktop/src/i18n/messages/mixer.ts b/desktop/src/i18n/messages/mixer.ts
deleted file mode 100644
index 92673873e..000000000
--- a/desktop/src/i18n/messages/mixer.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-// SPDX-License-Identifier: Apache-2.0
-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-/**
- * @file mixer.ts — Audio Mixer panel: bus strips, effects, ducking.
- */
-import { defineMessages } from './types';
-
-export const mixerMessages = defineMessages({
- 'mix.panelTitle': { en: 'Audio Mixer', zh: '音频混音器' },
- 'mix.noProjectTitle': { en: 'No project open', zh: '未打开项目' },
- 'mix.noProject': { en: 'Open a project to edit its mixer.', zh: '打开项目后编辑其混音器。' },
- 'mix.mute': { en: 'Mute', zh: '静音' },
- 'mix.addBus': { en: 'Add Bus', zh: '添加总线' },
- 'mix.removeBus': { en: 'Remove bus', zh: '移除总线' },
- 'mix.duckBy': { en: 'Duck by', zh: '被压低于' },
- 'mix.duckNone': { en: '(none)', zh: '(无)' },
- 'mix.duckAmount': { en: 'Duck level while the trigger bus is active', zh: '触发总线活跃时压低到的音量' },
-
- 'mix.fx.add': { en: '+ Effect', zh: '+ 效果' },
- 'mix.fx.filter': { en: 'Filter', zh: '滤波器' },
- 'mix.fx.filterKind': { en: 'Filter type', zh: '滤波类型' },
- 'mix.fx.reverb': { en: 'Reverb', zh: '混响' },
- 'mix.fx.compressor': { en: 'Compressor', zh: '压缩器' },
- 'mix.fx.seconds': { en: 'Tail s', zh: '尾音秒' },
- 'mix.fx.wet': { en: 'Wet', zh: '湿声' },
- 'mix.fx.ratio': { en: 'Ratio', zh: '压缩比' },
- 'mix.fx.remove': { en: 'Remove effect', zh: '移除效果' },
-});
diff --git a/desktop/src/i18n/messages/plugins.ts b/desktop/src/i18n/messages/plugins.ts
index b7136174b..dfa0d40a1 100644
--- a/desktop/src/i18n/messages/plugins.ts
+++ b/desktop/src/i18n/messages/plugins.ts
@@ -38,6 +38,7 @@ export const pluginMessages = defineMessages({
'plug.scope.project': { en: 'project', zh: '项目' },
'plug.scope.package': { en: 'package', zh: '依赖包' },
+ 'plug.scope.builtin': { en: 'built in', zh: '内置' },
'plug.scope.user': { en: 'user', zh: '用户' },
// The trust gate. Deliberately plain about what loading a plugin means: it runs
diff --git a/desktop/src/i18n/messages/project.ts b/desktop/src/i18n/messages/project.ts
index 2988cc2a0..10fa00472 100644
--- a/desktop/src/i18n/messages/project.ts
+++ b/desktop/src/i18n/messages/project.ts
@@ -360,7 +360,7 @@ export const projectMessages = defineMessages({
'proj.saveAssetGroupsFailed': { en: 'Failed to save asset delivery config', zh: '保存资产交付配置失败' },
'proj.savePlatformFailed': { en: 'Failed to save platform settings', zh: '保存平台设置失败' },
'proj.savePhysicsFailed': { en: 'Failed to save physics setting', zh: '保存物理设置失败' },
- 'proj.saveAudioFailed': { en: 'Failed to save audio setting', zh: '保存音频设置失败' },
+ 'proj.saveFeatureFailed': { en: 'Failed to save project setting: {name}', zh: '保存项目设置失败:{name}' },
'proj.saveUiThemeFailed': { en: 'Failed to save UI theme', zh: '保存 UI 主题失败' },
'proj.startupScene': { en: 'Startup scene: {name}', zh: '启动场景:{name}' },
'proj.saveStartupSceneFailed': { en: 'Failed to save startup scene', zh: '保存启动场景失败' },
diff --git a/desktop/src/layout/ActivityBar.tsx b/desktop/src/layout/ActivityBar.tsx
index 53de1cf5b..6535df546 100644
--- a/desktop/src/layout/ActivityBar.tsx
+++ b/desktop/src/layout/ActivityBar.tsx
@@ -3,7 +3,7 @@
// Far-left icon rail (activity bar). Switches the editing mode, reveals docked
// panels, and toggles the Content Drawer — the summoned quick-access surface.
import { useSyncExternalStore } from 'react';
-import { ListTree, SlidersHorizontal, SlidersVertical, FolderOpen, Terminal, Clapperboard, Gauge, Settings, Sparkles } from 'lucide-react';
+import { ListTree, SlidersHorizontal, FolderOpen, Terminal, Clapperboard, Gauge, Settings, Sparkles } from 'lucide-react';
import { useEditorStore } from '@/store/editorStore';
import { useEditorMode } from '@/store/editorModeStore';
import { useSelection } from '@/store/selectionStore';
@@ -96,16 +96,6 @@ export function ActivityBar() {
>
<Gauge size={19} strokeWidth={1.7} />
</button>
- <button
- type="button"
- className="act"
- title={t('mix.panelTitle')}
- onClick={() => dockApi.revealAndExpand('audiomixer')}
- >
- {/* Vertical faders read as a mixing console — distinct from the Details
- toggle's horizontal sliders just above it on the rail. */}
- <SlidersVertical size={19} strokeWidth={1.7} />
- </button>
<span className="act-spacer" />
diff --git a/desktop/src/layout/DockLayout.tsx b/desktop/src/layout/DockLayout.tsx
index 1d210834b..8e3dcac31 100644
--- a/desktop/src/layout/DockLayout.tsx
+++ b/desktop/src/layout/DockLayout.tsx
@@ -23,6 +23,7 @@ import {
panelRegistry, panelTitle,
} from '@/layout/panels';
import { PANEL_RENDERERS, MountedPanel, type PanelRenderer } from '@/layout/panelComponents';
+import { pruneLayout } from '@/layout/pruneLayout';
import { t } from '@/i18n';
// Each dock panel is a thin wrapper so dockview owns mount/unmount. The
@@ -248,9 +249,13 @@ export function DockLayout() {
});
const saved = localStorage.getItem(LAYOUT_KEY);
- if (saved) {
+ // dockview refuses a layout WHOLE over one panel it cannot render, so the
+ // missing ones are dropped from it first: a panel costs its own tab rather
+ // than the arrangement.
+ const restorable = saved ? pruneLayout(JSON.parse(saved), new Set(Object.keys(components))) : null;
+ if (restorable) {
try {
- api.fromJSON(JSON.parse(saved));
+ api.fromJSON(restorable as Parameters<typeof api.fromJSON>[0]);
retitleRestoredPanels(api);
} catch {
api.clear();
diff --git a/desktop/src/layout/panelComponents.tsx b/desktop/src/layout/panelComponents.tsx
index 7f7bf0295..78c45ef5d 100644
--- a/desktop/src/layout/panelComponents.tsx
+++ b/desktop/src/layout/panelComponents.tsx
@@ -22,7 +22,6 @@ import { GamePanel, GameClientPanel } from '@/panels/GamePanel';
import { Sequencer } from '@/panels/Sequencer';
import { TilesetEditor } from '@/panels/TilesetEditor';
import { FlipbookEditor } from '@/panels/FlipbookEditor';
-import { AudioMixerPanel } from '@/panels/AudioMixerPanel';
import { TilemapPainter } from '@/panels/TilemapPainter';
import { UIWidgetsPanel } from '@/panels/UIWidgetsPanel';
import { ControllersPanel } from '@/panels/ControllersPanel';
@@ -74,7 +73,6 @@ export const PANEL_RENDERERS: Record<string, PanelRenderer> = {
sequencer: () => <Sequencer />,
tileset: () => <TilesetEditor />,
flipbook: () => <FlipbookEditor />,
- audiomixer: () => <AudioMixerPanel />,
tilemap: () => <TilemapPainter />,
uiWidgets: () => <UIWidgetsPanel />,
controllers: () => <ControllersPanel />,
diff --git a/desktop/src/layout/panels.ts b/desktop/src/layout/panels.ts
index f87d20d83..694ae6b90 100644
--- a/desktop/src/layout/panels.ts
+++ b/desktop/src/layout/panels.ts
@@ -95,7 +95,6 @@ const STRUCTURAL: PanelDef[] = [
const BOTTOM: PanelDef[] = [
{ id: 'sequencer', title: () => t('layout.panel.sequencer'), placement: 'bottom', refs: ['content', 'log'], ensure: true },
{ id: 'profiler', title: () => t('layout.panel.profiler'), placement: 'bottom', refs: ['log', 'content'], ensure: true, noPerf: true },
- { id: 'audiomixer', title: () => t('mix.panelTitle'), placement: 'bottom', refs: ['log', 'content'], ensure: true },
// Opened on demand rather than ensured: most sessions have no plugins, and a
// permanent tab for an empty list is noise.
{ id: 'plugins', title: () => t('plug.panelTitle'), placement: 'bottom', refs: ['log', 'content'] },
diff --git a/desktop/src/layout/pruneLayout.ts b/desktop/src/layout/pruneLayout.ts
new file mode 100644
index 000000000..25ba8d101
--- /dev/null
+++ b/desktop/src/layout/pruneLayout.ts
@@ -0,0 +1,107 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file pruneLayout.ts — a saved dock layout, minus what this build cannot render.
+ *
+ * dockview refuses a WHOLE layout over one unknown component — a panel removed
+ * from the editor, or contributed by a plugin that is not loaded. Dropping that
+ * panel alone keeps the arrangement.
+ *
+ * Pure: JSON in, JSON out. `null` means nothing usable is left, and the caller
+ * should build the default layout.
+ */
+
+interface PanelState {
+ contentComponent?: string;
+ [key: string]: unknown;
+}
+interface LeafData {
+ views?: string[];
+ activeView?: string;
+ id?: string;
+ [key: string]: unknown;
+}
+interface GridNode {
+ type?: string;
+ data?: LeafData | GridNode[];
+ [key: string]: unknown;
+}
+interface SavedLayout {
+ grid?: { root?: GridNode; [key: string]: unknown };
+ panels?: Record<string, PanelState>;
+ activeGroup?: string;
+ floatingGroups?: Array<{ data?: LeafData; [key: string]: unknown }>;
+ popoutGroups?: Array<{ data?: LeafData; [key: string]: unknown }>;
+ [key: string]: unknown;
+}
+
+const isBranch = (node: GridNode): node is GridNode & { data: GridNode[] } => Array.isArray(node.data);
+
+/** A leaf with the dropped ids gone, or null when nothing is left in it. */
+function pruneLeaf(data: LeafData, keep: (id: string) => boolean): LeafData | null {
+ const views = (data.views ?? []).filter(keep);
+ if (views.length === 0) return null;
+ return {
+ ...data,
+ views,
+ // An active tab that was dropped leaves the group with none; the first
+ // surviving one is what dockview would have shown anyway.
+ activeView: data.activeView && views.includes(data.activeView) ? data.activeView : views[0],
+ };
+}
+
+function pruneNode(node: GridNode, keep: (id: string) => boolean): GridNode | null {
+ if (isBranch(node)) {
+ const children = node.data.map((c) => pruneNode(c, keep)).filter((c): c is GridNode => c !== null);
+ return children.length === 0 ? null : { ...node, data: children };
+ }
+ const data = pruneLeaf((node.data ?? {}) as LeafData, keep);
+ return data === null ? null : { ...node, data };
+}
+
+/**
+ * `layout` with every panel whose component this build does not have removed,
+ * or null when that empties it. `known` is the set of component keys the dock
+ * can render right now.
+ */
+export function pruneLayout(layout: unknown, known: ReadonlySet<string>): unknown | null {
+ if (!layout || typeof layout !== 'object') return null;
+ const saved = layout as SavedLayout;
+ const panels = saved.panels ?? {};
+ const kept = new Set(
+ Object.entries(panels)
+ .filter(([, p]) => p?.contentComponent === undefined || known.has(p.contentComponent))
+ .map(([id]) => id),
+ );
+ if (kept.size === Object.keys(panels).length) return layout; // nothing to do
+ const keep = (id: string): boolean => kept.has(id);
+
+ const root = saved.grid?.root ? pruneNode(saved.grid.root, keep) : null;
+ if (!root) return null;
+
+ type Group = NonNullable<SavedLayout['floatingGroups']>[number];
+ const groups = (list: Group[]): Group[] =>
+ list
+ .map((g) => ({ ...g, data: g.data ? pruneLeaf(g.data, keep) ?? undefined : undefined }))
+ .filter((g) => g.data !== undefined);
+
+ const surviving = new Set<string>();
+ const collect = (node: GridNode): void => {
+ if (isBranch(node)) {
+ node.data.forEach(collect);
+ return;
+ }
+ const id = (node.data as LeafData | undefined)?.id;
+ if (typeof id === 'string') surviving.add(id);
+ };
+ collect(root);
+
+ return {
+ ...saved,
+ grid: { ...saved.grid, root },
+ panels: Object.fromEntries(Object.entries(panels).filter(([id]) => kept.has(id))),
+ ...(saved.activeGroup && !surviving.has(saved.activeGroup) ? { activeGroup: undefined } : {}),
+ ...(saved.floatingGroups ? { floatingGroups: groups(saved.floatingGroups) } : {}),
+ ...(saved.popoutGroups ? { popoutGroups: groups(saved.popoutGroups) } : {}),
+ };
+}
diff --git a/desktop/src/panels/AudioMixerPanel.tsx b/desktop/src/panels/AudioMixerPanel.tsx
deleted file mode 100644
index 287328a96..000000000
--- a/desktop/src/panels/AudioMixerPanel.tsx
+++ /dev/null
@@ -1,236 +0,0 @@
-// SPDX-License-Identifier: Apache-2.0
-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-/**
- * @file AudioMixerPanel.tsx
- * @brief The project mixer — one strip per bus (volume fader, mute, insert
- * chain, duck rule) editing `project.esproject` features.audio. Every
- * edit persists through ProjectStore.setAudio AND live-applies to the
- * edit realm's Audio resource, so tweaks are audible immediately and
- * Play/exports boot the same mix (the config rides the physics-config
- * pipeline).
- */
-
-import { useSyncExternalStore } from 'react';
-import { Plus, Trash2, VolumeX, Volume2 } from 'lucide-react';
-import {
- type AudioProjectConfig, type AudioBusDecl, type BusEffectDef,
-} from 'esengine';
-import { ProjectStore } from '@/project/ProjectStore';
-import { Select } from '@/components/Select';
-import { EmptyState } from '@/components/EmptyState';
-import { t } from '@/i18n';
-
-/** The always-present mixer tree; custom buses append after these. */
-const DEFAULT_BUSES = ['master', 'music', 'sfx', 'ui', 'voice'];
-const DEFAULT_VOLUME: Record<string, number> = { master: 1, music: 0.8, sfx: 1, ui: 1, voice: 1 };
-
-interface StripModel extends AudioBusDecl {
- builtin: boolean;
-}
-
-/** Default buses merged with the project declarations, declaration order kept. */
-function stripsOf(config: AudioProjectConfig): StripModel[] {
- const byName = new Map((config.buses ?? []).map((b) => [b.name, b]));
- const strips: StripModel[] = DEFAULT_BUSES.map((name) => ({
- name, volume: DEFAULT_VOLUME[name], ...byName.get(name), builtin: true,
- }));
- for (const b of config.buses ?? []) {
- if (!DEFAULT_BUSES.includes(b.name)) strips.push({ ...b, builtin: false });
- }
- return strips;
-}
-
-/** Persist one new config state; the store live-applies it to the edit session
- * (setAudio → applyEditorRuntimeConfig), the same way opening a project does —
- * this panel used to be the ONLY thing that applied the mixer, so a project's
- * bus levels were silent until someone opened it. */
-function commit(next: AudioProjectConfig): void {
- void ProjectStore.setAudio(next);
-}
-
-/** Replace/patch one bus's declaration inside the config. */
-function patchBus(config: AudioProjectConfig, name: string, patch: Partial<AudioBusDecl> | null): AudioProjectConfig {
- const buses = [...(config.buses ?? [])];
- const i = buses.findIndex((b) => b.name === name);
- if (patch === null) {
- if (i >= 0) buses.splice(i, 1);
- } else if (i >= 0) {
- buses[i] = { ...buses[i], ...patch };
- } else {
- buses.push({ name, ...patch });
- }
- return { buses };
-}
-
-const FX_KINDS: Array<{ value: BusEffectDef['type']; label: () => string }> = [
- { value: 'filter', label: () => t('mix.fx.filter') },
- { value: 'reverb', label: () => t('mix.fx.reverb') },
- { value: 'compressor', label: () => t('mix.fx.compressor') },
-];
-
-function defaultEffect(type: BusEffectDef['type']): BusEffectDef {
- switch (type) {
- case 'filter': return { type: 'filter', filter: 'lowpass', frequency: 1200, q: 1 };
- case 'reverb': return { type: 'reverb', seconds: 1.5, wet: 0.35 };
- case 'compressor': return { type: 'compressor', thresholdDb: -24, ratio: 4 };
- }
-}
-
-function NumCell(props: { label: string; value: number; step?: number; onCommit: (n: number) => void }) {
- return (
- <label className="mix-num">
- <span>{props.label}</span>
- <input
- type="number" defaultValue={props.value} key={props.value} step={props.step ?? 1}
- onBlur={(e) => {
- const n = Number(e.target.value);
- if (Number.isFinite(n) && n !== props.value) props.onCommit(n);
- }}
- onKeyDown={(e) => { if (e.key === 'Enter') (e.target as HTMLInputElement).blur(); }}
- />
- </label>
- );
-}
-
-function EffectRow(props: { fx: BusEffectDef; onChange: (fx: BusEffectDef) => void; onRemove: () => void }) {
- const { fx, onChange, onRemove } = props;
- return (
- <div className="mix-fx">
- <span className="mix-fx-kind">{FX_KINDS.find((k) => k.value === fx.type)?.label()}</span>
- {fx.type === 'filter' && (
- <>
- <Select
- ariaLabel={t('mix.fx.filterKind')}
- value={fx.filter}
- options={(['lowpass', 'highpass', 'bandpass', 'lowshelf', 'highshelf', 'peaking', 'notch'] as const)
- .map((v) => ({ value: v, label: v }))}
- onChange={(v) => onChange({ ...fx, filter: v })}
- />
- <NumCell label="Hz" value={fx.frequency} step={50} onCommit={(n) => onChange({ ...fx, frequency: Math.max(10, n) })} />
- <NumCell label="Q" value={fx.q ?? 1} step={0.1} onCommit={(n) => onChange({ ...fx, q: n })} />
- </>
- )}
- {fx.type === 'reverb' && (
- <>
- <NumCell label={t('mix.fx.seconds')} value={fx.seconds ?? 1.5} step={0.1} onCommit={(n) => onChange({ ...fx, seconds: Math.max(0.05, n) })} />
- <NumCell label={t('mix.fx.wet')} value={fx.wet ?? 0.35} step={0.05} onCommit={(n) => onChange({ ...fx, wet: Math.max(0, Math.min(1, n)) })} />
- </>
- )}
- {fx.type === 'compressor' && (
- <>
- <NumCell label="dB" value={fx.thresholdDb ?? -24} onCommit={(n) => onChange({ ...fx, thresholdDb: n })} />
- <NumCell label={t('mix.fx.ratio')} value={fx.ratio ?? 4} step={0.5} onCommit={(n) => onChange({ ...fx, ratio: Math.max(1, n) })} />
- </>
- )}
- <button type="button" className="mix-rm" title={t('mix.fx.remove')} onClick={onRemove}>
- <Trash2 size={12} />
- </button>
- </div>
- );
-}
-
-function BusStrip(props: { strip: StripModel; all: StripModel[]; config: AudioProjectConfig }) {
- const { strip, all, config } = props;
- const volume = strip.volume ?? 1;
- const patch = (p: Partial<AudioBusDecl> | null) => commit(patchBus(config, strip.name, p));
- const effects = strip.effects ?? [];
- const duckTargets = all.filter((s) => s.name !== strip.name).map((s) => s.name);
-
- return (
- <div className="mix-strip">
- <div className="mix-head">
- <span className="mix-name">{strip.name}</span>
- {!strip.builtin && (
- <button type="button" className="mix-rm" title={t('mix.removeBus')} onClick={() => patch(null)}>
- <Trash2 size={12} />
- </button>
- )}
- </div>
-
- <div className="mix-vol">
- <input
- type="range" min={0} max={1} step={0.01} value={volume}
- className="mix-fader"
- onChange={(e) => patch({ volume: Number(e.target.value) })}
- />
- <span className="mix-vol-num">{Math.round(volume * 100)}</span>
- <button
- type="button"
- className={'mix-mute' + (strip.muted ? ' is-on' : '')}
- title={t('mix.mute')}
- onClick={() => patch({ muted: !strip.muted })}
- >
- {strip.muted ? <VolumeX size={13} /> : <Volume2 size={13} />}
- </button>
- </div>
-
- <div className="mix-fxs">
- {effects.map((fx, i) => (
- <EffectRow
- key={`${i}-${fx.type}`}
- fx={fx}
- onChange={(nf) => patch({ effects: effects.map((e, j) => (j === i ? nf : e)) })}
- onRemove={() => patch({ effects: effects.filter((_, j) => j !== i) })}
- />
- ))}
- <Select
- ariaLabel={t('mix.fx.add')}
- value={'' as string}
- options={[
- { value: '', label: t('mix.fx.add') },
- ...FX_KINDS.map((k) => ({ value: k.value as string, label: k.label() })),
- ]}
- onChange={(v) => { if (v) patch({ effects: [...effects, defaultEffect(v as BusEffectDef['type'])] }); }}
- />
- </div>
-
- {strip.name !== 'master' && (
- <div className="mix-duck">
- <span className="mix-lbl">{t('mix.duckBy')}</span>
- <Select
- ariaLabel={t('mix.duckBy')}
- value={strip.duck?.trigger ?? ''}
- options={[{ value: '', label: t('mix.duckNone') }, ...duckTargets.map((n) => ({ value: n, label: n }))]}
- onChange={(v) => patch({ duck: v ? { trigger: v, amount: strip.duck?.amount ?? 0.3 } : undefined })}
- />
- {strip.duck && (
- <input
- type="range" min={0} max={1} step={0.05} value={strip.duck.amount}
- className="mix-duck-amt" title={t('mix.duckAmount')}
- onChange={(e) => patch({ duck: { ...strip.duck!, amount: Number(e.target.value) } })}
- />
- )}
- </div>
- )}
- </div>
- );
-}
-
-export function AudioMixerPanel() {
- const project = useSyncExternalStore(ProjectStore.subscribe, ProjectStore.getSnapshot);
- if (!project) {
- return <EmptyState icon={Volume2} title={t('mix.noProjectTitle')} hint={t('mix.noProject')} />;
- }
- const config = ProjectStore.audioFeature();
- const strips = stripsOf(config);
-
- const addBus = () => {
- let n = 1;
- let name = 'bus';
- while (strips.some((s) => s.name === name)) name = `bus-${n++}`;
- commit(patchBus(config, name, { parent: 'master', volume: 1 }));
- };
-
- return (
- <div className="mix-panel">
- <div className="mix-strips">
- {strips.map((s) => (
- <BusStrip key={s.name} strip={s} all={strips} config={config} />
- ))}
- <button type="button" className="mix-add" title={t('mix.addBus')} onClick={addBus}>
- <Plus size={14} /> {t('mix.addBus')}
- </button>
- </div>
- </div>
- );
-}
diff --git a/desktop/src/panels/PluginsPanel.tsx b/desktop/src/panels/PluginsPanel.tsx
index f536b9456..9aef809a2 100644
--- a/desktop/src/panels/PluginsPanel.tsx
+++ b/desktop/src/panels/PluginsPanel.tsx
@@ -42,6 +42,7 @@ const PHASE_LABEL: Record<PluginPhase, MsgKey> = {
const SCOPE_LABEL: Record<PluginRecord['scope'], MsgKey> = {
project: 'plug.scope.project',
package: 'plug.scope.package',
+ builtin: 'plug.scope.builtin',
user: 'plug.scope.user',
};
diff --git a/desktop/src/plugins/PluginHost.ts b/desktop/src/plugins/PluginHost.ts
index 5f98abde3..59d19b546 100644
--- a/desktop/src/plugins/PluginHost.ts
+++ b/desktop/src/plugins/PluginHost.ts
@@ -68,7 +68,7 @@ export interface PluginRecord {
/** What kind of project-supplied code this is. A `project-platform` row has no
* activation — approving it only permits the export pipeline to import it. */
kind: 'plugin' | 'project-platform';
- scope: 'project' | 'package' | 'user';
+ scope: 'project' | 'package' | 'user' | 'builtin';
dir: string;
phase: PluginPhase;
/** Why it's failed / incompatible / shadowed. */
diff --git a/desktop/src/plugins/context.ts b/desktop/src/plugins/context.ts
index dfaad356d..a33bc3d70 100644
--- a/desktop/src/plugins/context.ts
+++ b/desktop/src/plugins/context.ts
@@ -27,6 +27,7 @@ import { inspectorRegistry } from './inspector';
import { contextMenuRegistry } from './contextMenus';
import { importerRegistry, runImporters } from './importers';
import { localizePlugin as localize } from './localize';
+import { editorLocale } from '@/i18n';
import { settingsRegistry } from '@/settings/registry';
import { useSettings } from '@/store/settingsStore';
import { useSelection } from '@/store/selectionStore';
@@ -129,13 +130,22 @@ function toPluginPointer(p: CorePointerInput): PluginPointerInput {
};
}
-function projectApi(): EditorProjectApi {
+function projectApi(id: string, capabilities: PluginCapability[]): EditorProjectApi {
return {
root: () => ProjectStore.getSnapshot()?.root ?? null,
currentScene: () => ProjectStore.getSnapshot()?.currentScene ?? null,
save: () => ProjectStore.save(),
listAssets: () => AssetRegistry.listAssets().map((a) => a.path),
refreshAssets: () => ProjectStore.refreshAssets(),
+ feature: <T,>(name: string) => ProjectStore.feature(name) as T | undefined,
+ // Writing a settings block writes the project, so it answers to the same
+ // capability reaching its files does.
+ setFeature: (name, value) => {
+ if (!capabilities.includes('fs:project')) {
+ throw new Error(`plugin "${id}" needs the "fs:project" capability in plugin.json to write project settings`);
+ }
+ return ProjectStore.setFeature(name, value);
+ },
};
}
@@ -176,6 +186,7 @@ function editorEvents(track: (d: Disposable) => Disposable): EditorEvents {
case 'selectionChanged':
return track({ dispose: useSelection.subscribe(handler) });
case 'sceneChanged':
+ case 'projectChanged':
return track({ dispose: ProjectStore.subscribe(handler) });
case 'playStateChanged':
// Fires only on an actual edit↔play transition, not on every store touch.
@@ -270,11 +281,19 @@ export function buildPluginContext(
error: (...args: unknown[]) => LogStore.push('error', `plugin:${id}`, args.map(String).join(' ')),
};
+ /**
+ * A contribution id, under its plugin. Idempotent, so the convention the docs
+ * ask for and the guarantee the host gives are the same string — and a plugin
+ * that forgets cannot claim `details` or `viewport` out from under a built-in.
+ */
+ const scoped = (contributionId: string): string =>
+ contributionId === id || contributionId.startsWith(`${id}.`) ? contributionId : `${id}.${contributionId}`;
+
const registerCommand = (c: CommandContribution): Disposable => {
const disposals: CoreDisposable[] = [
commands.register(
{
- id: c.id,
+ id: scoped(c.id),
label: localize(c.title),
category: localize(c.category) || localize(manifest.name),
keybinding: c.keybinding,
@@ -289,25 +308,25 @@ export function buildPluginContext(
// built-in menus are — so a contributed row can't restate label or enablement.
if (c.menu) {
disposals.push(
- registerMenuItem({ id: `${c.menu}/${c.id}`, location: c.menu, group: c.menu === 'tools' ? 'tools' : 'plugins', command: c.id }, owner),
+ registerMenuItem({ id: `${c.menu}/${scoped(c.id)}`, location: c.menu, group: c.menu === 'tools' ? 'tools' : 'plugins', command: scoped(c.id) }, owner),
);
}
- return noted('command', c.id, localize(c.title), { dispose: () => disposals.forEach((d) => d.dispose()) });
+ return noted('command', scoped(c.id), localize(c.title), { dispose: () => disposals.forEach((d) => d.dispose()) });
};
const registerPluginPanel = (p: PanelContribution): Disposable =>
noted(
'panel',
- p.id,
+ scoped(p.id),
localize(p.title),
registerPanel(
{
- id: p.id,
+ id: scoped(p.id),
title: () => localize(p.title),
placement: p.placement ?? 'bottom',
width: p.width,
refs: ['log', 'content'],
- mount: (host) => guard(`panel ${p.id} mount`, () => p.mount(host), () => {}),
+ mount: (host) => guard(`panel ${scoped(p.id)} mount`, () => p.mount(host), () => {}),
},
owner,
),
@@ -320,7 +339,7 @@ export function buildPluginContext(
if (!settingsRegistry.getSection(section)) {
adopt(settingsRegistry.registerSection({ id: section, label: localize(manifest.name), category: 'plugin' }, owner));
}
- const base = { id: s.id, scope: 'editor' as const, section, label: localize(s.label), description: localize(s.description) || undefined };
+ const base = { id: scoped(s.id), scope: 'editor' as const, section, label: localize(s.label), description: localize(s.description) || undefined };
const descriptor =
s.type === 'enum'
? { ...base, type: 'enum' as const, default: s.default, options: s.options.map((o) => ({ value: o.value, label: localize(o.label) })) }
@@ -329,16 +348,16 @@ export function buildPluginContext(
: s.type === 'string'
? { ...base, type: 'string' as const, default: s.default, placeholder: s.placeholder }
: { ...base, type: 'boolean' as const, default: s.default };
- return noted('setting', s.id, localize(s.label), settingsRegistry.register(descriptor, owner));
+ return noted('setting', scoped(s.id), localize(s.label), settingsRegistry.register(descriptor, owner));
};
const registerTool = (tool: ToolContribution): Disposable =>
noted(
'tool',
- tool.id,
+ scoped(tool.id),
localize(tool.title),
toolRegistry.register(owner, {
- id: tool.id,
+ id: scoped(tool.id),
title: localize(tool.title),
modes: tool.modes,
// Every stroke callback is guarded: a throw mid-drag must not wedge the
@@ -362,7 +381,7 @@ export function buildPluginContext(
// itself, so a per-frame throw is attributed once, at the frame boundary.
// No label: an overlay has no title of its own, and repeating the id in the
// label column would just print it twice on the same row.
- noted('overlay', overlay.id, '', overlayRegistry.register(owner, overlay));
+ noted('overlay', scoped(overlay.id), '', overlayRegistry.register(owner, { ...overlay, id: scoped(overlay.id) }));
const registerInspector = (section: InspectorContribution): Disposable =>
noted(
@@ -385,10 +404,10 @@ export function buildPluginContext(
const registerImporter = (importer: AssetImporterContribution): Disposable =>
noted(
'importer',
- `${id}.${importer.id}`,
+ scoped(importer.id),
importer.extensions.map((e) => `.${e}`).join(' '),
importerRegistry.register(owner, {
- id: `${id}.${importer.id}`,
+ id: scoped(importer.id),
extensions: importer.extensions,
run: (path) => guardAsync(`import ${path}`, () => importer.import(path)),
}),
@@ -397,10 +416,10 @@ export function buildPluginContext(
const registerAssetType = (type: AssetTypeContribution): Disposable =>
noted(
'assetType',
- type.id,
+ scoped(type.id),
type.extensions.map((e) => `.${e}`).join(' '),
assetTypeRegistry.register(owner, {
- id: type.id,
+ id: scoped(type.id),
extensions: type.extensions,
badge: type.badge ?? '',
icon: CONTRIBUTED_ASSET_ICON,
@@ -418,10 +437,10 @@ export function buildPluginContext(
const registerTemplate = (template: EntityTemplateContribution): Disposable =>
noted(
'entityTemplate',
- template.id,
+ scoped(template.id),
localize(template.label),
entitySourceRegistry.register(owner, {
- id: template.id,
+ id: scoped(template.id),
label: localize(template.label),
category: template.category ?? 'Scripts',
icon: CONTRIBUTED_ASSET_ICON,
@@ -456,10 +475,11 @@ export function buildPluginContext(
const registerContextMenuItem = (item: ContextMenuContribution): Disposable =>
noted(
'contextMenu',
- item.id,
+ scoped(item.id),
localize(item.label),
contextMenuRegistry.register(owner, {
...item,
+ id: scoped(item.id),
// A plain string is itself a LocalizedString, so resolving it here means
// every consumer reads one already-localized label.
label: localize(item.label),
@@ -471,6 +491,7 @@ export function buildPluginContext(
const ctx: PluginContext = {
id,
version: manifest.version,
+ locale: editorLocale,
subscriptions: [],
log,
ui: { toast: (message, level = 'info') => Toasts.push(message, level) },
@@ -482,7 +503,7 @@ export function buildPluginContext(
},
settings: {
register: registerSetting,
- get: <T extends boolean | number | string>(sid: string) => useSettings.getState().getValue(sid) as T | undefined,
+ get: <T extends boolean | number | string>(sid: string) => useSettings.getState().getValue(scoped(sid)) as T | undefined,
},
tools: {
register: registerTool,
@@ -500,7 +521,7 @@ export function buildPluginContext(
contextMenus: { register: registerContextMenuItem },
agentTools: { register: registerAgentToolContribution },
scene: sceneApi(),
- project: projectApi(),
+ project: projectApi(id, capabilities),
viewport: viewportProjection,
fs: pluginFs(id, dir, capabilities),
events: editorEvents(track),
diff --git a/desktop/src/plugins/types.ts b/desktop/src/plugins/types.ts
index 326dc28d1..d83f63a19 100644
--- a/desktop/src/plugins/types.ts
+++ b/desktop/src/plugins/types.ts
@@ -65,7 +65,8 @@ export interface SceneNode {
export type Keybinding = string | string[];
export interface CommandContribution {
- /** Namespace with your plugin id, e.g. `acme.bakeOcclusion`. */
+ /** Under your plugin id, e.g. `acme.level-tools.bake`. The host puts it there
+ * if you do not, so it can never claim a built-in's id. */
id: string;
title: LocalizedString;
/** Grouping shown in the command palette. */
@@ -88,7 +89,7 @@ export interface CommandContribution {
export type PanelPlacement = 'document' | 'side-left' | 'side-right' | 'bottom';
export interface PanelContribution {
- /** Namespace with your plugin id, e.g. `acme.budget`. */
+ /** Under your plugin id, e.g. `acme.level-tools.budget` (see {@link CommandContribution.id}). */
id: string;
title: LocalizedString;
placement?: PanelPlacement;
@@ -106,7 +107,8 @@ export interface PanelContribution {
}
export interface SettingContributionBase {
- /** Namespace with your plugin id, e.g. `acme.budget.warnAt`. */
+ /** Under your plugin id, e.g. `acme.level-tools.warnAt`. Read it back with
+ * {@link PluginContext.settings}.get, which takes the same id you wrote. */
id: string;
label: LocalizedString;
description?: LocalizedString;
@@ -182,7 +184,7 @@ export interface ToolContext {
* user is never stuck in a plugin's tool.
*/
export interface ToolContribution {
- /** Namespaced id, e.g. `acme.measure`. */
+ /** Under your plugin id, e.g. `acme.level-tools.measure`. */
id: string;
title: LocalizedString;
/** Restrict to these editor modes ('scene' | 'ui' | 'tilemap'); omitted ⇒ all. */
@@ -234,7 +236,7 @@ export interface OverlayGraphics {
}
export interface OverlayContribution {
- /** Namespaced id, e.g. `acme.spawn-radius`. */
+ /** Under your plugin id, e.g. `acme.level-tools.spawn-radius`. */
id: string;
/** Restrict to these editor modes; omitted ⇒ drawn in all of them. */
modes?: readonly string[];
@@ -297,7 +299,7 @@ export type InspectorContribution = ComponentInspectorContribution | AssetInspec
// — Asset types ———————————————————————————————————————————————————————————————
export interface AssetTypeContribution {
- /** Namespaced type id, e.g. `acme.dialogue`. */
+ /** Under your plugin id, e.g. `acme.level-tools.dialogue`. */
id: string;
/** Extensions (lower-case, no dot) that resolve to this type. */
extensions: readonly string[];
@@ -322,7 +324,7 @@ export interface AssetTypeContribution {
* it is then an ordinary asset, and nothing downstream learns your format.
*/
export interface AssetImporterContribution {
- /** Namespaced id, e.g. `acme.ldtk`. */
+ /** Under your plugin id, e.g. `acme.level-tools.ldtk`. */
id: string;
/** Source extensions (lower-case, no dot) this converts. */
extensions: readonly string[];
@@ -341,7 +343,7 @@ export interface ComponentSpec {
/** A ready-made entity offered by the Create picker (and drag-drop, and the menu). */
export interface EntityTemplateContribution {
- /** Namespaced id, e.g. `acme.turret`. */
+ /** Under your plugin id, e.g. `acme.level-tools.turret`. */
id: string;
label: LocalizedString;
/** Create-picker bucket; unknown categories fall under `Other`. */
@@ -413,7 +415,7 @@ export interface AgentToolContribution {
}
export interface ContextMenuContribution {
- /** Namespaced id, e.g. `acme.reveal-refs`. */
+ /** Under your plugin id, e.g. `acme.level-tools.reveal-refs`. */
id: string;
location: ContextMenuLocation;
label: LocalizedString;
@@ -476,6 +478,19 @@ export interface EditorProjectApi {
listAssets(): string[];
/** Re-scan the asset registry; resolves when a new ref is resolvable. */
refreshAssets(): Promise<void>;
+
+ /**
+ * One block of the project's own settings — `features.<name>` in
+ * `project.esproject`. A built-in name (`audio`, `physics`, `rendering`, …)
+ * reads what Project Settings edits; any other name is yours to define.
+ */
+ feature<T = unknown>(name: string): T | undefined;
+ /**
+ * Replace a settings block and persist it. Requires the `fs:project`
+ * capability — it writes the project. Fields the editor does not model
+ * survive, so a block you own is safe to keep anything in.
+ */
+ setFeature(name: string, value: unknown): Promise<void>;
}
/** Files a plugin may read/write. Paths are relative to the plugin's own folder
@@ -500,9 +515,18 @@ export interface EditorViewportApi {
worldToViewport(x: number, y: number): Vec2 | null;
}
-/** Editor events a plugin can observe. Handlers are dropped on unload. */
+/**
+ * Editor events a plugin can observe. Handlers are dropped on unload.
+ *
+ * `sceneChanged` and `projectChanged` share a source today — the open scene is
+ * part of the project's state. Neither ever misses; either may fire more often
+ * than its name suggests.
+ */
export interface EditorEvents {
- on(event: 'selectionChanged' | 'sceneChanged' | 'playStateChanged', handler: () => void): Disposable;
+ on(
+ event: 'selectionChanged' | 'sceneChanged' | 'playStateChanged' | 'projectChanged',
+ handler: () => void,
+ ): Disposable;
}
// =============================================================================
@@ -517,6 +541,11 @@ export interface EditorEvents {
export interface PluginContext {
readonly id: string;
readonly version: string;
+ /** The editor's language (`en`, `zh-CN`), for text a plugin renders ITSELF —
+ * {@link localize} resolves your own {@link LocalizedString}s against it.
+ * Labels handed to a contribution are resolved by the host already. Fixed for
+ * the session: changing the language reloads the editor. */
+ readonly locale: string;
/** Disposables retracted on unload — the simplest correct cleanup. */
readonly subscriptions: Disposable[];
diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.ts
index ee3945c3d..96c1e3b51 100644
--- a/desktop/src/project/ProjectStore.ts
+++ b/desktop/src/project/ProjectStore.ts
@@ -1620,14 +1620,29 @@ class ProjectStoreImpl {
* the Mixer reflects immediately.
*/
async setAudio(config: AudioProjectConfig): Promise<void> {
+ await this.setFeature('audio', config);
+ }
+
+ /**
+ * Replace one `features.<name>` block and persist it — the one door a project
+ * setting is written through, whoever writes it. In-memory first (the UI
+ * reflects immediately), the editor runtime re-derived, then the RAW manifest
+ * rewritten so unmodeled fields survive.
+ */
+ async setFeature(name: string, value: unknown): Promise<void> {
const st = this.state;
if (!st) return;
- const features: ProjectFeatures = { ...st.features, audio: config };
+ const features = { ...st.features, [name]: value } as ProjectFeatures;
this.store.setState({ project: { ...st, features } });
this.applyEditorRuntimeConfig();
await this.patchManifest((raw) => {
- raw.features = { ...(raw.features as Record<string, unknown> ?? {}), audio: config };
- }, t('proj.saveAudioFailed'));
+ raw.features = { ...(raw.features as Record<string, unknown> ?? {}), [name]: value };
+ }, t('proj.saveFeatureFailed', { name }));
+ }
+
+ /** One block of the project's own settings, or undefined when it has none. */
+ feature(name: string): unknown {
+ return (this.state?.features as Record<string, unknown> | undefined)?.[name];
}
/** The project's declared physics feature, with defaults (for Project Settings). The
diff --git a/desktop/src/theme/settings.css b/desktop/src/theme/settings.css
index 5dffebe73..d3cc82ad8 100644
--- a/desktop/src/theme/settings.css
+++ b/desktop/src/theme/settings.css
@@ -268,78 +268,6 @@
/* The pill toggle is the shared `.toggle` primitive (controls.css). */
-/* ── Audio Mixer panel ──────────────────────────────────────────────────── */
-.mix-panel {
- height: 100%;
- overflow: auto;
- background: var(--srf-1);
- color: var(--text);
- font-size: var(--fs-sm);
-}
-/* Wraps rather than scrolling sideways. The panel docks wide and short, so an
- overflowing row put "Add Bus" — and every bus past the fold — behind a horizontal
- scrollbar macOS only draws while scrolling: the button simply looked cut off.
- Stretch so a bus without a ducking row doesn't leave the row ragged. */
-.mix-strips {
- display: flex;
- flex-wrap: wrap;
- align-items: stretch;
- gap: 8px;
- padding: 10px;
-}
-.mix-strip {
- flex: 0 0 220px;
- background: var(--srf-2);
- border: 1px solid var(--line);
- border-radius: var(--r-sm);
- padding: 8px;
- display: flex;
- flex-direction: column;
- gap: 8px;
-}
-.mix-head { display: flex; align-items: center; gap: 6px; }
-.mix-name { font-weight: 600; }
-.mix-head .mix-rm { margin-left: auto; }
-.mix-vol { display: flex; align-items: center; gap: 6px; }
-.mix-fader { flex: 1 1 auto; accent-color: var(--star); }
-.mix-vol-num {
- width: 26px; text-align: right;
- color: var(--text-faint); font-variant-numeric: tabular-nums; font-size: var(--fs-2xs);
-}
-.mix-mute {
- background: none; border: 1px solid var(--line); border-radius: var(--r-sm);
- color: var(--text-dim); padding: 2px 5px; cursor: pointer; display: inline-flex;
-}
-.mix-mute.is-on { color: var(--error-hi); border-color: var(--error-hi); }
-.mix-fxs { display: flex; flex-direction: column; gap: 4px; }
-.mix-fx {
- display: flex; align-items: center; gap: 4px; flex-wrap: wrap;
- background: var(--inset); border: 1px solid var(--line); border-radius: var(--r-sm);
- padding: 3px 5px;
-}
-.mix-fx-kind { color: var(--text-dim); font-size: var(--fs-2xs); min-width: 44px; }
-.mix-num { display: inline-flex; align-items: center; gap: 3px; color: var(--text-faint); font-size: var(--fs-2xs); }
-.mix-num input {
- width: 52px; background: var(--srf-2); border: 1px solid var(--line); border-radius: var(--r-sm);
- color: var(--text); padding: 1px 4px; font: inherit; font-size: var(--fs-2xs);
-}
-.mix-rm {
- background: none; border: none; color: var(--text-dim);
- padding: 2px; cursor: pointer; display: inline-flex;
-}
-.mix-rm:hover { color: var(--error-hi); }
-.mix-duck { display: flex; align-items: center; gap: 6px; }
-.mix-lbl { color: var(--text-faint); font-size: var(--fs-2xs); }
-.mix-duck-amt { flex: 1 1 auto; accent-color: var(--star); }
-.mix-add {
- flex: 0 0 auto;
- display: inline-flex; align-items: center; gap: 5px;
- background: transparent; color: var(--text-dim);
- border: 1px dashed var(--line); border-radius: var(--r-sm);
- padding: 8px 12px; cursor: pointer; font: inherit;
-}
-.mix-add:hover { color: var(--text); border-color: var(--line-strong); }
-
/* Block row: the control stacks under its label at full width, for anything a
230px column cannot hold. Set by `layout: 'block'` on the descriptor. */
.set-row--block { grid-template-columns: 1fr 18px; }
diff --git a/desktop/tests/panel-registry.test.ts b/desktop/tests/panel-registry.test.ts
index 22b409cca..e21ba0e3a 100644
--- a/desktop/tests/panel-registry.test.ts
+++ b/desktop/tests/panel-registry.test.ts
@@ -44,7 +44,7 @@ describe('panel registry', () => {
});
it('ensures exactly the bottom utility tabs, each with dock references', () => {
- expect(ensuredPanels().map((d) => d.id)).toEqual(['sequencer', 'profiler', 'audiomixer']);
+ expect(ensuredPanels().map((d) => d.id)).toEqual(['sequencer', 'profiler']);
for (const def of ensuredPanels()) {
expect(def.placement).toBe('bottom');
expect(def.refs?.length).toBeGreaterThan(0);
diff --git a/desktop/tests/plugin-inventory.test.ts b/desktop/tests/plugin-inventory.test.ts
index 3a375743b..2d586cfa6 100644
--- a/desktop/tests/plugin-inventory.test.ts
+++ b/desktop/tests/plugin-inventory.test.ts
@@ -44,17 +44,17 @@ afterEach(() => {
/** Register one of every kind, and hand back the disposables by kind. */
function registerAll(ctx: PluginContext): Record<string, { dispose(): void }> {
return {
- command: ctx.commands.register({ id: 'acme.hello', title: 'Say hello', run() {} }),
- panel: ctx.panels.register({ id: 'acme.panel', title: 'Acme', mount: () => () => {} }),
+ command: ctx.commands.register({ id: 'acme.tools.hello', title: 'Say hello', run() {} }),
+ panel: ctx.panels.register({ id: 'acme.tools.panel', title: 'Acme', mount: () => () => {} }),
setting: ctx.settings.register({ id: 'acme.warn', type: 'boolean', label: 'Warn', default: true }),
tool: ctx.tools.register({
- id: 'acme.measure',
+ id: 'acme.tools.measure',
title: 'Measure',
onPointerDown: () => true,
onPointerMove: () => {},
onPointerUp: () => {},
}),
- overlay: ctx.overlays.register({ id: 'acme.gizmo', render: () => {} }),
+ overlay: ctx.overlays.register({ id: 'acme.tools.gizmo', render: () => {} }),
inspector: ctx.inspector.register({
kind: 'component',
id: 'audit',
@@ -62,11 +62,11 @@ function registerAll(ctx: PluginContext): Record<string, { dispose(): void }> {
title: 'Audit',
build: () => {},
}),
- assetType: ctx.assets.registerType({ id: 'acme.dialogue', extensions: ['dlg'] }),
+ assetType: ctx.assets.registerType({ id: 'acme.tools.dialogue', extensions: ['dlg'] }),
importer: ctx.assets.registerImporter({ id: 'ldtk', extensions: ['ldtk'], import: () => {} }),
- entityTemplate: ctx.entities.registerTemplate({ id: 'acme.turret', label: 'Turret', components: [] }),
+ entityTemplate: ctx.entities.registerTemplate({ id: 'acme.tools.turret', label: 'Turret', components: [] }),
contextMenu: ctx.contextMenus.register({
- id: 'acme.reveal',
+ id: 'acme.tools.reveal',
location: 'outliner/item',
label: 'Reveal',
run: () => {},
@@ -96,9 +96,9 @@ describe('contribution inventory', () => {
const b = build();
registerAll(b.ctx);
const byKind = new Map(b.contributions().map((c) => [c.kind, c]));
- expect(byKind.get('command')).toMatchObject({ id: 'acme.hello', label: 'Say hello' });
- expect(byKind.get('panel')).toMatchObject({ id: 'acme.panel', label: 'Acme' });
- expect(byKind.get('tool')).toMatchObject({ id: 'acme.measure', label: 'Measure' });
+ expect(byKind.get('command')).toMatchObject({ id: 'acme.tools.hello', label: 'Say hello' });
+ expect(byKind.get('panel')).toMatchObject({ id: 'acme.tools.panel', label: 'Acme' });
+ expect(byKind.get('tool')).toMatchObject({ id: 'acme.tools.measure', label: 'Measure' });
// Inspector ids are namespaced by the host, and the list must show the id that
// actually landed in the registry — not the one the plugin asked for.
expect(byKind.get('inspector')?.id).toBe('acme.tools.audit');
@@ -108,12 +108,22 @@ describe('contribution inventory', () => {
expect(byKind.get('importer')).toMatchObject({ id: 'acme.tools.ldtk', label: '.ldtk' });
// An overlay has neither — and must NOT fall back to its id, or the panel row
// prints the same string in the label column and the id column.
- expect(byKind.get('overlay')).toMatchObject({ id: 'acme.gizmo', label: '' });
+ expect(byKind.get('overlay')).toMatchObject({ id: 'acme.tools.gizmo', label: '' });
+ });
+
+ it('puts a contribution under its plugin, however the author spelled the id', () => {
+ // The convention was documented and unenforced, so a plugin registering
+ // `details` could claim a built-in panel's id. Idempotent, so an id already
+ // under the plugin is left exactly as written.
+ const b = build();
+ b.ctx.panels.register({ id: 'mixer', title: 'Mixer', mount: () => () => {} });
+ b.ctx.commands.register({ id: 'acme.tools.already', title: 'Already', run() {} });
+ expect(b.contributions().map((c) => c.id)).toEqual(['acme.tools.mixer', 'acme.tools.already']);
});
it('resolves a localized label rather than listing the object', () => {
const b = build();
- b.ctx.commands.register({ id: 'acme.l10n', title: { en: 'Bake', 'zh-CN': '烘焙' }, run() {} });
+ b.ctx.commands.register({ id: 'acme.tools.l10n', title: { en: 'Bake', 'zh-CN': '烘焙' }, run() {} });
expect(b.contributions()[0].label).toBe('Bake');
});
diff --git a/desktop/tests/plugin-loader.test.ts b/desktop/tests/plugin-loader.test.ts
index 871eb1c33..79bc051de 100644
--- a/desktop/tests/plugin-loader.test.ts
+++ b/desktop/tests/plugin-loader.test.ts
@@ -20,6 +20,8 @@ import { discoverPlugins, compilePlugin, PROJECT_PLUGIN_DIR } from '../electron/
const HERE = path.dirname(fileURLToPath(import.meta.url));
const SAMPLE_PROJECT = path.resolve(HERE, '../../examples/sprite-animation');
const SAMPLE_ID = 'estella.scene-report';
+/** The plugins the editor ships with, as a dev run resolves them. */
+const SHIPPED_PLUGINS = path.resolve(HERE, '../../plugins');
let scratch: string;
/** A second project, for the npm-installed plugins (its own package.json). */
@@ -91,6 +93,34 @@ describe('plugin discovery', () => {
it('returns nothing (rather than throwing) with no project open', async () => {
await expect(discoverPlugins(null, path.join(userData, 'absent'))).resolves.toEqual([]);
});
+
+ it('finds the editor’s own plugins, without a project', async () => {
+ // They ship with the app, so they are there before anything is opened.
+ const found = await discoverPlugins(null, userData, SHIPPED_PLUGINS);
+ const mixer = found.find((p) => p.id === 'estella.audio-mixer');
+ expect(mixer, 'the shipped mixer is missing from plugins/').toBeDefined();
+ expect(mixer!.scope).toBe('builtin');
+ expect(mixer!.error).toBeUndefined();
+ });
+
+ it('passes over a shipped package that has no editor half', async () => {
+ // plugins/ holds packages, and a runtime-only one is not a broken plugin.
+ const shipped = (await discoverPlugins(null, userData, SHIPPED_PLUGINS))
+ .filter((p) => p.scope === 'builtin');
+ expect(shipped.some((p) => p.error)).toBe(false);
+ expect(shipped.some((p) => p.dir.endsWith('minigame-services'))).toBe(false);
+ });
+
+ it('lets a project plugin shadow a shipped one of the same id', async () => {
+ // How a project pins its own build of a plugin the editor ships.
+ writePlugin(scratch, 'mixer', {
+ id: 'estella.audio-mixer', name: 'Mine', version: '9.0.0', main: { editor: 'src/editor.ts' },
+ }, 'export default { activate() {} }');
+ const found = (await discoverPlugins(scratch, userData, SHIPPED_PLUGINS))
+ .filter((p) => p.id === 'estella.audio-mixer');
+ expect(found.find((p) => p.scope === 'project')!.shadowedBy).toBeUndefined();
+ expect(found.find((p) => p.scope === 'builtin')!.shadowedBy).toBe('project');
+ });
});
describe('plugins installed from npm', () => {
diff --git a/desktop/tests/prune-layout.test.ts b/desktop/tests/prune-layout.test.ts
new file mode 100644
index 000000000..b9627ec8b
--- /dev/null
+++ b/desktop/tests/prune-layout.test.ts
@@ -0,0 +1,87 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file A saved dock layout outliving the panels in it.
+ *
+ * dockview refuses a whole layout over one component it cannot resolve, so
+ * "this panel went away" and "your arrangement is gone" were the same event.
+ * These are the claims that separate them: the panel leaves, the layout stays,
+ * and a group emptied by the removal does not linger as a blank frame.
+ */
+import { describe, it, expect } from 'vitest';
+import { pruneLayout } from '@/layout/pruneLayout';
+
+const leaf = (id: string, views: string[], activeView?: string) =>
+ ({ type: 'leaf', size: 100, data: { id, views, ...(activeView ? { activeView } : {}) } });
+
+const layout = (root: unknown, panels: Record<string, string>) => ({
+ grid: { root, width: 1000, height: 800, orientation: 'HORIZONTAL' },
+ panels: Object.fromEntries(
+ Object.entries(panels).map(([id, component]) => [id, { id, contentComponent: component, title: id }]),
+ ),
+ activeGroup: 'g1',
+});
+
+const known = (...keys: string[]) => new Set(keys);
+
+describe('a saved layout meeting a build that lost a panel', () => {
+ it('keeps everything when every component is still there', () => {
+ const l = layout(leaf('g1', ['viewport', 'mixer']), { viewport: 'viewport', mixer: 'mixer' });
+ // Same object back: nothing to rewrite is the common case, every launch.
+ expect(pruneLayout(l, known('viewport', 'mixer'))).toBe(l);
+ });
+
+ it('drops only the panel whose component is gone', () => {
+ const l = layout(leaf('g1', ['viewport', 'mixer'], 'viewport'), { viewport: 'viewport', mixer: 'mixer' });
+ const out = pruneLayout(l, known('viewport')) as typeof l;
+ expect(Object.keys(out.panels)).toEqual(['viewport']);
+ expect((out.grid.root as ReturnType<typeof leaf>).data.views).toEqual(['viewport']);
+ });
+
+ it('re-points the active tab when it was the one that went', () => {
+ const l = layout(leaf('g1', ['viewport', 'mixer'], 'mixer'), { viewport: 'viewport', mixer: 'mixer' });
+ const out = pruneLayout(l, known('viewport')) as typeof l;
+ expect((out.grid.root as ReturnType<typeof leaf>).data.activeView).toBe('viewport');
+ });
+
+ it('removes a group the loss emptied, rather than leaving a blank frame', () => {
+ const root = {
+ type: 'branch',
+ size: 800,
+ data: [leaf('g1', ['viewport']), leaf('g2', ['mixer'])],
+ };
+ const out = pruneLayout(layout(root, { viewport: 'viewport', mixer: 'mixer' }), known('viewport')) as {
+ grid: { root: { data: Array<{ data: { id: string } }> } };
+ };
+ expect(out.grid.root.data).toHaveLength(1);
+ expect(out.grid.root.data[0].data.id).toBe('g1');
+ });
+
+ it('gives up when nothing is left, so the caller builds the default', () => {
+ // Not an empty layout — dockview would render a blank editor and call it
+ // restored.
+ expect(pruneLayout(layout(leaf('g1', ['mixer']), { mixer: 'mixer' }), known('viewport'))).toBeNull();
+ });
+
+ it('forgets an active group that the pruning removed', () => {
+ const root = { type: 'branch', size: 800, data: [leaf('g0', ['viewport']), leaf('g1', ['mixer'])] };
+ const out = pruneLayout(layout(root, { viewport: 'viewport', mixer: 'mixer' }), known('viewport')) as {
+ activeGroup?: string;
+ };
+ expect(out.activeGroup).toBeUndefined();
+ });
+
+ it('prunes a floating group the same way', () => {
+ const l = {
+ ...layout(leaf('g1', ['viewport']), { viewport: 'viewport', mixer: 'mixer' }),
+ floatingGroups: [{ data: { id: 'f1', views: ['mixer'], activeView: 'mixer' }, position: {} }],
+ };
+ const out = pruneLayout(l, known('viewport')) as typeof l;
+ expect(out.floatingGroups).toEqual([]);
+ });
+
+ it('refuses junk rather than handing dockview something shaped wrong', () => {
+ expect(pruneLayout(null, known('viewport'))).toBeNull();
+ expect(pruneLayout('{}', known('viewport'))).toBeNull();
+ });
+});
diff --git a/plugins/audio-mixer/README.md b/plugins/audio-mixer/README.md
new file mode 100644
index 000000000..c2e92983a
--- /dev/null
+++ b/plugins/audio-mixer/README.md
@@ -0,0 +1,36 @@
+# estella-plugin-audio-mixer
+
+The project's audio mixer, as an editor panel: one strip per bus with a fader,
+mute, insert effects and ducking.
+
+**Ships with the Estella editor** — open it from **Window ▸ Audio Mixer**. It is
+listed in the Plugins panel like any other, because it is one.
+
+```bash
+# Only if you want to pin your own build of it in a project
+npm install estella-plugin-audio-mixer
+```
+
+A project that depends on the package, or drops a copy in
+`.esengine/plugins/`, shadows the shipped one — that is how you run a fork.
+
+## What it edits
+
+`features.audio` in `project.esproject`: the same block Play and every export
+read, so a level you set here is the level the game ships with. Writes go
+through the editor's own project-settings door, which persists and live-applies
+in one step — a fader is audible while you drag it.
+
+## Built on the public API
+
+Nothing here reaches into the editor. It uses `ctx.panels.register` to mount a
+React root, `ctx.project.feature` / `setFeature` (hence the `fs:project`
+capability), `ctx.events.on('projectChanged')` to re-render, and `ctx.locale`
+for its own bilingual strings. It brings its own CSS, written against the
+editor's theme *variables* rather than its class names — those are internal, and
+styling against them would break the day one is renamed.
+
+The merge between "what the project declared" and "what the engine always has"
+is a pure function in `src/model.ts`, tested on its own.
+
+Apache-2.0.
diff --git a/plugins/audio-mixer/package.json b/plugins/audio-mixer/package.json
new file mode 100644
index 000000000..7d0b30381
--- /dev/null
+++ b/plugins/audio-mixer/package.json
@@ -0,0 +1,19 @@
+{
+ "name": "estella-plugin-audio-mixer",
+ "version": "0.1.0",
+ "description": "The project audio mixer for the Estella editor: a strip per bus, with effects and ducking.",
+ "license": "Apache-2.0",
+ "type": "module",
+ "files": ["plugin.json", "src", "README.md"],
+ "keywords": ["estella", "estella-plugin", "audio", "mixer"],
+ "scripts": { "test": "vitest run" },
+ "peerDependencies": { "esengine": ">=0.51", "react": ">=19", "react-dom": ">=19" },
+ "devDependencies": {
+ "esengine": "workspace:*",
+ "react": "^19.2.0",
+ "react-dom": "^19.2.0",
+ "@types/react": "^19.2.0",
+ "@types/react-dom": "^19.2.0",
+ "vitest": "^2.1.9"
+ }
+}
diff --git a/plugins/audio-mixer/plugin.json b/plugins/audio-mixer/plugin.json
new file mode 100644
index 000000000..1772d02b5
--- /dev/null
+++ b/plugins/audio-mixer/plugin.json
@@ -0,0 +1,13 @@
+{
+ "id": "estella.audio-mixer",
+ "name": { "en": "Audio Mixer", "zh-CN": "音频混音台" },
+ "version": "0.1.0",
+ "description": {
+ "en": "One strip per audio bus: fader, mute, insert effects and ducking.",
+ "zh-CN": "每条音频总线一条推子:音量、静音、插入效果和闪避。"
+ },
+ "publisher": "estella",
+ "engines": { "editor": ">=0.51" },
+ "main": { "editor": "src/editor.tsx" },
+ "capabilities": ["fs:project"]
+}
diff --git a/plugins/audio-mixer/src/Mixer.tsx b/plugins/audio-mixer/src/Mixer.tsx
new file mode 100644
index 000000000..eed8b26a6
--- /dev/null
+++ b/plugins/audio-mixer/src/Mixer.tsx
@@ -0,0 +1,206 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Mixer.tsx — one strip per bus, over the project's `features.audio`.
+ *
+ * Every edit goes through `ctx.project.setFeature`, which persists to
+ * project.esproject AND live-applies to the edit realm, so a fader is audible
+ * immediately and Play boots the same mix.
+ */
+import { useSyncExternalStore } from 'react';
+import type { PluginContext } from '@estella/editor-api';
+import type { AudioProjectConfig, AudioBusDecl, BusEffectDef } from 'esengine';
+import { stripsOf, patchBus, defaultEffect, freeBusName, type StripModel } from './model';
+import { text, type Strings } from './strings';
+
+const FX_KINDS: BusEffectDef['type'][] = ['filter', 'reverb', 'compressor'];
+const FILTERS = ['lowpass', 'highpass', 'bandpass', 'lowshelf', 'highshelf', 'peaking', 'notch'] as const;
+
+/** A tiny inline glyph — a plugin brings its own rather than reaching for the
+ * editor's icon set, which is not part of any contract. */
+function Glyph({ d, size = 12 }: { d: string; size?: number }) {
+ return (
+ <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true">
+ <path d={d} />
+ </svg>
+ );
+}
+const TRASH = 'M3 6h18M8 6V4h8v2M6 6l1 14h10l1-14';
+const PLUS = 'M12 5v14M5 12h14';
+const SOUND = 'M11 5 6 9H2v6h4l5 4V5zM15.5 8.5a5 5 0 0 1 0 7';
+const MUTED = 'M11 5 6 9H2v6h4l5 4V5zM22 9l-6 6M16 9l6 6';
+
+export function Mixer({ ctx }: { ctx: PluginContext }) {
+ const s = text(ctx.locale);
+ // The store hands back the same object until a write replaces it, so this is a
+ // stable snapshot — a fresh one per read would re-render for ever.
+ const config = useSyncExternalStore(
+ (cb) => {
+ const d = ctx.events.on('projectChanged', cb);
+ return () => d.dispose();
+ },
+ () => ctx.project.feature<AudioProjectConfig>('audio'),
+ );
+ if (ctx.project.root() === null) return <p className="mixer-empty">{s.noProject}</p>;
+
+ const current = config ?? {};
+ const strips = stripsOf(current);
+ const commit = (next: AudioProjectConfig) => void ctx.project.setFeature('audio', next);
+
+ return (
+ <div className="mixer">
+ {strips.map((strip) => (
+ <Strip key={strip.name} strip={strip} all={strips} config={current} s={s} commit={commit} />
+ ))}
+ <button
+ type="button"
+ className="mixer-add"
+ onClick={() => commit(patchBus(current, freeBusName(strips), { parent: 'master', volume: 1 }))}
+ >
+ <Glyph d={PLUS} size={14} /> {s.addBus}
+ </button>
+ </div>
+ );
+}
+
+interface StripProps {
+ strip: StripModel;
+ all: StripModel[];
+ config: AudioProjectConfig;
+ s: Strings;
+ commit: (next: AudioProjectConfig) => void;
+}
+
+function Strip({ strip, all, config, s, commit }: StripProps) {
+ const volume = strip.volume ?? 1;
+ const effects = strip.effects ?? [];
+ const patch = (p: Partial<AudioBusDecl> | null) => commit(patchBus(config, strip.name, p));
+
+ return (
+ <div className="mixer-strip">
+ <div className="mixer-head">
+ <span className="mixer-name">{strip.name}</span>
+ {!strip.builtin && (
+ <button type="button" className="mixer-icon" title={s.removeBus} onClick={() => patch(null)}>
+ <Glyph d={TRASH} />
+ </button>
+ )}
+ </div>
+
+ <div className="mixer-row">
+ <input
+ type="range" min={0} max={1} step={0.01} value={volume} aria-label={s.volume}
+ onChange={(e) => patch({ volume: Number(e.target.value) })}
+ />
+ <span className="mixer-num">{Math.round(volume * 100)}</span>
+ <button
+ type="button"
+ className={`mixer-icon${strip.muted ? ' is-on' : ''}`}
+ title={s.mute}
+ onClick={() => patch({ muted: !strip.muted })}
+ >
+ <Glyph d={strip.muted ? MUTED : SOUND} size={13} />
+ </button>
+ </div>
+
+ {effects.map((fx, i) => (
+ <Effect
+ key={`${i}-${fx.type}`}
+ fx={fx}
+ s={s}
+ onChange={(next) => patch({ effects: effects.map((e, j) => (j === i ? next : e)) })}
+ onRemove={() => patch({ effects: effects.filter((_, j) => j !== i) })}
+ />
+ ))}
+
+ <select
+ className="mixer-select"
+ aria-label={s.addEffect}
+ value=""
+ onChange={(e) => {
+ if (e.target.value) patch({ effects: [...effects, defaultEffect(e.target.value as BusEffectDef['type'])] });
+ }}
+ >
+ <option value="">{s.addEffect}</option>
+ {FX_KINDS.map((k) => <option key={k} value={k}>{s.fx[k]}</option>)}
+ </select>
+
+ {strip.name !== 'master' && (
+ <div className="mixer-row">
+ <span className="mixer-label">{s.duckBy}</span>
+ <select
+ className="mixer-select"
+ aria-label={s.duckBy}
+ value={strip.duck?.trigger ?? ''}
+ onChange={(e) => patch({
+ duck: e.target.value ? { trigger: e.target.value, amount: strip.duck?.amount ?? 0.3 } : undefined,
+ })}
+ >
+ <option value="">{s.duckNone}</option>
+ {all.filter((o) => o.name !== strip.name).map((o) => <option key={o.name} value={o.name}>{o.name}</option>)}
+ </select>
+ {strip.duck && (
+ <input
+ type="range" min={0} max={1} step={0.05} value={strip.duck.amount} title={s.duckAmount}
+ onChange={(e) => patch({ duck: { ...strip.duck!, amount: Number(e.target.value) } })}
+ />
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
+
+/** A number that commits on blur / Enter, so typing "12" is not read as "1". */
+function Num(props: { label: string; value: number; step?: number; onCommit: (n: number) => void }) {
+ return (
+ <label className="mixer-num-field">
+ <span>{props.label}</span>
+ <input
+ type="number" defaultValue={props.value} key={props.value} step={props.step ?? 1}
+ onBlur={(e) => {
+ const n = Number(e.target.value);
+ if (Number.isFinite(n) && n !== props.value) props.onCommit(n);
+ }}
+ onKeyDown={(e) => { if (e.key === 'Enter') (e.target as HTMLInputElement).blur(); }}
+ />
+ </label>
+ );
+}
+
+function Effect({ fx, s, onChange, onRemove }: {
+ fx: BusEffectDef; s: Strings; onChange: (fx: BusEffectDef) => void; onRemove: () => void;
+}) {
+ return (
+ <div className="mixer-fx">
+ <span className="mixer-label">{s.fx[fx.type]}</span>
+ {fx.type === 'filter' && (
+ <>
+ <select
+ className="mixer-select" aria-label={s.filterKind} value={fx.filter}
+ onChange={(e) => onChange({ ...fx, filter: e.target.value as typeof FILTERS[number] })}
+ >
+ {FILTERS.map((f) => <option key={f} value={f}>{f}</option>)}
+ </select>
+ <Num label="Hz" value={fx.frequency} step={50} onCommit={(n) => onChange({ ...fx, frequency: Math.max(10, n) })} />
+ <Num label="Q" value={fx.q ?? 1} step={0.1} onCommit={(n) => onChange({ ...fx, q: n })} />
+ </>
+ )}
+ {fx.type === 'reverb' && (
+ <>
+ <Num label={s.seconds} value={fx.seconds ?? 1.5} step={0.1} onCommit={(n) => onChange({ ...fx, seconds: Math.max(0.05, n) })} />
+ <Num label={s.wet} value={fx.wet ?? 0.35} step={0.05} onCommit={(n) => onChange({ ...fx, wet: Math.max(0, Math.min(1, n)) })} />
+ </>
+ )}
+ {fx.type === 'compressor' && (
+ <>
+ <Num label="dB" value={fx.thresholdDb ?? -24} onCommit={(n) => onChange({ ...fx, thresholdDb: n })} />
+ <Num label={s.ratio} value={fx.ratio ?? 4} step={0.5} onCommit={(n) => onChange({ ...fx, ratio: Math.max(1, n) })} />
+ </>
+ )}
+ <button type="button" className="mixer-icon" title={s.removeEffect} onClick={onRemove}>
+ <Glyph d={TRASH} />
+ </button>
+ </div>
+ );
+}
diff --git a/plugins/audio-mixer/src/editor.tsx b/plugins/audio-mixer/src/editor.tsx
new file mode 100644
index 000000000..0da020c87
--- /dev/null
+++ b/plugins/audio-mixer/src/editor.tsx
@@ -0,0 +1,35 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { createRoot } from 'react-dom/client';
+import { definePlugin, type PluginContext } from '@estella/editor-api';
+import { Mixer } from './Mixer';
+import { PANEL_TITLE } from './strings';
+import { CSS } from './style';
+
+export default definePlugin({
+ activate(ctx: PluginContext) {
+ ctx.panels.register({
+ id: 'estella.audio-mixer.panel',
+ title: PANEL_TITLE,
+ placement: 'bottom',
+ mount(host) {
+ const style = document.createElement('style');
+ style.textContent = CSS;
+ host.appendChild(style);
+ const root = createRoot(host.appendChild(document.createElement('div')));
+ root.render(<Mixer ctx={ctx} />);
+ // Unmount on the next tick: React refuses to unmount from inside the
+ // render pass a panel close can be dispatched in.
+ return () => setTimeout(() => root.unmount(), 0);
+ },
+ });
+
+ ctx.commands.register({
+ id: 'estella.audio-mixer.open',
+ title: PANEL_TITLE,
+ category: { en: 'Audio', 'zh-CN': '音频' },
+ menu: 'window',
+ run: () => ctx.panels.open('estella.audio-mixer.panel'),
+ });
+ },
+});
diff --git a/plugins/audio-mixer/src/model.ts b/plugins/audio-mixer/src/model.ts
new file mode 100644
index 000000000..b4c2067a2
--- /dev/null
+++ b/plugins/audio-mixer/src/model.ts
@@ -0,0 +1,64 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file model.ts — the mixer's state, without a screen.
+ *
+ * Pure functions over the project's `features.audio` block, so what the strips
+ * mean is testable without mounting anything.
+ */
+import type { AudioProjectConfig, AudioBusDecl, BusEffectDef } from 'esengine';
+
+/** The always-present mixer tree; custom buses append after these. */
+export const DEFAULT_BUSES = ['master', 'music', 'sfx', 'ui', 'voice'];
+
+const DEFAULT_VOLUME: Record<string, number> = { master: 1, music: 0.8, sfx: 1, ui: 1, voice: 1 };
+
+export interface StripModel extends AudioBusDecl {
+ /** One of the buses the engine always has: it can be edited, never removed. */
+ builtin: boolean;
+}
+
+/** Default buses merged with the project's declarations, declaration order kept. */
+export function stripsOf(config: AudioProjectConfig): StripModel[] {
+ const byName = new Map((config.buses ?? []).map((b) => [b.name, b]));
+ const strips: StripModel[] = DEFAULT_BUSES.map((name) => ({
+ name, volume: DEFAULT_VOLUME[name], ...byName.get(name), builtin: true,
+ }));
+ for (const b of config.buses ?? []) {
+ if (!DEFAULT_BUSES.includes(b.name)) strips.push({ ...b, builtin: false });
+ }
+ return strips;
+}
+
+/** Replace, patch (or with `null`, remove) one bus's declaration in the config. */
+export function patchBus(
+ config: AudioProjectConfig,
+ name: string,
+ patch: Partial<AudioBusDecl> | null,
+): AudioProjectConfig {
+ const buses = [...(config.buses ?? [])];
+ const i = buses.findIndex((b) => b.name === name);
+ if (patch === null) {
+ if (i >= 0) buses.splice(i, 1);
+ } else if (i >= 0) {
+ buses[i] = { ...buses[i], ...patch };
+ } else {
+ buses.push({ name, ...patch });
+ }
+ return { buses };
+}
+
+/** A name no strip has yet, for the Add button. */
+export function freeBusName(strips: readonly StripModel[]): string {
+ let name = 'bus';
+ for (let n = 1; strips.some((s) => s.name === name); n++) name = `bus-${n}`;
+ return name;
+}
+
+export function defaultEffect(type: BusEffectDef['type']): BusEffectDef {
+ switch (type) {
+ case 'filter': return { type: 'filter', filter: 'lowpass', frequency: 1200, q: 1 };
+ case 'reverb': return { type: 'reverb', seconds: 1.5, wet: 0.35 };
+ case 'compressor': return { type: 'compressor', thresholdDb: -24, ratio: 4 };
+ }
+}
diff --git a/plugins/audio-mixer/src/strings.ts b/plugins/audio-mixer/src/strings.ts
new file mode 100644
index 000000000..f37401a37
--- /dev/null
+++ b/plugins/audio-mixer/src/strings.ts
@@ -0,0 +1,74 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file strings.ts — the panel's own text, resolved against the editor's locale.
+ *
+ * A plugin renders its own UI, so it carries its own strings; `ctx.locale` is
+ * what says which language the editor is speaking.
+ */
+import { localize, type LocalizedString } from '@estella/editor-api';
+
+const TEXT = {
+ panel: { en: 'Audio Mixer', 'zh-CN': '音频混音台' },
+ noProject: { en: 'Open a project to mix its audio buses.', 'zh-CN': '打开一个项目才能调它的音频总线。' },
+ addBus: { en: 'Add bus', 'zh-CN': '添加总线' },
+ removeBus: { en: 'Remove bus', 'zh-CN': '删除总线' },
+ volume: { en: 'Volume', 'zh-CN': '音量' },
+ mute: { en: 'Mute', 'zh-CN': '静音' },
+ addEffect: { en: 'Add effect…', 'zh-CN': '添加效果…' },
+ removeEffect: { en: 'Remove effect', 'zh-CN': '删除效果' },
+ filterKind: { en: 'Filter type', 'zh-CN': '滤波器类型' },
+ seconds: { en: 'sec', 'zh-CN': '秒' },
+ wet: { en: 'wet', 'zh-CN': '湿度' },
+ ratio: { en: 'ratio', 'zh-CN': '压缩比' },
+ duckBy: { en: 'Duck by', 'zh-CN': '被闪避' },
+ duckNone: { en: 'none', 'zh-CN': '无' },
+ duckAmount: { en: 'Duck amount', 'zh-CN': '闪避量' },
+ fxFilter: { en: 'Filter', 'zh-CN': '滤波' },
+ fxReverb: { en: 'Reverb', 'zh-CN': '混响' },
+ fxCompressor: { en: 'Compressor', 'zh-CN': '压缩' },
+} satisfies Record<string, LocalizedString>;
+
+export interface Strings {
+ panel: string;
+ noProject: string;
+ addBus: string;
+ removeBus: string;
+ volume: string;
+ mute: string;
+ addEffect: string;
+ removeEffect: string;
+ filterKind: string;
+ seconds: string;
+ wet: string;
+ ratio: string;
+ duckBy: string;
+ duckNone: string;
+ duckAmount: string;
+ fx: { filter: string; reverb: string; compressor: string };
+}
+
+/** Every string resolved once for a locale. */
+export function text(locale: string): Strings {
+ const at = (key: keyof typeof TEXT) => localize(TEXT[key], locale);
+ return {
+ panel: at('panel'),
+ noProject: at('noProject'),
+ addBus: at('addBus'),
+ removeBus: at('removeBus'),
+ volume: at('volume'),
+ mute: at('mute'),
+ addEffect: at('addEffect'),
+ removeEffect: at('removeEffect'),
+ filterKind: at('filterKind'),
+ seconds: at('seconds'),
+ wet: at('wet'),
+ ratio: at('ratio'),
+ duckBy: at('duckBy'),
+ duckNone: at('duckNone'),
+ duckAmount: at('duckAmount'),
+ fx: { filter: at('fxFilter'), reverb: at('fxReverb'), compressor: at('fxCompressor') },
+ };
+}
+
+export const PANEL_TITLE: LocalizedString = TEXT.panel;
diff --git a/plugins/audio-mixer/src/style.ts b/plugins/audio-mixer/src/style.ts
new file mode 100644
index 000000000..5e254d090
--- /dev/null
+++ b/plugins/audio-mixer/src/style.ts
@@ -0,0 +1,51 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file style.ts — the panel's own CSS.
+ *
+ * Written against the editor's theme VARIABLES, which are in scope inside a
+ * contributed panel — not against its class names, which are internal and would
+ * silently restyle this the day one of them is renamed.
+ */
+export const CSS = `
+.mixer { display: flex; gap: 8px; padding: 10px; overflow-x: auto; align-items: flex-start; height: 100%; }
+.mixer-empty { padding: 16px; color: var(--text-mute); font-size: var(--fs-sm); }
+.mixer-strip {
+ display: flex; flex-direction: column; gap: 6px;
+ min-width: 190px; padding: 8px;
+ background: var(--srf-2); border: 1px solid var(--border); border-radius: 6px;
+}
+.mixer-head { display: flex; align-items: center; gap: 6px; }
+.mixer-name { flex: 1; font-size: var(--fs-sm); font-weight: 500; color: var(--text); }
+.mixer-row { display: flex; align-items: center; gap: 6px; }
+.mixer-row input[type='range'] { flex: 1; min-width: 0; accent-color: var(--acc); }
+.mixer-num { width: 26px; text-align: right; font-family: var(--mono); font-size: var(--fs-2xs); color: var(--text-mute); }
+.mixer-label { font-size: var(--fs-2xs); color: var(--text-mute); }
+.mixer-icon {
+ display: grid; place-items: center; width: 22px; height: 22px;
+ background: none; border: 0; border-radius: 4px; color: var(--text-mute); cursor: pointer;
+}
+.mixer-icon:hover { background: var(--srf-3); color: var(--text); }
+.mixer-icon.is-on { color: var(--acc); }
+.mixer-select {
+ background: var(--inset); color: var(--text);
+ border: 1px solid var(--border); border-radius: 4px;
+ font-size: var(--fs-2xs); padding: 2px 4px; min-width: 0;
+}
+.mixer-fx {
+ display: flex; flex-wrap: wrap; align-items: center; gap: 4px;
+ padding: 4px; background: var(--srf-3); border-radius: 4px;
+}
+.mixer-num-field { display: flex; align-items: center; gap: 3px; font-size: var(--fs-2xs); color: var(--text-mute); }
+.mixer-num-field input {
+ width: 52px; background: var(--inset); color: var(--text);
+ border: 1px solid var(--border); border-radius: 4px; font-size: var(--fs-2xs); padding: 2px 4px;
+}
+.mixer-add {
+ display: flex; align-items: center; gap: 5px; align-self: stretch;
+ padding: 8px 12px; background: none; cursor: pointer;
+ border: 1px dashed var(--border); border-radius: 6px;
+ color: var(--text-mute); font-size: var(--fs-sm); white-space: nowrap;
+}
+.mixer-add:hover { color: var(--text); border-color: var(--acc); }
+`;
diff --git a/plugins/audio-mixer/tests/model.test.ts b/plugins/audio-mixer/tests/model.test.ts
new file mode 100644
index 000000000..394bb3e63
--- /dev/null
+++ b/plugins/audio-mixer/tests/model.test.ts
@@ -0,0 +1,74 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file What a strip is, before anything is drawn.
+ *
+ * The mixer shows buses the project never declared — the engine always has
+ * master/music/sfx/ui/voice — so "what is on screen" and "what is written down"
+ * are different lists, and the merge between them is where a fader would
+ * otherwise start at the wrong place.
+ */
+import { describe, it, expect } from 'vitest';
+import { stripsOf, patchBus, freeBusName, defaultEffect, DEFAULT_BUSES } from '../src/model';
+
+describe('the strips a project shows', () => {
+ it('shows the engine buses even when the project declares nothing', () => {
+ const strips = stripsOf({});
+ expect(strips.map((s) => s.name)).toEqual(DEFAULT_BUSES);
+ expect(strips.every((s) => s.builtin)).toBe(true);
+ // Music is quieter by default, and a fader must open where the engine is.
+ expect(strips.find((s) => s.name === 'music')!.volume).toBe(0.8);
+ });
+
+ it('lets a declaration override a built-in bus without moving it', () => {
+ const strips = stripsOf({ buses: [{ name: 'music', volume: 0.2, muted: true }] });
+ expect(strips.map((s) => s.name)).toEqual(DEFAULT_BUSES);
+ const music = strips.find((s) => s.name === 'music')!;
+ expect([music.volume, music.muted, music.builtin]).toEqual([0.2, true, true]);
+ });
+
+ it('appends a custom bus after the built-ins, in declaration order', () => {
+ const strips = stripsOf({ buses: [{ name: 'ambience' }, { name: 'radio' }] });
+ expect(strips.slice(DEFAULT_BUSES.length).map((s) => s.name)).toEqual(['ambience', 'radio']);
+ expect(strips.slice(DEFAULT_BUSES.length).every((s) => s.builtin)).toBe(false);
+ });
+});
+
+describe('editing one bus', () => {
+ it('declares a built-in the first time it is touched', () => {
+ // Nothing was written down before: the volume came from the engine.
+ expect(patchBus({}, 'sfx', { volume: 0.5 })).toEqual({ buses: [{ name: 'sfx', volume: 0.5 }] });
+ });
+
+ it('merges into an existing declaration rather than replacing it', () => {
+ const config = { buses: [{ name: 'sfx', volume: 0.5, muted: true }] };
+ expect(patchBus(config, 'sfx', { volume: 0.9 })).toEqual({ buses: [{ name: 'sfx', volume: 0.9, muted: true }] });
+ });
+
+ it('removes a bus with a null patch, leaving the others in order', () => {
+ const config = { buses: [{ name: 'a' }, { name: 'b' }, { name: 'c' }] };
+ expect(patchBus(config, 'b', null)).toEqual({ buses: [{ name: 'a' }, { name: 'c' }] });
+ });
+
+ it('never edits the config it was handed', () => {
+ const config = { buses: [{ name: 'sfx', volume: 0.5 }] };
+ patchBus(config, 'sfx', { volume: 0.1 });
+ expect(config.buses[0].volume).toBe(0.5);
+ });
+});
+
+describe('adding a bus', () => {
+ it('picks a name nothing is using, including the built-ins', () => {
+ expect(freeBusName(stripsOf({}))).toBe('bus');
+ expect(freeBusName(stripsOf({ buses: [{ name: 'bus' }, { name: 'bus-1' }] }))).toBe('bus-2');
+ });
+});
+
+describe('a new effect', () => {
+ it('starts audible rather than at zero', () => {
+ // An effect added with null values does nothing and reads as broken.
+ expect(defaultEffect('filter')).toMatchObject({ type: 'filter', filter: 'lowpass', frequency: 1200 });
+ expect(defaultEffect('reverb')).toMatchObject({ type: 'reverb', seconds: 1.5 });
+ expect(defaultEffect('compressor')).toMatchObject({ type: 'compressor', ratio: 4 });
+ });
+});
diff --git a/plugins/audio-mixer/tsconfig.json b/plugins/audio-mixer/tsconfig.json
new file mode 100644
index 000000000..72a0a96ce
--- /dev/null
+++ b/plugins/audio-mixer/tsconfig.json
@@ -0,0 +1,13 @@
+{
+ "compilerOptions": {
+ "strict": true,
+ "target": "ES2020",
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "jsx": "react-jsx",
+ "noEmit": true,
+ "skipLibCheck": true,
+ "paths": { "@estella/editor-api": ["../../desktop/src/plugins/types.ts"] }
+ },
+ "include": ["src", "tests"]
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 462d6c0ac..d39a5a224 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -113,6 +113,27 @@ importers:
specifier: ^2.1.0
+ plugins/audio-mixer:
+ devDependencies:
+ '@types/react':
+ specifier: ^19.2.0
+ version: 19.2.17
+ '@types/react-dom':
+ specifier: ^19.2.0
+ version: 19.2.3(@types/[email protected])
+ esengine:
+ specifier: workspace:*
+ version: link:../../sdk
+ react:
+ specifier: ^19.2.0
+ version: 19.2.7
+ react-dom:
+ specifier: ^19.2.0
+ version: 19.2.7([email protected])
+ vitest:
+ specifier: ^2.1.9
+
plugins/ldtk:
devDependencies:
vitest:
diff --git a/tools/check-path-sandbox.mjs b/tools/check-path-sandbox.mjs
index 0a117808a..e9b32b4a8 100644
--- a/tools/check-path-sandbox.mjs
+++ b/tools/check-path-sandbox.mjs
@@ -12,7 +12,7 @@
* on the line above with `path-sandbox: <why>`.
*/
import { execFileSync } from 'node:child_process';
-import { readFileSync } from 'node:fs';
+import { readFileSync, existsSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -29,7 +29,9 @@ const OPT_OUT = /path-sandbox:/;
const files = execFileSync('git', ['ls-files'], { cwd: ROOT, encoding: 'utf8' })
.split('\n')
- .filter((f) => SCOPE.test(f) && f !== HOME);
+ // `git ls-files` lists what is TRACKED, which includes a file deleted in the
+ // working tree: reading one throws and takes every later gate with it.
+ .filter((f) => SCOPE.test(f) && f !== HOME && existsSync(path.join(ROOT, f)));
const findings = [];
for (const file of files) {