diff --git a/components/editor/TextEditorPane.shortcuts.test.ts b/components/editor/TextEditorPane.shortcuts.test.ts index 63e53ffdd..dea3776c1 100644 --- a/components/editor/TextEditorPane.shortcuts.test.ts +++ b/components/editor/TextEditorPane.shortcuts.test.ts @@ -2,51 +2,271 @@ import assert from 'node:assert/strict'; import test from 'node:test'; import { readFileSync } from 'node:fs'; import { createRequire } from 'node:module'; +import type * as Monaco from 'monaco-editor'; const require = createRequire(import.meta.url); const { ContextKeyExpr } = require('monaco-editor/esm/vs/platform/contextkey/common/contextkey.js'); const { KeybindingResolver } = require('monaco-editor/esm/vs/platform/keybinding/common/keybindingResolver.js'); -import { registerTextEditorCommand } from './TextEditorPane.tsx'; +import { pasteForMonacoEditorCommand } from '../../infrastructure/monaco/monacoClipboardPaste.ts'; +import { + bindTextEditorActions, + registerTextEditorAction, + type TextEditorActionConfig, +} from './TextEditorPane.tsx'; + +type RegisteredBinding = { + command: string; + commandArgs: undefined; + chords: string[]; + when: ReturnType; + isDefault: boolean; + bubble: boolean; +}; + +function createStandaloneActionRegistry() { + const commands = new Map void>(); + const bindings: RegisteredBinding[] = []; + + function createEditor(editorId: string) { + const disposeListeners = new Set<() => void>(); + const actionDisposals: string[] = []; + let onDidDisposeDisposals = 0; -test('save, close, find and paste resolve to the focused editor when two editors share a window', () => { - const commands = new Map[2]>(); - const bindings: Array<{ command: string; commandArgs: undefined; chords: string[]; when: ReturnType; isDefault: boolean; bubble: boolean }> = []; - const calls: string[] = []; - const actions = ['save', 'close', 'find', 'paste']; - // Match the native regression: beta was created first, alpha last, then - // beta was clicked. Unscoped Monaco commands incorrectly chose alpha. - for (const editorId of ['vs.editor.ICodeEditor:beta', 'vs.editor.ICodeEditor:alpha']) { const editor = { getId: () => editorId, - addCommand(keybinding: number, handler: Parameters[2], context?: string) { - const command = `${editorId}:${keybinding}`; - commands.set(command, handler); - bindings.push({ command, commandArgs: undefined, chords: [String(keybinding)], when: ContextKeyExpr.deserialize(context), isDefault: false, bubble: false }); - return command; + addAction(descriptor: Monaco.editor.IActionDescriptor): Monaco.IDisposable { + assert.equal(descriptor.contextMenuGroupId, undefined, 'contextMenuGroupId must be omitted'); + assert.ok(descriptor.label.trim().length > 0, 'action must provide a non-empty label'); + const uniqueId = `${editorId}:${descriptor.id}`; + const precondition = ContextKeyExpr.and( + ContextKeyExpr.equals('editorId', editorId), + ContextKeyExpr.deserialize(descriptor.precondition), + ); + const keybindingsWhen = ContextKeyExpr.and( + precondition, + ContextKeyExpr.deserialize(descriptor.keybindingContext), + ); + const run = () => { + void descriptor.run(editor as unknown as Monaco.editor.ICodeEditor); + }; + commands.set(uniqueId, run); + const added: RegisteredBinding[] = []; + for (const kb of descriptor.keybindings ?? []) { + const entry: RegisteredBinding = { + command: uniqueId, + commandArgs: undefined, + chords: [String(kb)], + when: keybindingsWhen, + isDefault: false, + bubble: false, + }; + bindings.push(entry); + added.push(entry); + } + let disposed = false; + return { + dispose() { + if (disposed) return; + disposed = true; + actionDisposals.push(descriptor.id); + commands.delete(uniqueId); + for (const entry of added) { + const idx = bindings.indexOf(entry); + if (idx >= 0) bindings.splice(idx, 1); + } + }, + }; + }, + onDidDispose(listener: () => void): Monaco.IDisposable { + disposeListeners.add(listener); + let disposed = false; + return { + dispose() { + if (disposed) return; + disposed = true; + onDidDisposeDisposals += 1; + disposeListeners.delete(listener); + }, + }; + }, + triggerDispose() { + for (const listener of [...disposeListeners]) { + listener(); + } + }, + get stats() { + return { + actionDisposals: [...actionDisposals], + onDidDisposeDisposals, + activeDisposeListeners: disposeListeners.size, + }; }, }; - actions.forEach((action, keybinding) => registerTextEditorCommand(editor, keybinding, () => { calls.push(`${editorId}:${action}`); })); + + return editor; } - const resolver = new KeybindingResolver([], bindings, () => {}); + function press(editorId: string | undefined, keybinding: number) { - const result = resolver.resolve({ getValue: (key: string) => key === 'editorId' ? editorId : undefined }, [], String(keybinding)) as { kind: number; commandId?: string }; - if (result.kind === 2) commands.get(result.commandId!)!(null as never); + const resolver = new KeybindingResolver([], bindings, () => {}); + const result = resolver.resolve( + { getValue: (key: string) => (key === 'editorId' ? editorId : undefined) }, + [], + String(keybinding), + ) as { kind: number; commandId?: string }; + if (result.kind === 2) commands.get(result.commandId!)!(); return result.kind; } + + return { commands, bindings, createEditor, press }; +} + +test('save, close, find and paste actions resolve to the focused editor and unregister cleanly on dispose', () => { + const registry = createStandaloneActionRegistry(); + const calls: string[] = []; + const actions: Array<{ id: string; label: string; name: string }> = [ + { id: 'netcatty.textEditor.save', label: 'Save File', name: 'save' }, + { id: 'netcatty.textEditor.closeTab', label: 'Close Editor Tab', name: 'close' }, + { id: 'netcatty.textEditor.find', label: 'Find', name: 'find' }, + { id: 'netcatty.textEditor.paste', label: 'Paste', name: 'paste' }, + ]; + + const editors = ['vs.editor.ICodeEditor:beta', 'vs.editor.ICodeEditor:alpha'].map((editorId) => { + const editor = registry.createEditor(editorId); + const binding = bindTextEditorActions( + editor, + actions.map((action, keybinding): TextEditorActionConfig => ({ + id: action.id, + label: action.label, + keybinding, + run: () => { + calls.push(`${editorId}:${action.name}`); + }, + })), + ); + return { editorId, editor, binding }; + }); + for (const editorId of ['vs.editor.ICodeEditor:beta', 'vs.editor.ICodeEditor:alpha', 'vs.editor.ICodeEditor:beta']) { actions.forEach((action, keybinding) => { const before = calls.length; - assert.equal(press(editorId, keybinding), 2); - assert.deepEqual(calls.slice(before), [`${editorId}:${action}`]); + assert.equal(registry.press(editorId, keybinding), 2); + assert.deepEqual(calls.slice(before), [`${editorId}:${action.name}`]); }); } + const before = calls.length; - actions.forEach((_, keybinding) => assert.equal(press(undefined, keybinding), 0)); + actions.forEach((_, keybinding) => assert.equal(registry.press(undefined, keybinding), 0)); assert.equal(calls.length, before, 'no hidden editor handles keys outside editor context'); + + // Disposing alpha via editor.onDidDispose removes all 4 commands & keybindings from the registry + assert.equal(registry.commands.size, 8); + assert.equal(registry.bindings.length, 8); + editors[1]!.editor.triggerDispose(); + assert.equal(registry.commands.size, 4); + assert.equal(registry.bindings.length, 4); + assert.equal(editors[1]!.editor.stats.actionDisposals.length, 4); + assert.equal(editors[1]!.editor.stats.onDidDisposeDisposals, 1); + assert.equal(editors[1]!.editor.stats.activeDisposeListeners, 0); + + // Calling React unmount cleanup afterward is an idempotent no-op + editors[1]!.binding.dispose(); + assert.equal(editors[1]!.editor.stats.actionDisposals.length, 4); + assert.equal(editors[1]!.editor.stats.onDidDisposeDisposals, 1); + + // Beta still resolves all 4 shortcuts until React unmount disposes it + actions.forEach((action, keybinding) => { + const start = calls.length; + assert.equal(registry.press('vs.editor.ICodeEditor:beta', keybinding), 2); + assert.deepEqual(calls.slice(start), [`vs.editor.ICodeEditor:beta:${action.name}`]); + }); + + editors[0]!.binding.dispose(); + assert.equal(registry.commands.size, 0, 'all commands must be unregistered after unmount'); + assert.equal(registry.bindings.length, 0, 'all keybindings must be unregistered after unmount'); + assert.equal(editors[0]!.editor.stats.actionDisposals.length, 4); + assert.equal(editors[0]!.editor.stats.onDidDisposeDisposals, 1); + assert.equal(editors[0]!.editor.stats.activeDisposeListeners, 0); }); -test('every TextEditorPane Monaco shortcut uses the scoped registration', () => { +test('Ctrl/Cmd+V paste action still pastes into the Monaco Find/Replace widget when focused', async () => { + const registry = createStandaloneActionRegistry(); + const editor = registry.createEditor('vs.editor.ICodeEditor:find-paste'); + let bodyPasteCount = 0; + const findInput = { + value: 'abc', + selectionStart: 3, + selectionEnd: 3, + closest: (selector: string) => (selector === '.find-widget' ? {} : null), + focus() {}, + setSelectionRange(start: number, end: number) { + this.selectionStart = start; + this.selectionEnd = end; + }, + }; + + let pastePromise: Promise | null = null; + const disposable = registerTextEditorAction(editor, { + id: 'netcatty.textEditor.paste', + label: 'Paste', + keybinding: 42, + run: () => { + pastePromise = pasteForMonacoEditorCommand({ + activeElement: findInput, + readClipboardText: async () => 'XYZ', + pasteIntoEditor: () => { + bodyPasteCount += 1; + }, + }); + }, + }); + + assert.equal(registry.press('vs.editor.ICodeEditor:find-paste', 42), 2); + await pastePromise; + assert.equal(findInput.value, 'abcXYZ'); + assert.equal(bodyPasteCount, 0); + + disposable.dispose(); + assert.equal(registry.commands.size, 0); + assert.equal(registry.bindings.length, 0); +}); + +test('repeated mount/unmount cycles leak zero Monaco commands or keybindings', () => { + const registry = createStandaloneActionRegistry(); + let cleanupCalls = 0; + + for (let i = 0; i < 20; i += 1) { + const editor = registry.createEditor(`vs.editor.ICodeEditor:cycle-${i}`); + const binding = bindTextEditorActions( + editor, + [ + { id: 'netcatty.textEditor.save', label: 'Save File', keybinding: 1, run: () => {} }, + { id: 'netcatty.textEditor.closeTab', label: 'Close Editor Tab', keybinding: 2, run: () => {} }, + { id: 'netcatty.textEditor.find', label: 'Find', keybinding: 3, run: () => {} }, + { id: 'netcatty.textEditor.paste', label: 'Paste', keybinding: 4, run: () => {} }, + ], + () => { + cleanupCalls += 1; + }, + ); + if (i % 2 === 0) { + editor.triggerDispose(); + binding.dispose(); + } else { + binding.dispose(); + editor.triggerDispose(); + } + } + + assert.equal(cleanupCalls, 20); + assert.equal(registry.commands.size, 0); + assert.equal(registry.bindings.length, 0); +}); + +test('every TextEditorPane Monaco shortcut uses disposable bindTextEditorActions without addCommand or contextMenuGroupId', () => { const source = readFileSync(new URL('./TextEditorPane.tsx', import.meta.url), 'utf8'); const mount = source.slice(source.indexOf('const handleEditorMount:'), source.indexOf('// Capture-phase close-tab')); - assert.equal(mount.match(/registerTextEditorCommand\(editor,/g)?.length, 4); - assert.doesNotMatch(mount, /editor\.addCommand\(/); + assert.match(mount, /actionBindingRef\.current\?\.dispose\(\);/); + assert.match(mount, /bindTextEditorActions\(/); + assert.equal(mount.match(/id:\s*'netcatty\.textEditor\.(?:save|closeTab|find|paste)'/g)?.length, 4); + assert.doesNotMatch(source, /\.addCommand\(/); + assert.doesNotMatch(source, /contextMenuGroupId\s*:/); }); diff --git a/components/editor/TextEditorPane.tsx b/components/editor/TextEditorPane.tsx index 5b38eac42..3c5772f44 100644 --- a/components/editor/TextEditorPane.tsx +++ b/components/editor/TextEditorPane.tsx @@ -112,13 +112,65 @@ export interface TextEditorPaneProps { initialViewState?: Monaco.editor.ICodeEditorViewState | null; } -/** Monaco commands share a window-level resolver; bind each to its owning editor. */ -export function registerTextEditorCommand( - editor: Pick, - keybinding: number, - handler: Monaco.editor.ICommandHandler, -): string | null { - return editor.addCommand(keybinding, handler, `editorId == '${editor.getId()}'`); +export interface TextEditorActionConfig { + id: string; + label: string; + keybinding: number; + run: () => void; +} + +/** + * Register a disposable Monaco editor action instead of `editor.addCommand` + * (which drops the keybinding disposable in Monaco's global registry). + * `addAction` auto-scopes keybindings to `editorId == editor.getId()`, and + * omitting `contextMenuGroupId` keeps the editor context menu untouched. + */ +export function registerTextEditorAction( + editor: Pick, + { id, label, keybinding, run }: TextEditorActionConfig, +): Monaco.IDisposable { + return editor.addAction({ + id, + label, + keybindings: [keybinding], + run: () => { + run(); + }, + }); +} + +export function bindTextEditorActions( + editor: Pick, + actions: readonly TextEditorActionConfig[], + onCleanup?: () => void, +): Monaco.IDisposable { + const disposables: Monaco.IDisposable[] = []; + let disposed = false; + + const dispose = () => { + if (disposed) return; + disposed = true; + for (const handle of disposables.splice(0)) { + try { + handle.dispose(); + } catch { + // Best-effort cleanup during editor teardown. + } + } + onCleanup?.(); + }; + + try { + for (const action of actions) { + disposables.push(registerTextEditorAction(editor, action)); + } + disposables.push(editor.onDidDispose(dispose)); + } catch (error) { + dispose(); + throw error; + } + + return { dispose }; } export const isTextEditorReadOnly = ({ saving }: { saving: boolean }): boolean => saving; @@ -198,6 +250,13 @@ const TextEditorPaneInner: React.FC = ({ const monaco = useMonaco(); const customThemeName = useNetcattyMonacoTheme(monaco); const editorRef = useRef(null); + const actionBindingRef = useRef(null); + + useEffect(() => () => { + actionBindingRef.current?.dispose(); + actionBindingRef.current = null; + editorRef.current = null; + }, []); // Ref to store the latest save function to avoid stale closure in keyboard shortcut const handleSaveRef = useRef<() => void>(() => {}); @@ -296,39 +355,73 @@ const TextEditorPaneInner: React.FC = ({ }, [onContentChange, saving]); const handleEditorMount: OnMount = useCallback((editor, monaco) => { + actionBindingRef.current?.dispose(); + actionBindingRef.current = null; editorRef.current = editor; if (initialViewState) editor.restoreViewState(initialViewState); - // Add save shortcut - use ref to avoid stale closure - registerTextEditorCommand(editor, monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS, () => { - handleSaveRef.current(); - }); - - // Close-tab shortcut inside Monaco. The capture-phase keydown on the - // Pane's root div also tries to handle this, but Monaco's internal - // key-event dispatcher fires first for focused editor keystrokes, so - // registering the command here is the reliable path. - registerTextEditorCommand(editor, monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyW, () => { - if (!closeTabCommandWEnabledRef.current) return; - handleCloseRef.current?.(); - }); - - // Add find shortcut (Ctrl+F / Cmd+F) - registerTextEditorCommand(editor, monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyF, () => { - // Trigger Monaco's built-in find widget - editor.trigger('keyboard', 'actions.find', null); - }); - - // Fallback paste path for Electron environments where Monaco paste can fail. - // When focus is in the find/replace widget, paste into that input instead of the body. - registerTextEditorCommand(editor, monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyV, () => { - void pasteForMonacoEditorCommand({ - activeElement: document.activeElement, - readClipboardText: () => readClipboardTextRef.current(), - pasteIntoEditor: () => handlePasteRef.current(), - }); - }); + let binding: Monaco.IDisposable | null = null; + binding = bindTextEditorActions( + editor, + [ + // Add save shortcut - use ref to avoid stale closure + { + id: 'netcatty.textEditor.save', + label: 'Save File', + keybinding: monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS, + run: () => { + handleSaveRef.current(); + }, + }, + // Close-tab shortcut inside Monaco. The capture-phase keydown on the + // Pane's root div also tries to handle this, but Monaco's internal + // key-event dispatcher fires first for focused editor keystrokes, so + // registering the action here is the reliable path. + { + id: 'netcatty.textEditor.closeTab', + label: 'Close Editor Tab', + keybinding: monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyW, + run: () => { + if (!closeTabCommandWEnabledRef.current) return; + handleCloseRef.current?.(); + }, + }, + // Add find shortcut (Ctrl+F / Cmd+F) + { + id: 'netcatty.textEditor.find', + label: 'Find', + keybinding: monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyF, + run: () => { + // Trigger Monaco's built-in find widget + editor.trigger('keyboard', 'actions.find', null); + }, + }, + // Fallback paste path for Electron environments where Monaco paste can fail. + // When focus is in the find/replace widget, paste into that input instead of the body. + { + id: 'netcatty.textEditor.paste', + label: 'Paste', + keybinding: monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyV, + run: () => { + void pasteForMonacoEditorCommand({ + activeElement: document.activeElement, + readClipboardText: () => readClipboardTextRef.current(), + pasteIntoEditor: () => handlePasteRef.current(), + }); + }, + }, + ], + () => { + if (actionBindingRef.current === binding) { + actionBindingRef.current = null; + } + if (editorRef.current === editor) { + editorRef.current = null; + } + }, + ); + actionBindingRef.current = binding; editor.focus(); }, [initialViewState]); diff --git a/components/scripts/ScriptCodeEditor.shortcuts.test.ts b/components/scripts/ScriptCodeEditor.shortcuts.test.ts new file mode 100644 index 000000000..d7090b116 --- /dev/null +++ b/components/scripts/ScriptCodeEditor.shortcuts.test.ts @@ -0,0 +1,153 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { readFileSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import type * as Monaco from 'monaco-editor'; +const require = createRequire(import.meta.url); +const { ContextKeyExpr } = require('monaco-editor/esm/vs/platform/contextkey/common/contextkey.js'); +const { KeybindingResolver } = require('monaco-editor/esm/vs/platform/keybinding/common/keybindingResolver.js'); +import { bindScriptEditorActions } from './ScriptCodeEditor.tsx'; + +type RegisteredBinding = { + command: string; + commandArgs: undefined; + chords: string[]; + when: ReturnType; + isDefault: boolean; + bubble: boolean; +}; + +test('bindScriptEditorActions scopes actions per editor and disposes all handles on onDidDispose and unmount', () => { + const commands = new Map void>(); + const bindings: RegisteredBinding[] = []; + + function createEditor(editorId: string) { + const disposeListeners = new Set<() => void>(); + let actionDisposals = 0; + let onDidDisposeDisposals = 0; + + return { + addAction(descriptor: Monaco.editor.IActionDescriptor) { + assert.equal(descriptor.contextMenuGroupId, undefined, 'contextMenuGroupId must be omitted'); + assert.ok(descriptor.label.trim().length > 0, 'action must provide a non-empty label'); + const uniqueId = `${editorId}:${descriptor.id}`; + const when = ContextKeyExpr.equals('editorId', editorId); + commands.set(uniqueId, () => { + void descriptor.run({} as Monaco.editor.ICodeEditor); + }); + const added: RegisteredBinding[] = []; + for (const kb of descriptor.keybindings ?? []) { + const entry: RegisteredBinding = { + command: uniqueId, + commandArgs: undefined, + chords: [String(kb)], + when, + isDefault: false, + bubble: false, + }; + bindings.push(entry); + added.push(entry); + } + let disposed = false; + return { + dispose() { + if (disposed) return; + disposed = true; + actionDisposals += 1; + commands.delete(uniqueId); + for (const entry of added) { + const idx = bindings.indexOf(entry); + if (idx >= 0) bindings.splice(idx, 1); + } + }, + }; + }, + onDidDispose(listener: () => void) { + disposeListeners.add(listener); + let disposed = false; + return { + dispose() { + if (disposed) return; + disposed = true; + onDidDisposeDisposals += 1; + disposeListeners.delete(listener); + }, + }; + }, + triggerDispose() { + for (const listener of [...disposeListeners]) listener(); + }, + get stats() { + return { actionDisposals, onDidDisposeDisposals, activeListeners: disposeListeners.size }; + }, + }; + } + + const calls: string[] = []; + const editorA = createEditor('script:a'); + const editorB = createEditor('script:b'); + let cleanupsA = 0; + let cleanupsB = 0; + + const bindingA = bindScriptEditorActions( + editorA, + [ + { id: 'netcatty.scriptEditor.submit', label: 'Submit Script', keybinding: 10, run: () => calls.push('a:submit') }, + { id: 'netcatty.scriptEditor.paste', label: 'Paste', keybinding: 20, run: () => calls.push('a:paste') }, + ], + () => { cleanupsA += 1; }, + ); + const bindingB = bindScriptEditorActions( + editorB, + [ + { id: 'netcatty.scriptEditor.paste', label: 'Paste', keybinding: 20, run: () => calls.push('b:paste') }, + ], + () => { cleanupsB += 1; }, + ); + + const press = (editorId: string, kb: number) => { + const resolver = new KeybindingResolver([], bindings, () => {}); + const res = resolver.resolve( + { getValue: (key: string) => (key === 'editorId' ? editorId : undefined) }, + [], + String(kb), + ) as { kind: number; commandId?: string }; + if (res.kind === 2) commands.get(res.commandId!)!(); + return res.kind; + }; + + assert.equal(press('script:a', 10), 2); + assert.equal(press('script:a', 20), 2); + assert.equal(press('script:b', 20), 2); + assert.deepEqual(calls, ['a:submit', 'a:paste', 'b:paste']); + + // Dispose A via editor.onDidDispose + editorA.triggerDispose(); + bindingA.dispose(); + assert.equal(cleanupsA, 1); + assert.equal(editorA.stats.actionDisposals, 2); + assert.equal(editorA.stats.onDidDisposeDisposals, 1); + assert.equal(editorA.stats.activeListeners, 0); + assert.equal(commands.size, 1); + assert.equal(bindings.length, 1); + + // Dispose B via React unmount before onDidDispose + bindingB.dispose(); + editorB.triggerDispose(); + assert.equal(cleanupsB, 1); + assert.equal(editorB.stats.actionDisposals, 1); + assert.equal(editorB.stats.onDidDisposeDisposals, 1); + assert.equal(editorB.stats.activeListeners, 0); + assert.equal(commands.size, 0); + assert.equal(bindings.length, 0); +}); + +test('ScriptCodeEditor uses disposable bindScriptEditorActions without addCommand or contextMenuGroupId', () => { + const source = readFileSync(new URL('./ScriptCodeEditor.tsx', import.meta.url), 'utf8'); + assert.match(source, /actionBindingRef\.current\?\.dispose\(\);/); + assert.match(source, /bindScriptEditorActions\(/); + assert.match(source, /id:\s*'netcatty\.scriptEditor\.submit'/); + assert.match(source, /id:\s*'netcatty\.scriptEditor\.paste'/); + assert.doesNotMatch(source, /\.addCommand\(/); + assert.doesNotMatch(source, /contextMenuGroupId\s*:/); +}); diff --git a/components/scripts/ScriptCodeEditor.tsx b/components/scripts/ScriptCodeEditor.tsx index b4c78f9c7..6a74cbbf8 100644 --- a/components/scripts/ScriptCodeEditor.tsx +++ b/components/scripts/ScriptCodeEditor.tsx @@ -43,6 +43,62 @@ export interface ScriptCodeEditorHandle { focus: () => void; } +export interface ScriptEditorActionConfig { + id: string; + label: string; + keybinding: number; + run: () => void; +} + +type ScriptEditorActionHost = Pick[0], 'addAction' | 'onDidDispose'>; + +/** + * Register disposable Monaco editor actions for ScriptCodeEditor instead of + * `editor.addCommand` (which leaks keybindings in Monaco's global registry). + * `addAction` auto-scopes to `editorId == editor.getId()`, and omitting + * `contextMenuGroupId` keeps the context menu clean. + */ +export function bindScriptEditorActions( + editor: ScriptEditorActionHost, + actions: readonly ScriptEditorActionConfig[], + onCleanup?: () => void, +): { dispose: () => void } { + const disposables: Array<{ dispose: () => void }> = []; + let disposed = false; + + const dispose = () => { + if (disposed) return; + disposed = true; + for (const handle of disposables.splice(0)) { + try { + handle.dispose(); + } catch { + // Best-effort cleanup during editor teardown. + } + } + onCleanup?.(); + }; + + try { + for (const { id, label, keybinding, run } of actions) { + disposables.push(editor.addAction({ + id, + label, + keybindings: [keybinding], + run: () => { + run(); + }, + })); + } + disposables.push(editor.onDidDispose(dispose)); + } catch (error) { + dispose(); + throw error; + } + + return { dispose }; +} + export const ScriptCodeEditor = React.forwardRef(({ value, onChange, @@ -61,6 +117,7 @@ export const ScriptCodeEditor = React.forwardRef(null); + const actionBindingRef = useRef<{ dispose: () => void } | null>(null); const completionDisposableRef = useRef<{ dispose: () => void } | null>(null); const onSubmitShortcutRef = useRef(onSubmitShortcut); onSubmitShortcutRef.current = onSubmitShortcut; @@ -72,8 +129,11 @@ export const ScriptCodeEditor = React.forwardRef () => { + actionBindingRef.current?.dispose(); + actionBindingRef.current = null; completionDisposableRef.current?.dispose(); completionDisposableRef.current = null; + editorRef.current = null; }, []); useEffect(() => { @@ -122,29 +182,51 @@ export const ScriptCodeEditor = React.forwardRef { + actionBindingRef.current?.dispose(); + actionBindingRef.current = null; editorRef.current = editor; completionDisposableRef.current?.dispose(); completionDisposableRef.current = language === 'javascript' ? registerNctMonacoCompletionProvider(monacoInstance) : null; + + const actions: ScriptEditorActionConfig[] = []; if (onSubmitShortcut) { - editor.addCommand( - monacoInstance.KeyMod.CtrlCmd | monacoInstance.KeyCode.Enter, - () => onSubmitShortcutRef.current?.(), - ); + actions.push({ + id: 'netcatty.scriptEditor.submit', + label: 'Submit Script', + keybinding: monacoInstance.KeyMod.CtrlCmd | monacoInstance.KeyCode.Enter, + run: () => { + onSubmitShortcutRef.current?.(); + }, + }); } // Fallback paste path for Electron where Monaco clipboardPasteAction can fail. // When focus is in the find/replace widget, paste into that input instead of the body. - editor.addCommand( - monacoInstance.KeyMod.CtrlCmd | monacoInstance.KeyCode.KeyV, - () => { + actions.push({ + id: 'netcatty.scriptEditor.paste', + label: 'Paste', + keybinding: monacoInstance.KeyMod.CtrlCmd | monacoInstance.KeyCode.KeyV, + run: () => { void pasteForMonacoEditorCommand({ activeElement: document.activeElement, readClipboardText: () => readClipboardTextRef.current(), pasteIntoEditor: () => handlePasteRef.current(), }); }, - ); + }); + + let binding: { dispose: () => void } | null = null; + binding = bindScriptEditorActions(editor, actions, () => { + if (actionBindingRef.current === binding) { + actionBindingRef.current = null; + } + if (editorRef.current === editor) { + editorRef.current = null; + } + }); + actionBindingRef.current = binding; + requestAnimationFrame(() => editor.layout()); if (autoFocus) editor.focus(); }, [autoFocus, language, onSubmitShortcut]);