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
feat(editor): editable keyboard shortcuts in Settings
esenginedc1955e9d878
diff --git a/desktop/src/commands/registry.ts b/desktop/src/commands/registry.tsindex 8ffefaaa0..0f6833925 100644--- a/desktop/src/commands/registry.ts+++ b/desktop/src/commands/registry.ts@@ -6,11 +6,30 @@* reactive state of its own; enablement is derived on demand from the* domain stores the UI already subscribes to.*/-import type { Command } from './types';+import type { Command, Keybinding } from './types';import { chordMatches } from './keybinding';+const OVERRIDE_KEY = 'estella.keybindings';++const primaryChord = (kb: Keybinding | undefined): string =>+ (Array.isArray(kb) ? kb[0] : kb) ?? '';+class CommandRegistry {private readonly map = new Map<string, 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>();++ constructor() {+ if (typeof localStorage !== 'undefined') {+ try {+ const saved = JSON.parse(localStorage.getItem(OVERRIDE_KEY) ?? '{}') as Record<string, string>;+ for (const [id, chord] of Object.entries(saved)) this.overrides.set(id, chord);+ } catch {+ /* corrupt / absent — start with no overrides */+ }+ }+ }register(cmd: Command): void {this.map.set(cmd.id, cmd);@@ -24,6 +43,36 @@ class CommandRegistry {return [...this.map.values()];}+ /** 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;+ }++ hasOverride(id: string): boolean {+ return this.overrides.has(id);+ }++ /** 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);+ else this.overrides.set(id, chord);+ this.persistOverrides();+ }++ resetKeybinding(id: string): void {+ this.overrides.delete(id);+ this.persistOverrides();+ }++ private persistOverrides(): void {+ if (typeof localStorage === 'undefined') return;+ try {+ localStorage.setItem(OVERRIDE_KEY, JSON.stringify(Object.fromEntries(this.overrides)));+ } catch {+ /* quota / private mode */+ }+ }+isEnabled(id: string): boolean {const c = this.map.get(id);return c ? c.isEnabled?.() ?? true : false;@@ -39,10 +88,11 @@ class CommandRegistry {if (c && (c.isEnabled?.() ?? true)) c.run();}- /** The enabled command bound to a key event, if any. */+ /** The enabled command bound to a key event, if any (honors overrides). */forEvent(e: KeyboardEvent): Command | undefined {for (const c of this.map.values()) {- if (c.keybinding && chordMatches(e, c.keybinding) && (c.isEnabled?.() ?? true)) return c;+ const kb = this.keybindingFor(c.id);+ if (kb && chordMatches(e, kb) && (c.isEnabled?.() ?? true)) return c;}return undefined;}diff --git a/desktop/src/components/SettingsDialog.tsx b/desktop/src/components/SettingsDialog.tsxindex 65fdc07e9..de82fc487 100644--- a/desktop/src/components/SettingsDialog.tsx+++ b/desktop/src/components/SettingsDialog.tsx@@ -12,7 +12,8 @@ import { Settings as SettingsIcon, Search, X, RotateCcw } from 'lucide-react';import { useEditorStore } from '@/store/editorStore';import { useSettings } from '@/store/settingsStore';import { settingsRegistry } from '@/settings/registry';-import type { Setting, NumberSetting } from '@/settings/types';+import { eventToChord, formatKeybinding } from '@/commands/keybinding';+import type { Setting, NumberSetting, KeybindingSetting } from '@/settings/types';const CATEGORY_LABEL: Record<string, string> = {editor: 'Editor',@@ -80,6 +81,41 @@ function NumberControl({ setting }: { setting: NumberSetting }) {);}+// Click to capture the next chord (Esc cancels). Bound to the command registry,+// so the new binding persists and takes effect immediately.+function KeybindCapture({ setting }: { setting: KeybindingSetting }) {+ const setValue = useSettings((s) => s.setValue);+ const chord = useSettings((s) => s.getValue<string>(setting.id));+ const [capturing, setCapturing] = useState(false);+ useEffect(() => {+ if (!capturing) return;+ const onKey = (e: KeyboardEvent) => {+ e.preventDefault();+ e.stopPropagation();+ if (e.key === 'Escape') {+ setCapturing(false);+ return;+ }+ if (['Control', 'Shift', 'Alt', 'Meta'].includes(e.key)) return; // wait for the real key+ setValue(setting.id, eventToChord(e));+ setCapturing(false);+ };+ // Capture phase + stopPropagation so neither commands nor the dialog Esc fire.+ window.addEventListener('keydown', onKey, true);+ return () => window.removeEventListener('keydown', onKey, true);+ }, [capturing, setting.id, setValue]);+ return (+ <button+ type="button"+ className={`set-key${capturing ? ' capturing' : ''}`}+ title="Click to rebind"+ onClick={() => setCapturing((c) => !c)}+ >+ {capturing ? 'Press keys…' : formatKeybinding(chord) || 'Unbound'}+ </button>+ );+}+function Control({ setting }: { setting: Setting }) {const setValue = useSettings((s) => s.setValue);const value = useSettings((s) => s.getValue(setting.id));@@ -135,16 +171,15 @@ function Control({ setting }: { setting: Setting }) {</div>);case 'keybinding':- return <span className="set-key">{setting.default}</span>;+ return <KeybindCapture setting={setting} />;}}function Row({ setting }: { setting: Setting }) {const isChanged = useSettings((s) => s.isChanged(setting.id));const reset = useSettings((s) => s.reset);- const resettable = setting.type !== 'keybinding';return (- <div className={`set-row${isChanged && resettable ? ' changed' : ''}`}>+ <div className={`set-row${isChanged ? ' changed' : ''}`}><div><div className="sn">{setting.label}</div>{setting.description && <div className="sd">{setting.description}</div>}@@ -152,17 +187,13 @@ function Row({ setting }: { setting: Setting }) {<div className="set-ctrl"><Control setting={setting} /></div>- {resettable ? (- <span- className={`set-reset${isChanged ? ' show' : ''}`}- title="Reset to default"- onClick={() => isChanged && reset(setting.id)}- >- {isChanged && <RotateCcw size={11} strokeWidth={2} />}- </span>- ) : (- <span className="set-reset" />- )}+ <span+ className={`set-reset${isChanged ? ' show' : ''}`}+ title="Reset to default"+ onClick={() => isChanged && reset(setting.id)}+ >+ {isChanged && <RotateCcw size={11} strokeWidth={2} />}+ </span></div>);}diff --git a/desktop/src/settings/editorSettings.ts b/desktop/src/settings/editorSettings.tsindex 9610c8877..4377015f2 100644--- a/desktop/src/settings/editorSettings.ts+++ b/desktop/src/settings/editorSettings.ts@@ -12,7 +12,6 @@ import { settingsRegistry } from './registry';import { useEditorStore } from '@/store/editorStore';import { LogStore } from '@/store/LogStore';import { commands } from '@/commands';-import { formatKeybinding } from '@/commands/keybinding';const root = () => document.documentElement.style;@@ -125,9 +124,12 @@ settingsRegistry.register({effect: (v) => LogStore.setCap(v),});-// ── Keyboard Shortcuts (read-only, generated from the command registry) ──────-// Editing is a later feature; here we surface the live bindings so they're-// discoverable in one place (the design's "快捷键" section).+// ── Keyboard Shortcuts (editable, bound to the command registry overrides) ───+// Each keybound command gets a row; the value is the effective chord, bound to+// the registry so rebinding persists + takes effect, and reset clears the override.+const primaryChord = (kb: ReturnType<typeof commands.keybindingFor>): string =>+ (Array.isArray(kb) ? kb[0] : kb) ?? '';+for (const cmd of commands.all()) {if (!cmd.keybinding) continue;settingsRegistry.register({@@ -138,6 +140,10 @@ for (const cmd of commands.all()) {group: cmd.category ?? 'General',label: cmd.label,commandId: cmd.id,- default: formatKeybinding(cmd.keybinding),+ default: primaryChord(cmd.keybinding),+ bind: {+ get: () => primaryChord(commands.keybindingFor(cmd.id)),+ set: (chord) => commands.setKeybinding(cmd.id, chord),+ },});}diff --git a/desktop/src/theme/settings.css b/desktop/src/theme/settings.cssindex 6eedfa5d8..a1cf768d4 100644--- a/desktop/src/theme/settings.css+++ b/desktop/src/theme/settings.css@@ -192,7 +192,11 @@font-family: var(--mono);font-size: var(--fs-xs);color: var(--text);+ cursor: pointer;+ transition: border-color var(--t-fast), color var(--t-fast);}+.set-key:hover { border-color: var(--border-line); }+.set-key.capturing { border-color: var(--acc); color: var(--acc); box-shadow: 0 0 0 2px var(--acc-soft); }.set-swatches { display: flex; gap: 6px; }.set-swatch {width: 22px;diff --git a/desktop/tests/settings.test.ts b/desktop/tests/settings.test.tsindex 401b228fa..3a593ac38 100644--- a/desktop/tests/settings.test.ts+++ b/desktop/tests/settings.test.ts@@ -11,6 +11,7 @@ import { settingsRegistry } from '@/settings/registry';import { useSettings } from '@/store/settingsStore';import { useEditorStore } from '@/store/editorStore';import { LogStore } from '@/store/LogStore';+import { commands } from '@/commands';describe('settings registry', () => {it('registers the editor sections', () => {@@ -54,4 +55,14 @@ describe('settings store', () => {expect(useEditorStore.getState().showGrid).toBe(false);expect(s.getValue('viewport.showGrid')).toBe(false);});++ it('a keybinding setting rebinds the command and reset clears the override', () => {+ const s = useSettings.getState();+ s.setValue('shortcut.tool.move', 'x');+ expect(commands.keybindingFor('tool.move')).toBe('x');+ expect(commands.hasOverride('tool.move')).toBe(true);+ s.reset('shortcut.tool.move'); // → default 'w', clears override+ expect(commands.hasOverride('tool.move')).toBe(false);+ expect(commands.keybindingFor('tool.move')).toBe('w');+ });});