A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
refactor(editor): derive the dock from a panel registry instead of four tables
esengine9b8046fcf67b
diff --git a/desktop/src/commands/editorCommands.ts b/desktop/src/commands/editorCommands.tsindex 90e0b23b9..1ef9e5c59 100644--- a/desktop/src/commands/editorCommands.ts+++ b/desktop/src/commands/editorCommands.ts@@ -279,13 +279,7 @@ for (const m of EDITOR_MODES) {return;}modeStore.setMode(m.id);- for (const p of m.panels ?? []) {- if (p.tabWith) {- dockApi.openTabbedPanel(p.id, p.component, p.title, p.tabWith, p.side ?? 'left', p.width ?? 300);- } else {- dockApi.openSidePanel(p.id, p.component, p.title, p.side ?? 'left', p.width ?? 300);- }- }+ for (const p of m.panels ?? []) dockApi.openPanel(p.panel, { tabWith: p.tabWith });// A mode with a design frame (UI) is entered to work against the authored screen;// the free editor camera never adopts the design aspect, so frame it on entry so// the design resolution (e.g. a portrait 750×1334) reads at once instead of hidingdiff --git a/desktop/src/document/openGraphAsset.ts b/desktop/src/document/openGraphAsset.tsindex c5e6b1de8..b87761b7d 100644--- a/desktop/src/document/openGraphAsset.ts+++ b/desktop/src/document/openGraphAsset.ts@@ -46,7 +46,7 @@ export interface GraphAssetKind {/** Open an existing graph asset into its editor and reveal the panel. */export async function openGraphAsset(kind: GraphAssetKind, path: string): Promise<void> {- const front = (): void => dockApi.openDocument(kind.panelId, kind.panelId, t(kind.titleKey));+ const front = (): void => dockApi.openPanel(kind.panelId);// Already-open file: just front the panel — a reload would clobber unsaved edits.if (kind.document.isOpen && kind.document.filePath === path) {front();diff --git a/desktop/src/flipbook/openFlipbook.ts b/desktop/src/flipbook/openFlipbook.tsindex 0ec7ab18e..91281d482 100644--- a/desktop/src/flipbook/openFlipbook.ts+++ b/desktop/src/flipbook/openFlipbook.ts@@ -20,7 +20,7 @@ import { t } from '@/i18n';export async function openFlipbook(path: string): Promise<void> {// Already-open file: just front the panel — a reload would clobber unsaved edits.if (AnimClipDocument.isOpen && AnimClipDocument.filePath === path) {- dockApi.openDocument('flipbook', 'flipbook', t('fb.panelTitle'));+ dockApi.openPanel('flipbook');useSelection.getState().selectAsset(path);return;}@@ -28,7 +28,7 @@ export async function openFlipbook(path: string): Promise<void> {try {const text = await window.estella.fs.read(path);AnimClipDocument.openJson(JSON.parse(text), path);- dockApi.openDocument('flipbook', 'flipbook', t('fb.panelTitle'));+ dockApi.openPanel('flipbook');useSelection.getState().selectAsset(path);} catch (e) {Toasts.push(t('fb.toast.openFailed', { error: String(e) }), 'error');diff --git a/desktop/src/layout/DockLayout.tsx b/desktop/src/layout/DockLayout.tsxindex 44ceb7a46..3996e4806 100644--- a/desktop/src/layout/DockLayout.tsx+++ b/desktop/src/layout/DockLayout.tsx@@ -1,6 +1,6 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-import { useEffect, useState, useSyncExternalStore, type FC, type ReactNode } from 'react';+import { useEffect, useMemo, useState, useSyncExternalStore, type FC, type ReactNode } from 'react';import {DockviewReact,type DockviewReadyEvent,@@ -13,73 +13,47 @@ import { ChevronDown, X, SquareArrowOutUpRight } from 'lucide-react';import { DirtyDot } from '@/components/DirtyDot';import { panelDirtySource } from '@/layout/panelDirty';import { confirmDiscardDoc } from '@/project/discardGuard';-import { Outliner } from '@/panels/Outliner';-import { Viewport } from '@/panels/Viewport';-import { Details } from '@/panels/Details';-import { ContentBrowser } from '@/panels/ContentBrowser';-import { OutputLog } from '@/panels/OutputLog';-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';-import { MaterialGraphEditor } from '@/panels/MaterialGraphEditor';-import { StateMachineEditor } from '@/panels/StateMachineEditor';-import { AnimatorEditor } from '@/panels/AnimatorEditor';-import { BtTreeEditor } from '@/panels/BtTreeEditor';-import { ProfilerPanel } from '@/panels/ProfilerPanel';import { Perf } from '@/components/Perf';import { ErrorBoundary } from '@/components/ErrorBoundary';import { PanelWindowProvider } from '@/components/PanelWindow';import { dockApi, applyPopoutTheme } from '@/layout/dockApi';import { addEditorWindow, removeEditorWindow } from '@/layout/editorWindows';+import {+ panelDef, panelDefs, panelComponent, isPanelClosable, ensuredPanels,+ panelRegistry, panelTitle,+} from '@/layout/panels';+import { PANEL_RENDERERS } from '@/layout/panelComponents';import { t } from '@/i18n';// Each dock panel is a thin wrapper so dockview owns mount/unmount. The// PanelWindowProvider hands the panel's live window down the tree so floating UI// (menus, popovers, tooltips) lands in the right OS window once it's popped out.-const panel = (id: string, api: DockviewPanelApi, node: ReactNode) => (+// The wrapper keys off the LIVE panel id (api.id), which is also what the profiler+// and error boundary label — so a multi-instance panel needs no bespoke wiring.+const panel = (api: DockviewPanelApi, node: ReactNode, noPerf?: boolean) => (<PanelWindowProvider api={api}>- <Perf id={id}>- <ErrorBoundary label={id}>{node}</ErrorBoundary>- </Perf>+ {noPerf ? (+ <ErrorBoundary label={api.id}>{node}</ErrorBoundary>+ ) : (+ <Perf id={api.id}>+ <ErrorBoundary label={api.id}>{node}</ErrorBoundary>+ </Perf>+ )}</PanelWindowProvider>);-const components: Record<string, FC<IDockviewPanelProps>> = {- outliner: (p) => panel('outliner', p.api, <Outliner />),- viewport: (p) => panel('viewport', p.api, <Viewport />),- details: (p) => panel('details', p.api, <Details />),- content: (p) => panel('content', p.api, <ContentBrowser />),- log: (p) => panel('log', p.api, <OutputLog />),- sequencer: (p) => panel('sequencer', p.api, <Sequencer />),- tileset: (p) => panel('tileset', p.api, <TilesetEditor />),- flipbook: (p) => panel('flipbook', p.api, <FlipbookEditor />),- audiomixer: (p) => panel('audiomixer', p.api, <AudioMixerPanel />),- tilemap: (p) => panel('tilemap', p.api, <TilemapPainter />),- uiWidgets: (p) => panel('uiWidgets', p.api, <UIWidgetsPanel />),- controllers: (p) => panel('controllers', p.api, <ControllersPanel />),- materialgraph: (p) => panel('materialgraph', p.api, <MaterialGraphEditor />),- statemachine: (p) => panel('statemachine', p.api, <StateMachineEditor />),- animatorcontroller: (p) => panel('animatorcontroller', p.api, <AnimatorEditor />),- behaviortree: (p) => panel('behaviortree', p.api, <BtTreeEditor />),- // Profiler skips the Perf wrapper (it must not profile its own render).- profiler: (p) => (- <PanelWindowProvider api={p.api}>- <ErrorBoundary label="profiler"><ProfilerPanel /></ErrorBoundary>- </PanelWindowProvider>- ),- // The "Game" view (isolated play realm) — added on Play, removed on Stop.- game: (p) => panel('game', p.api, <GamePanel />),- // Multiplayer client realms ("Game P2..N") — session-scoped, keyed by realmId.- gameClient: (props) => {- const realmId = Number((props.params as { realmId?: number } | undefined)?.realmId ?? 0);- return panel(`game-client-${realmId}`, props.api, <GameClientPanel realmId={realmId} />);- },-};+/** dockview's component map, derived from the panel registry. */+function buildComponents(): Record<string, FC<IDockviewPanelProps>> {+ const out: Record<string, FC<IDockviewPanelProps>> = {};+ for (const def of panelDefs()) {+ const key = panelComponent(def);+ const render = PANEL_RENDERERS[key];+ if (!render) continue; // registered with no renderer — nothing to mount+ out[key] = (p) =>+ panel(p.api, render({ panelId: p.api.id, params: p.params as Record<string, unknown> | undefined }), def.noPerf);+ }+ return out;+}// Bumped to v6 (document-area editors): Viewport center, right column Outliner-// over-Details, Content Browser + Output Log + Sequencer as bottom tabs. The big@@ -107,107 +81,52 @@ export function resetLayout() {api.getPanel('content')?.api.setActive();}+// The default ARRANGEMENT — a layout recipe (who anchors whom, at what size),+// which is why it stays here rather than in the panel registry. Titles and+// component keys still come from the registry, so they can't drift from it.function buildDefaultLayout(api: DockviewReadyEvent['api']) {- // Viewport is the anchor; the right column stacks Outliner over Details.- api.addPanel({ id: 'viewport', component: 'viewport', title: t('layout.panel.viewport') });-- api.addPanel({- id: 'outliner',- component: 'outliner',- title: t('layout.panel.worldOutliner'),- position: { referencePanel: 'viewport', direction: 'right' },- initialWidth: 366, // --w-rightdock- });-- api.addPanel({- id: 'details',- component: 'details',- title: t('layout.panel.details'),- position: { referencePanel: 'outliner', direction: 'below' },- });-- api.addPanel({- id: 'content',- component: 'content',- title: t('layout.panel.contentBrowser'),- position: { referencePanel: 'viewport', direction: 'below' },- initialHeight: 300,- });+ const add = (id: string, position?: Parameters<typeof api.addPanel>[0]['position'], size?: { initialWidth?: number; initialHeight?: number }) => {+ const def = panelDef(id);+ if (!def) return;+ api.addPanel({ id, component: panelComponent(def), title: def.title(), position, ...size });+ };+ // Viewport is the anchor; the right column stacks Outliner over Details.+ add('viewport');+ add('outliner', { referencePanel: 'viewport', direction: 'right' }, { initialWidth: 366 }); // --w-rightdock+ add('details', { referencePanel: 'outliner', direction: 'below' });+ add('content', { referencePanel: 'viewport', direction: 'below' }, { initialHeight: 300 });// Output Log shares the bottom group as a sibling tab of the Content Browser.- api.addPanel({- id: 'log',- component: 'log',- title: t('layout.panel.outputLog'),- position: { referencePanel: 'content', direction: 'within' },- });+ add('log', { referencePanel: 'content', direction: 'within' });}// Bottom-dock utility tabs added on both fresh builds and restored layouts, so a// saved layout predating a tab gains it without resetting the user's arrangement.-// Each docks next to the first of `refs` that exists. The big editing canvases-// (Material Graph / Tilemap / Tileset) are intentionally NOT here — they open as-// center document tabs on demand (dockApi.openDocument); only the timeline-shaped-// Sequencer belongs in the bottom utility row (UE convention).-const BOTTOM_TABS: { id: string; component: string; title: string; refs: string[] }[] = [- { id: 'sequencer', component: 'sequencer', title: t('layout.panel.sequencer'), refs: ['content', 'log'] },- { id: 'profiler', component: 'profiler', title: t('layout.panel.profiler'), refs: ['log', 'content'] },- { id: 'audiomixer', component: 'audiomixer', title: t('mix.panelTitle'), refs: ['log', 'content'] },-];-+// Each docks next to the first of its `refs` that exists.function ensureBottomTabs(api: DockviewReadyEvent['api']) {- for (const tab of BOTTOM_TABS) {- if (api.getPanel(tab.id)) continue;- const ref = tab.refs.find((r) => api.getPanel(r));+ for (const def of ensuredPanels()) {+ if (api.getPanel(def.id)) continue;+ const ref = def.refs?.find((r) => api.getPanel(r));api.addPanel({- id: tab.id,- component: tab.component,- title: tab.title,+ id: def.id,+ component: panelComponent(def),+ title: def.title(),position: ref ? { referencePanel: ref, direction: 'within' } : undefined,});}}// dockview persists panel TITLES inside the saved layout JSON, in whatever-// language wrote them — so a restored layout would pin the old language on-// every tab. All our panel ids are stable, so re-title the known ones from-// the live catalog after a restore. Ids not listed (game clients) are-// session-scoped and never usefully restored.-const PANEL_TITLES: Record<string, () => string> = {- viewport: () => t('layout.panel.viewport'),- outliner: () => t('layout.panel.worldOutliner'),- details: () => t('layout.panel.details'),- content: () => t('layout.panel.contentBrowser'),- log: () => t('layout.panel.outputLog'),- sequencer: () => t('layout.panel.sequencer'),- profiler: () => t('layout.panel.profiler'),- game: () => t('layout.panel.game'),- tileset: () => t('tile.panelTileset'),- flipbook: () => t('fb.panelTitle'),- audiomixer: () => t('mix.panelTitle'),- tilemap: () => t('panel.tilemap'),- 'ui-widgets': () => t('panel.uiWidgets'),- controllers: () => t('panel.controllers'),- materialgraph: () => t('mat.panelTitle'),- statemachine: () => t('fsm.tabTitle'),- animatorcontroller: () => t('anim.tabTitle'),- behaviortree: () => t('bt.tabTitle'),-};-+// language wrote them — so a restored layout would pin the old language on every+// tab. Panel ids are stable, so re-title from the registry after a restore. A+// panel with no registered def (a session-scoped game client) is skipped.function retitleRestoredPanels(api: DockviewReadyEvent['api']) {for (const panel of api.panels) {- const title = PANEL_TITLES[panel.id];- if (title) panel.api.setTitle(title());+ const title = panelTitle(panel.id);+ if (title) panel.api.setTitle(title);}}-// The essential editing panels have no reopen path (only the nuke-everything Reset-// Layout), and the Viewport is the structural anchor other panels dock against — so-// closing any is a dead-end. They stay open; resize or collapse-to-header for space.-// The dockable extras (sequencer/profiler/mixer) keep their X — the activity bar-// re-adds them.-const NON_CLOSABLE_PANELS = new Set(['viewport', 'outliner', 'details', 'content', 'log']);-// Custom tab content: title + the shared dirty dot (asset editors) + a close// button that only shows on hover / on the active tab, so the strip stays calm.function EstellaTab(props: IDockviewPanelHeaderProps) {@@ -242,7 +161,7 @@ function EstellaTab(props: IDockviewPanelHeaderProps) {<SquareArrowOutUpRight size={11} strokeWidth={2} /></button>)}- {!NON_CLOSABLE_PANELS.has(props.api.id) && (+ {isPanelClosable(props.api.id) && (<buttontype="button"className="tab-x"@@ -298,6 +217,14 @@ function CollapseHeaderAction(props: IDockviewHeaderActionsProps) {}export function DockLayout() {+ // Rebuilt when the panel set changes, so a contributed panel's component key+ // exists by the time something opens it.+ const revision = useSyncExternalStore(+ panelRegistry.subscribe.bind(panelRegistry),+ panelRegistry.getRevision.bind(panelRegistry),+ );+ const components = useMemo(() => buildComponents(), [revision]);+const onReady = (event: DockviewReadyEvent) => {const { api } = event;dockApi.set(api); // expose to the activity bar (reveal/focus panels)diff --git a/desktop/src/layout/dockApi.ts b/desktop/src/layout/dockApi.tsindex 636a59ca4..d5a3c2e7d 100644--- a/desktop/src/layout/dockApi.ts+++ b/desktop/src/layout/dockApi.ts@@ -8,6 +8,7 @@*/import type { DockviewApi, DockviewGroupPanelApi } from 'dockview';import { t } from '@/i18n';+import { panelDef, panelComponent, isPanelPoppable } from '@/layout/panels';let api: DockviewApi | null = null;// Remembered pre-collapse sizes, per panel id (so a re-expand restores them).@@ -34,12 +35,13 @@ const prefersReducedMotion = (): boolean =>typeof window.matchMedia === 'function' &&window.matchMedia('(prefers-reduced-motion: reduce)').matches;-// The Game view hosts the play-realm iframe, and re-parenting an iframe across-// documents reloads it (its wasm/GL would restart) — so it stays put. The Viewport-// CAN pop out: a same-origin canvas move preserves the live WebGL context, so its-// single engine canvas rides the move into the new window (EngineHost.rebindResize-// re-binds sizing). Everything else is model/store-driven and pops out cleanly.-const NON_POPPABLE = new Set(['game']);+// Whether a panel may pop out is a per-panel FACT, so it lives on the panel def+// (`poppable`). The Game views host the play-realm iframe, and re-parenting an+// iframe across documents reloads it (its wasm/GL would restart) — so they stay+// put. The Viewport CAN pop out: a same-origin canvas move preserves the live+// WebGL context, so its single engine canvas rides the move into the new window+// (EngineHost.rebindResize re-binds sizing). Everything else is model/store-driven+// and pops out cleanly.// dockview's getDockviewTheme copies only the FIRST `dockview-theme-*` class onto// the popout container (our root carries `dockview-theme-abyss dockview-theme-estella`,@@ -75,9 +77,9 @@ export const dockApi = {setPanelSize(id: string, size: { width?: number; height?: number }) {api?.getPanel(id)?.api.setSize(size);},- /** True when a panel may be popped out into its own OS window (see NON_POPPABLE). */+ /** True when a panel may be popped out into its own OS window (per its panel def). */canPopout(id: string): boolean {- return !NON_POPPABLE.has(id) && !id.startsWith('game-client-');+ return isPanelPoppable(id);},/*** Move a docked panel into its own OS window (dockview addPopoutGroup → a real@@ -148,18 +150,66 @@ export const dockApi = {// Keep the reference tab (the primary companion) foremost so the mode opens showing it.ref.api.setActive();},+ /**+ * Open (or front) a registered panel, docked where its def says it belongs — the+ * ONE door for "show me panel X". Call sites name a panel id and nothing else, so+ * a panel's component key, title, side, and width can't drift per call site the+ * way they did when every opener repeated the triple.+ *+ * `tabWith` overrides the def's placement to tab the panel inside another one's+ * group (a mode companion that shouldn't claim its own column).+ */+ openPanel(id: string, opts?: { tabWith?: string }) {+ const def = panelDef(id);+ if (!api || !def) return;+ const side = def.placement === 'side-right' ? 'right' : 'left';+ if (opts?.tabWith) {+ this.openTabbedPanel(id, panelComponent(def), def.title(), opts.tabWith, side, def.width ?? 300);+ return;+ }+ switch (def.placement) {+ case 'document':+ this.openDocument(id, panelComponent(def), def.title());+ return;+ case 'side-left':+ case 'side-right':+ this.openSidePanel(id, panelComponent(def), def.title(), side, def.width ?? 300);+ return;+ case 'bottom': {+ if (!api.getPanel(id)) {+ const ref = def.refs?.find((r) => api?.getPanel(r));+ api.addPanel({+ id,+ component: panelComponent(def),+ title: def.title(),+ position: ref ? { referencePanel: ref, direction: 'within' } : undefined,+ });+ }+ api.getPanel(id)?.api.setActive();+ return;+ }+ case 'viewport-tab': {+ if (!api.getPanel(id)) {+ api.addPanel({+ id,+ component: panelComponent(def),+ title: def.title(),+ position: api.getPanel('viewport') ? { referencePanel: 'viewport', direction: 'within' } : undefined,+ });+ }+ api.getPanel(id)?.api.setActive();+ return;+ }+ case 'structural':+ // Placed by the default layout; "opening" it means bringing it forward.+ this.revealAndExpand(id);+ return;+ }+ },+/** Open (or reveal) the Game view as a tab beside the Viewport — used on Play. */openGame() {- if (!api) return;- if (!api.getPanel('game')) {- api.addPanel({- id: 'game',- component: 'game',- title: t('layout.panel.game'),- position: api.getPanel('viewport') ? { referencePanel: 'viewport', direction: 'within' } : undefined,- });- }- api.getPanel('game')?.api.setActive();+ this.openPanel('game');},/** Close the Game view — used on Stop. */closeGame() {@@ -168,14 +218,16 @@ export const dockApi = {/** Open the multiplayer client views ("Game P2..N") beside the primary Game* view — used on multiplayer Play. Splits right so players sit side by side. */openGameClients(realmIds: number[]) {- if (!api) return;+ const def = panelDef('gameClient');+ if (!api || !def) return;for (const realmId of realmIds) {- const id = `game-client-${realmId}`;+ const id = `${def.instanceIdPrefix}${realmId}`;if (!api.getPanel(id)) {const anchor = api.getPanel('game') ?? api.getPanel('viewport');api.addPanel({id,- component: 'gameClient',+ component: panelComponent(def),+ // Per-instance title (the def's is the generic one) — players are 1-based.title: t('layout.panel.gamePlayer', { n: realmId + 1 }),params: { realmId },position: anchor ? { referencePanel: anchor.id, direction: 'right' } : undefined,diff --git a/desktop/src/layout/panelComponents.tsx b/desktop/src/layout/panelComponents.tsxnew file mode 100644index 000000000..f647bb9b5--- /dev/null+++ b/desktop/src/layout/panelComponents.tsx@@ -0,0 +1,60 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file panelComponents.tsx+ * @brief The render half of the panel registry: dockview component key → React+ * subtree. Split from the pure `panels.ts` registry because these imports+ * pull in the entire panel tree (and cycle back through the command+ * registry), while most consumers only need a panel's title or dock rules —+ * the same separation assetTypes/assetOpen use.+ */+import type { ReactNode } from 'react';+import { Outliner } from '@/panels/Outliner';+import { Viewport } from '@/panels/Viewport';+import { Details } from '@/panels/Details';+import { ContentBrowser } from '@/panels/ContentBrowser';+import { OutputLog } from '@/panels/OutputLog';+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';+import { MaterialGraphEditor } from '@/panels/MaterialGraphEditor';+import { StateMachineEditor } from '@/panels/StateMachineEditor';+import { AnimatorEditor } from '@/panels/AnimatorEditor';+import { BtTreeEditor } from '@/panels/BtTreeEditor';+import { ProfilerPanel } from '@/panels/ProfilerPanel';++/** What a panel renderer is handed: its live panel id and dockview params. */+export interface PanelRenderContext {+ panelId: string;+ params?: Record<string, unknown>;+}++export type PanelRenderer = (ctx: PanelRenderContext) => ReactNode;++/** Renderer per dockview component key. Keys match `panelComponent(def)`. */+export const PANEL_RENDERERS: Record<string, PanelRenderer> = {+ outliner: () => <Outliner />,+ viewport: () => <Viewport />,+ details: () => <Details />,+ content: () => <ContentBrowser />,+ log: () => <OutputLog />,+ sequencer: () => <Sequencer />,+ tileset: () => <TilesetEditor />,+ flipbook: () => <FlipbookEditor />,+ audiomixer: () => <AudioMixerPanel />,+ tilemap: () => <TilemapPainter />,+ uiWidgets: () => <UIWidgetsPanel />,+ controllers: () => <ControllersPanel />,+ materialgraph: () => <MaterialGraphEditor />,+ statemachine: () => <StateMachineEditor />,+ animatorcontroller: () => <AnimatorEditor />,+ behaviortree: () => <BtTreeEditor />,+ profiler: () => <ProfilerPanel />,+ game: () => <GamePanel />,+ gameClient: ({ params }) => <GameClientPanel realmId={Number(params?.realmId ?? 0)} />,+};diff --git a/desktop/src/layout/panels.ts b/desktop/src/layout/panels.tsnew file mode 100644index 000000000..12c398189--- /dev/null+++ b/desktop/src/layout/panels.ts@@ -0,0 +1,182 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file panels.ts+ * @brief THE authority for editor dock panels — one entry per panel carries its+ * dockview component key, title, where it docks when opened, whether it can+ * be closed or popped out, and whether the layout ensures it exists. The+ * dockview component map, the restore-time re-title pass, the bottom utility+ * tab list, and the closable/poppable rules all derive from it.+ *+ * Adding a panel used to mean four separate tables in DockLayout plus a rule in+ * dockApi, and opening one meant repeating its (id, component, title) triple at+ * every call site. Both are now single-sourced here.+ *+ * Kept free of React imports on purpose — the renderers live in panelComponents.tsx+ * and are imported only by DockLayout. Folding them in here would drag the whole+ * panel tree into every module that just wants to know a panel's title, and cycle+ * back through the command registry (the same split assetTypes/assetOpen use).+ */+import { t } from '@/i18n';+import { ContributionRegistry, type Disposable, type Owner } from '@/contrib/ContributionRegistry';++/**+ * Where a panel lands when opened on demand.+ * - `document` — a center tab beside the Viewport (the big editing canvases).+ * - `side-left` / `side-right` — a companion column that stays visible WHILE you+ * work in the Viewport (palettes).+ * - `bottom` — a utility tab in the bottom dock (timeline-shaped tools).+ * - `structural` — placed by the default layout; never opened on demand.+ * - `viewport-tab` — a tab in the Viewport's own group (the Game view).+ */+export type PanelPlacement = 'document' | 'side-left' | 'side-right' | 'bottom' | 'structural' | 'viewport-tab';++export interface PanelDef {+ /** Dock panel id — also the dockview component key unless `component` differs. */+ id: string;+ /** dockview component key (defaults to `id`). */+ component?: string;+ /** Read lazily: a restored layout re-titles from here, so the saved language+ * in the layout JSON never pins stale strings onto the tabs. */+ title: () => string;+ placement: PanelPlacement;+ /** `side-*` panels: initial column width. */+ width?: number;+ /** `bottom` panels: dock next to the first of these that exists. */+ refs?: string[];+ /** Ensure the panel exists on fresh builds AND restored layouts, so a layout+ * predating the panel gains it without resetting the user's arrangement. */+ ensure?: boolean;+ /**+ * Whether the tab offers an X. The essential editing panels have no reopen path+ * and the Viewport is the anchor others dock against, so closing any is a dead+ * end — they stay open (resize or collapse-to-header for space). Default true.+ */+ closable?: boolean;+ /**+ * Whether the panel may move into its own OS window. Default true: a popout is a+ * same-origin window.open, so the panel's React tree and every editor store stay+ * in this window's JS realm. False for iframe hosts — re-parenting an iframe+ * across documents reloads it (its wasm/GL would restart).+ */+ poppable?: boolean;+ /** Skip the Perf wrapper (the profiler must not profile its own render). */+ noPerf?: boolean;+ /**+ * Set for a MULTI-INSTANCE panel: `id` is then only a component key, and its live+ * panels are `${instanceIdPrefix}<n>`. Such a panel has no static title/layout+ * entry (it is session-scoped), but its closable/poppable rules still resolve+ * through {@link panelDefForInstance}.+ */+ instanceIdPrefix?: string;+}++// The Viewport is the anchor; the right column stacks Outliner over Details; the+// Content Browser + Output Log share the bottom group. Widths/heights of the+// default ARRANGEMENT stay in DockLayout — that's a layout recipe, not panel data.+const STRUCTURAL: PanelDef[] = [+ { id: 'viewport', title: () => t('layout.panel.viewport'), placement: 'structural', closable: false },+ { id: 'outliner', title: () => t('layout.panel.worldOutliner'), placement: 'structural', closable: false },+ { id: 'details', title: () => t('layout.panel.details'), placement: 'structural', closable: false },+ { id: 'content', title: () => t('layout.panel.contentBrowser'), placement: 'structural', closable: false },+ { id: 'log', title: () => t('layout.panel.outputLog'), placement: 'structural', closable: false },+];++// Bottom-dock utility tabs. The big editing canvases are deliberately NOT here —+// they open as center document tabs on demand; only timeline/monitor-shaped tools+// belong in the bottom utility row.+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 },+];++// Full editing canvases — opened on demand as center tabs beside the Viewport.+const DOCUMENTS: PanelDef[] = [+ { id: 'tileset', title: () => t('tile.panelTileset'), placement: 'document' },+ { id: 'flipbook', title: () => t('fb.panelTitle'), placement: 'document' },+ { id: 'materialgraph', title: () => t('mat.panelTitle'), placement: 'document' },+ { id: 'statemachine', title: () => t('fsm.tabTitle'), placement: 'document' },+ { id: 'animatorcontroller', title: () => t('anim.tabTitle'), placement: 'document' },+ { id: 'behaviortree', title: () => t('bt.tabTitle'), placement: 'document' },+];++// Companion palettes — revealed by an editor mode, docked beside the Viewport so+// they stay visible while you paint / lay out in it.+const COMPANIONS: PanelDef[] = [+ { id: 'tilemap', title: () => t('panel.tilemap'), placement: 'side-left', width: 300 },+ { id: 'ui-widgets', component: 'uiWidgets', title: () => t('panel.uiWidgets'), placement: 'side-left', width: 240 },+ { id: 'controllers', title: () => t('panel.controllers'), placement: 'side-left', width: 240 },+];++// The isolated play realm's views. Both host an estella:// iframe, so neither can+// pop out. The multiplayer clients are session-scoped and keyed by realm id.+const PLAY: PanelDef[] = [+ { id: 'game', title: () => t('layout.panel.game'), placement: 'viewport-tab', poppable: false },+ {+ id: 'gameClient',+ title: () => t('layout.panel.gamePlayer', { n: 1 }),+ placement: 'viewport-tab',+ poppable: false,+ instanceIdPrefix: 'game-client-',+ },+];++/** The panels the editor ships, in declaration order. */+export const BUILTIN_PANELS: PanelDef[] = [...STRUCTURAL, ...BOTTOM, ...DOCUMENTS, ...COMPANIONS, ...PLAY];++const panelContrib = new ContributionRegistry<PanelDef>('panel');+panelContrib.registerAll('core', BUILTIN_PANELS);++export const panelRegistry = panelContrib;++export function registerPanel(def: PanelDef, owner: Owner = 'core'): Disposable {+ return panelContrib.register(owner, def);+}++/** Every panel def — built-ins first, then contributed ones. */+export function panelDefs(): readonly PanelDef[] {+ return panelContrib.all();+}++/** The def registered under this id (a panel id, or a multi-instance component key). */+export function panelDef(id: string): PanelDef | undefined {+ return panelContrib.get(id);+}++/** The dockview component key a panel renders through. */+export function panelComponent(def: PanelDef): string {+ return def.component ?? def.id;+}++/**+ * The def behind a LIVE panel id — exact match first, then the multi-instance def+ * whose prefix it carries (`game-client-2` → the `gameClient` def). This is how+ * per-panel rules resolve for dynamically created panels.+ */+export function panelDefForInstance(panelId: string): PanelDef | undefined {+ return (+ panelContrib.get(panelId) ??+ panelDefs().find((d) => d.instanceIdPrefix && panelId.startsWith(d.instanceIdPrefix))+ );+}++/** A panel's current title, or null when nothing is registered under `id`. */+export function panelTitle(id: string): string | null {+ return panelDef(id)?.title() ?? null;+}++/** Panels the layout ensures exist (fresh builds and restored layouts alike). */+export function ensuredPanels(): readonly PanelDef[] {+ return panelDefs().filter((d) => d.ensure);+}++/** Whether a live panel's tab offers an X (unknown ids are closable). */+export function isPanelClosable(panelId: string): boolean {+ return panelDefForInstance(panelId)?.closable ?? true;+}++/** Whether a live panel may be popped out into its own OS window. */+export function isPanelPoppable(panelId: string): boolean {+ return panelDefForInstance(panelId)?.poppable ?? true;+}diff --git a/desktop/src/material/openMaterialGraph.ts b/desktop/src/material/openMaterialGraph.tsindex ece899e6c..fb423a3bc 100644--- a/desktop/src/material/openMaterialGraph.ts+++ b/desktop/src/material/openMaterialGraph.ts@@ -23,14 +23,14 @@ const shaderPathOf = (graphPath: string) => graphPath.replace(/\.esmatgraph$/, 'export async function openMaterialGraph(path: string): Promise<void> {// Already-open file: just front the panel — a reload would clobber unsaved edits.if (MaterialGraphDocument.isOpen && MaterialGraphDocument.filePath === path) {- dockApi.openDocument('materialgraph', 'materialgraph', t('mat.panelTitle'));+ dockApi.openPanel('materialgraph');return;}if (!(await confirmDiscardDoc(MaterialGraphDocument.dirty, t('discard.openAsset', { name: baseName(path) })))) return;try {const text = await window.estella.fs.read(path);MaterialGraphDocument.openJson(JSON.parse(text), path);- dockApi.openDocument('materialgraph', 'materialgraph', t('mat.panelTitle'));+ dockApi.openPanel('materialgraph');} catch (e) {Toasts.push(t('mat.openGraphFailed', { error: String(e) }), 'error');}diff --git a/desktop/src/mode/editorModes.ts b/desktop/src/mode/editorModes.tsindex 2902b891c..1c2c1a2c5 100644--- a/desktop/src/mode/editorModes.ts+++ b/desktop/src/mode/editorModes.ts@@ -30,16 +30,17 @@ export interface SelectionProbe {hasComponent(type: string): boolean;}-/** A companion panel a mode reveals when entered (routed through dockApi.openSidePanel). */+/**+ * A companion panel a mode reveals when entered — a REFERENCE into the panel+ * registry, which owns the panel's component key, title, side, and width. A mode+ * only says "reveal that panel, maybe tabbed behind this one".+ */export interface ModePanel {- id: string;- component: string;- title: string;- side?: 'left' | 'right';- width?: number;- /** Dock as a TAB in another mode-panel's group (by id) instead of its own column —- * keeps a companion (e.g. Controllers) one click away without eating a second column- * of viewport width. Falls back to `side` if that panel isn't open. */+ /** Registered panel id (see layout/panels.ts). */+ panel: string;+ /** Dock as a TAB in another mode-panel's group instead of its own column — keeps+ * a companion (e.g. Controllers) one click away without eating a second column+ * of viewport width. Falls back to its own placement if that panel isn't open. */tabWith?: string;}@@ -70,7 +71,7 @@ const tilemapMode: EditorModeDef = {commandLabel: t('cmd.mode.tilemap'),icon: Grid3x3,toolset: 'tilemap',- panels: [{ id: 'tilemap', component: 'tilemap', title: t('panel.tilemap'), side: 'left', width: 300 }],+ panels: [{ panel: 'tilemap' }],suggestFor: (s) => s.hasComponent('TilemapLayer'),};@@ -81,11 +82,11 @@ const uiMode: EditorModeDef = {icon: LayoutPanelTop,toolset: 'transform',panels: [- { id: 'ui-widgets', component: 'uiWidgets', title: t('panel.uiWidgets'), side: 'left', width: 240 },+ { panel: 'ui-widgets' },// The Controllers panel is node-scoped and reached occasionally — tab it behind the// widget palette (one left column, two tabs) so entering UI mode doesn't eat a second// column of the viewport you're laying out in.- { id: 'controllers', component: 'controllers', title: t('panel.controllers'), tabWith: 'ui-widgets', side: 'left', width: 240 },+ { panel: 'controllers', tabWith: 'ui-widgets' },],overlays: { designFrame: true, safeArea: true, letterbox: true },suggestFor: (s) => s.hasComponent('Canvas') || s.hasComponent('UINode'),diff --git a/desktop/src/tilemap/createTilemap.ts b/desktop/src/tilemap/createTilemap.tsindex e815895cb..79d913f8f 100644--- a/desktop/src/tilemap/createTilemap.ts+++ b/desktop/src/tilemap/createTilemap.ts@@ -41,7 +41,7 @@ function tilesetSource(useTilemapPaint.getState().setTool('brush');// Dock the painter to the side so the Viewport stays visible (a center tab would// hide what you paint on).- dockApi.openSidePanel('tilemap', 'tilemap', t('panel.tilemap'), 'left', 300);+ dockApi.openPanel('tilemap');Toasts.push(t('tile.toast.created'), 'info');},};@@ -87,7 +87,7 @@ export async function createCollisionLayer(): Promise<void> {// Start on the solid brush (palette gid 1) with the brush tool, painter open.useTilemapPaint.getState().setBrushTile(1);useTilemapPaint.getState().setTool('brush');- dockApi.openSidePanel('tilemap', 'tilemap', t('panel.tilemap'), 'left', 300);+ dockApi.openPanel('tilemap');Toasts.push(t('tile.toast.collisionCreated'), 'info');},}, { parent: null });diff --git a/desktop/src/tileset/openTileset.ts b/desktop/src/tileset/openTileset.tsindex e8b77c80a..3873a5f0e 100644--- a/desktop/src/tileset/openTileset.ts+++ b/desktop/src/tileset/openTileset.ts@@ -20,14 +20,14 @@ import { t } from '@/i18n';export async function openTileset(path: string): Promise<void> {// Already-open file: just front the panel — a reload would clobber unsaved edits.if (TilesetDocument.isOpen && TilesetDocument.filePath === path) {- dockApi.openDocument('tileset', 'tileset', t('tile.panelTileset'));+ dockApi.openPanel('tileset');return;}if (!(await confirmDiscardDoc(TilesetDocument.dirty, t('discard.openAsset', { name: baseName(path) })))) return;try {const text = await window.estella.fs.read(path);TilesetDocument.openJson(JSON.parse(text), path);- dockApi.openDocument('tileset', 'tileset', t('tile.panelTileset'));+ dockApi.openPanel('tileset');} catch (e) {Toasts.push(t('tile.toast.openFailed', { error: String(e) }), 'error');}diff --git a/desktop/tests/editor-mode.test.ts b/desktop/tests/editor-mode.test.tsindex 9b016bcec..bcc7dd137 100644--- a/desktop/tests/editor-mode.test.ts+++ b/desktop/tests/editor-mode.test.ts@@ -21,6 +21,7 @@ vi.mock('@/engine/SceneModel', () => ({}));import { EDITOR_MODES, EDITOR_MODE_BY_ID, editorModes, modeById, editorModeRegistry } from '@/mode/editorModes';+import { panelDef } from '@/layout/panels';import { suggestedMode, activeMode } from '@/mode/activeMode';import { resolveActiveTool } from '@/tools';import { TILE_TOOLS } from '@/tools/tileTools';@@ -54,11 +55,22 @@ describe('editor-mode registry + derivation', () => {it('UI mode reveals the widget palette + controllers panels on entry', () => {expect(EDITOR_MODE_BY_ID.ui.panels).toEqual([- expect.objectContaining({ component: 'uiWidgets', side: 'left' }),- expect.objectContaining({ component: 'controllers', side: 'left' }),+ { panel: 'ui-widgets' },+ { panel: 'controllers', tabWith: 'ui-widgets' },]);});+ it('every mode panel reference resolves in the panel registry', () => {+ // A mode names panels by id only; a typo would silently reveal nothing, so the+ // reference is checked here rather than at runtime.+ for (const mode of editorModes()) {+ for (const p of mode.panels ?? []) {+ expect(panelDef(p.panel), `mode "${mode.id}" panel "${p.panel}"`).toBeDefined();+ if (p.tabWith) expect(panelDef(p.tabWith), `mode "${mode.id}" tabWith "${p.tabWith}"`).toBeDefined();+ }+ }+ });+it('suggests the mode implied by the selection', () => {withComponents('TilemapLayer');expect(suggestedMode().id).toBe('tilemap');diff --git a/desktop/tests/panel-registry.test.ts b/desktop/tests/panel-registry.test.tsnew file mode 100644index 000000000..22b409cca--- /dev/null+++ b/desktop/tests/panel-registry.test.ts@@ -0,0 +1,88 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The panel registry that DockLayout's component map, restore-time re-title+ * pass, bottom utility tabs, and closable/poppable rules all derive from.+ * These assertions pin the values the four hardcoded tables used to carry, so+ * the migration to a registry is provably behavior-preserving — and lock the+ * two rules that are easy to get wrong: an iframe host must never be+ * poppable, and the essential editing panels must never gain an X.+ */+import { describe, it, expect, vi } from 'vitest';+import {+ BUILTIN_PANELS, panelDef, panelDefs, panelComponent, panelDefForInstance, panelTitle,+ ensuredPanels, isPanelClosable, isPanelPoppable, panelRegistry, registerPanel,+} from '@/layout/panels';++describe('panel registry', () => {+ it('has unique ids and a title for every panel', () => {+ const ids = BUILTIN_PANELS.map((d) => d.id);+ expect(new Set(ids).size).toBe(ids.length);+ for (const def of BUILTIN_PANELS) expect(def.title()).toBeTruthy();+ });++ it('reproduces the non-closable set (the panels with no reopen path)', () => {+ const nonClosable = panelDefs().filter((d) => !isPanelClosable(d.id)).map((d) => d.id);+ expect(new Set(nonClosable)).toEqual(new Set(['viewport', 'outliner', 'details', 'content', 'log']));+ });++ it('withholds pop-out from the iframe hosts only', () => {+ const nonPoppable = panelDefs().filter((d) => !isPanelPoppable(d.id)).map((d) => d.id);+ expect(new Set(nonPoppable)).toEqual(new Set(['game', 'gameClient']));+ // The Viewport CAN pop out — a same-origin canvas move keeps its live GL context.+ expect(isPanelPoppable('viewport')).toBe(true);+ });++ it('resolves a dynamic panel instance to its component def', () => {+ // Multiplayer client views are created as game-client-<realmId>; their rules must+ // still resolve, which is what kept the old hardcoded prefix check in dockApi.+ expect(panelDefForInstance('game-client-2')?.id).toBe('gameClient');+ expect(isPanelPoppable('game-client-2')).toBe(false);+ expect(isPanelClosable('game-client-2')).toBe(true);+ // A session-scoped instance has no static title, so a layout restore skips it.+ expect(panelTitle('game-client-2')).toBeNull();+ });++ it('ensures exactly the bottom utility tabs, each with dock references', () => {+ expect(ensuredPanels().map((d) => d.id)).toEqual(['sequencer', 'profiler', 'audiomixer']);+ for (const def of ensuredPanels()) {+ expect(def.placement).toBe('bottom');+ expect(def.refs?.length).toBeGreaterThan(0);+ // Each reference must itself be a real panel, or the tab silently floats.+ for (const ref of def.refs ?? []) expect(panelDef(ref)).toBeDefined();+ }+ });++ it('keeps the one panel whose component key differs from its id', () => {+ // The UI widget palette docks as `ui-widgets` but renders `uiWidgets`; conflating+ // the two is what the separate component field exists to prevent.+ expect(panelComponent(panelDef('ui-widgets')!)).toBe('uiWidgets');+ expect(panelComponent(panelDef('details')!)).toBe('details');+ });++ it('exempts only the profiler from the Perf wrapper', () => {+ expect(panelDefs().filter((d) => d.noPerf).map((d) => d.id)).toEqual(['profiler']);+ });++ it('a contributed panel joins the registry and is retracted with its owner', () => {+ const d = registerPanel(+ { id: 'acme.budget', title: () => 'Level Budget', placement: 'bottom', refs: ['log'] },+ 'plugin:acme',+ );+ expect(panelDef('acme.budget')?.placement).toBe('bottom');+ expect(panelTitle('acme.budget')).toBe('Level Budget');+ expect(isPanelClosable('acme.budget')).toBe(true); // contributed panels close by default+ expect(isPanelPoppable('acme.budget')).toBe(true);++ d.dispose();+ expect(panelDef('acme.budget')).toBeUndefined();+ });++ it('a contributed panel cannot take over a built-in panel id', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ panelRegistry.register('plugin:evil', { id: 'viewport', title: () => 'Hijacked', placement: 'document' });+ expect(panelTitle('viewport')).not.toBe('Hijacked');+ expect(isPanelClosable('viewport')).toBe(false); // the built-in rule survives+ warn.mockRestore();+ });+});