Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(editor): async discard guard - the last window.confirm falls

yhh55b7631d6a5b
diff --git a/desktop/src/App.tsx b/desktop/src/App.tsx
index 4b9b719d4..049dbe0ba 100644
--- a/desktop/src/App.tsx
+++ b/desktop/src/App.tsx
@@ -10,6 +10,7 @@ import { ContentDrawer } from '@/layout/ContentDrawer';
import '@/engine/EditorSession'; // side effect: constructs defaultSession → wires the editor engine
import { Launcher } from '@/launcher/Launcher';
import { Toaster } from '@/components/Toaster';
+import { ConfirmHost } from '@/components/ConfirmHost';
import { Perf } from '@/components/Perf';
import { PerfRealmBridge } from '@/components/PerfRealmBridge';
import { BuildDialog } from '@/components/BuildDialog';
@@ -179,6 +180,7 @@ export function App() {
{settingsOpen && <SettingsDialog />}
{tilemapPickerOpen && <TilemapPickerDialog />}
<Toaster />
+ <ConfirmHost />
</div>
);
}
diff --git a/desktop/src/commands/editorCommands.ts b/desktop/src/commands/editorCommands.ts
index 231f7961d..1f3b3e5e1 100644
--- a/desktop/src/commands/editorCommands.ts
+++ b/desktop/src/commands/editorCommands.ts
@@ -33,8 +33,8 @@ commands.register({
category: 'File',
keybinding: 'mod+n',
isEnabled: () => !!ProjectStore.getSnapshot(),
- run: () => {
- if (!confirmDiscard('Creating a new scene will discard them')) return;
+ run: async () => {
+ if (!(await confirmDiscard('Creating a new scene will discard them'))) return;
void ProjectStore.newScene().then(() => sel().select(null));
},
});
@@ -78,8 +78,8 @@ commands.register({
label: 'Close Project',
category: 'File',
isEnabled: () => !!ProjectStore.getSnapshot(),
- run: () => {
- if (!confirmDiscard('Closing the project will discard them')) return;
+ run: async () => {
+ if (!(await confirmDiscard('Closing the project will discard them'))) return;
editor().openLauncher();
},
});
diff --git a/desktop/src/components/ConfirmHost.tsx b/desktop/src/components/ConfirmHost.tsx
new file mode 100644
index 000000000..2a367e19e
--- /dev/null
+++ b/desktop/src/components/ConfirmHost.tsx
@@ -0,0 +1,27 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ConfirmHost.tsx — renders the ConfirmService queue's front request as
+ * a ConfirmDialog. Mounted once in the editor shell (next to Toaster);
+ * queued requests show one at a time in arrival order.
+ */
+import { useSyncExternalStore } from 'react';
+import { ConfirmService } from './confirm';
+import { ConfirmDialog } from './ConfirmDialog';
+
+export function ConfirmHost() {
+ const queue = useSyncExternalStore(ConfirmService.subscribe, ConfirmService.getSnapshot);
+ const cur = queue[0];
+ if (!cur) return null;
+ return (
+ <ConfirmDialog
+ key={cur.id}
+ title={cur.title}
+ body={cur.body}
+ confirmLabel={cur.confirmLabel ?? 'OK'}
+ danger={cur.danger}
+ onConfirm={() => ConfirmService.settle(cur.id, true)}
+ onCancel={() => ConfirmService.settle(cur.id, false)}
+ />
+ );
+}
diff --git a/desktop/src/components/confirm.ts b/desktop/src/components/confirm.ts
new file mode 100644
index 000000000..9a8a7c881
--- /dev/null
+++ b/desktop/src/components/confirm.ts
@@ -0,0 +1,56 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file confirm.ts
+ * @brief Imperative confirm — `confirm(opts)` resolves true/false when the
+ * user answers the themed ConfirmDialog that <ConfirmHost> (mounted
+ * once in the shell) renders for it. The store is plain (same
+ * subscribe/getSnapshot shape as Toasts) so non-React modules —
+ * ProjectStore, command handlers — can await a confirmation without
+ * reaching for window.confirm (blocking, unthemed, no keyboard
+ * contract). Concurrent requests queue; dialogs show one at a time.
+ */
+import { createStore } from 'zustand/vanilla';
+
+export interface ConfirmOptions {
+ title: string;
+ body: string;
+ confirmLabel?: string;
+ /** Destructive action — the confirm button wears the error fill. */
+ danger?: boolean;
+}
+
+export interface PendingConfirm extends ConfirmOptions {
+ id: number;
+}
+
+class ConfirmServiceImpl {
+ private readonly store = createStore<{ queue: PendingConfirm[] }>(() => ({ queue: [] }));
+ private readonly resolvers = new Map<number, (ok: boolean) => void>();
+ private seq = 0;
+
+ subscribe = (fn: () => void): (() => void) => this.store.subscribe(fn);
+ getSnapshot = (): PendingConfirm[] => this.store.getState().queue;
+
+ request(opts: ConfirmOptions): Promise<boolean> {
+ return new Promise((resolve) => {
+ const id = ++this.seq;
+ this.resolvers.set(id, resolve);
+ this.store.setState((s) => ({ queue: [...s.queue, { ...opts, id }] }));
+ });
+ }
+
+ /** Answer a pending request (the host calls this from the dialog buttons). */
+ settle(id: number, ok: boolean): void {
+ const resolve = this.resolvers.get(id);
+ if (!resolve) return;
+ this.resolvers.delete(id);
+ this.store.setState((s) => ({ queue: s.queue.filter((c) => c.id !== id) }));
+ resolve(ok);
+ }
+}
+
+export const ConfirmService = new ConfirmServiceImpl();
+
+/** Ask the user; resolves when they answer (false on cancel/Escape). */
+export const confirm = (opts: ConfirmOptions): Promise<boolean> => ConfirmService.request(opts);
diff --git a/desktop/src/panels/Details.tsx b/desktop/src/panels/Details.tsx
index dfb5a1274..b67e6ffbd 100644
--- a/desktop/src/panels/Details.tsx
+++ b/desktop/src/panels/Details.tsx
@@ -1808,8 +1808,8 @@ function GenericAssetInspector({ path }: { path: string }) {
<button
type="button"
className="primary"
- onClick={() => {
- if (confirmDiscard(`Opening ${baseName(path)} will discard them`)) void ProjectStore.openScene(path);
+ onClick={async () => {
+ if (await confirmDiscard(`Opening ${baseName(path)} will discard them`)) void ProjectStore.openScene(path);
}}
>
<FolderOpen size={13} strokeWidth={1.85} /> Open Scene
diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.ts
index 71a45c808..6b4357878 100644
--- a/desktop/src/project/ProjectStore.ts
+++ b/desktop/src/project/ProjectStore.ts
@@ -133,6 +133,8 @@ class ProjectStoreImpl {
private lastAssetResult: PreloadResult | null = null;
private knownSceneText: string | null = null;
private knownScenePath: string | null = null;
+ /** A disk-change discard prompt is showing — don't stack another. */
+ private reloadPromptOpen = false;
constructor() {
// The inspector's override-aware reset reads prefab base data from the loaded
// `.esprefab` cache this store owns. Non-variant prefabs resolve their base
@@ -1010,11 +1012,18 @@ class ProjectStoreImpl {
catch { return; }
if (text === this.knownSceneText && st.currentScene === this.knownScenePath) return;
const name = st.currentScene.split('/').pop() ?? st.currentScene;
- if (EditorHistory.isDirty() &&
- !confirmDiscard(`"${name}" changed on disk. Reloading discards your unsaved edits`)) {
- this.knownSceneText = text;
- this.knownScenePath = st.currentScene;
- return;
+ if (EditorHistory.isDirty()) {
+ // The confirm is async — further disk-change events while it's open must
+ // not stack more dialogs for the same question.
+ if (this.reloadPromptOpen) return;
+ this.reloadPromptOpen = true;
+ const ok = await confirmDiscard(`"${name}" changed on disk. Reloading discards your unsaved edits`);
+ this.reloadPromptOpen = false;
+ if (!ok) {
+ this.knownSceneText = text;
+ this.knownScenePath = st.currentScene;
+ return;
+ }
}
await this.loadCurrentScene();
Toasts.push(`Reloaded ${name} from disk`, 'info', 1600);
diff --git a/desktop/src/project/assetOpen.ts b/desktop/src/project/assetOpen.ts
index fc4c6fa33..83e31da8e 100644
--- a/desktop/src/project/assetOpen.ts
+++ b/desktop/src/project/assetOpen.ts
@@ -20,8 +20,8 @@ import { openBehaviorTree } from '@/bt/openBehaviorTree';
/** Open action per asset type; types absent here aren't double-click-openable. */
export const ASSET_OPEN: Partial<Record<AssetType, (path: string, name: string) => void>> = {
- scene: (path, name) => {
- if (!confirmDiscard(`Opening ${name} will discard them`)) return;
+ scene: async (path, name) => {
+ if (!(await confirmDiscard(`Opening ${name} will discard them`))) return;
void ProjectStore.openScene(path);
},
audio: (path) => toggleAudioPreview(path),
diff --git a/desktop/src/project/discardGuard.ts b/desktop/src/project/discardGuard.ts
index 6158bd382..39d85dca2 100644
--- a/desktop/src/project/discardGuard.ts
+++ b/desktop/src/project/discardGuard.ts
@@ -9,13 +9,21 @@
* after a save and false-warned.
*/
import { EditorHistory } from '@/engine/EditorHistory';
+import { confirm } from '@/components/confirm';
/**
- * Returns true if it's safe to proceed with a destructive document action: when
- * there are no unsaved changes, or the user confirms discarding them. `what`
- * names the consequence, e.g. "Creating a new scene will discard them".
+ * Resolves true if it's safe to proceed with a destructive document action:
+ * when there are no unsaved changes, or the user confirms discarding them.
+ * `what` names the consequence, e.g. "Creating a new scene will discard them".
+ * Async (a themed dialog, not window.confirm) — callers gate with
+ * `if (!(await confirmDiscard(...))) return;`.
*/
-export function confirmDiscard(what = 'They will be lost'): boolean {
+export async function confirmDiscard(what = 'They will be lost'): Promise<boolean> {
if (!EditorHistory.isDirty()) return true;
- return window.confirm(`You have unsaved changes. ${what}. Continue?`);
+ return confirm({
+ title: 'Unsaved changes',
+ body: `You have unsaved changes. ${what}.`,
+ confirmLabel: 'Discard changes',
+ danger: true,
+ });
}