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): give every extension point one owner + disposal mechanism
esenginee7d3bf70ae7d
diff --git a/desktop/src/commands/editorCommands.ts b/desktop/src/commands/editorCommands.tsindex 2884b868e..90e0b23b9 100644--- a/desktop/src/commands/editorCommands.ts+++ b/desktop/src/commands/editorCommands.ts@@ -266,7 +266,7 @@ commands.register({ id: 'tool.scale', label: t('cmd.tool.scale'), category: t('cfor (const m of EDITOR_MODES) {commands.register({id: `mode.${m.id}`,- label: t(`cmd.mode.${m.id}`),+ label: m.commandLabel,category: t('cat.tools'),isChecked: () => activeMode().id === m.id,run: () => {diff --git a/desktop/src/commands/registry.ts b/desktop/src/commands/registry.tsindex d73dd62ba..b7f4a3359 100644--- a/desktop/src/commands/registry.ts+++ b/desktop/src/commands/registry.ts@@ -2,15 +2,21 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/*** @file registry.ts- * @brief The editor command registry — one map of id → Command, plus the- * dispatch helpers every consumer shares: run by id, query enablement /- * checked state, resolve the command bound to a key event. Holds no- * reactive state of its own; enablement is derived on demand from the- * domain stores the UI already subscribes to.+ * @brief The editor command registry — the dispatch helpers every consumer+ * shares: run by id, query enablement / checked state, resolve the command+ * bound to a key event. Enablement is derived on demand from the domain+ * stores the UI already subscribes to, so the registry holds no reactive+ * state beyond the contribution set itself.+ *+ * The set lives in a ContributionRegistry, so a command carries an owner and a+ * plugin's commands are retractable as a group. `register(cmd)` keeps its+ * one-argument shape (implicitly `'core'`) — a built-in registration reads exactly+ * as before, and there is no separate door for plugins to drift from.*/import type { Command, Keybinding } from './types';import { chordMatches, normalizeChord } from './keybinding';import { PerfMonitor } from '@/engine/PerfMonitor';+import { ContributionRegistry, type Disposable, type Owner } from '@/contrib/ContributionRegistry';const OVERRIDE_KEY = 'estella.keybindings';@@ -18,7 +24,7 @@ const primaryChord = (kb: Keybinding | undefined): string =>(Array.isArray(kb) ? kb[0] : kb) ?? '';class CommandRegistry {- private readonly map = new Map<string, Command>();+ private readonly contrib = new ContributionRegistry<Command>('command');// User keybinding overrides (commandId → chord), persisted per-user. The// effective binding is `override ?? command.keybinding`, resolved on demand.private readonly overrides = new Map<string, string>();@@ -34,21 +40,43 @@ class CommandRegistry {}}- register(cmd: Command): void {- this.map.set(cmd.id, cmd);+ /** Register a command. `owner` defaults to the editor itself; a plugin passes+ * its own owner so the returned Disposable (and disposeOwner) can retract it. */+ register(cmd: Command, owner: Owner = 'core'): Disposable {+ return this.contrib.register(owner, cmd);}get(id: string): Command | undefined {- return this.map.get(id);+ return this.contrib.get(id);}all(): Command[] {- return [...this.map.values()];+ return [...this.contrib.all()];+ }++ ownerOf(id: string): Owner | undefined {+ return this.contrib.ownerOf(id);+ }++ /** Retract every command of one owner (plugin unload / disable / reload). */+ disposeOwner(owner: Owner): void {+ this.contrib.disposeOwner(owner);+ }++ /** Subscribe to the command SET changing (registrations, not enablement) —+ * menus and the palette re-derive from it. Returns an unsubscribe. */+ subscribe(fn: () => void): () => void {+ return this.contrib.subscribe(fn);+ }++ /** Snapshot of the command set's identity, for useSyncExternalStore. */+ getRevision(): number {+ return this.contrib.getRevision();}/** Effective keybinding: the user override if set, else the command default. */keybindingFor(id: string): Keybinding | undefined {- return this.overrides.has(id) ? this.overrides.get(id) : this.map.get(id)?.keybinding;+ return this.overrides.has(id) ? this.overrides.get(id) : this.contrib.get(id)?.keybinding;}hasOverride(id: string): boolean {@@ -62,7 +90,7 @@ class CommandRegistry {conflictsFor(chord: string, exceptId?: string): string[] {const target = normalizeChord(chord);const out: string[] = [];- for (const c of this.map.values()) {+ for (const c of this.contrib.all()) {if (c.id === exceptId) continue;const kb = this.keybindingFor(c.id);if (!kb) continue;@@ -74,7 +102,7 @@ class CommandRegistry {/** Rebind a command. Setting it back to the default clears the override. */setKeybinding(id: string, chord: string): void {- if (chord === primaryChord(this.map.get(id)?.keybinding)) this.overrides.delete(id);+ if (chord === primaryChord(this.contrib.get(id)?.keybinding)) this.overrides.delete(id);else this.overrides.set(id, chord);this.persistOverrides();}@@ -94,23 +122,23 @@ class CommandRegistry {}isEnabled(id: string): boolean {- const c = this.map.get(id);+ const c = this.contrib.get(id);return c ? c.isEnabled?.() ?? true : false;}isChecked(id: string): boolean | undefined {- return this.map.get(id)?.isChecked?.();+ return this.contrib.get(id)?.isChecked?.();}/** Run a command by id (no-op if missing or currently disabled). */run(id: string): void {- const c = this.map.get(id);+ const c = this.contrib.get(id);if (c && (c.isEnabled?.() ?? true)) PerfMonitor.measure(`cmd.${id}`, () => c.run());}/** The enabled command bound to a key event, if any (honors overrides). */forEvent(e: KeyboardEvent): Command | undefined {- for (const c of this.map.values()) {+ for (const c of this.contrib.all()) {const kb = this.keybindingFor(c.id);if (kb && chordMatches(e, kb) && (c.isEnabled?.() ?? true)) return c;}diff --git a/desktop/src/components/CreatePopover.tsx b/desktop/src/components/CreatePopover.tsxindex 8e9640b58..c5e99fd34 100644--- a/desktop/src/components/CreatePopover.tsx+++ b/desktop/src/components/CreatePopover.tsx@@ -12,7 +12,7 @@*/import { useEffect, useMemo, useRef, useState } from 'react';import { createPortal } from 'react-dom';-import { ENTITY_SOURCES, userComponentSources, matchSources, CREATE_CATEGORY_ORDER, type EntitySource } from '@/engine/entitySources';+import { entitySources, userComponentSources, matchSources, CREATE_CATEGORY_ORDER, type EntitySource } from '@/engine/entitySources';import { ProjectStore } from '@/project/ProjectStore';import { SearchField } from '@/components/SearchField';import { useDialogFocus } from '@/components/dialogFocus';@@ -55,7 +55,7 @@ export function CreatePopover({// Static builtins + the user's own components + the project's prefab assets;// computed once when the popover opens.- const all = useMemo(() => [...ENTITY_SOURCES, ...userComponentSources(), ...ProjectStore.prefabSources()], []);+ const all = useMemo(() => [...entitySources(), ...userComponentSources(), ...ProjectStore.prefabSources()], []);const results = useMemo(() => matchSources(all, query), [all, query]);const groups = useMemo(() => groupByCategory(results), [results]);diff --git a/desktop/src/contrib/ContributionRegistry.ts b/desktop/src/contrib/ContributionRegistry.tsnew file mode 100644index 000000000..881cdfa43--- /dev/null+++ b/desktop/src/contrib/ContributionRegistry.ts@@ -0,0 +1,155 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file ContributionRegistry.ts+ * @brief ONE ownership + disposal mechanism behind every editor extension point+ * (commands, settings, panels, menus, modes, entity templates, …). The+ * editor was already registry-driven; this adds the single missing+ * concept — who registered what.+ *+ * Ownership is what makes a plugin system possible at all: disposing an owner+ * retracts its whole contribution set, so enable/disable, unload, and hot reload+ * are one operation instead of per-kind teardown code. Built-ins register under+ * `'core'` and never dispose, so they cost nothing but read through the same door+ * a plugin does — there is no separate "plugin API" to drift from.+ *+ * Conflicts resolve FIRST-REGISTRATION-WINS rather than by throwing: core+ * registers at module load, so a plugin can never hijack `edit.undo`, and one bad+ * id in a plugin's activate() must not abort the registrations after it. Losers+ * are recorded in {@link ContributionRegistry.conflicts} for the Plugins panel.+ */++/** Who owns a contribution. `'core'` is the editor itself. */+export type Owner = 'core' | `plugin:${string}`;++export interface Disposable {+ dispose(): void;+}++/** A rejected registration — its id was already taken by another owner. */+export interface Conflict {+ id: string;+ /** The owner that holds the id. */+ heldBy: Owner;+ /** The owner whose registration was rejected. */+ rejected: Owner;+}++interface Entry<T> {+ item: T;+ owner: Owner;+ /** Monotonic registration sequence — the tiebreaker that keeps `all()` stable. */+ seq: number;+}++const ownerRank = (owner: Owner): number => (owner === 'core' ? 0 : 1);++export class ContributionRegistry<T extends { id: string }> {+ private readonly entries = new Map<string, Entry<T>>();+ private readonly listeners = new Set<() => void>();+ private readonly conflictList: Conflict[] = [];+ private seq = 0;+ private revision = 0;+ // `all()` is read from render paths and the viewport pointer path, so the+ // ordered projection is cached and rebuilt only when the set changes.+ private ordered: readonly T[] | null = null;++ /** @param kind Human name used in conflict warnings (e.g. 'command', 'panel'). */+ constructor(private readonly kind: string) {}++ /**+ * Register `item` under `owner`. Re-registering the same id from the SAME owner+ * replaces it (idempotent module re-eval, plugin hot reload); a different owner+ * is rejected and recorded. The returned Disposable retracts only this entry.+ */+ register(owner: Owner, item: T): Disposable {+ const held = this.entries.get(item.id);+ if (held && held.owner !== owner) {+ this.conflictList.push({ id: item.id, heldBy: held.owner, rejected: owner });+ console.warn(`[contrib] ${this.kind} id "${item.id}" is already provided by ${held.owner}; ignoring ${owner}`);+ return { dispose: () => {} };+ }+ // A same-owner replacement keeps its original seq so re-registration doesn't+ // reshuffle menus/palettes under the user.+ this.entries.set(item.id, { item, owner, seq: held?.seq ?? this.seq++ });+ this.changed();+ return { dispose: () => this.remove(item.id, owner) };+ }++ /** Register every item of one owner at once (the core tables' entry point). */+ registerAll(owner: Owner, items: readonly T[]): Disposable {+ const disposables = items.map((item) => this.register(owner, item));+ return { dispose: () => disposables.forEach((d) => d.dispose()) };+ }++ get(id: string): T | undefined {+ return this.entries.get(id)?.item;+ }++ /** Every contribution: core first, then plugins in registration order. */+ all(): readonly T[] {+ if (!this.ordered) {+ this.ordered = [...this.entries.values()]+ .sort((a, b) => ownerRank(a.owner) - ownerRank(b.owner) || a.seq - b.seq)+ .map((e) => e.item);+ }+ return this.ordered;+ }++ ownerOf(id: string): Owner | undefined {+ return this.entries.get(id)?.owner;+ }++ /** Contributions of one owner (the Plugins panel's "what does this add?" view). */+ byOwner(owner: Owner): readonly T[] {+ return this.all().filter((item) => this.entries.get(item.id)?.owner === owner);+ }++ /** Retract every contribution of `owner` — the whole point of this class. */+ disposeOwner(owner: Owner): void {+ let removed = false;+ for (const [id, entry] of [...this.entries]) {+ if (entry.owner === owner) {+ this.entries.delete(id);+ removed = true;+ }+ }+ // Conflicts naming this owner are stale once it's gone, either way round: it+ // no longer holds an id, and its rejected attempts are no longer pending.+ for (let i = this.conflictList.length - 1; i >= 0; i--) {+ const c = this.conflictList[i];+ if (c.heldBy === owner || c.rejected === owner) this.conflictList.splice(i, 1);+ }+ if (removed) this.changed();+ }++ /** Registrations rejected because their id was taken (newest last). */+ conflicts(): readonly Conflict[] {+ return this.conflictList;+ }++ /** Bumps on every set change — the useSyncExternalStore snapshot. */+ getRevision(): number {+ return this.revision;+ }++ subscribe(fn: () => void): () => void {+ this.listeners.add(fn);+ return () => this.listeners.delete(fn);+ }++ private remove(id: string, owner: Owner): void {+ const entry = this.entries.get(id);+ // Guard against a stale Disposable retracting a LATER registration of the+ // same id (dispose after the owner re-registered, or after a reload).+ if (entry?.owner !== owner) return;+ this.entries.delete(id);+ this.changed();+ }++ private changed(): void {+ this.ordered = null;+ this.revision++;+ for (const fn of this.listeners) fn();+ }+}diff --git a/desktop/src/engine/entitySources.ts b/desktop/src/engine/entitySources.tsindex 04115e064..90e537dab 100644--- a/desktop/src/engine/entitySources.ts+++ b/desktop/src/engine/entitySources.ts@@ -9,11 +9,16 @@* SceneCommands.create pipeline via `createFromSource`. New items — including the* future async / asset-driven sources — slot in here without touching the picker* UI. (REARCH_ENTITY_CREATION E2.)+ *+ * {@link ENTITY_SOURCES} is this module's REGISTRATION input (and what the built-in+ * catalog tests assert over); pickers read {@link entitySources} so a contributed+ * template shows up everywhere an entity can be born.*/import type { LucideIcon } from 'lucide-react';import { CircleDot, LayoutPanelTop, ToggleLeft, SlidersHorizontal, List, ChevronDown, SquareMousePointer, RectangleHorizontal, Box, Type, Image as ImageIcon, SquareDashed, ScrollText, AppWindow, TextCursorInput, Grid3x3, MapPin, Scan } from 'lucide-react';import { BUILTIN_UI_PREFABS, BUILTIN_UI_WIDGET_NAMES, PREFAB_FORMAT_VERSION, getUserComponents, applyThemeToWorld, type PrefabData } from 'esengine';import type { EntityId } from '@/types';+import { ContributionRegistry } from '@/contrib/ContributionRegistry';import { componentByName, componentDefaults, prettyLabel, componentCategory } from './schema';import { componentGlyph } from '@/components/icons';import { SceneCommands } from './SceneCommands';@@ -322,9 +327,21 @@ export function userComponentSources(): EntitySource[] {* the viewport drop handler agree on one string. */export const SOURCE_DND_MIME = 'application/x-estella-source';+const sourceContrib = new ContributionRegistry<EntitySource>('entity template');+sourceContrib.registerAll('core', ENTITY_SOURCES);++export const entitySourceRegistry = sourceContrib;++/** Every static entity template — built-ins first, then contributed ones. The+ * DYNAMIC sources (user components, project prefabs) are separate generators the+ * Create popover concatenates, since they change with the project, not the session. */+export function entitySources(): readonly EntitySource[] {+ return sourceContrib.all();+}+/** The source with this id, or null. */export function sourceById(id: string): EntitySource | null {- return ENTITY_SOURCES.find((s) => s.id === id) ?? null;+ return sourceContrib.get(id) ?? null;}/** Case-insensitive filter over label + category + keywords, for the Create popover. */@@ -364,7 +381,7 @@ export async function createFromSource(source: EntitySource, ctx: CreateContext)// Canvas can't lay out or be positioned. If the scene has none, spin one up first// so the widget is hosted, not orphaned. (Canvas itself has no such placement.)if (source.placement === 'under-canvas' && parent == null) {- const canvasSrc = ENTITY_SOURCES.find((s) => s.id === 'canvas');+ const canvasSrc = sourceById('canvas');if (canvasSrc) parent = await createFromSource(canvasSrc, { parent: null });}const id = SceneCommands.create(prefab, {diff --git a/desktop/src/layout/ActivityBar.tsx b/desktop/src/layout/ActivityBar.tsxindex dceaeb2b9..510d9937a 100644--- a/desktop/src/layout/ActivityBar.tsx+++ b/desktop/src/layout/ActivityBar.tsx@@ -2,11 +2,12 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team// 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 } from 'lucide-react';import { useEditorStore } from '@/store/editorStore';import { useEditorMode } from '@/store/editorModeStore';import { useSelection } from '@/store/selectionStore';-import { EDITOR_MODES } from '@/mode/editorModes';+import { editorModes, editorModeRegistry } from '@/mode/editorModes';import { activeMode } from '@/mode/activeMode';import { dockApi } from '@/layout/dockApi';import { commands } from '@/commands';@@ -20,17 +21,20 @@ export function ActivityBar() {useEditorMode((s) => s.pinned);useSelection((s) => s.selectedId);const current = activeMode().id;+ // The mode rail is derived from the registry, so a contributed mode appears+ // (and a retracted one disappears) without a reload.+ const modes = useSyncExternalStore(editorModeRegistry.subscribe.bind(editorModeRegistry), editorModes);return (<div className="activity">- {EDITOR_MODES.map((m) => {+ {modes.map((m) => {const Icon = m.icon;return (<buttonkey={m.id}type="button"className={`act${current === m.id ? ' active' : ''}`}- title={t(`cmd.mode.${m.id}` as const)}+ title={m.commandLabel}onClick={() => commands.run(`mode.${m.id}`)}><Icon size={19} strokeWidth={1.7} />diff --git a/desktop/src/main.tsx b/desktop/src/main.tsxindex 2a3869d5f..1d24d5b19 100644--- a/desktop/src/main.tsx+++ b/desktop/src/main.tsx@@ -50,7 +50,7 @@ import { Particle, getComponent } from 'esengine';import { actionNames, actionParams, conditionNames } from '@/ai/actionCatalog';import { applyFxPreview, initFxPreviewEditRestart } from './engine/fxPreview';import { commands } from './commands/registry';-import { ENTITY_SOURCES, sourceById, createFromSource, type TileGridConfig } from './engine/entitySources';+import { entitySources, sourceById, createFromSource, type TileGridConfig } from './engine/entitySources';import { createTilemapFromTileset, createCollisionLayer } from './tilemap/createTilemap';import { layerTilesetRefs, loadLayerTilesetModel } from './tilemap/layerTilesetModel';import { SceneCommands } from './engine/SceneCommands';@@ -147,7 +147,7 @@ if (new URLSearchParams(location.search).has('automation')) {/** Create a blank scene FILE under `destDir` (Content Browser "New Scene"). */createSceneFile: (destDir: string) => ProjectStore.createSceneFile(destDir),/** The Create-popover catalog: every ready-made entity the editor can spawn. */- listEntityTemplates: () => ENTITY_SOURCES.map(({ id, label, category }) => ({ id, label, category })),+ listEntityTemplates: () => entitySources().map(({ id, label, category }) => ({ id, label, category })),/** Create a TilemapLayer from an .estileset with an optional grid layout* (orientation/stagger/hex) — drives the New-Tilemap flow headlessly. */createTilemap: (tilesetPath: string, grid?: TileGridConfig) => createTilemapFromTileset(tilesetPath, grid),diff --git a/desktop/src/mode/activeMode.ts b/desktop/src/mode/activeMode.tsindex 6d3d99f04..90cb0b323 100644--- a/desktop/src/mode/activeMode.ts+++ b/desktop/src/mode/activeMode.ts@@ -8,7 +8,7 @@import { SceneModel } from '@/engine/SceneModel';import { useSelection } from '@/store/selectionStore';import { useEditorMode } from '@/store/editorModeStore';-import { EDITOR_MODES, EDITOR_MODE_BY_ID, type EditorModeDef, type SelectionProbe } from './editorModes';+import { editorModes, modeById, FALLBACK_MODE, type EditorModeDef, type SelectionProbe } from './editorModes';/** The active selection's component membership, for a mode's `suggestFor`. */function probe(): SelectionProbe {@@ -20,13 +20,14 @@ function probe(): SelectionProbe {/** The mode the current selection implies (first matching in priority order, else Scene). */export function suggestedMode(): EditorModeDef {const p = probe();- return EDITOR_MODES.find((m) => m.suggestFor?.(p)) ?? EDITOR_MODE_BY_ID.scene;+ return editorModes().find((m) => m.suggestFor?.(p)) ?? FALLBACK_MODE;}-/** The effective mode: an explicit pin wins, else the selection-suggested mode. */+/** The effective mode: an explicit pin wins, else the selection-suggested mode. A pin+ * naming a mode that's gone (a plugin unloaded while pinned) falls back to derivation. */export function activeMode(): EditorModeDef {const pinned = useEditorMode.getState().pinned;- return pinned ? EDITOR_MODE_BY_ID[pinned] : suggestedMode();+ return (pinned ? modeById(pinned) : undefined) ?? suggestedMode();}/** The active mode's overlay flags, never undefined (for the viewport rAF gate). */diff --git a/desktop/src/mode/editorModes.ts b/desktop/src/mode/editorModes.tsindex 5fd069014..2902b891c 100644--- a/desktop/src/mode/editorModes.ts+++ b/desktop/src/mode/editorModes.ts@@ -10,12 +10,20 @@* viewport overlays it turns on, and a `suggestFor` predicate over the current* selection. The active mode is selection-derived (see activeMode.ts) with an* optional explicit pin (editorModeStore) — adding a mode here wires it everywhere.+ *+ * The built-in table below is this module's REGISTRATION input; reads go through+ * {@link editorModes} / {@link modeById}, so a plugin-contributed mode is seen by+ * the activity bar, the tool router, and the mode commands alike.*/import type { LucideIcon } from 'lucide-react';import { MousePointer2, LayoutPanelTop, Grid3x3 } from 'lucide-react';import { t } from '@/i18n';+import { ContributionRegistry } from '@/contrib/ContributionRegistry';-export type EditorModeId = 'scene' | 'ui' | 'tilemap';+/** The modes the editor ships. Plugin modes widen this at runtime. */+export type BuiltinEditorModeId = 'scene' | 'ui' | 'tilemap';+/** A mode id: one of the built-ins, or a plugin-contributed one. */+export type EditorModeId = BuiltinEditorModeId | (string & {});/** The current selection's component membership — all a mode's `suggestFor` needs. */export interface SelectionProbe {@@ -37,9 +45,16 @@ export interface ModePanel {export interface EditorModeDef {id: EditorModeId;+ /** Short name (activity-bar tooltip, viewport badge), e.g. 'Tilemap'. */label: string;+ /** Label for the mode's switch command / palette row, e.g. 'Tilemap Mode'.+ * Carried by the def rather than derived from the id, so a contributed mode+ * isn't forced to own an entry in the editor's compile-time message catalog. */+ commandLabel: string;icon: LucideIcon;- /** Which tool family the viewport routes pointer input to (resolveActiveTool). */+ /** Which tool family the viewport routes pointer input to (resolveActiveTool).+ * Stays a closed set until the tool registry lands — an unrouted toolset name+ * would silently fall back to transform, which is worse than a compile error. */toolset: 'transform' | 'tilemap';/** Companion panels revealed on entering the mode. */panels?: ModePanel[];@@ -52,6 +67,7 @@ export interface EditorModeDef {const tilemapMode: EditorModeDef = {id: 'tilemap',label: t('mode.tilemap'),+ commandLabel: t('cmd.mode.tilemap'),icon: Grid3x3,toolset: 'tilemap',panels: [{ id: 'tilemap', component: 'tilemap', title: t('panel.tilemap'), side: 'left', width: 300 }],@@ -61,6 +77,7 @@ const tilemapMode: EditorModeDef = {const uiMode: EditorModeDef = {id: 'ui',label: t('mode.ui'),+ commandLabel: t('cmd.mode.ui'),icon: LayoutPanelTop,toolset: 'transform',panels: [@@ -77,6 +94,7 @@ const uiMode: EditorModeDef = {const sceneMode: EditorModeDef = {id: 'scene',label: t('mode.scene'),+ commandLabel: t('cmd.mode.scene'),icon: MousePointer2,toolset: 'transform',};@@ -84,8 +102,30 @@ const sceneMode: EditorModeDef = {/** Suggestion priority: the first mode whose `suggestFor` matches wins; sceneMode is the fallback. */export const EDITOR_MODES: EditorModeDef[] = [tilemapMode, uiMode, sceneMode];-export const EDITOR_MODE_BY_ID: Record<EditorModeId, EditorModeDef> = {+export const EDITOR_MODE_BY_ID: Record<BuiltinEditorModeId, EditorModeDef> = {scene: sceneMode,ui: uiMode,tilemap: tilemapMode,};++/** The fallback mode — always present, so mode resolution never returns undefined. */+export const FALLBACK_MODE = sceneMode;++const modeContrib = new ContributionRegistry<EditorModeDef>('editor mode');+modeContrib.registerAll('core', EDITOR_MODES);++export const editorModeRegistry = modeContrib;++/**+ * Every editing mode, built-ins first in suggestion-priority order, then contributed+ * ones — so a plugin mode can never outrank a built-in suggestion. A mode without+ * `suggestFor` is simply never suggested (activeMode falls back to {@link FALLBACK_MODE}),+ * which is why sceneMode's position in the list is immaterial.+ */+export function editorModes(): readonly EditorModeDef[] {+ return modeContrib.all();+}++export function modeById(id: EditorModeId): EditorModeDef | undefined {+ return modeContrib.get(id);+}diff --git a/desktop/src/panels/Details.tsx b/desktop/src/panels/Details.tsxindex 758757936..f69696962 100644--- a/desktop/src/panels/Details.tsx+++ b/desktop/src/panels/Details.tsx@@ -71,7 +71,7 @@ import { SceneQuery, buildEntityInfo, buildInspector } from '@/engine/SceneQueryimport { SceneModel } from '@/engine/SceneModel';import { InspectorClipboard } from '@/engine/inspectorClipboard';import { SceneCommands, toModelValue } from '@/engine/SceneCommands';-import { ENTITY_SOURCES, createFromSource } from '@/engine/entitySources';+import { sourceById, createFromSource } from '@/engine/entitySources';import { PlayInspect } from '@/engine/PlayInspect';import { DimensionUnit, AnchorAxis, detectAnchorAxes, UIPositionType, FlexDirection, FlexWrap, JustifyContent, AlignItems, INTERACTION_CONTROLLER, INTERACTION_PAGES, parseLocaleTable, EasingType, BUILTIN_SHADER_TEMPLATES, INVALID_ENTITY } from 'esengine';import type { SceneData, InputMapAsset, ActionType, Binding, LocaleTableAsset, PluralCategory, GearValue, GearTween, MaterialAssetData } from 'esengine';@@ -1572,7 +1572,7 @@ const ADVANCED_FOLD = '__advanced__';async function addTextLayoutBox(sourceId: EntityId): Promise<void> {let canvas = SceneCommands.findCanvas();if (canvas == null) {- const src = ENTITY_SOURCES.find((s) => s.id === 'canvas');+ const src = sourceById('canvas');canvas = src ? await createFromSource(src, { parent: null }) : null;}if (canvas != null) SceneCommands.attachUINodeBox(sourceId, canvas, 240, 80);@@ -1602,7 +1602,7 @@ function hasCanvasAncestor(sourceId: EntityId): boolean {async function placeUnderCanvas(sourceIds: EntityId[]): Promise<void> {let canvas = SceneCommands.findCanvas();if (canvas == null) {- const src = ENTITY_SOURCES.find((s) => s.id === 'canvas');+ const src = sourceById('canvas');canvas = src ? await createFromSource(src, { parent: null }) : null;}if (canvas == null) return;diff --git a/desktop/src/panels/UIWidgetsPanel.tsx b/desktop/src/panels/UIWidgetsPanel.tsxindex ace42c1b3..0e9b0687a 100644--- a/desktop/src/panels/UIWidgetsPanel.tsx+++ b/desktop/src/panels/UIWidgetsPanel.tsx@@ -4,17 +4,20 @@* @file UIWidgetsPanel — the UI-mode widget palette. Drag an item onto the* viewport to place it, or click to add it under the Canvas.*- * Data-driven from the SAME `ENTITY_SOURCES` registry the Create popover uses —- * there is no parallel widget list, so a new UI source (builtin or user) appears- * here for free with its registry label + icon.+ * Data-driven from the SAME entity-template registry the Create popover uses —+ * there is no parallel widget list, so a new UI source (builtin, user, or+ * contributed) appears here for free with its registry label + icon.*/-import { ENTITY_SOURCES, createFromSource, SOURCE_DND_MIME, type EntitySource } from '@/engine/entitySources';+import { useSyncExternalStore } from 'react';+import { entitySources, entitySourceRegistry, createFromSource, SOURCE_DND_MIME, type EntitySource } from '@/engine/entitySources';import { t } from '@/i18n';import { useSelection } from '@/store/selectionStore';-const UI_SOURCES = ENTITY_SOURCES.filter((s) => s.category === 'UI');-export function UIWidgetsPanel() {+ // Read through the registry (not a module-load snapshot) so a contributed UI+ // template appears in the palette without a reload.+ const sources = useSyncExternalStore(entitySourceRegistry.subscribe.bind(entitySourceRegistry), entitySources);+ const uiSources = sources.filter((s) => s.category === 'UI');// A clicked widget passes no drop point, so createFromSource centres it in the Canvas// (the shared UI-placement path also handles the viewport drop's drop-point landing).const add = (s: EntitySource) => {@@ -26,7 +29,7 @@ export function UIWidgetsPanel() {<div className="ui-palette"><div className="ui-palette-hint">{t('uiw.hint')}</div><div className="ui-palette-grid">- {UI_SOURCES.map((s) => {+ {uiSources.map((s) => {const Icon = s.icon;return (<buttondiff --git a/desktop/src/settings/registry.ts b/desktop/src/settings/registry.tsindex 3cbbccf97..10401b839 100644--- a/desktop/src/settings/registry.ts+++ b/desktop/src/settings/registry.ts@@ -6,19 +6,23 @@* sections + settings; the store holds values, SettingsDialog renders from* here. Holds no reactive state — the single source of ids, defaults, and* schema. One place to add a setting; the UI follows automatically.+ *+ * Both sets live in a ContributionRegistry, so a plugin's sections + settings are+ * owned and retractable as a group (the `plugin` nav category is where they land).*/import type { Setting, SettingsSection, SettingCategory } from './types';+import { ContributionRegistry, type Disposable, type Owner } from '@/contrib/ContributionRegistry';class SettingsRegistry {- private readonly settings = new Map<string, Setting>();- private readonly sections = new Map<string, SettingsSection>();+ private readonly settings = new ContributionRegistry<Setting>('setting');+ private readonly sections = new ContributionRegistry<SettingsSection>('settings section');- registerSection(section: SettingsSection): void {- this.sections.set(section.id, section);+ registerSection(section: SettingsSection, owner: Owner = 'core'): Disposable {+ return this.sections.register(owner, section);}- register(setting: Setting): void {- this.settings.set(setting.id, setting);+ register(setting: Setting, owner: Owner = 'core'): Disposable {+ return this.settings.register(owner, setting);}get(id: string): Setting | undefined {@@ -26,7 +30,7 @@ class SettingsRegistry {}all(): Setting[] {- return [...this.settings.values()];+ return [...this.settings.all()];}getSection(id: string): SettingsSection | undefined {@@ -34,7 +38,8 @@ class SettingsRegistry {}allSections(): SettingsSection[] {- return [...this.sections.values()].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));+ // Stable sort: ties keep registration order (core before plugins).+ return [...this.sections.all()].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));}/** Sections grouped by nav category, in declared order. */@@ -52,6 +57,27 @@ class SettingsRegistry {settingsForSection(sectionId: string): Setting[] {return this.all().filter((s) => s.section === sectionId);}++ /** Retract every section + setting of one owner (plugin unload / disable). */+ disposeOwner(owner: Owner): void {+ this.settings.disposeOwner(owner);+ this.sections.disposeOwner(owner);+ }++ /** Subscribe to either set changing — the dialog re-derives its nav from it. */+ subscribe(fn: () => void): () => void {+ const offSettings = this.settings.subscribe(fn);+ const offSections = this.sections.subscribe(fn);+ return () => {+ offSettings();+ offSections();+ };+ }++ /** Snapshot of both sets' identity, for useSyncExternalStore. */+ getRevision(): number {+ return this.settings.getRevision() + this.sections.getRevision();+ }}export const settingsRegistry = new SettingsRegistry();diff --git a/desktop/tests/contribution-registry.test.ts b/desktop/tests/contribution-registry.test.tsnew file mode 100644index 000000000..aec742d28--- /dev/null+++ b/desktop/tests/contribution-registry.test.ts@@ -0,0 +1,113 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The ownership/disposal mechanism every extension point shares. The rules+ * that matter: core always outranks a plugin (order AND id conflicts), an+ * owner is retractable as a set, and a stale Disposable can never retract+ * someone else's later registration of the same id.+ */+import { describe, it, expect, vi } from 'vitest';+import { ContributionRegistry } from '@/contrib/ContributionRegistry';++interface Item {+ id: string;+ label?: string;+}++const reg = () => new ContributionRegistry<Item>('thing');+const ids = (r: ContributionRegistry<Item>) => r.all().map((i) => i.id);++describe('ContributionRegistry', () => {+ it('orders core before plugins, registration order within each', () => {+ const r = reg();+ r.register('plugin:b', { id: 'b1' });+ r.register('core', { id: 'c1' });+ r.register('plugin:a', { id: 'a1' });+ r.register('core', { id: 'c2' });+ r.register('plugin:b', { id: 'b2' });+ expect(ids(r)).toEqual(['c1', 'c2', 'b1', 'a1', 'b2']);+ });++ it('first registration wins an id conflict, and the loser is recorded', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const r = reg();+ r.register('core', { id: 'edit.undo', label: 'core' });+ const d = r.register('plugin:evil', { id: 'edit.undo', label: 'hijacked' });++ expect(r.get('edit.undo')?.label).toBe('core');+ expect(r.ownerOf('edit.undo')).toBe('core');+ expect(r.conflicts()).toEqual([{ id: 'edit.undo', heldBy: 'core', rejected: 'plugin:evil' }]);+ // The rejected registration's disposable must be inert — not a way to evict core.+ d.dispose();+ expect(r.get('edit.undo')?.label).toBe('core');+ warn.mockRestore();+ });++ it('same-owner re-registration replaces in place, keeping position', () => {+ const r = reg();+ r.register('core', { id: 'a', label: 'v1' });+ r.register('core', { id: 'b' });+ r.register('core', { id: 'a', label: 'v2' });+ expect(r.get('a')?.label).toBe('v2');+ expect(ids(r)).toEqual(['a', 'b']); // 'a' did not jump to the end+ });++ it('disposeOwner retracts the whole set and clears its conflicts', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const r = reg();+ r.register('core', { id: 'c1' });+ r.registerAll('plugin:p', [{ id: 'p1' }, { id: 'p2' }]);+ r.register('plugin:p', { id: 'c1' }); // conflict, recorded+ expect(r.conflicts()).toHaveLength(1);++ r.disposeOwner('plugin:p');+ expect(ids(r)).toEqual(['c1']);+ expect(r.byOwner('plugin:p')).toEqual([]);+ expect(r.conflicts()).toEqual([]);+ warn.mockRestore();+ });++ it('a stale disposable cannot retract a later registration of the same id', () => {+ const r = reg();+ const stale = r.register('plugin:p', { id: 'x', label: 'old' });+ r.disposeOwner('plugin:p');+ r.register('plugin:q', { id: 'x', label: 'new' });++ stale.dispose();+ expect(r.get('x')?.label).toBe('new');+ });++ it('notifies subscribers and bumps the revision on every set change', () => {+ const r = reg();+ const seen: number[] = [];+ const unsub = r.subscribe(() => seen.push(r.getRevision()));++ const d = r.register('core', { id: 'a' });+ r.registerAll('plugin:p', [{ id: 'p1' }, { id: 'p2' }]);+ d.dispose();+ r.disposeOwner('plugin:p');+ expect(seen).toEqual([1, 2, 3, 4, 5]);++ unsub();+ r.register('core', { id: 'z' });+ expect(seen).toHaveLength(5);+ });++ it('disposeOwner on an owner with nothing registered is silent', () => {+ const r = reg();+ r.register('core', { id: 'a' });+ const seen: number[] = [];+ r.subscribe(() => seen.push(r.getRevision()));+ r.disposeOwner('plugin:absent');+ expect(seen).toEqual([]);+ expect(ids(r)).toEqual(['a']);+ });++ it('byOwner reports each owner`s own contributions', () => {+ const r = reg();+ r.register('core', { id: 'c1' });+ r.registerAll('plugin:p', [{ id: 'p1' }, { id: 'p2' }]);+ expect(r.byOwner('core').map((i) => i.id)).toEqual(['c1']);+ expect(r.byOwner('plugin:p').map((i) => i.id)).toEqual(['p1', 'p2']);+ });+});diff --git a/desktop/tests/editor-mode.test.ts b/desktop/tests/editor-mode.test.tsindex cc42288c2..9b016bcec 100644--- a/desktop/tests/editor-mode.test.ts+++ b/desktop/tests/editor-mode.test.ts@@ -20,7 +20,7 @@ vi.mock('@/engine/SceneModel', () => ({},}));-import { EDITOR_MODES, EDITOR_MODE_BY_ID } from '@/mode/editorModes';+import { EDITOR_MODES, EDITOR_MODE_BY_ID, editorModes, modeById, editorModeRegistry } from '@/mode/editorModes';import { suggestedMode, activeMode } from '@/mode/activeMode';import { resolveActiveTool } from '@/tools';import { TILE_TOOLS } from '@/tools/tileTools';@@ -110,4 +110,37 @@ describe('editor-mode registry + derivation', () => {useEditorMode.getState().setMode('scene');expect(tileTools).not.toContain(resolveActiveTool());});++ it('the built-in table is exactly the core registration set', () => {+ expect(editorModes().map((m) => m.id)).toEqual(EDITOR_MODES.map((m) => m.id));+ expect(modeById('tilemap')).toBe(EDITOR_MODE_BY_ID.tilemap);+ expect(modeById('nope')).toBeUndefined();+ });++ it('a contributed mode is visible, pinnable, and retracted with its owner', () => {+ const contributed = {+ id: 'acme.paint',+ label: 'Paint',+ commandLabel: 'Paint Mode',+ icon: EDITOR_MODE_BY_ID.scene.icon,+ toolset: 'transform' as const,+ suggestFor: (s: { hasComponent(t: string): boolean }) => s.hasComponent('AcmeCanvas'),+ };+ const d = editorModeRegistry.register('plugin:acme', contributed);++ // Built-ins keep priority: a contributed mode sorts after them.+ expect(editorModes().map((m) => m.id)).toEqual([...EDITOR_MODES.map((m) => m.id), 'acme.paint']);+ expect(modeById('acme.paint')).toBe(contributed);+ withComponents('AcmeCanvas');+ expect(suggestedMode().id).toBe('acme.paint');+ useEditorMode.getState().setMode('acme.paint');+ expect(activeMode().id).toBe('acme.paint');++ // Unloading the plugin while its mode is pinned must not wedge the editor —+ // resolution falls back to derivation rather than a dangling pin.+ d.dispose();+ expect(modeById('acme.paint')).toBeUndefined();+ expect(activeMode().id).toBe('scene');+ useEditorMode.getState().clearPin();+ });});diff --git a/desktop/tests/entity-sources.test.ts b/desktop/tests/entity-sources.test.tsindex f3e470546..50da8aac5 100644--- a/desktop/tests/entity-sources.test.ts+++ b/desktop/tests/entity-sources.test.ts@@ -7,8 +7,11 @@* an icon + a known category + a well-formed build(), placement is a field* (not hardcoded), and search matches label/category/keyword. Pure TS.*/-import { describe, it, expect } from 'vitest';-import { ENTITY_SOURCES, matchSources, CREATE_CATEGORY_ORDER, tilemapPrefab, createFromSource } from '@/engine/entitySources';+import { describe, it, expect, vi } from 'vitest';+import {+ ENTITY_SOURCES, matchSources, CREATE_CATEGORY_ORDER, tilemapPrefab, createFromSource,+ entitySources, sourceById, entitySourceRegistry,+} from '@/engine/entitySources';const ctx = { parent: null };@@ -85,4 +88,31 @@ describe('entitySources registry (Create-entity E2)', () => {const bad = { ...ENTITY_SOURCES[0], id: 'bad', build: () => { throw new Error('nope'); } };expect(await createFromSource(bad, { parent: null })).toBeNull();});++ it('the built-in table is exactly the core registration set', () => {+ expect(entitySources().map((s) => s.id)).toEqual(ENTITY_SOURCES.map((s) => s.id));+ expect(sourceById('canvas')).toBe(ENTITY_SOURCES.find((s) => s.id === 'canvas'));+ expect(sourceById('nope')).toBeNull();+ });++ it('a contributed template is visible through the accessors, and retracted with its owner', () => {+ const contributed = { ...ENTITY_SOURCES[0], id: 'acme.turret', label: 'Turret', category: 'Scripts' };+ const d = entitySourceRegistry.register('plugin:acme', contributed);++ // Built-ins keep their order; the contributed one lands after them.+ expect(entitySources().map((s) => s.id)).toEqual([...ENTITY_SOURCES.map((s) => s.id), 'acme.turret']);+ expect(sourceById('acme.turret')).toBe(contributed);++ d.dispose();+ expect(sourceById('acme.turret')).toBeNull();+ expect(entitySources()).toHaveLength(ENTITY_SOURCES.length);+ });++ it('a contributed template cannot hijack a built-in id', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const builtin = sourceById('empty');+ entitySourceRegistry.register('plugin:evil', { ...ENTITY_SOURCES[0], id: 'empty', label: 'Hijacked' });+ expect(sourceById('empty')).toBe(builtin);+ warn.mockRestore();+ });});