diff --git a/App.tsx b/App.tsx index 61f71d570..1cc8c0845 100755 --- a/App.tsx +++ b/App.tsx @@ -1,8 +1,9 @@ import React, { useCallback, useEffect, useMemo, useState } from 'react'; -import { useIsVaultActive } from './application/state/activeTabStore'; +import { activeTabStore, useIsVaultActive } from './application/state/activeTabStore'; import { useSessionState } from './application/state/useSessionState'; import { useSettingsState } from './application/state/useSettingsState'; import { useVaultState } from './application/state/useVaultState'; +import { matchesKeyBinding } from './domain/models'; import ProtocolSelectDialog from './components/ProtocolSelectDialog'; import { QuickSwitcher } from './components/QuickSwitcher'; import SettingsDialog from './components/SettingsDialog'; @@ -57,6 +58,12 @@ function App() { setTerminalFontSize, terminalSettings, updateTerminalSetting, + hotkeyScheme, + setHotkeyScheme, + keyBindings, + updateKeyBinding, + resetKeyBinding, + resetAllKeyBindings, } = useSettingsState(); const { @@ -111,6 +118,153 @@ function App() { // isMacClient is used for window controls styling const isMacClient = typeof navigator !== 'undefined' && /Mac|Macintosh/.test(navigator.userAgent); + // Global hotkey handler + useEffect(() => { + if (hotkeyScheme === 'disabled') return; + + const isMac = hotkeyScheme === 'mac'; + + const handleGlobalKeyDown = (e: KeyboardEvent) => { + // Don't handle if we're in an input or textarea (except for Escape) + // 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; + } + + // Check each key binding + for (const binding of keyBindings) { + const keyStr = isMac ? binding.mac : binding.pc; + if (matchesKeyBinding(e, keyStr, isMac)) { + // Terminal-specific actions should be handled by the terminal + // Don't handle them at app level + const terminalActions = ['copy', 'paste', 'selectAll', 'clearBuffer', 'searchTerminal']; + if (terminalActions.includes(binding.action)) { + return; // Let terminal handle it + } + + 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; + } + } + return; + } + } + }; + + window.addEventListener('keydown', handleGlobalKeyDown, true); + return () => window.removeEventListener('keydown', handleGlobalKeyDown, true); + }, [hotkeyScheme, keyBindings, orderedTabs, sessions, workspaces, setActiveTabId, closeSession, closeWorkspace, createLocalTerminal]); + useEffect(() => { const onKeyDown = (e: KeyboardEvent) => { if (e.key === 'Escape' && isQuickSwitcherOpen) { @@ -256,6 +410,8 @@ function App() { draggingSessionId={draggingSessionId} terminalTheme={currentTerminalTheme} fontSize={terminalFontSize} + hotkeyScheme={hotkeyScheme} + keyBindings={keyBindings} onCloseSession={closeSession} onUpdateSessionStatus={updateSessionStatus} onUpdateHostDistro={updateHostDistro} @@ -347,6 +503,12 @@ function App() { onTerminalFontSizeChange={setTerminalFontSize} terminalSettings={terminalSettings} onTerminalSettingsChange={updateTerminalSetting} + hotkeyScheme={hotkeyScheme} + onHotkeySchemeChange={setHotkeyScheme} + keyBindings={keyBindings} + onUpdateKeyBinding={updateKeyBinding} + onResetKeyBinding={resetKeyBinding} + onResetAllKeyBindings={resetAllKeyBindings} /> {/* Protocol Select Dialog for QuickSwitcher */} diff --git a/application/state/useGlobalHotkeys.ts b/application/state/useGlobalHotkeys.ts new file mode 100644 index 000000000..10598904a --- /dev/null +++ b/application/state/useGlobalHotkeys.ts @@ -0,0 +1,246 @@ +import { useCallback, useEffect, useRef } from 'react'; +import { KeyBinding, matchesKeyBinding } from '../../domain/models'; +import { activeTabStore } from './activeTabStore'; + +export interface HotkeyActions { + // Tab management + switchToTab: (tabIndex: number) => void; + nextTab: () => void; + prevTab: () => void; + closeTab: () => void; + newTab: () => void; + + // Navigation + openHosts: () => void; + openSftp: () => void; + quickSwitch: () => void; + commandPalette: () => void; + portForwarding: () => void; + snippets: () => void; + + // Terminal actions (handled per-terminal) + copy: () => void; + paste: () => void; + selectAll: () => void; + clearBuffer: () => void; + searchTerminal: () => void; + + // Workspace/split actions + splitHorizontal: () => void; + splitVertical: () => void; + moveFocus: (direction: 'up' | 'down' | 'left' | 'right') => void; + + // App features + broadcast: () => void; + sidePanel: () => void; + openLocal: () => void; +} + +// Check if keyboard event matches our app-level shortcuts +// Returns the matched binding action or null +export const checkAppShortcut = ( + e: KeyboardEvent, + keyBindings: KeyBinding[], + isMac: boolean +): { action: string; binding: KeyBinding } | null => { + for (const binding of keyBindings) { + const keyStr = isMac ? binding.mac : binding.pc; + if (matchesKeyBinding(e, keyStr, isMac)) { + return { action: binding.action, binding }; + } + } + return null; +}; + +// Get list of key bindings that should be handled at app level (not by terminal) +export const getAppLevelActions = (): Set => { + return new Set([ + 'switchToTab', + 'nextTab', + 'prevTab', + 'closeTab', + 'newTab', + 'openHosts', + 'openSftp', + 'quickSwitch', + 'commandPalette', + 'portForwarding', + 'snippets', + 'splitHorizontal', + 'splitVertical', + 'moveFocus', + 'broadcast', + 'sidePanel', + 'openLocal', + ]); +}; + +// Terminal-level actions that xterm should not intercept +export const getTerminalPassthroughActions = (): Set => { + return new Set([ + 'copy', + 'paste', + 'selectAll', + 'clearBuffer', + 'searchTerminal', + ]); +}; + +interface UseGlobalHotkeysOptions { + hotkeyScheme: 'disabled' | 'mac' | 'pc'; + keyBindings: KeyBinding[]; + actions: Partial; + orderedTabs: string[]; + sessions: { id: string }[]; + workspaces: { id: string }[]; + isSettingsOpen?: boolean; +} + +export const useGlobalHotkeys = ({ + hotkeyScheme, + keyBindings, + actions, + orderedTabs, + sessions, + workspaces, + isSettingsOpen = false, +}: UseGlobalHotkeysOptions) => { + const actionsRef = useRef(actions); + actionsRef.current = actions; + + const orderedTabsRef = useRef(orderedTabs); + orderedTabsRef.current = orderedTabs; + + const sessionsRef = useRef(sessions); + sessionsRef.current = sessions; + + const workspacesRef = useRef(workspaces); + workspacesRef.current = workspaces; + + const handleGlobalKeyDown = useCallback((e: KeyboardEvent) => { + if (hotkeyScheme === 'disabled') return; + if (isSettingsOpen) return; // Don't handle hotkeys when settings is open + + const isMac = hotkeyScheme === 'mac'; + const appLevelActions = getAppLevelActions(); + + // Check if this is an app-level shortcut + const matched = checkAppShortcut(e, keyBindings, isMac); + if (!matched) return; + + const { action, binding: _binding } = matched; + + // Only handle app-level actions here + // Terminal-level actions are handled by the terminal itself + if (!appLevelActions.has(action)) return; + + e.preventDefault(); + e.stopPropagation(); + + const currentActions = actionsRef.current; + const tabs = orderedTabsRef.current; + + switch (action) { + case 'switchToTab': { + const num = parseInt(e.key, 10); + if (num >= 1 && num <= 9) { + currentActions.switchToTab?.(num); + } + break; + } + case 'nextTab': + currentActions.nextTab?.(); + break; + case 'prevTab': + currentActions.prevTab?.(); + break; + case 'closeTab': + currentActions.closeTab?.(); + break; + case 'newTab': + currentActions.newTab?.(); + break; + case 'openHosts': + currentActions.openHosts?.(); + break; + case 'openSftp': + currentActions.openSftp?.(); + break; + case 'openLocal': + currentActions.openLocal?.(); + break; + case 'quickSwitch': + currentActions.quickSwitch?.(); + break; + case 'commandPalette': + currentActions.commandPalette?.(); + break; + case 'portForwarding': + currentActions.portForwarding?.(); + break; + case 'snippets': + currentActions.snippets?.(); + break; + case 'splitHorizontal': + currentActions.splitHorizontal?.(); + break; + case 'splitVertical': + currentActions.splitVertical?.(); + break; + case 'moveFocus': { + // Determine direction from arrow key + const key = e.key; + if (key === 'ArrowUp') currentActions.moveFocus?.('up'); + else if (key === 'ArrowDown') currentActions.moveFocus?.('down'); + else if (key === 'ArrowLeft') currentActions.moveFocus?.('left'); + else if (key === 'ArrowRight') currentActions.moveFocus?.('right'); + break; + } + case 'broadcast': + currentActions.broadcast?.(); + break; + case 'sidePanel': + currentActions.sidePanel?.(); + break; + } + }, [hotkeyScheme, keyBindings, isSettingsOpen]); + + useEffect(() => { + // Use capture phase to intercept before xterm + window.addEventListener('keydown', handleGlobalKeyDown, true); + return () => window.removeEventListener('keydown', handleGlobalKeyDown, true); + }, [handleGlobalKeyDown]); +}; + +// Helper to create key event handler for xterm's attachCustomKeyEventHandler +// Returns false to let xterm handle the key, true to prevent xterm from handling +export const createXtermKeyHandler = ( + keyBindings: KeyBinding[], + isMac: boolean, + onTerminalAction?: (action: string, e: KeyboardEvent) => void +) => { + const appLevelActions = getAppLevelActions(); + const terminalActions = getTerminalPassthroughActions(); + + return (e: KeyboardEvent): boolean => { + const matched = checkAppShortcut(e, keyBindings, isMac); + if (!matched) return true; // Let xterm handle it + + const { action } = matched; + + // App-level actions: prevent xterm from handling, let global handler take over + if (appLevelActions.has(action)) { + return false; // Don't let xterm handle, will bubble to global handler + } + + // Terminal-level actions: handle here and prevent default + if (terminalActions.has(action)) { + e.preventDefault(); + e.stopPropagation(); + onTerminalAction?.(action, e); + return false; + } + + return true; // Let xterm handle other keys + }; +}; diff --git a/application/state/useSettingsState.ts b/application/state/useSettingsState.ts index 3d37c54a5..ea36f108b 100644 --- a/application/state/useSettingsState.ts +++ b/application/state/useSettingsState.ts @@ -1,5 +1,5 @@ import { useCallback,useEffect,useMemo,useState } from 'react'; -import { SyncConfig, TerminalSettings, DEFAULT_TERMINAL_SETTINGS } from '../../domain/models'; +import { SyncConfig, TerminalSettings, DEFAULT_TERMINAL_SETTINGS, HotkeyScheme, CustomKeyBindings, DEFAULT_KEY_BINDINGS, KeyBinding } from '../../domain/models'; import { STORAGE_KEY_COLOR, STORAGE_KEY_SYNC, @@ -8,6 +8,8 @@ STORAGE_KEY_THEME, STORAGE_KEY_TERM_FONT_FAMILY, STORAGE_KEY_TERM_FONT_SIZE, STORAGE_KEY_TERM_SETTINGS, +STORAGE_KEY_HOTKEY_SCHEME, +STORAGE_KEY_CUSTOM_KEY_BINDINGS, } from '../../infrastructure/config/storageKeys'; import { TERMINAL_THEMES } from '../../infrastructure/config/terminalThemes'; import { TERMINAL_FONTS, DEFAULT_FONT_SIZE } from '../../infrastructure/config/fonts'; @@ -17,6 +19,7 @@ const DEFAULT_COLOR = '221.2 83.2% 53.3%'; const DEFAULT_THEME: 'light' | 'dark' = 'light'; const DEFAULT_TERMINAL_THEME = 'netcatty-dark'; const DEFAULT_FONT_FAMILY = 'menlo'; +const DEFAULT_HOTKEY_SCHEME: HotkeyScheme = 'mac'; const applyThemeTokens = (theme: 'light' | 'dark', primaryColor: string) => { const root = window.document.documentElement; @@ -46,6 +49,10 @@ export const useSettingsState = () => { const stored = localStorageAdapter.read(STORAGE_KEY_TERM_SETTINGS); return stored ? { ...DEFAULT_TERMINAL_SETTINGS, ...stored } : DEFAULT_TERMINAL_SETTINGS; }); + const [hotkeyScheme, setHotkeyScheme] = useState(() => (localStorageAdapter.readString(STORAGE_KEY_HOTKEY_SCHEME) as HotkeyScheme) || DEFAULT_HOTKEY_SCHEME); + const [customKeyBindings, setCustomKeyBindings] = useState(() => + localStorageAdapter.read(STORAGE_KEY_CUSTOM_KEY_BINDINGS) || {} + ); useEffect(() => { applyThemeTokens(theme, primaryColor); @@ -69,6 +76,61 @@ export const useSettingsState = () => { localStorageAdapter.write(STORAGE_KEY_TERM_SETTINGS, terminalSettings); }, [terminalSettings]); + useEffect(() => { + localStorageAdapter.writeString(STORAGE_KEY_HOTKEY_SCHEME, hotkeyScheme); + }, [hotkeyScheme]); + + useEffect(() => { + localStorageAdapter.write(STORAGE_KEY_CUSTOM_KEY_BINDINGS, customKeyBindings); + }, [customKeyBindings]); + + // Get merged key bindings (defaults + custom overrides) + const keyBindings = useMemo((): KeyBinding[] => { + return DEFAULT_KEY_BINDINGS.map(binding => { + const custom = customKeyBindings[binding.id]; + if (!custom) return binding; + return { + ...binding, + mac: custom.mac ?? binding.mac, + pc: custom.pc ?? binding.pc, + }; + }); + }, [customKeyBindings]); + + // Update a single key binding + const updateKeyBinding = useCallback((bindingId: string, scheme: 'mac' | 'pc', newKey: string) => { + setCustomKeyBindings(prev => ({ + ...prev, + [bindingId]: { + ...prev[bindingId], + [scheme]: newKey, + }, + })); + }, []); + + // Reset a key binding to default + const resetKeyBinding = useCallback((bindingId: string, scheme?: 'mac' | 'pc') => { + setCustomKeyBindings(prev => { + const next = { ...prev }; + if (scheme) { + if (next[bindingId]) { + delete next[bindingId][scheme]; + if (Object.keys(next[bindingId]).length === 0) { + delete next[bindingId]; + } + } + } else { + delete next[bindingId]; + } + return next; + }); + }, []); + + // Reset all key bindings to defaults + const resetAllKeyBindings = useCallback(() => { + setCustomKeyBindings({}); + }, []); + const updateSyncConfig = useCallback((config: SyncConfig | null) => { setSyncConfig(config); localStorageAdapter.write(STORAGE_KEY_SYNC, config); @@ -109,5 +171,12 @@ export const useSettingsState = () => { terminalSettings, setTerminalSettings, updateTerminalSetting, + hotkeyScheme, + setHotkeyScheme, + keyBindings, + customKeyBindings, + updateKeyBinding, + resetKeyBinding, + resetAllKeyBindings, }; }; diff --git a/components/SettingsDialog.tsx b/components/SettingsDialog.tsx index b0af85e99..95f7879a8 100644 --- a/components/SettingsDialog.tsx +++ b/components/SettingsDialog.tsx @@ -3,15 +3,18 @@ import { Cloud, Download, Github, + Keyboard, Loader2, Moon, Palette, + RotateCcw, Sun, TerminalSquare, Upload, + X, } from "lucide-react"; -import React, { useState } from "react"; -import { Host, SSHKey, Snippet, TerminalSettings, CursorShape, RightClickBehavior, LinkModifier, DEFAULT_TERMINAL_SETTINGS } from "../domain/models"; +import React, { useCallback, useEffect, useRef, useState } from "react"; +import { Host, SSHKey, Snippet, TerminalSettings, CursorShape, RightClickBehavior, LinkModifier, DEFAULT_TERMINAL_SETTINGS, HotkeyScheme, KeyBinding, keyEventToString } from "../domain/models"; import { TERMINAL_THEMES } from "../infrastructure/config/terminalThemes"; import { TERMINAL_FONTS, MIN_FONT_SIZE, MAX_FONT_SIZE } from "../infrastructure/config/fonts"; import { @@ -53,6 +56,12 @@ interface SettingsDialogProps { onTerminalFontSizeChange?: (size: number) => void; terminalSettings?: TerminalSettings; onTerminalSettingsChange?: (key: K, value: TerminalSettings[K]) => void; + hotkeyScheme?: HotkeyScheme; + onHotkeySchemeChange?: (scheme: HotkeyScheme) => void; + keyBindings?: KeyBinding[]; + onUpdateKeyBinding?: (bindingId: string, scheme: 'mac' | 'pc', newKey: string) => void; + onResetKeyBinding?: (bindingId: string, scheme?: 'mac' | 'pc') => void; + onResetAllKeyBindings?: () => void; } const COLORS = [ @@ -138,8 +147,8 @@ function Select({ value, options, onChange, className ({ value: t.id, label: t.name }))} - onChange={onTerminalThemeChange} - className="w-48" + +
+ {TERMINAL_THEMES.map((t) => ( + onTerminalThemeChange(t.id)} /> -
+ ))} {/* Font Section */} @@ -450,7 +563,7 @@ const SettingsDialog: React.FC = ({ - @@ -478,7 +591,7 @@ const SettingsDialog: React.FC = ({ /> - @@ -492,7 +605,7 @@ const SettingsDialog: React.FC = ({ /> - @@ -542,7 +655,7 @@ const SettingsDialog: React.FC = ({ {/* Rendering Section */}
- @@ -557,7 +670,7 @@ const SettingsDialog: React.FC = ({ /> - = ({ /> - @@ -584,7 +697,7 @@ const SettingsDialog: React.FC = ({ {/* Keyboard Section */}
- @@ -594,7 +707,7 @@ const SettingsDialog: React.FC = ({ /> - @@ -628,7 +741,7 @@ const SettingsDialog: React.FC = ({ /> - @@ -640,7 +753,7 @@ const SettingsDialog: React.FC = ({ /> - @@ -659,13 +772,144 @@ const SettingsDialog: React.FC = ({
{/* Bottom padding */} - + + + {/* Shortcuts Tab */} + + {/* Hotkey Scheme Selector */} +
+