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.

fix(editor): close global-chrome safety gaps

yhh4545b2921bdf
diff --git a/desktop/src/App.tsx b/desktop/src/App.tsx
index e4a6e6c09..642814d0c 100644
--- a/desktop/src/App.tsx
+++ b/desktop/src/App.tsx
@@ -23,6 +23,7 @@ import { TilemapPickerDialog } from '@/components/TilemapPickerDialog';
import { CommandPalette } from '@/components/CommandPalette';
import { useEditorStore } from '@/store/editorStore';
import { ConfirmService } from '@/components/confirm';
+import { overlayGuard } from '@/components/overlayGuard';
import { commands } from '@/commands';
import { handleTilePaintKey } from '@/tools/tileMode';
import { suggestedMode } from '@/mode/activeMode';
@@ -70,6 +71,10 @@ export function App() {
if (ui.settingsOpen || ui.paletteOpen || ui.buildOpen || ui.tilemapPickerOpen || ConfirmService.getSnapshot().length > 0) {
return;
}
+ // A floating context menu / popover / field dropdown owns the keyboard while
+ // open — don't let global shortcuts (Delete, Ctrl+Z, F5, Ctrl+D) run against
+ // the scene behind it (the overlay handles its own Escape/nav keys).
+ if (overlayGuard.active) return;
// Ctrl+Space summons the Content Drawer — works even from a field.
if ((e.ctrlKey || e.metaKey) && e.code === 'Space') {
e.preventDefault();
diff --git a/desktop/src/commands/editorCommands.ts b/desktop/src/commands/editorCommands.ts
index 5ec91e432..62d48a8e0 100644
--- a/desktop/src/commands/editorCommands.ts
+++ b/desktop/src/commands/editorCommands.ts
@@ -19,6 +19,7 @@ import { ViewportController } from '@/engine/ViewportController';
import { PerfMonitor } from '@/engine/PerfMonitor';
import { applyFxPreview } from '@/engine/fxPreview';
import { dockApi } from '@/layout/dockApi';
+import { resetLayout } from '@/layout/DockLayout';
import { panelDirtySource } from '@/layout/panelDirty';
import { DirtyRegistry } from '@/document/DirtyRegistry';
import { MaterialDocument } from '@/material/MaterialDocument';
@@ -336,6 +337,14 @@ commands.register({
isChecked: () => dockApi.isMaximized(),
run: () => dockApi.toggleMaximizePanel('viewport'),
});
+commands.register({
+ id: 'view.resetLayout',
+ label: t('menu.resetLayout'),
+ category: t('cat.view'),
+ // Rebuild the default dock arrangement in place (keeps scene/engine/undo). A real
+ // command so it reaches the palette + is rebindable, not a one-off menu handler.
+ run: () => void confirmDiscard(t('discard.resetLayout')).then((ok) => ok && resetLayout()),
+});
commands.register({
id: 'view.toggleGrid',
label: t('cmd.view.toggleGrid'),
diff --git a/desktop/src/commands/registry.ts b/desktop/src/commands/registry.ts
index 58f7bfbcb..d73dd62ba 100644
--- a/desktop/src/commands/registry.ts
+++ b/desktop/src/commands/registry.ts
@@ -9,7 +9,7 @@
* domain stores the UI already subscribes to.
*/
import type { Command, Keybinding } from './types';
-import { chordMatches } from './keybinding';
+import { chordMatches, normalizeChord } from './keybinding';
import { PerfMonitor } from '@/engine/PerfMonitor';
const OVERRIDE_KEY = 'estella.keybindings';
@@ -55,6 +55,23 @@ class CommandRegistry {
return this.overrides.has(id);
}
+ /** Other commands whose effective binding matches `chord` (canonical compare),
+ * excluding `exceptId` — for rebind conflict warnings. Note some overlaps are
+ * intentional (context-gated keys like Escape = Stop / Deselect), so callers
+ * warn rather than block. */
+ conflictsFor(chord: string, exceptId?: string): string[] {
+ const target = normalizeChord(chord);
+ const out: string[] = [];
+ for (const c of this.map.values()) {
+ if (c.id === exceptId) continue;
+ const kb = this.keybindingFor(c.id);
+ if (!kb) continue;
+ const list = Array.isArray(kb) ? kb : [kb];
+ if (list.some((k) => normalizeChord(k) === target)) out.push(c.id);
+ }
+ return out;
+ }
+
/** 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);
diff --git a/desktop/src/components/ConfirmDialog.tsx b/desktop/src/components/ConfirmDialog.tsx
index a519c6cb9..1b55c3c2a 100644
--- a/desktop/src/components/ConfirmDialog.tsx
+++ b/desktop/src/components/ConfirmDialog.tsx
@@ -2,9 +2,11 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file ConfirmDialog.tsx — a themed yes/no confirm built on Modal, replacing
- * native window.confirm (blocking, unthemed, no keyboard contract). The
- * confirm button takes focus so Enter confirms; Escape/backdrop cancel
- * via Modal. `danger` puts the error fill on the confirm action.
+ * native window.confirm (blocking, unthemed, no keyboard contract). A safe
+ * dialog focuses Confirm (Enter proceeds); a `danger` dialog focuses Cancel
+ * instead, so a reflexive Enter on "Discard unsaved changes?" can't destroy
+ * anything. Escape/backdrop cancel via Modal. `danger` also puts the error
+ * fill on the confirm action.
*/
import { useEffect, useRef, type ReactNode } from 'react';
import { t } from '@/i18n';
@@ -30,9 +32,14 @@ export function ConfirmDialog({
onConfirm: () => void;
onCancel: () => void;
}) {
- // Runs after Modal's dialogFocus (child effects first), so this wins.
- const btn = useRef<HTMLButtonElement>(null);
- useEffect(() => btn.current?.focus(), []);
+ // Runs after Modal's dialogFocus (child effects first), so this wins. A
+ // destructive dialog seeds focus on Cancel (Enter = the safe choice); a safe or
+ // info dialog seeds Confirm (Enter = proceed).
+ const confirmBtn = useRef<HTMLButtonElement>(null);
+ const cancelBtn = useRef<HTMLButtonElement>(null);
+ useEffect(() => {
+ (danger && !info ? cancelBtn : confirmBtn).current?.focus();
+ }, [danger, info]);
return (
<Modal
@@ -41,8 +48,8 @@ export function ConfirmDialog({
width={420}
footer={
<>
- {!info && <Button onClick={onCancel}>{t('ui.cancel')}</Button>}
- <Button ref={btn} variant={danger ? 'danger' : 'primary'} onClick={onConfirm}>
+ {!info && <Button ref={cancelBtn} onClick={onCancel}>{t('ui.cancel')}</Button>}
+ <Button ref={confirmBtn} variant={danger ? 'danger' : 'primary'} onClick={onConfirm}>
{confirmLabel}
</Button>
</>
diff --git a/desktop/src/components/Menu.tsx b/desktop/src/components/Menu.tsx
index d12d7f338..9e6b24d7a 100644
--- a/desktop/src/components/Menu.tsx
+++ b/desktop/src/components/Menu.tsx
@@ -11,6 +11,7 @@ import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 're
import { createPortal } from 'react-dom';
import { Check, ChevronRight } from 'lucide-react';
import { usePanelWindow } from '@/components/PanelWindow';
+import { overlayGuard } from '@/components/overlayGuard';
export type MenuItem =
| { sep: true }
@@ -136,6 +137,13 @@ export function ContextMenu({
// seed-focus effect steals it) — keyboard focus returns there on close.
const opener = useRef<HTMLElement | null>(doc.activeElement as HTMLElement | null);
+ // While the menu is open it owns the keyboard: the global shortcut handler
+ // must not run scene commands (Delete/Ctrl+Z/F5) against the scene behind it.
+ useEffect(() => {
+ overlayGuard.open();
+ return () => overlayGuard.close();
+ }, []);
+
// Restore focus to the opener — unless the dismissal itself moved focus
// somewhere real (outside-press on another control must keep that focus).
useEffect(
diff --git a/desktop/src/components/Popover.tsx b/desktop/src/components/Popover.tsx
index 420ffbe84..f41ddb5ea 100644
--- a/desktop/src/components/Popover.tsx
+++ b/desktop/src/components/Popover.tsx
@@ -13,6 +13,7 @@
import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react';
import { createPortal } from 'react-dom';
import { usePanelWindow } from '@/components/PanelWindow';
+import { overlayGuard } from '@/components/overlayGuard';
export function Popover({
anchor,
@@ -39,6 +40,13 @@ export function Popover({
// returns there on close, unless the dismissal itself focused another control.
const opener = useRef<HTMLElement | null>(doc.activeElement as HTMLElement | null);
+ // While open, the popover owns the keyboard — suppress global scene shortcuts
+ // so Delete/Ctrl+Z don't bubble past an open dropdown/picker to the scene.
+ useEffect(() => {
+ overlayGuard.open();
+ return () => overlayGuard.close();
+ }, []);
+
useEffect(
() => () => {
const cur = doc.activeElement;
diff --git a/desktop/src/components/SettingsDialog.tsx b/desktop/src/components/SettingsDialog.tsx
index c2ba21725..0929151ca 100644
--- a/desktop/src/components/SettingsDialog.tsx
+++ b/desktop/src/components/SettingsDialog.tsx
@@ -16,6 +16,8 @@ import { useEditorStore } from '@/store/editorStore';
import { useSettings } from '@/store/settingsStore';
import { settingsRegistry } from '@/settings/registry';
import { eventToChord, formatKeybinding } from '@/commands/keybinding';
+import { commands } from '@/commands';
+import { Toasts } from '@/store/Toasts';
import { useDialogFocus } from '@/components/dialogFocus';
import { IconButton } from '@/components/IconButton';
import { SearchField } from '@/components/SearchField';
@@ -114,8 +116,19 @@ function KeybindCapture({ setting }: { setting: KeybindingSetting }) {
return;
}
if (['Control', 'Shift', 'Alt', 'Meta'].includes(e.key)) return; // wait for the real key
- setValue(setting.id, eventToChord(e));
+ const chord = eventToChord(e);
+ setValue(setting.id, chord);
setCapturing(false);
+ // Warn (don't block) if the chord already drives another command — some
+ // overlaps are intentional (context-gated keys), but a SILENT shadow is the
+ // real bug, so name the clash and let the user decide.
+ const clash = commands.conflictsFor(chord, setting.commandId);
+ if (clash.length) {
+ Toasts.push(
+ t('set.rebindConflict', { keys: formatKeybinding(chord), cmd: commands.get(clash[0])?.label ?? clash[0] }),
+ 'warn',
+ );
+ }
};
// Capture phase + stopPropagation so neither commands nor the dialog Esc fire.
window.addEventListener('keydown', onKey, true);
diff --git a/desktop/src/components/overlayGuard.ts b/desktop/src/components/overlayGuard.ts
new file mode 100644
index 000000000..164cbe2bc
--- /dev/null
+++ b/desktop/src/components/overlayGuard.ts
@@ -0,0 +1,28 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file overlayGuard.ts — a live count of open transient overlays (context
+ * menus, popovers, field dropdowns). While any is open it OWNS the
+ * keyboard, so the global shortcut handler (App.tsx) suppresses scene
+ * commands — otherwise Delete / Ctrl+Z / F5 would bubble past a floating
+ * menu and hit the scene *behind* it. A plain module counter (not a store)
+ * because the handler reads it synchronously on every keydown; overlays
+ * bump it on mount and drop it on unmount. Shared across editor windows
+ * (popouts run in the same JS realm), so a menu in any window guards all.
+ */
+let count = 0;
+
+export const overlayGuard = {
+ /** An overlay opened — call from a mount effect. */
+ open() {
+ count++;
+ },
+ /** An overlay closed — call from that effect's cleanup. */
+ close() {
+ count = Math.max(0, count - 1);
+ },
+ /** True while at least one transient overlay is open. */
+ get active(): boolean {
+ return count > 0;
+ },
+};
diff --git a/desktop/src/i18n/messages/settings.ts b/desktop/src/i18n/messages/settings.ts
index af76a4bcc..6ff854129 100644
--- a/desktop/src/i18n/messages/settings.ts
+++ b/desktop/src/i18n/messages/settings.ts
@@ -19,6 +19,10 @@ export const settingsMessages = defineMessages({
'set.pressKeys': { en: 'Press keys…', zh: '请按键…' },
'set.unbound': { en: 'Unbound', zh: '未绑定' },
'set.rebindHint': { en: 'Click to rebind', zh: '点击重新绑定' },
+ 'set.rebindConflict': {
+ en: '{keys} is also bound to “{cmd}” — one may shadow the other',
+ zh: '{keys} 也绑定了“{cmd}”——两者可能相互覆盖',
+ },
'set.layerN': { en: 'Layer {i}', zh: '层 {i}' },
// — Nav categories —
diff --git a/desktop/src/layout/MenuBar.tsx b/desktop/src/layout/MenuBar.tsx
index 216b7f30f..ca97aef94 100644
--- a/desktop/src/layout/MenuBar.tsx
+++ b/desktop/src/layout/MenuBar.tsx
@@ -8,8 +8,6 @@
import { useEffect, useRef, useState, useSyncExternalStore } from 'react';
import { WindowControls } from '@/layout/WindowControls';
import { DirtyDot } from '@/components/DirtyDot';
-import { resetLayout } from '@/layout/DockLayout';
-import { confirmDiscard } from '@/project/discardGuard';
import { ProjectStore } from '@/project/ProjectStore';
import { EditorHistory } from '@/engine/EditorHistory';
import { MenuItems, handleMenuListKey, type MenuItem } from '@/components/Menu';
@@ -153,8 +151,9 @@ export function MenuBar() {
title: t('menu.window'),
items: [
// Reset only the dock layout — rebuild in place (keeps scene/engine/undo),
- // guarded so a wedged dirty asset-editor tab can't vanish unwarned.
- { label: t('menu.resetLayout'), onClick: () => void confirmDiscard(t('discard.resetLayout')).then((ok) => ok && resetLayout()) },
+ // guarded so a wedged dirty asset-editor tab can't vanish unwarned. A real
+ // command, so it's in the palette + rebindable.
+ cmdItem('view.resetLayout'),
{ sep: true },
// Same destination as File ▸ Close Project — run the guarded command so
// leaving a project can't silently drop unsaved scene + asset edits.