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.
This commit is contained in:
bincxz committed 2025-12-12 03:33:56 +08:00
1 parent 151cd4bfab
commit 07cdde7976
5 files changed
+748 -712

No files matched your search

+120 -111
View File
@@ -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}
File diff suppressed because it is too large. Load diff
+74 -50
View File
@@ -48,6 +48,8 @@ interface TerminalProps {
// Hotkey configuration
hotkeyScheme?: 'disabled' | 'mac' | 'pc';
keyBindings?: KeyBinding[];
// Hotkey action callbacks
onHotkeyAction?: (action: string, event: KeyboardEvent) => void;
onStatusChange?: (
sessionId: string,
status: TerminalSession["status"],
@@ -84,6 +86,7 @@ const TerminalComponent: React.FC<TerminalProps> = ({
startupCommand,
hotkeyScheme = 'disabled',
keyBindings = [],
onHotkeyAction,
onStatusChange,
onSessionExit,
onOsDetected,
@@ -104,6 +107,14 @@ const TerminalComponent: React.FC<TerminalProps> = ({
const hasConnectedRef = useRef(false);
const hasRunStartupCommandRef = useRef(false); // Track if startup command has been executed
const commandBufferRef = useRef<string>(""); // Buffer for tracking typed commands
// Refs to store latest hotkey config for use in keyboard handler
const hotkeySchemeRef = useRef(hotkeyScheme);
const keyBindingsRef = useRef(keyBindings);
const onHotkeyActionRef = useRef(onHotkeyAction);
hotkeySchemeRef.current = hotkeyScheme;
keyBindingsRef.current = keyBindings;
onHotkeyActionRef.current = onHotkeyAction;
const [isScriptsOpen, setIsScriptsOpen] = useState(false);
const [status, setStatus] = useState<TerminalSession["status"]>("connecting");
@@ -381,65 +392,78 @@ const TerminalComponent: React.FC<TerminalProps> = ({
// Attach custom key event handler to intercept app-level shortcuts
// This allows keyboard shortcuts to work even when terminal is focused
if (hotkeyScheme !== 'disabled' && keyBindings.length > 0) {
const isMac = hotkeyScheme === 'mac';
const appLevelActions = getAppLevelActions();
const terminalActions = getTerminalPassthroughActions();
// Always attach the handler - it will check the ref values dynamically
const appLevelActions = getAppLevelActions();
const terminalActions = getTerminalPassthroughActions();
term.attachCustomKeyEventHandler((e: KeyboardEvent) => {
// Check if this matches any of our shortcuts
const matched = checkAppShortcut(e, keyBindings, isMac);
if (!matched) return true; // Let xterm handle it
term.attachCustomKeyEventHandler((e: KeyboardEvent) => {
// Read current values from refs
const currentScheme = hotkeySchemeRef.current;
const currentBindings = keyBindingsRef.current;
const hotkeyCallback = onHotkeyActionRef.current;
// Skip if hotkeys are disabled
if (currentScheme === 'disabled' || currentBindings.length === 0) {
return true; // Let xterm handle it
}
const isMac = currentScheme === 'mac';
// Check if this matches any of our shortcuts
const matched = checkAppShortcut(e, currentBindings, isMac);
if (!matched) return true; // Let xterm handle it
const { action } = matched;
const { action } = matched;
// App-level actions: return false to prevent xterm from handling
// The event will bubble up to our global handler
if (appLevelActions.has(action)) {
return false;
// App-level actions: call the callback directly and prevent xterm from handling
if (appLevelActions.has(action)) {
e.preventDefault();
if (hotkeyCallback) {
hotkeyCallback(action, e);
}
return false;
}
// Terminal-level actions: handle here
if (terminalActions.has(action)) {
e.preventDefault();
switch (action) {
case 'copy': {
const selection = term.getSelection();
if (selection) {
navigator.clipboard.writeText(selection);
}
break;
}
case 'paste': {
navigator.clipboard.readText().then((text) => {
const id = sessionRef.current;
if (id && window.netcatty?.writeToSession) {
window.netcatty.writeToSession(id, text);
}
});
break;
}
case 'selectAll': {
term.selectAll();
break;
}
case 'clearBuffer': {
term.clear();
break;
}
case 'searchTerminal': {
// TODO: Open search UI - for now just log
console.log('[Terminal] Search requested');
// Could trigger a search UI component here
break;
// Terminal-level actions: handle here
if (terminalActions.has(action)) {
e.preventDefault();
switch (action) {
case 'copy': {
const selection = term.getSelection();
if (selection) {
navigator.clipboard.writeText(selection);
}
break;
}
case 'paste': {
navigator.clipboard.readText().then((text) => {
const id = sessionRef.current;
if (id && window.netcatty?.writeToSession) {
window.netcatty.writeToSession(id, text);
}
});
break;
}
case 'selectAll': {
term.selectAll();
break;
}
case 'clearBuffer': {
term.clear();
break;
}
case 'searchTerminal': {
// TODO: Open search UI - for now just log
console.log('[Terminal] Search requested');
// Could trigger a search UI component here
break;
}
return false;
}
return false;
}
return true; // Let xterm handle other keys
});
}
return true; // Let xterm handle other keys
});
fitAddon.fit();
term.focus();
+3
View File
@@ -40,6 +40,7 @@ interface TerminalLayerProps {
fontSize?: number;
hotkeyScheme?: 'disabled' | 'mac' | 'pc';
keyBindings?: KeyBinding[];
onHotkeyAction?: (action: string, event: KeyboardEvent) => void;
onCloseSession: (sessionId: string, e?: React.MouseEvent) => void;
onUpdateSessionStatus: (sessionId: string, status: TerminalSession['status']) => void;
onUpdateHostDistro: (hostId: string, distro: string) => void;
@@ -66,6 +67,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
fontSize = 14,
hotkeyScheme = 'disabled',
keyBindings = [],
onHotkeyAction,
onCloseSession,
onUpdateSessionStatus,
onUpdateHostDistro,
@@ -564,6 +566,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
startupCommand={session.startupCommand}
hotkeyScheme={hotkeyScheme}
keyBindings={keyBindings}
onHotkeyAction={onHotkeyAction}
onCloseSession={handleCloseSession}
onStatusChange={handleStatusChange}
onSessionExit={handleSessionExit}
@@ -2,10 +2,10 @@
* Generate Key Panel - Standard SSH Key generation form
*/
import { Eye,EyeOff } from 'lucide-react';
import { Eye, EyeOff } from 'lucide-react';
import React from 'react';
import { cn } from '../../lib/utils';
import { KeyType,SSHKey } from '../../types';
import { KeyType, SSHKey } from '../../types';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
import { Label } from '../ui/label';