From 07cdde79762be467cae1f8de6dd0c8cf8ed552a1 Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Fri, 12 Dec 2025 03:33:56 +0800 Subject: [PATCH] Refactors hotkey handling for unified app-terminal actions Centralizes hotkey action logic to enable consistent shortcut behavior across both app-level and terminal contexts. Improves maintainability and extensibility by introducing a shared hotkey action handler and callback prop, reducing code duplication and streamlining future shortcut feature development. --- App.tsx | 231 ++-- components/SettingsDialog.tsx | 1098 ++++++++--------- components/Terminal.tsx | 124 +- components/TerminalLayer.tsx | 3 + components/keychain/GenerateStandardPanel.tsx | 4 +- 5 files changed, 748 insertions(+), 712 deletions(-) diff --git a/App.tsx b/App.tsx index 1cc8c0845..9e682538d 100755 --- a/App.tsx +++ b/App.tsx @@ -118,6 +118,122 @@ function App() { // isMacClient is used for window controls styling const isMacClient = typeof navigator !== 'undefined' && /Mac|Macintosh/.test(navigator.userAgent); + // Shared hotkey action handler - used by both global handler and terminal callback + const executeHotkeyAction = useCallback((action: string, e: KeyboardEvent) => { + switch (action) { + case 'switchToTab': { + // Get the number key pressed (1-9) + const num = parseInt(e.key, 10); + if (num >= 1 && num <= 9) { + // Build complete tab list: vault + sessions/workspaces + const allTabs = ['vault', ...orderedTabs]; + if (num <= allTabs.length) { + setActiveTabId(allTabs[num - 1]); + } + } + break; + } + case 'nextTab': { + // Build complete tab list: vault + sessions/workspaces + const allTabs = ['vault', ...orderedTabs]; + const currentId = activeTabStore.getActiveTabId(); + const currentIdx = allTabs.indexOf(currentId); + if (currentIdx !== -1 && allTabs.length > 0) { + const nextIdx = (currentIdx + 1) % allTabs.length; + setActiveTabId(allTabs[nextIdx]); + } else if (allTabs.length > 0) { + setActiveTabId(allTabs[0]); + } + break; + } + case 'prevTab': { + // Build complete tab list: vault + sessions/workspaces + const allTabs = ['vault', ...orderedTabs]; + const currentId = activeTabStore.getActiveTabId(); + const currentIdx = allTabs.indexOf(currentId); + if (currentIdx !== -1 && allTabs.length > 0) { + const prevIdx = (currentIdx - 1 + allTabs.length) % allTabs.length; + setActiveTabId(allTabs[prevIdx]); + } else if (allTabs.length > 0) { + setActiveTabId(allTabs[allTabs.length - 1]); + } + break; + } + case 'closeTab': { + const currentId = activeTabStore.getActiveTabId(); + if (currentId !== 'vault' && currentId !== 'sftp') { + // Find if it's a session or workspace + const session = sessions.find(s => s.id === currentId); + if (session) { + closeSession(currentId); + } else { + const workspace = workspaces.find(w => w.id === currentId); + if (workspace) { + closeWorkspace(currentId); + } + } + } + break; + } + case 'newTab': + case 'openLocal': + createLocalTerminal(); + break; + case 'openHosts': + setActiveTabId('vault'); + break; + case 'openSftp': + setActiveTabId('sftp'); + break; + case 'quickSwitch': + case 'commandPalette': + setIsQuickSwitcherOpen(true); + break; + case 'portForwarding': + // Navigate to vault and could open port forwarding section + setActiveTabId('vault'); + break; + case 'snippets': + // Navigate to vault + setActiveTabId('vault'); + break; + case 'broadcast': + // TODO: Implement broadcast mode toggle + console.log('[Hotkey] Broadcast mode toggle requested'); + break; + case 'sidePanel': + // TODO: Implement side panel toggle + console.log('[Hotkey] Side panel toggle requested'); + break; + case 'splitHorizontal': + // TODO: Implement horizontal split + console.log('[Hotkey] Split horizontal requested'); + break; + case 'splitVertical': + // TODO: Implement vertical split + console.log('[Hotkey] Split vertical requested'); + break; + case 'moveFocus': { + // Move focus between split panes + const direction = e.key === 'ArrowUp' ? 'up' + : e.key === 'ArrowDown' ? 'down' + : e.key === 'ArrowLeft' ? 'left' + : e.key === 'ArrowRight' ? 'right' + : null; + if (direction) { + console.log(`[Hotkey] Move focus ${direction}`); + // TODO: Implement focus movement in workspace + } + break; + } + } + }, [orderedTabs, sessions, workspaces, setActiveTabId, closeSession, closeWorkspace, createLocalTerminal]); + + // Callback for terminal to invoke app-level hotkey actions + const handleHotkeyAction = useCallback((action: string, e: KeyboardEvent) => { + executeHotkeyAction(action, e); + }, [executeHotkeyAction]); + // Global hotkey handler useEffect(() => { if (hotkeyScheme === 'disabled') return; @@ -129,7 +245,7 @@ function App() { // Note: xterm terminal handles its own key interception via attachCustomKeyEventHandler const target = e.target as HTMLElement; const isFormElement = target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable; - + if (isFormElement && e.key !== 'Escape') { return; } @@ -147,115 +263,7 @@ function App() { e.preventDefault(); e.stopPropagation(); - - // Execute the action - switch (binding.action) { - case 'switchToTab': { - // Get the number key pressed (1-9) - const num = parseInt(e.key, 10); - if (num >= 1 && num <= 9) { - // Build complete tab list: vault + sessions/workspaces - const allTabs = ['vault', ...orderedTabs]; - if (num <= allTabs.length) { - setActiveTabId(allTabs[num - 1]); - } - } - break; - } - case 'nextTab': { - // Build complete tab list: vault + sessions/workspaces - const allTabs = ['vault', ...orderedTabs]; - const currentId = activeTabStore.getActiveTabId(); - const currentIdx = allTabs.indexOf(currentId); - if (currentIdx !== -1 && allTabs.length > 0) { - const nextIdx = (currentIdx + 1) % allTabs.length; - setActiveTabId(allTabs[nextIdx]); - } else if (allTabs.length > 0) { - setActiveTabId(allTabs[0]); - } - break; - } - case 'prevTab': { - // Build complete tab list: vault + sessions/workspaces - const allTabs = ['vault', ...orderedTabs]; - const currentId = activeTabStore.getActiveTabId(); - const currentIdx = allTabs.indexOf(currentId); - if (currentIdx !== -1 && allTabs.length > 0) { - const prevIdx = (currentIdx - 1 + allTabs.length) % allTabs.length; - setActiveTabId(allTabs[prevIdx]); - } else if (allTabs.length > 0) { - setActiveTabId(allTabs[allTabs.length - 1]); - } - break; - } - case 'closeTab': { - const currentId = activeTabStore.getActiveTabId(); - if (currentId !== 'vault' && currentId !== 'sftp') { - // Find if it's a session or workspace - const session = sessions.find(s => s.id === currentId); - if (session) { - closeSession(currentId); - } else { - const workspace = workspaces.find(w => w.id === currentId); - if (workspace) { - closeWorkspace(currentId); - } - } - } - break; - } - case 'newTab': - case 'openLocal': - createLocalTerminal(); - break; - case 'openHosts': - setActiveTabId('vault'); - break; - case 'openSftp': - setActiveTabId('sftp'); - break; - case 'quickSwitch': - case 'commandPalette': - setIsQuickSwitcherOpen(true); - break; - case 'portForwarding': - // Navigate to vault and could open port forwarding section - setActiveTabId('vault'); - break; - case 'snippets': - // Navigate to vault - setActiveTabId('vault'); - break; - case 'broadcast': - // TODO: Implement broadcast mode toggle - console.log('[Hotkey] Broadcast mode toggle requested'); - break; - case 'sidePanel': - // TODO: Implement side panel toggle - console.log('[Hotkey] Side panel toggle requested'); - break; - case 'splitHorizontal': - // TODO: Implement horizontal split - console.log('[Hotkey] Split horizontal requested'); - break; - case 'splitVertical': - // TODO: Implement vertical split - console.log('[Hotkey] Split vertical requested'); - break; - case 'moveFocus': { - // Move focus between split panes - const direction = e.key === 'ArrowUp' ? 'up' - : e.key === 'ArrowDown' ? 'down' - : e.key === 'ArrowLeft' ? 'left' - : e.key === 'ArrowRight' ? 'right' - : null; - if (direction) { - console.log(`[Hotkey] Move focus ${direction}`); - // TODO: Implement focus movement in workspace - } - break; - } - } + executeHotkeyAction(binding.action, e); return; } } @@ -263,7 +271,7 @@ function App() { window.addEventListener('keydown', handleGlobalKeyDown, true); return () => window.removeEventListener('keydown', handleGlobalKeyDown, true); - }, [hotkeyScheme, keyBindings, orderedTabs, sessions, workspaces, setActiveTabId, closeSession, closeWorkspace, createLocalTerminal]); + }, [hotkeyScheme, keyBindings, executeHotkeyAction]); useEffect(() => { const onKeyDown = (e: KeyboardEvent) => { @@ -412,6 +420,7 @@ function App() { fontSize={terminalFontSize} hotkeyScheme={hotkeyScheme} keyBindings={keyBindings} + onHotkeyAction={handleHotkeyAction} onCloseSession={closeSession} onUpdateSessionStatus={updateSessionStatus} onUpdateHostDistro={updateHostDistro} diff --git a/components/SettingsDialog.tsx b/components/SettingsDialog.tsx index 95f7879a8..42e4df466 100644 --- a/components/SettingsDialog.tsx +++ b/components/SettingsDialog.tsx @@ -254,25 +254,25 @@ const SettingsDialog: React.FC = ({ // Handle key recording for shortcut editing const handleKeyDown = useCallback((e: KeyboardEvent) => { if (!editingBindingId) return; - + e.preventDefault(); e.stopPropagation(); - + const keyStr = keyEventToString(e, isMac); - + // If it's just modifier keys, keep waiting if (['Meta', 'Control', 'Alt', 'Shift'].includes(e.key)) { setRecordedKey(keyStr); return; } - + // Complete key combination recorded setRecordedKey(keyStr); }, [editingBindingId, isMac]); const handleKeyUp = useCallback((e: KeyboardEvent) => { if (!editingBindingId || !recordedKey) return; - + // If we have a complete key combo (not just modifiers), save it if (!['Meta', 'Control', 'Alt', 'Shift'].includes(e.key)) { // Recorded key is complete, will be saved on blur or confirm @@ -474,567 +474,567 @@ const SettingsDialog: React.FC = ({ {/* Content Area */}
- {/* Appearance Tab */} - - -
- onThemeChange("light")} - icon={} - label="Light" - /> - onThemeChange("dark")} - icon={} - label="Dark" - /> -
+ {/* Appearance Tab */} + + +
+ onThemeChange("light")} + icon={} + label="Light" + /> + onThemeChange("dark")} + icon={} + label="Dark" + /> +
- -
- {COLORS.map((c) => ( - - ))} -
-
- - {/* Terminal Tab - Redesigned */} - - {/* Color Scheme Section */} - -
- {TERMINAL_THEMES.map((t) => ( - onTerminalThemeChange(t.id)} - /> - ))} -
- - {/* Font Section */} - -
- - { - const val = parseInt(e.target.value); - if (val >= MIN_FONT_SIZE && val <= MAX_FONT_SIZE) { - onTerminalFontSizeChange?.(val); - } - }} - className="w-20 text-center" + +
+ {COLORS.map((c) => ( +
-
+ )} + + ))} +
+
- - onTerminalSettingsChange?.('fontLigatures', v)} - /> - + {/* Terminal Tab - Redesigned */} + + {/* Color Scheme Section */} + +
+ {TERMINAL_THEMES.map((t) => ( + onTerminalThemeChange(t.id)} + /> + ))} +
- - onTerminalSettingsChange?.('fontWeightBold', v)} - className="w-44" - /> - - - - onTerminalSettingsChange?.('linePadding', parseInt(e.target.value) || 0)} - className="w-20 text-center" - /> - - - - onTerminalSettingsChange?.('fallbackFont', e.target.value)} - placeholder="e.g., Noto Sans" - className="w-44" - /> - -
- - {/* Cursor Section */} - -
- -
- {(['block', 'bar', 'underline'] as CursorShape[]).map((shape) => ( - - ))} -
-
- - - onTerminalSettingsChange?.('cursorBlink', v)} - /> - -
- - {/* Rendering Section */} - -
- - onTerminalSettingsChange?.('scrollback', parseInt(e.target.value) || 10000)} - className="w-28 text-center" - /> - - - - onTerminalSettingsChange?.('drawBoldInBrightColors', v)} - /> - - - - onTerminalSettingsChange?.('minimumContrastRatio', parseFloat(e.target.value) || 1)} - className="w-20 text-center" - /> - -
- - {/* Keyboard Section */} - -
- - onTerminalSettingsChange?.('altAsMeta', v)} - /> - - - - onTerminalSettingsChange?.('scrollOnInput', v)} - /> - -
- - {/* Mouse Section */} - -
- - onTerminalSettingsChange?.('wordSeparators', e.target.value)} - className="w-32 font-mono" - /> - - - - onHotkeySchemeChange?.(v)} + value={terminalFontFamilyId} + options={TERMINAL_FONTS.map(f => ({ value: f.id, label: f.name }))} + onChange={(id) => onTerminalFontFamilyChange?.(id)} className="w-44" /> - {hotkeyScheme !== 'disabled' && ( - - )} -
+ - {hotkeyScheme !== 'disabled' && ( - <> - {/* Shortcuts Table Header */} -
-
Shortcut
-
Action
-
- - {/* Shortcuts List */} -
- {keyBindings.map((binding) => { - const shortcut = hotkeyScheme === 'mac' ? binding.mac : binding.pc; - const isDisabled = shortcut === 'Disabled'; - const isEditing = editingBindingId === binding.id; - - return ( -
-
- {isEditing ? ( -
-
- {recordedKey || 'Press keys...'} -
- - -
- ) : ( -
startEditing(binding.id)} - > - {isDisabled ? ( - Disabled - ) : ( - - )} -
- )} -
-
- - {binding.label} - - {!isEditing && ( -
- - -
- )} -
-
- ); - })} -
- - )} - - {hotkeyScheme === 'disabled' && ( -
- -

Keyboard shortcuts are disabled

-

Select a hotkey scheme above to enable

-
- )} - - - {/* Sync Tab */} - -
- -
-

GitHub Gist Sync

-

- Backup and sync your hosts, keys, and snippets across - devices securely using a private GitHub Gist. -

-
-
- -
-
- + +
setGithubToken(e.target.value)} - className="font-mono" - /> -

- Token needs gist scope. -

-
-
- - setGistId(e.target.value)} - className="font-mono" + type="number" + min={MIN_FONT_SIZE} + max={MAX_FONT_SIZE} + value={terminalFontSize} + onChange={(e) => { + const val = parseInt(e.target.value); + if (val >= MIN_FONT_SIZE && val <= MAX_FONT_SIZE) { + onTerminalFontSizeChange?.(val); + } + }} + className="w-20 text-center" />
-
- -
-
+ - {syncConfig?.githubToken && ( - <> - -
- - -
- {syncConfig.lastSync && ( -

- Last Sync:{" "} - {new Date(syncConfig.lastSync).toLocaleString()} -

- )} - - )} - - - {/* Data Tab */} - -
-

- Export Data -

-

- Download a JSON file containing all your hosts, keys, and - snippets. -

- -
- -
-

- Import Data -

-

- Restore your configuration from a previously exported JSON - file. -

-