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.

refactor: introduce DisposableStore to fix event listener leaks across panels

esenginea426dd91b40e
diff --git a/editor/src/panels/InspectorPanel.ts b/editor/src/panels/InspectorPanel.ts
index 364af2d23..2c8f581c3 100644
--- a/editor/src/panels/InspectorPanel.ts
+++ b/editor/src/panels/InspectorPanel.ts
@@ -18,6 +18,7 @@ import { type ImageUrlRef } from './inspector/ImageInspector';
import { getPlayModeService } from '../services/PlayModeService';
import { getInspectorRenderer } from '../asset/AssetTypeRegistry';
import { RuntimeStoreProxy } from '../services/RuntimeStoreProxy';
+import { DisposableStore } from '../utils/Disposable';
// =============================================================================
// InspectorPanel
@@ -25,9 +26,9 @@ import { RuntimeStoreProxy } from '../services/RuntimeStoreProxy';
export class InspectorPanel {
private container_: HTMLElement;
+ private disposables_ = new DisposableStore();
private store_: EditorStore;
private contentContainer_: HTMLElement;
- private unsubscribe_: (() => void) | null = null;
private editors_: EditorInfo[] = [];
private currentEntity_: Entity | null = null;
private currentAssetPath_: string | null = null;
@@ -42,7 +43,6 @@ export class InspectorPanel {
private materialPreviewState_: MaterialPreviewState;
private extensionSections_: InspectorSectionInstance[] = [];
private playMode_: boolean = false;
- private playModeCleanups_: (() => void)[] = [];
private runtimeEntityId_: number | null = null;
private runtimeRefreshRafId_: number = 0;
private runtimeRefreshPending_ = false;
@@ -71,37 +71,35 @@ export class InspectorPanel {
this.lockBtn_ = this.container_.querySelector('.es-lock-btn');
this.setupLockButton();
- this.unsubscribe_ = store.subscribe((_state, dirtyFlags) => this.onStoreNotify(dirtyFlags));
+ this.disposables_.add(store.subscribe((_state, dirtyFlags) => this.onStoreNotify(dirtyFlags)));
this.render();
const pms = getPlayModeService();
- this.playModeCleanups_.push(
- pms.onStateChange((state) => {
- const isPlaying = state === 'playing';
- this.playMode_ = isPlaying;
- if (isPlaying) {
- this.container_.classList.add('es-play-mode');
- hideMaterialPreview(this.materialPreviewState_);
- this.runtimeProxy_ = new RuntimeStoreProxy(this.store_);
- } else {
- this.container_.classList.remove('es-play-mode');
- this.stopRuntimeRefresh();
- this.runtimeEntityId_ = null;
- this.runtimeProxy_ = null;
- this.render();
- }
- }),
- pms.onSelectionChange((entityId) => {
- if (!this.playMode_) return;
- if (entityId !== null && entityId === this.runtimeEntityId_) return;
- this.runtimeEntityId_ = entityId;
- if (entityId !== null) {
- this.renderPlayModeEntity(entityId);
- } else {
- this.renderPlayModeEmpty();
- }
- }),
- );
+ this.disposables_.add(pms.onStateChange((state) => {
+ const isPlaying = state === 'playing';
+ this.playMode_ = isPlaying;
+ if (isPlaying) {
+ this.container_.classList.add('es-play-mode');
+ hideMaterialPreview(this.materialPreviewState_);
+ this.runtimeProxy_ = new RuntimeStoreProxy(this.store_);
+ } else {
+ this.container_.classList.remove('es-play-mode');
+ this.stopRuntimeRefresh();
+ this.runtimeEntityId_ = null;
+ this.runtimeProxy_ = null;
+ this.render();
+ }
+ }));
+ this.disposables_.add(pms.onSelectionChange((entityId) => {
+ if (!this.playMode_) return;
+ if (entityId !== null && entityId === this.runtimeEntityId_) return;
+ this.runtimeEntityId_ = entityId;
+ if (entityId !== null) {
+ this.renderPlayModeEntity(entityId);
+ } else {
+ this.renderPlayModeEmpty();
+ }
+ }));
}
private setupLockButton(): void {
@@ -126,15 +124,10 @@ export class InspectorPanel {
}
dispose(): void {
- for (const cleanup of this.playModeCleanups_) cleanup();
- this.playModeCleanups_ = [];
+ this.disposables_.dispose();
this.stopRuntimeRefresh();
this.disposeEditors();
this.cleanupImageUrl();
- if (this.unsubscribe_) {
- this.unsubscribe_();
- this.unsubscribe_ = null;
- }
}
// =========================================================================
diff --git a/editor/src/panels/OutputPanel.ts b/editor/src/panels/OutputPanel.ts
index 264bc34e0..3d405028e 100644
--- a/editor/src/panels/OutputPanel.ts
+++ b/editor/src/panels/OutputPanel.ts
@@ -1,5 +1,6 @@
import type { PanelInstance } from './PanelRegistry';
import { icons } from '../utils/icons';
+import { DisposableStore } from '../utils/Disposable';
type OutputType = 'command' | 'stdout' | 'stderr' | 'error' | 'success';
@@ -32,6 +33,7 @@ function formatTimestamp(): string {
export class OutputPanel implements PanelInstance {
private container_: HTMLElement;
+ private disposables_ = new DisposableStore();
private contentEl_: HTMLElement | null = null;
private entries_: LogEntry[] = [];
private lastEntry_: LogEntry | null = null;
@@ -153,6 +155,7 @@ export class OutputPanel implements PanelInstance {
}
dispose(): void {
+ this.disposables_.dispose();
this.container_.innerHTML = '';
}
@@ -185,35 +188,43 @@ export class OutputPanel implements PanelInstance {
btn.className = `es-output-filter-btn es-active es-output-filter-${type}`;
btn.title = `Toggle ${type}`;
btn.innerHTML = `${TYPE_LABELS[type]} <span class="es-output-filter-count">0</span>`;
- btn.addEventListener('click', () => this.toggleFilter(type));
+ this.disposables_.addListener(btn, 'click', () => this.toggleFilter(type));
filtersEl.appendChild(btn);
this.filterBtns_.set(type, btn);
}
this.scrollBtn_ = this.container_.querySelector('[data-action="toggle-scroll"]');
- this.scrollBtn_?.addEventListener('click', () => this.toggleAutoScroll());
+ if (this.scrollBtn_) {
+ this.disposables_.addListener(this.scrollBtn_, 'click', () => this.toggleAutoScroll());
+ }
this.searchInput_ = this.container_.querySelector('.es-output-search');
- this.searchInput_?.addEventListener('input', (e) => {
- this.searchText_ = (e.target as HTMLInputElement).value.toLowerCase();
- this.applyFilters();
- });
+ if (this.searchInput_) {
+ this.disposables_.addListener(this.searchInput_, 'input', (e) => {
+ this.searchText_ = ((e as Event).target as HTMLInputElement).value.toLowerCase();
+ this.applyFilters();
+ });
+ }
const clearBtn = this.container_.querySelector('[data-action="clear-output"]');
- clearBtn?.addEventListener('click', () => this.clear());
-
- this.contentEl_?.addEventListener('scroll', () => {
- if (!this.contentEl_) return;
- const { scrollTop, scrollHeight, clientHeight } = this.contentEl_;
- const atBottom = scrollHeight - scrollTop - clientHeight < 30;
- if (atBottom && !this.autoScroll_) {
- this.autoScroll_ = true;
- this.scrollBtn_?.classList.add('es-active');
- } else if (!atBottom && this.autoScroll_) {
- this.autoScroll_ = false;
- this.scrollBtn_?.classList.remove('es-active');
- }
- });
+ if (clearBtn) {
+ this.disposables_.addListener(clearBtn, 'click', () => this.clear());
+ }
+
+ if (this.contentEl_) {
+ this.disposables_.addListener(this.contentEl_, 'scroll', () => {
+ if (!this.contentEl_) return;
+ const { scrollTop, scrollHeight, clientHeight } = this.contentEl_;
+ const atBottom = scrollHeight - scrollTop - clientHeight < 30;
+ if (atBottom && !this.autoScroll_) {
+ this.autoScroll_ = true;
+ this.scrollBtn_?.classList.add('es-active');
+ } else if (!atBottom && this.autoScroll_) {
+ this.autoScroll_ = false;
+ this.scrollBtn_?.classList.remove('es-active');
+ }
+ });
+ }
}
private toggleFilter(type: OutputType): void {
diff --git a/editor/src/panels/content-browser/ContentBrowserPanel.ts b/editor/src/panels/content-browser/ContentBrowserPanel.ts
index 41b53c2ab..cf4b7598a 100644
--- a/editor/src/panels/content-browser/ContentBrowserPanel.ts
+++ b/editor/src/panels/content-browser/ContentBrowserPanel.ts
@@ -12,6 +12,7 @@ import {
deleteSelectedAssets, renameAsset,
importDroppedFiles, saveDroppedEntityAsPrefab,
} from './AssetContextMenu';
+import { DisposableStore } from '../../utils/Disposable';
export class ContentBrowserPanel implements ContentBrowserState {
container: HTMLElement;
@@ -34,7 +35,7 @@ export class ContentBrowserPanel implements ContentBrowserState {
lastSelectedPath: string | null = null;
viewMode: ViewMode;
- private unwatchFn_: (() => void) | null = null;
+ private disposables_ = new DisposableStore();
private refreshing_ = false;
private refreshPending_ = false;
private thumbnailCache_ = new ThumbnailCache();
@@ -85,10 +86,7 @@ export class ContentBrowserPanel implements ContentBrowserState {
}
dispose(): void {
- if (this.unwatchFn_) {
- this.unwatchFn_();
- this.unwatchFn_ = null;
- }
+ this.disposables_.dispose();
}
async navigateToAsset(assetPath: string): Promise<void> {
@@ -253,11 +251,12 @@ export class ContentBrowserPanel implements ContentBrowserState {
const projectDir = getParentDir(this.projectPath);
try {
- this.unwatchFn_ = await fs.watchDirectory(
+ const unwatchFn = await fs.watchDirectory(
projectDir,
() => { this.refresh(); },
{ recursive: true }
);
+ this.disposables_.add(unwatchFn);
} catch (err) {
console.error('Failed to setup file watcher:', err);
}
@@ -284,209 +283,226 @@ export class ContentBrowserPanel implements ContentBrowserState {
}
private setupEvents(): void {
- this.searchInput?.addEventListener('input', () => {
- this.searchFilter = this.searchInput?.value.toLowerCase() ?? '';
- this.renderGrid();
- });
+ if (this.searchInput) {
+ this.disposables_.addListener(this.searchInput, 'input', () => {
+ this.searchFilter = this.searchInput?.value.toLowerCase() ?? '';
+ this.renderGrid();
+ });
+ }
- this.breadcrumbContainer?.addEventListener('click', (e) => {
- const target = e.target as HTMLElement;
- const item = target.closest('.es-breadcrumb-item') as HTMLElement;
- if (!item) return;
- const path = item.dataset.path;
- if (path) {
- selectFolder(this, path);
- }
- });
+ if (this.breadcrumbContainer) {
+ this.disposables_.addListener(this.breadcrumbContainer, 'click', (e) => {
+ const target = (e as MouseEvent).target as HTMLElement;
+ const item = target.closest('.es-breadcrumb-item') as HTMLElement;
+ if (!item) return;
+ const path = item.dataset.path;
+ if (path) {
+ selectFolder(this, path);
+ }
+ });
+ }
const upBtn = this.container.querySelector('.es-cb-up-btn');
- upBtn?.addEventListener('click', () => {
- this.navigateToParent();
- });
+ if (upBtn) {
+ this.disposables_.addListener(upBtn, 'click', () => {
+ this.navigateToParent();
+ });
+ }
const viewToggle = this.container.querySelector('.es-cb-view-toggle');
- viewToggle?.addEventListener('click', () => {
- this.viewMode = this.viewMode === 'grid' ? 'list' : 'grid';
- localStorage.setItem(VIEW_MODE_KEY, this.viewMode);
- this.updateViewToggleButton();
- this.renderGrid();
- });
-
- this.treeContainer?.addEventListener('click', async (e) => {
- const target = e.target as HTMLElement;
- const item = target.closest('.es-folder-item') as HTMLElement;
- if (!item) return;
- const path = item.dataset.path;
- if (!path) return;
-
- if (target.closest('.es-folder-expand')) {
- await toggleFolder(this, path);
- } else {
- selectFolder(this, path);
- }
- });
-
- this.gridContainer?.addEventListener('click', (e) => {
- const target = e.target as HTMLElement;
- const item = (target.closest('.es-asset-item') || target.closest('.es-cb-list-row')) as HTMLElement;
-
- if (!item) {
- this.selectedPaths.clear();
- this.lastSelectedPath = null;
- this.updateAssetSelection();
- return;
- }
+ if (viewToggle) {
+ this.disposables_.addListener(viewToggle, 'click', () => {
+ this.viewMode = this.viewMode === 'grid' ? 'list' : 'grid';
+ localStorage.setItem(VIEW_MODE_KEY, this.viewMode);
+ this.updateViewToggleButton();
+ this.renderGrid();
+ });
+ }
- const path = item.dataset.path;
- if (!path) return;
+ if (this.treeContainer) {
+ this.disposables_.addListener(this.treeContainer, 'click', async (e) => {
+ const target = (e as MouseEvent).target as HTMLElement;
+ const item = target.closest('.es-folder-item') as HTMLElement;
+ if (!item) return;
+ const path = item.dataset.path;
+ if (!path) return;
- if (e.shiftKey && this.lastSelectedPath) {
- this.rangeSelect(this.lastSelectedPath, path);
- } else if (e.ctrlKey || e.metaKey) {
- if (this.selectedPaths.has(path)) {
- this.selectedPaths.delete(path);
+ if (target.closest('.es-folder-expand')) {
+ await toggleFolder(this, path);
} else {
- this.selectedPaths.add(path);
+ selectFolder(this, path);
}
- this.lastSelectedPath = path;
- } else {
- this.selectedPaths.clear();
- this.selectedPaths.add(path);
- this.lastSelectedPath = path;
- }
+ });
- this.updateAssetSelection();
- this.notifyStoreSelection();
- });
-
- this.gridContainer?.addEventListener('dblclick', async (e) => {
- const target = e.target as HTMLElement;
- const item = (target.closest('.es-asset-item') || target.closest('.es-cb-list-row')) as HTMLElement;
- if (!item) return;
-
- const path = item.dataset.path;
- const type = item.dataset.type;
-
- if (type === 'folder' && path) {
- selectFolder(this, path);
- await expandFolder(this, path);
- } else if (path) {
- this.onAssetDoubleClick(path, type as AssetItem['type']);
- }
- });
+ this.disposables_.addListener(this.treeContainer, 'contextmenu', (e) => {
+ (e as MouseEvent).preventDefault();
+ const target = (e as MouseEvent).target as HTMLElement;
+ const item = target.closest('.es-folder-item') as HTMLElement;
+ const path = item?.dataset.path ?? this.currentPath;
+ if (path) {
+ showFolderContextMenu(this, e as MouseEvent, path);
+ }
+ });
+ }
- const refreshBtn = this.container.querySelector('.es-refresh-btn');
- refreshBtn?.addEventListener('click', () => {
- this.refresh();
- });
+ if (this.gridContainer) {
+ this.disposables_.addListener(this.gridContainer, 'click', (e) => {
+ const target = (e as MouseEvent).target as HTMLElement;
+ const item = (target.closest('.es-asset-item') || target.closest('.es-cb-list-row')) as HTMLElement;
- this.gridContainer?.addEventListener('contextmenu', (e) => {
- e.preventDefault();
- const target = e.target as HTMLElement;
- const item = (target.closest('.es-asset-item') || target.closest('.es-cb-list-row')) as HTMLElement;
+ if (!item) {
+ this.selectedPaths.clear();
+ this.lastSelectedPath = null;
+ this.updateAssetSelection();
+ return;
+ }
- if (item) {
const path = item.dataset.path;
- const type = item.dataset.type;
- if (path) {
- if (!this.selectedPaths.has(path)) {
- this.selectedPaths.clear();
- this.selectedPaths.add(path);
- this.lastSelectedPath = path;
- this.updateAssetSelection();
- }
-
- if (this.selectedPaths.size > 1) {
- showMultiSelectContextMenu(this, e);
+ if (!path) return;
+
+ const me = e as MouseEvent;
+ if (me.shiftKey && this.lastSelectedPath) {
+ this.rangeSelect(this.lastSelectedPath, path);
+ } else if (me.ctrlKey || me.metaKey) {
+ if (this.selectedPaths.has(path)) {
+ this.selectedPaths.delete(path);
} else {
- showAssetContextMenu(this, e, path, type as AssetItem['type']);
+ this.selectedPaths.add(path);
}
+ this.lastSelectedPath = path;
+ } else {
+ this.selectedPaths.clear();
+ this.selectedPaths.add(path);
+ this.lastSelectedPath = path;
}
- } else {
- showFolderContextMenu(this, e, this.currentPath);
- }
- });
-
- this.treeContainer?.addEventListener('contextmenu', (e) => {
- e.preventDefault();
- const target = e.target as HTMLElement;
- const item = target.closest('.es-folder-item') as HTMLElement;
- const path = item?.dataset.path ?? this.currentPath;
- if (path) {
- showFolderContextMenu(this, e, path);
- }
- });
- this.gridContainer?.addEventListener('dragstart', (e) => {
- const target = e.target as HTMLElement;
- const item = (target.closest('.es-asset-item') || target.closest('.es-cb-list-row')) as HTMLElement;
- if (!item) return;
+ this.updateAssetSelection();
+ this.notifyStoreSelection();
+ });
- const path = item.dataset.path;
- const type = item.dataset.type;
- if (!path || !type) return;
+ this.disposables_.addListener(this.gridContainer, 'dblclick', async (e) => {
+ const target = (e as MouseEvent).target as HTMLElement;
+ const item = (target.closest('.es-asset-item') || target.closest('.es-cb-list-row')) as HTMLElement;
+ if (!item) return;
- if (!this.selectedPaths.has(path)) {
- this.selectedPaths.clear();
- this.selectedPaths.add(path);
- this.lastSelectedPath = path;
- this.updateAssetSelection();
- }
+ const path = item.dataset.path;
+ const type = item.dataset.type;
- const dragItems = this.filteredItems.filter(i => this.selectedPaths.has(i.path));
- const payload = dragItems.map(i => ({ type: i.type, path: i.path, name: i.name }));
+ if (type === 'folder' && path) {
+ selectFolder(this, path);
+ await expandFolder(this, path);
+ } else if (path) {
+ this.onAssetDoubleClick(path, type as AssetItem['type']);
+ }
+ });
- e.dataTransfer?.setData('application/esengine-asset', JSON.stringify(
- payload.length === 1 ? payload[0] : payload
- ));
- e.dataTransfer!.effectAllowed = 'copy';
+ this.disposables_.addListener(this.gridContainer, 'contextmenu', (e) => {
+ (e as MouseEvent).preventDefault();
+ const target = (e as MouseEvent).target as HTMLElement;
+ const item = (target.closest('.es-asset-item') || target.closest('.es-cb-list-row')) as HTMLElement;
- item.classList.add('es-dragging');
- });
+ if (item) {
+ const path = item.dataset.path;
+ const type = item.dataset.type;
+ if (path) {
+ if (!this.selectedPaths.has(path)) {
+ this.selectedPaths.clear();
+ this.selectedPaths.add(path);
+ this.lastSelectedPath = path;
+ this.updateAssetSelection();
+ }
+
+ if (this.selectedPaths.size > 1) {
+ showMultiSelectContextMenu(this, e as MouseEvent);
+ } else {
+ showAssetContextMenu(this, e as MouseEvent, path, type as AssetItem['type']);
+ }
+ }
+ } else {
+ showFolderContextMenu(this, e as MouseEvent, this.currentPath);
+ }
+ });
- this.gridContainer?.addEventListener('dragend', (e) => {
- const target = e.target as HTMLElement;
- const item = (target.closest('.es-asset-item') || target.closest('.es-cb-list-row')) as HTMLElement;
- item?.classList.remove('es-dragging');
- });
+ this.disposables_.addListener(this.gridContainer, 'dragstart', (e) => {
+ const target = (e as DragEvent).target as HTMLElement;
+ const item = (target.closest('.es-asset-item') || target.closest('.es-cb-list-row')) as HTMLElement;
+ if (!item) return;
- this.gridContainer?.addEventListener('dragover', (e) => {
- const types = e.dataTransfer?.types ?? [];
- const typesArr = Array.from(types);
- if (!typesArr.includes('application/esengine-entity') && !typesArr.includes('Files')) return;
- e.preventDefault();
- e.dataTransfer!.dropEffect = 'copy';
- this.gridContainer?.classList.add('es-drag-over');
- });
+ const path = item.dataset.path;
+ const type = item.dataset.type;
+ if (!path || !type) return;
- this.gridContainer?.addEventListener('dragleave', (e) => {
- const related = e.relatedTarget as HTMLElement;
- if (this.gridContainer?.contains(related)) return;
- this.gridContainer?.classList.remove('es-drag-over');
- });
+ if (!this.selectedPaths.has(path)) {
+ this.selectedPaths.clear();
+ this.selectedPaths.add(path);
+ this.lastSelectedPath = path;
+ this.updateAssetSelection();
+ }
- this.gridContainer?.addEventListener('drop', (e) => {
- this.gridContainer?.classList.remove('es-drag-over');
+ const dragItems = this.filteredItems.filter(i => this.selectedPaths.has(i.path));
+ const payload = dragItems.map(i => ({ type: i.type, path: i.path, name: i.name }));
+
+ (e as DragEvent).dataTransfer?.setData('application/esengine-asset', JSON.stringify(
+ payload.length === 1 ? payload[0] : payload
+ ));
+ (e as DragEvent).dataTransfer!.effectAllowed = 'copy';
+
+ item.classList.add('es-dragging');
+ });
+
+ this.disposables_.addListener(this.gridContainer, 'dragend', (e) => {
+ const target = (e as DragEvent).target as HTMLElement;
+ const item = (target.closest('.es-asset-item') || target.closest('.es-cb-list-row')) as HTMLElement;
+ item?.classList.remove('es-dragging');
+ });
+
+ this.disposables_.addListener(this.gridContainer, 'dragover', (e) => {
+ const de = e as DragEvent;
+ const types = de.dataTransfer?.types ?? [];
+ const typesArr = Array.from(types);
+ if (!typesArr.includes('application/esengine-entity') && !typesArr.includes('Files')) return;
+ de.preventDefault();
+ de.dataTransfer!.dropEffect = 'copy';
+ this.gridContainer?.classList.add('es-drag-over');
+ });
+
+ this.disposables_.addListener(this.gridContainer, 'dragleave', (e) => {
+ const related = (e as MouseEvent).relatedTarget as HTMLElement;
+ if (this.gridContainer?.contains(related)) return;
+ this.gridContainer?.classList.remove('es-drag-over');
+ });
+
+ this.disposables_.addListener(this.gridContainer, 'drop', (e) => {
+ const de = e as DragEvent;
+ this.gridContainer?.classList.remove('es-drag-over');
+
+ if (de.dataTransfer?.files && de.dataTransfer.files.length > 0) {
+ de.preventDefault();
+ importDroppedFiles(this, de.dataTransfer.files);
+ return;
+ }
- if (e.dataTransfer?.files && e.dataTransfer.files.length > 0) {
- e.preventDefault();
- importDroppedFiles(this, e.dataTransfer.files);
- return;
- }
+ const entityIdStr = de.dataTransfer?.getData('application/esengine-entity');
+ if (!entityIdStr) return;
- const entityIdStr = e.dataTransfer?.getData('application/esengine-entity');
- if (!entityIdStr) return;
+ de.preventDefault();
+ const entityId = parseInt(entityIdStr, 10);
+ if (isNaN(entityId)) return;
- e.preventDefault();
- const entityId = parseInt(entityIdStr, 10);
- if (isNaN(entityId)) return;
+ saveDroppedEntityAsPrefab(this, entityId);
+ });
- saveDroppedEntityAsPrefab(this, entityId);
- });
+ this.disposables_.addListener(this.gridContainer, 'keydown', (e) => {
+ this.handleKeyboardNavigation(e as KeyboardEvent);
+ });
+ }
- this.gridContainer?.addEventListener('keydown', (e) => {
- this.handleKeyboardNavigation(e);
- });
+ const refreshBtn = this.container.querySelector('.es-refresh-btn');
+ if (refreshBtn) {
+ this.disposables_.addListener(refreshBtn, 'click', () => {
+ this.refresh();
+ });
+ }
}
private navigateToParent(): void {
diff --git a/editor/src/panels/game-view/GameViewPanel.ts b/editor/src/panels/game-view/GameViewPanel.ts
index 64de64af1..4f386b34a 100644
--- a/editor/src/panels/game-view/GameViewPanel.ts
+++ b/editor/src/panels/game-view/GameViewPanel.ts
@@ -6,6 +6,7 @@ import { GameViewRenderer } from '../../renderer/GameViewRenderer';
import { getSharedRenderContext } from '../../renderer/SharedRenderContext';
import { getPlayModeService } from '../../services/PlayModeService';
import { Audio } from 'esengine';
+import { DisposableStore } from '../../utils/Disposable';
export interface GameViewPanelOptions {
projectPath?: string;
@@ -13,6 +14,7 @@ export interface GameViewPanelOptions {
export class GameViewPanel implements PanelInstance {
private container_: HTMLElement;
+ private disposables_ = new DisposableStore();
private toolbar_: GameViewToolbar;
private gameManager_: GameInstanceManager;
private canvasArea_: HTMLElement | null = null;
@@ -20,7 +22,6 @@ export class GameViewPanel implements PanelInstance {
private canvas2d_: HTMLCanvasElement | null = null;
private gameRenderer_: GameViewRenderer | null = null;
private inputCleanup_: (() => void) | null = null;
- private resizeObserver_: ResizeObserver | null = null;
private scale_ = 1;
constructor(container: HTMLElement, _store: EditorStore, _options?: GameViewPanelOptions) {
@@ -57,14 +58,8 @@ export class GameViewPanel implements PanelInstance {
}
dispose(): void {
- if (this.resizeObserver_) {
- this.resizeObserver_.disconnect();
- this.resizeObserver_ = null;
- }
this.cleanupInput();
- this.detachRenderer();
- this.gameManager_.dispose();
- this.toolbar_.dispose();
+ this.disposables_.dispose();
}
private buildUI(): void {
@@ -92,10 +87,15 @@ export class GameViewPanel implements PanelInstance {
this.toolbar_.setup();
if (this.canvasArea_) {
- this.resizeObserver_ = new ResizeObserver(() => this.updateCanvasSize());
- this.resizeObserver_.observe(this.canvasArea_);
+ const resizeObserver = new ResizeObserver(() => this.updateCanvasSize());
+ resizeObserver.observe(this.canvasArea_);
+ this.disposables_.add(() => resizeObserver.disconnect());
}
+ this.disposables_.add(this.gameManager_);
+ this.disposables_.add(this.toolbar_);
+ this.disposables_.add(() => this.detachRenderer());
+
this.updateCanvasSize();
}
diff --git a/editor/src/panels/hierarchy/HierarchyPanel.ts b/editor/src/panels/hierarchy/HierarchyPanel.ts
index c21eb58b9..11d000791 100644
--- a/editor/src/panels/hierarchy/HierarchyPanel.ts
+++ b/editor/src/panels/hierarchy/HierarchyPanel.ts
@@ -13,15 +13,16 @@ import { setupDragAndDrop } from './HierarchyDragDrop';
import { showEntityContextMenu, duplicateEntity, createEntityFromAsset } from './HierarchyContextMenu';
import { showContextMenu, type ContextMenuItem } from '../../ui/ContextMenu';
import { getPlayModeService, runtimeToEntityData } from '../../services/PlayModeService';
+import { DisposableStore } from '../../utils/Disposable';
export class HierarchyPanel implements HierarchyState {
private container_: HTMLElement;
+ private disposables_ = new DisposableStore();
store: EditorStore;
treeContainer: HTMLElement;
searchInput: HTMLInputElement | null = null;
private footerContainer_: HTMLElement | null = null;
private prefabEditBar_: HTMLElement | null = null;
- private unsubscribe_: (() => void) | null = null;
searchFilter: string = '';
searchResults: HierarchyState['searchResults'] = [];
selectedResultIndex: number = -1;
@@ -36,13 +37,11 @@ export class HierarchyPanel implements HierarchyState {
dragOverEntityId: number | null = null;
dropPosition: HierarchyState['dropPosition'] = null;
draggingEntityId: number | null = null;
- private boundOnScroll_: (() => void) | null = null;
renamingEntityId: number | null = null;
lastClickEntityId: number | null = null;
lastClickTime: number = 0;
playMode: boolean = false;
runtimeEntities?: HierarchyState['runtimeEntities'];
- private playModeCleanups_: (() => void)[] = [];
private toolbar_: HTMLElement | null = null;
private savedExpandedIds_: Set<number> | null = null;
@@ -81,52 +80,51 @@ export class HierarchyPanel implements HierarchyState {
this.visibleWindow.className = 'es-hierarchy-visible-window';
this.scrollContent.appendChild(this.visibleWindow);
this.treeContainer.appendChild(this.scrollContent);
- this.boundOnScroll_ = () => this.onScroll();
- this.treeContainer.addEventListener('scroll', this.boundOnScroll_);
+ this.disposables_.addListener(this.treeContainer, 'scroll', () => this.onScroll());
this.searchInput = this.container_.querySelector('.es-hierarchy-search');
this.footerContainer_ = this.container_.querySelector('.es-hierarchy-footer');
this.prefabEditBar_ = this.container_.querySelector('.es-prefab-edit-bar');
const backBtn = this.container_.querySelector('.es-prefab-back-btn');
- backBtn?.addEventListener('click', () => {
- this.store.exitPrefabEditMode();
- });
+ if (backBtn) {
+ this.disposables_.addListener(backBtn, 'click', () => {
+ this.store.exitPrefabEditMode();
+ });
+ }
this.toolbar_ = this.container_.querySelector('.es-hierarchy-toolbar');
this.setupEvents();
- this.unsubscribe_ = store.subscribe((_state, dirtyFlags) => this.onStoreNotify(dirtyFlags));
+ this.disposables_.add(store.subscribe((_state, dirtyFlags) => this.onStoreNotify(dirtyFlags)));
this.render();
const pms = getPlayModeService();
- this.playModeCleanups_.push(
- pms.onStateChange((state) => {
- const isPlaying = state === 'playing';
- this.playMode = isPlaying;
- if (isPlaying) {
- this.container_.classList.add('es-play-mode');
- this.savedExpandedIds_ = new Set(this.expandedIds);
- this.updateRuntimeEntities();
- } else {
- this.container_.classList.remove('es-play-mode');
- this.runtimeEntities = undefined;
- if (this.savedExpandedIds_) {
- this.expandedIds = this.savedExpandedIds_;
- this.savedExpandedIds_ = null;
- }
+ this.disposables_.add(pms.onStateChange((state) => {
+ const isPlaying = state === 'playing';
+ this.playMode = isPlaying;
+ if (isPlaying) {
+ this.container_.classList.add('es-play-mode');
+ this.savedExpandedIds_ = new Set(this.expandedIds);
+ this.updateRuntimeEntities();
+ } else {
+ this.container_.classList.remove('es-play-mode');
+ this.runtimeEntities = undefined;
+ if (this.savedExpandedIds_) {
+ this.expandedIds = this.savedExpandedIds_;
+ this.savedExpandedIds_ = null;
}
+ }
+ this.render();
+ }));
+ this.disposables_.add(pms.onEntityListUpdate(() => {
+ if (this.playMode) {
+ this.updateRuntimeEntities();
this.render();
- }),
- pms.onEntityListUpdate(() => {
- if (this.playMode) {
- this.updateRuntimeEntities();
- this.render();
- }
- }),
- pms.onSelectionChange(() => {
- if (this.playMode) this.renderVisibleRows();
- }),
- );
+ }
+ }));
+ this.disposables_.add(pms.onSelectionChange(() => {
+ if (this.playMode) this.renderVisibleRows();
+ }));
}
private updateRuntimeEntities(): void {
@@ -150,20 +148,11 @@ export class HierarchyPanel implements HierarchyState {
}
dispose(): void {
- for (const cleanup of this.playModeCleanups_) cleanup();
- this.playModeCleanups_ = [];
- if (this.unsubscribe_) {
- this.unsubscribe_();
- this.unsubscribe_ = null;
- }
+ this.disposables_.dispose();
if (this.scrollRafId_) {
cancelAnimationFrame(this.scrollRafId_);
this.scrollRafId_ = 0;
}
- if (this.boundOnScroll_) {
- this.treeContainer.removeEventListener('scroll', this.boundOnScroll_);
- this.boundOnScroll_ = null;
- }
}
private onStoreNotify(dirtyFlags?: ReadonlySet<DirtyFlag>): void {
@@ -202,64 +191,76 @@ export class HierarchyPanel implements HierarchyState {
private setupEvents(): void {
const addBtn = this.container_.querySelector('[data-action="add"]');
- addBtn?.addEventListener('click', () => {
- if (this.playMode) {
- const pms = getPlayModeService();
- pms.spawnEntity();
- return;
- }
- const entity = this.store.createEntity();
- this.store.addComponent(entity, 'Transform', getInitialComponentData('Transform'));
- });
+ if (addBtn) {
+ this.disposables_.addListener(addBtn, 'click', () => {
+ if (this.playMode) {
+ const pms = getPlayModeService();
+ pms.spawnEntity();
+ return;
+ }
+ const entity = this.store.createEntity();
+ this.store.addComponent(entity, 'Transform', getInitialComponentData('Transform'));
+ });
+ }
const dupBtn = this.container_.querySelector('[data-action="duplicate"]');
- dupBtn?.addEventListener('click', () => {
- if (this.playMode) return;
- const selected = this.store.selectedEntity;
- if (selected !== null) {
- duplicateEntity(this, selected);
- }
- });
+ if (dupBtn) {
+ this.disposables_.addListener(dupBtn, 'click', () => {
+ if (this.playMode) return;
+ const selected = this.store.selectedEntity;
+ if (selected !== null) {
+ duplicateEntity(this, selected);
+ }
+ });
+ }
const collapseAllBtn = this.container_.querySelector('[data-action="collapse-all"]');
- collapseAllBtn?.addEventListener('click', () => {
- this.expandedIds.clear();
- this.render();
- });
+ if (collapseAllBtn) {
+ this.disposables_.addListener(collapseAllBtn, 'click', () => {
+ this.expandedIds.clear();
+ this.render();
+ });
+ }
const expandAllBtn = this.container_.querySelector('[data-action="expand-all"]');
- expandAllBtn?.addEventListener('click', () => {
- const entities = this.runtimeEntities ?? this.store.scene.entities;
- for (const entity of entities) {
- if (entity.children.length > 0) {
- this.expandedIds.add(entity.id);
+ if (expandAllBtn) {
+ this.disposables_.addListener(expandAllBtn, 'click', () => {
+ const entities = this.runtimeEntities ?? this.store.scene.entities;
+ for (const entity of entities) {
+ if (entity.children.length > 0) {
+ this.expandedIds.add(entity.id);
+ }
}
- }
- this.render();
- });
-
- this.searchInput?.addEventListener('input', () => {
- this.searchFilter = this.searchInput?.value ?? '';
- performSearch(this);
- this.render();
- });
+ this.render();
+ });
+ }
- this.searchInput?.addEventListener('keydown', (e) => {
- if (e.key === 'ArrowDown') {
- e.preventDefault();
- selectNextResult(this);
- } else if (e.key === 'ArrowUp') {
- e.preventDefault();
- selectPreviousResult(this);
- } else if (e.key === 'Enter') {
- e.preventDefault();
- focusSelectedResult(this);
- } else if (e.key === 'Escape') {
- clearSearch(this);
- }
- });
+ if (this.searchInput) {
+ this.disposables_.addListener(this.searchInput, 'input', () => {
+ this.searchFilter = this.searchInput?.value ?? '';
+ performSearch(this);
+ this.render();
+ });
+
+ this.disposables_.addListener(this.searchInput, 'keydown', (e) => {
+ const ke = e as KeyboardEvent;
+ if (ke.key === 'ArrowDown') {
+ ke.preventDefault();
+ selectNextResult(this);
+ } else if (ke.key === 'ArrowUp') {
+ ke.preventDefault();
+ selectPreviousResult(this);
+ } else if (ke.key === 'Enter') {
+ ke.preventDefault();
+ focusSelectedResult(this);
+ } else if (ke.key === 'Escape') {
+ clearSearch(this);
+ }
+ });
+ }
- this.treeContainer.addEventListener('click', (e) => {
+ this.disposables_.addListener(this.treeContainer, 'click', (ev) => {
+ const e = ev as MouseEvent;
const target = e.target as HTMLElement;
if (target.closest('.es-hierarchy-rename-input')) return;
@@ -338,8 +339,9 @@ export class HierarchyPanel implements HierarchyState {
this.lastClickTime = now;
});
- this.treeContainer.addEventListener('dblclick', (e) => {
+ this.disposables_.addListener(this.treeContainer, 'dblclick', (ev) => {
if (this.playMode) return;
+ const e = ev as MouseEvent;
const target = e.target as HTMLElement;
if (target.closest('.es-hierarchy-rename-input')) return;
const item = target.closest('.es-hierarchy-item') as HTMLElement;
@@ -353,7 +355,8 @@ export class HierarchyPanel implements HierarchyState {
}
});
- this.treeContainer.addEventListener('contextmenu', (e) => {
+ this.disposables_.addListener(this.treeContainer, 'contextmenu', (ev) => {
+ const e = ev as MouseEvent;
if (this.playMode) {
e.preventDefault();
const target = e.target as HTMLElement;
diff --git a/editor/src/panels/scene-view/SceneViewInput.ts b/editor/src/panels/scene-view/SceneViewInput.ts
index ddf3b4dc0..6bdf7fff3 100644
--- a/editor/src/panels/scene-view/SceneViewInput.ts
+++ b/editor/src/panels/scene-view/SceneViewInput.ts
@@ -8,6 +8,7 @@ import { getEditorInstance } from '../../context/EditorContext';
import type { CameraController } from './CameraController';
import type { GizmoToolbar } from './GizmoToolbar';
import type { MarqueeSelection, BoundsProvider } from './MarqueeSelection';
+import { DisposableStore } from '../../utils/Disposable';
export interface InputDeps {
store: EditorStore;
@@ -26,6 +27,7 @@ export interface InputDeps {
export class SceneViewInput {
private deps_: InputDeps;
+ private disposables_ = new DisposableStore();
private skipNextClick_ = false;
private mouseDownX_ = 0;
@@ -34,18 +36,6 @@ export class SceneViewInput {
private boundOnDocumentMouseMove_: ((e: MouseEvent) => void) | null = null;
private boundOnDocumentMouseUp_: ((e: MouseEvent) => void) | null = null;
- private boundOnMouseDown_: ((e: MouseEvent) => void) | null = null;
- private boundOnMouseMove_: ((e: MouseEvent) => void) | null = null;
- private boundOnMouseUp_: ((e: MouseEvent) => void) | null = null;
- private boundOnMouseLeave_: ((e: MouseEvent) => void) | null = null;
- private boundOnWheel_: ((e: WheelEvent) => void) | null = null;
- private boundOnCanvasClick_: ((e: MouseEvent) => void) | null = null;
- private boundOnDblClick_: ((e: MouseEvent) => void) | null = null;
- private boundOnContextMenu_: ((e: MouseEvent) => void) | null = null;
-
- private keydownHandler_: ((e: KeyboardEvent) => void) | null = null;
- private keyupHandler_: ((e: KeyboardEvent) => void) | null = null;
-
constructor(deps: InputDeps) {
this.deps_ = deps;
}
@@ -67,7 +57,8 @@ export class SceneViewInput {
private setupKeyboard(): void {
const { camera, toolbar, store } = this.deps_;
- this.keydownHandler_ = (e: KeyboardEvent) => {
+ this.disposables_.addListener(document, 'keydown', (ev) => {
+ const e = ev as KeyboardEvent;
if (e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement) {
return;
}
@@ -126,10 +117,10 @@ export class SceneViewInput {
if (e.key === 'Control' || e.key === 'Meta') {
toolbar.updateSnapIndicator(true);
}
- };
- document.addEventListener('keydown', this.keydownHandler_);
+ });
- this.keyupHandler_ = (e: KeyboardEvent) => {
+ this.disposables_.addListener(document, 'keyup', (ev) => {
+ const e = ev as KeyboardEvent;
if (e.key === ' ') {
camera.spaceDown = false;
if (!camera.isDragging) {
@@ -139,33 +130,23 @@ export class SceneViewInput {
if (e.key === 'Control' || e.key === 'Meta') {
toolbar.updateSnapIndicator(false);
}
- };
- document.addEventListener('keyup', this.keyupHandler_);
+ });
}
private setupMouse(): void {
const { canvas } = this.deps_;
- this.boundOnMouseDown_ = this.onMouseDown.bind(this);
- this.boundOnMouseMove_ = this.onMouseMove.bind(this);
- this.boundOnMouseUp_ = this.onMouseUp.bind(this);
- this.boundOnMouseLeave_ = this.onMouseLeave.bind(this);
- this.boundOnWheel_ = (e: WheelEvent) => {
- this.deps_.camera.wheel(e);
+ this.disposables_.addListener(canvas, 'mousedown', (e) => this.onMouseDown(e as MouseEvent));
+ this.disposables_.addListener(canvas, 'mousemove', (e) => this.onMouseMove(e as MouseEvent));
+ this.disposables_.addListener(canvas, 'mouseup', (e) => this.onMouseUp(e as MouseEvent));
+ this.disposables_.addListener(canvas, 'mouseleave', (e) => this.onMouseLeave(e as MouseEvent));
+ this.disposables_.addListener(canvas, 'wheel', (e) => {
+ this.deps_.camera.wheel(e as WheelEvent);
this.deps_.toolbar.updateZoomDisplay(this.deps_.camera.zoom);
- };
- this.boundOnCanvasClick_ = this.onCanvasClick.bind(this);
- this.boundOnDblClick_ = this.onDblClick.bind(this);
- this.boundOnContextMenu_ = this.onContextMenu.bind(this);
-
- canvas.addEventListener('mousedown', this.boundOnMouseDown_);
- canvas.addEventListener('mousemove', this.boundOnMouseMove_);
- canvas.addEventListener('mouseup', this.boundOnMouseUp_);
- canvas.addEventListener('mouseleave', this.boundOnMouseLeave_);
- canvas.addEventListener('wheel', this.boundOnWheel_);
- canvas.addEventListener('click', this.boundOnCanvasClick_);
- canvas.addEventListener('dblclick', this.boundOnDblClick_);
- canvas.addEventListener('contextmenu', this.boundOnContextMenu_);
+ });
+ this.disposables_.addListener(canvas, 'click', (e) => this.onCanvasClick(e as MouseEvent));
+ this.disposables_.addListener(canvas, 'dblclick', (e) => this.onDblClick(e as MouseEvent));
+ this.disposables_.addListener(canvas, 'contextmenu', (e) => this.onContextMenu(e as MouseEvent));
}
private onMouseDown(e: MouseEvent): void {
@@ -455,50 +436,7 @@ export class SceneViewInput {
}
dispose(): void {
- const { canvas } = this.deps_;
-
- if (this.keydownHandler_) {
- document.removeEventListener('keydown', this.keydownHandler_);
- this.keydownHandler_ = null;
- }
- if (this.keyupHandler_) {
- document.removeEventListener('keyup', this.keyupHandler_);
- this.keyupHandler_ = null;
- }
-
this.stopDocumentDrag();
-
- if (this.boundOnMouseDown_) {
- canvas.removeEventListener('mousedown', this.boundOnMouseDown_);
- this.boundOnMouseDown_ = null;
- }
- if (this.boundOnMouseMove_) {
- canvas.removeEventListener('mousemove', this.boundOnMouseMove_);
- this.boundOnMouseMove_ = null;
- }
- if (this.boundOnMouseUp_) {
- canvas.removeEventListener('mouseup', this.boundOnMouseUp_);
- this.boundOnMouseUp_ = null;
- }
- if (this.boundOnMouseLeave_) {
- canvas.removeEventListener('mouseleave', this.boundOnMouseLeave_);
- this.boundOnMouseLeave_ = null;
- }
- if (this.boundOnWheel_) {
- canvas.removeEventListener('wheel', this.boundOnWheel_);
- this.boundOnWheel_ = null;
- }
- if (this.boundOnCanvasClick_) {
- canvas.removeEventListener('click', this.boundOnCanvasClick_);
- this.boundOnCanvasClick_ = null;
- }
- if (this.boundOnDblClick_) {
- canvas.removeEventListener('dblclick', this.boundOnDblClick_);
- this.boundOnDblClick_ = null;
- }
- if (this.boundOnContextMenu_) {
- canvas.removeEventListener('contextmenu', this.boundOnContextMenu_);
- this.boundOnContextMenu_ = null;
- }
+ this.disposables_.dispose();
}
}
diff --git a/editor/src/panels/scene-view/SceneViewPanel.ts b/editor/src/panels/scene-view/SceneViewPanel.ts
index 5b6712a61..70f19c564 100644
--- a/editor/src/panels/scene-view/SceneViewPanel.ts
+++ b/editor/src/panels/scene-view/SceneViewPanel.ts
@@ -22,6 +22,7 @@ import { MarqueeSelection } from './MarqueeSelection';
import { EntityDropHandler } from './EntityDropHandler';
import { SceneViewInput } from './SceneViewInput';
import { TilemapOverlay } from '../../gizmos/TilemapOverlay';
+import { DisposableStore } from '../../utils/Disposable';
const CAMERA_COLORS = [
'#ffaa00',
@@ -37,6 +38,7 @@ export interface SceneViewPanelOptions {
export class SceneViewPanel {
private container_: HTMLElement;
+ private disposables_ = new DisposableStore();
private store_: EditorStore;
private bridge_: EditorBridge | null = null;
private canvas_: HTMLCanvasElement;
@@ -44,15 +46,10 @@ export class SceneViewPanel {
private overlayCanvas_: HTMLCanvasElement | null = null;
private sceneViewportW_ = 0;
private sceneViewportH_ = 0;
- private unsubscribe_: (() => void) | null = null;
- private unsubscribeSceneSync_: (() => void) | null = null;
- private unsubscribeFocus_: (() => void) | null = null;
- private unsubscribeLivePreview_: (() => void) | null = null;
private animationId_: number | null = null;
private continuousRender_ = false;
private livePreview_ = false;
private isDirty_ = true;
- private resizeObserver_: ResizeObserver | null = null;
private projectPath_: string | null = null;
private app_: App | null = null;
@@ -147,24 +144,30 @@ export class SceneViewPanel {
(cx, cy) => this.camera_.screenToWorld(cx, cy),
);
- this.unsubscribe_ = store.subscribe(() => this.onSceneChanged());
- this.unsubscribeSceneSync_ = store.subscribeToSceneSync(() => this.onSceneSyncNeeded());
- this.unsubscribeFocus_ = store.onFocusEntity((entityId) => {
+ this.disposables_.add(store.subscribe(() => this.onSceneChanged()));
+ this.disposables_.add(store.subscribeToSceneSync(() => this.onSceneSyncNeeded()));
+ this.disposables_.add(store.onFocusEntity((entityId) => {
const worldTransform = this.store_.getWorldTransform(entityId);
this.camera_.focusOnEntity(worldTransform.position.x, worldTransform.position.y);
this.toolbar_.updateZoomDisplay(this.camera_.zoom);
- });
+ }));
this.livePreview_ = getSettingsValue<boolean>('scene.livePreview') ?? false;
- this.unsubscribeLivePreview_ = onSettingsChange((id, value) => {
+ this.disposables_.add(onSettingsChange((id, value) => {
if (id === 'scene.livePreview') {
this.livePreview_ = value as boolean;
if (this.livePreview_) this.requestRender();
}
- });
+ }));
- this.resizeObserver_ = new ResizeObserver(() => this.resize());
- this.resizeObserver_.observe(viewport);
+ this.disposables_.add(this.input_);
+ this.disposables_.add(this.toolbar_);
+ this.disposables_.add(() => { if (this.animationId_ !== null) cancelAnimationFrame(this.animationId_); });
+ this.disposables_.add(() => this.sceneRenderer_?.dispose());
+
+ const resizeObserver = new ResizeObserver(() => this.resize());
+ resizeObserver.observe(viewport);
+ this.disposables_.add(() => resizeObserver.disconnect());
this.resize();
@@ -264,37 +267,8 @@ export class SceneViewPanel {
dispose(): void {
this.continuousRender_ = false;
- if (this.animationId_ !== null) {
- cancelAnimationFrame(this.animationId_);
- this.animationId_ = null;
- }
- if (this.unsubscribe_) {
- this.unsubscribe_();
- this.unsubscribe_ = null;
- }
- if (this.unsubscribeSceneSync_) {
- this.unsubscribeSceneSync_();
- this.unsubscribeSceneSync_ = null;
- }
- if (this.unsubscribeFocus_) {
- this.unsubscribeFocus_();
- this.unsubscribeFocus_ = null;
- }
- if (this.unsubscribeLivePreview_) {
- this.unsubscribeLivePreview_();
- this.unsubscribeLivePreview_ = null;
- }
- if (this.resizeObserver_) {
- this.resizeObserver_.disconnect();
- this.resizeObserver_ = null;
- }
- if (this.sceneRenderer_) {
- this.sceneRenderer_.dispose();
- this.sceneRenderer_ = null;
- }
+ this.disposables_.dispose();
getSharedRenderContext().setSceneViewportSize(0, 0);
- this.input_.dispose();
- this.toolbar_.dispose();
}
get sharedContext() {
diff --git a/editor/src/panels/timeline/TimelinePanel.ts b/editor/src/panels/timeline/TimelinePanel.ts
index d083e8909..1d03c4cee 100644
--- a/editor/src/panels/timeline/TimelinePanel.ts
+++ b/editor/src/panels/timeline/TimelinePanel.ts
@@ -10,11 +10,13 @@ import { TimelineCurveEditor } from './TimelineCurveEditor';
import { AddKeyframeCommand } from './TimelineCommands';
import { getEditorContext, getEditorInstance } from '../../context/EditorContext';
import { getAssetDatabase as getAssetLibrary, isUUID } from '../../asset';
+import { DisposableStore } from '../../utils/Disposable';
const PLAYBACK_INTERVAL_MS = 16;
export class TimelinePanel implements PanelInstance {
private container_: HTMLElement;
+ private disposables_ = new DisposableStore();
private store_: EditorStore;
private state_: TimelineState;
private toolbar_: TimelineToolbar | null = null;
@@ -23,9 +25,6 @@ export class TimelinePanel implements PanelInstance {
private curveEditor_: TimelineCurveEditor | null = null;
private emptyEl_: HTMLElement | null = null;
private bodyEl_: HTMLElement | null = null;
- private storeUnsub_: (() => void) | null = null;
- private propertyUnsub_: (() => void) | null = null;
- private playbackUnsub_: (() => void) | null = null;
private isRecordingKeyframe_ = false;
private isScrubPreview_ = false;
private lastPreviewTime_ = -1;
@@ -42,24 +41,24 @@ export class TimelinePanel implements PanelInstance {
this.state_ = new TimelineState();
this.render();
- this.storeUnsub_ = store.subscribe((_state, dirtyFlags) => {
+ this.disposables_.add(store.subscribe((_state, dirtyFlags) => {
if (dirtyFlags?.has('selection') || dirtyFlags?.has('scene')) {
this.onSelectionOrSceneChanged();
}
- });
+ }));
- this.propertyUnsub_ = store.subscribeToPropertyChanges(
+ this.disposables_.add(store.subscribeToPropertyChanges(
(event) => this.onPropertyChanged(event),
- );
+ ));
- this.playbackUnsub_ = this.state_.onChange(() => {
+ this.disposables_.add(this.state_.onChange(() => {
if (this.state_.playing && this.playbackTimer_ === null) {
this.startPlayback();
} else if (!this.state_.playing && this.playbackTimer_ !== null) {
this.stopPlayback();
}
this.applyScrubPreview();
- });
+ }));
this.updateEmptyState();
}
@@ -70,9 +69,7 @@ export class TimelinePanel implements PanelInstance {
this.trackList_?.dispose();
this.keyframeArea_?.dispose();
this.curveEditor_?.dispose();
- this.storeUnsub_?.();
- this.propertyUnsub_?.();
- this.playbackUnsub_?.();
+ this.disposables_.dispose();
this.container_.innerHTML = '';
}
diff --git a/editor/src/utils/Disposable.ts b/editor/src/utils/Disposable.ts
new file mode 100644
index 000000000..a9c7a3229
--- /dev/null
+++ b/editor/src/utils/Disposable.ts
@@ -0,0 +1,49 @@
+export interface IDisposable {
+ dispose(): void;
+}
+
+export function toDisposable(fn: () => void): IDisposable {
+ return { dispose: fn };
+}
+
+export class DisposableStore implements IDisposable {
+ private disposables_: IDisposable[] = [];
+ private disposed_ = false;
+
+ add<T extends IDisposable>(d: T): T;
+ add(fn: () => void): IDisposable;
+ add(d: IDisposable | (() => void)): IDisposable {
+ const disposable = typeof d === 'function' ? toDisposable(d) : d;
+ if (this.disposed_) {
+ disposable.dispose();
+ return disposable;
+ }
+ this.disposables_.push(disposable);
+ return disposable;
+ }
+
+ addListener(
+ target: EventTarget,
+ event: string,
+ handler: EventListenerOrEventListenerObject,
+ options?: boolean | AddEventListenerOptions
+ ): IDisposable {
+ target.addEventListener(event, handler, options);
+ return this.add(() => target.removeEventListener(event, handler, options));
+ }
+
+ dispose(): void {
+ if (this.disposed_) {
+ return;
+ }
+ this.disposed_ = true;
+ const disposables = this.disposables_.splice(0);
+ for (let i = disposables.length - 1; i >= 0; i--) {
+ try {
+ disposables[i].dispose();
+ } catch (e) {
+ console.error('Error during dispose:', e);
+ }
+ }
+ }
+}