Adds terminal split functionality with context menu

Introduces support for horizontal and vertical splitting of terminal sessions, enabling users to split standalone sessions and manage panes within workspaces. Implements a context menu in the terminal for split actions and standard clipboard operations, improving usability and workflow efficiency. Integrates split logic across hotkeys, UI callbacks, and session state management.
This commit is contained in:
bincxz committed 2025-12-12 03:49:13 +08:00
1 parent 0d1c5f0b76
commit 8a49eeeb4c
6 files changed
+374 -72

No files matched your search

+31 -7
View File
@@ -107,6 +107,7 @@ function App() {
createWorkspaceFromSessions,
addSessionToWorkspace,
updateSplitSizes,
splitSession,
toggleWorkspaceViewMode,
setWorkspaceFocusedSession,
runSnippet,
@@ -205,14 +206,36 @@ function App() {
// 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');
case 'splitHorizontal': {
// Split current terminal horizontally (top/bottom)
const currentId = activeTabStore.getActiveTabId();
// Check if it's a standalone session or we're in a workspace
const activeSession = sessions.find(s => s.id === currentId);
const activeWs = workspaces.find(w => w.id === currentId);
if (activeSession && !activeSession.workspaceId) {
// Standalone session - split it
splitSession(activeSession.id, 'horizontal');
} else if (activeWs) {
// In a workspace - need to determine focused session
// For now, we'll need the terminal to handle this via context menu
console.log('[Hotkey] Split horizontal in workspace - use context menu on specific terminal');
}
break;
case 'splitVertical':
// TODO: Implement vertical split
console.log('[Hotkey] Split vertical requested');
}
case 'splitVertical': {
// Split current terminal vertically (left/right)
const currentId = activeTabStore.getActiveTabId();
const activeSession = sessions.find(s => s.id === currentId);
const activeWs = workspaces.find(w => w.id === currentId);
if (activeSession && !activeSession.workspaceId) {
// Standalone session - split it
splitSession(activeSession.id, 'vertical');
} else if (activeWs) {
// In a workspace - need to determine focused session
console.log('[Hotkey] Split vertical in workspace - use context menu on specific terminal');
}
break;
}
case 'moveFocus': {
// Move focus between split panes
const direction = e.key === 'ArrowUp' ? 'up'
@@ -227,7 +250,7 @@ function App() {
break;
}
}
}, [orderedTabs, sessions, workspaces, setActiveTabId, closeSession, closeWorkspace, createLocalTerminal]);
}, [orderedTabs, sessions, workspaces, setActiveTabId, closeSession, closeWorkspace, createLocalTerminal, splitSession]);
// Callback for terminal to invoke app-level hotkey actions
const handleHotkeyAction = useCallback((action: string, e: KeyboardEvent) => {
@@ -435,6 +458,7 @@ function App() {
onSetDraggingSessionId={setDraggingSessionId}
onToggleWorkspaceViewMode={toggleWorkspaceViewMode}
onSetWorkspaceFocusedSession={setWorkspaceFocusedSession}
onSplitSession={splitSession}
/>
</div>
+77
View File
@@ -6,6 +6,7 @@ createWorkspaceFromSessions as createWorkspaceEntity,
createWorkspaceFromSessionIds,
insertPaneIntoWorkspace,
pruneWorkspaceNode,
SplitDirection,
SplitHint,
updateWorkspaceSplitSizes,
} from '../../domain/workspace';
@@ -254,6 +255,81 @@ export const useSessionState = () => {
}));
}, []);
// Split a session to create a workspace with the same host connection
// direction: 'horizontal' = split top/bottom, 'vertical' = split left/right
const splitSession = useCallback((
sessionId: string,
direction: SplitDirection
) => {
setSessions(prevSessions => {
const session = prevSessions.find(s => s.id === sessionId);
if (!session) return prevSessions;
// If session is already in a workspace, split within that workspace
if (session.workspaceId) {
// Create a new session with the same host
const newSession: TerminalSession = {
id: crypto.randomUUID(),
hostId: session.hostId,
hostLabel: session.hostLabel,
hostname: session.hostname,
username: session.username,
status: 'connecting',
workspaceId: session.workspaceId,
protocol: session.protocol,
port: session.port,
moshEnabled: session.moshEnabled,
};
// Add pane to existing workspace
const hint: SplitHint = {
direction,
position: direction === 'horizontal' ? 'bottom' : 'right',
targetSessionId: sessionId,
};
setWorkspaces(prevWorkspaces => {
return prevWorkspaces.map(ws => {
if (ws.id !== session.workspaceId) return ws;
return { ...ws, root: insertPaneIntoWorkspace(ws.root, newSession.id, hint) };
});
});
return [...prevSessions, newSession];
}
// Session is standalone - create a new workspace
const newSession: TerminalSession = {
id: crypto.randomUUID(),
hostId: session.hostId,
hostLabel: session.hostLabel,
hostname: session.hostname,
username: session.username,
status: 'connecting',
protocol: session.protocol,
port: session.port,
moshEnabled: session.moshEnabled,
};
const hint: SplitHint = {
direction,
position: direction === 'horizontal' ? 'bottom' : 'right',
};
const newWorkspace = createWorkspaceEntity(sessionId, newSession.id, hint);
setWorkspaces(prev => [...prev, newWorkspace]);
setActiveTabId(newWorkspace.id);
return prevSessions.map(s => {
if (s.id === sessionId) {
return { ...s, workspaceId: newWorkspace.id };
}
return s;
}).concat({ ...newSession, workspaceId: newWorkspace.id });
});
// eslint-disable-next-line react-hooks/exhaustive-deps -- setActiveTabId is a stable store method reference
}, []);
// Toggle workspace view mode between split and focus
const toggleWorkspaceViewMode = useCallback((workspaceId: string) => {
setWorkspaces(prev => prev.map(ws => {
@@ -391,6 +467,7 @@ export const useSessionState = () => {
createWorkspaceFromSessions,
addSessionToWorkspace,
updateSplitSizes,
splitSession,
toggleWorkspaceViewMode,
setWorkspaceFocusedSession,
runSnippet,
+133 -64
View File
@@ -25,6 +25,7 @@ import { TERMINAL_THEMES } from "../infrastructure/config/terminalThemes";
// Import terminal sub-components
import { TerminalConnectionDialog } from "./terminal/TerminalConnectionDialog";
import { TerminalToolbar } from "./terminal/TerminalToolbar";
import { TerminalContextMenu } from "./terminal/TerminalContextMenu";
import {
XTERM_PERFORMANCE_CONFIG,
type XTermPlatform,
@@ -66,6 +67,9 @@ interface TerminalProps {
hostLabel: string,
sessionId: string,
) => void; // Callback when a command is executed
// Split actions
onSplitHorizontal?: () => void;
onSplitVertical?: () => void;
}
// xterm.js doesn't need async initialization like ghostty-web
@@ -95,6 +99,8 @@ const TerminalComponent: React.FC<TerminalProps> = ({
onAddKnownHost,
onExpandToFocus,
onCommandExecuted,
onSplitHorizontal,
onSplitVertical,
}) => {
const CONNECTION_TIMEOUT = 12000;
const containerRef = useRef<HTMLDivElement>(null);
@@ -125,6 +131,7 @@ const TerminalComponent: React.FC<TerminalProps> = ({
const [isCancelling, setIsCancelling] = useState(false);
const [showSFTP, setShowSFTP] = useState(false);
const [progressValue, setProgressValue] = useState(15);
const [hasSelection, setHasSelection] = useState(false);
// Chain connection progress state
const [chainProgress, setChainProgress] = useState<{
@@ -795,6 +802,20 @@ const TerminalComponent: React.FC<TerminalProps> = ({
return () => clearTimeout(timer);
}, [inWorkspace, isVisible]);
// Track terminal selection for context menu
useEffect(() => {
const term = termRef.current;
if (!term) return;
const onSelectionChange = () => {
const selection = term.getSelection();
setHasSelection(!!selection && selection.length > 0);
};
term.onSelectionChange(onSelectionChange);
// No need to return cleanup as xterm handles it when disposed
}, []);
useEffect(() => {
let resizeTimeout: ReturnType<typeof setTimeout> | null = null;
@@ -1392,6 +1413,42 @@ const TerminalComponent: React.FC<TerminalProps> = ({
}
};
// Context menu handlers
const handleContextCopy = () => {
const term = termRef.current;
if (!term) return;
const selection = term.getSelection();
if (selection) {
navigator.clipboard.writeText(selection);
}
};
const handleContextPaste = async () => {
const term = termRef.current;
if (!term) return;
try {
const text = await navigator.clipboard.readText();
if (text && sessionRef.current && window.netcatty?.writeToSession) {
window.netcatty.writeToSession(sessionRef.current, text);
}
} catch (err) {
console.warn("Failed to paste from clipboard", err);
}
};
const handleContextSelectAll = () => {
const term = termRef.current;
if (!term) return;
term.selectAll();
setHasSelection(true);
};
const handleContextClear = () => {
const term = termRef.current;
if (!term) return;
term.clear();
};
const renderControls = (opts?: { showClose?: boolean }) => (
<TerminalToolbar
status={status}
@@ -1418,58 +1475,69 @@ const TerminalComponent: React.FC<TerminalProps> = ({
const _hasError = Boolean(error);
return (
<div className="relative h-full w-full flex overflow-hidden bg-gradient-to-br from-[#050910] via-[#06101a] to-[#0b1220]">
{/* Unified statusbar for both single host and workspace modes */}
<div className="absolute left-0 right-0 top-0 z-20 pointer-events-none">
<div className="flex items-center gap-1 px-2 py-1 bg-black/55 text-white backdrop-blur-md pointer-events-auto min-w-0">
<div className="flex-1 min-w-0 flex items-center gap-1 text-[11px] font-semibold">
<span
className={cn(
"truncate",
inWorkspace ? "max-w-[80px]" : "max-w-[200px]",
)}
>
{host.label}
</span>
<span
className={cn(
"inline-block h-2 w-2 rounded-full flex-shrink-0",
statusDotTone,
)}
/>
</div>
<div className="flex items-center gap-0.5 flex-shrink-0">
{/* Expand to focus mode button - only show in workspace split view mode */}
{inWorkspace && !isFocusMode && onExpandToFocus && (
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0 text-white/70 hover:text-white hover:bg-white/10"
onClick={onExpandToFocus}
title="Focus Mode"
<TerminalContextMenu
hasSelection={hasSelection}
hotkeyScheme={hotkeyScheme}
onCopy={handleContextCopy}
onPaste={handleContextPaste}
onSelectAll={handleContextSelectAll}
onClear={handleContextClear}
onSplitHorizontal={onSplitHorizontal}
onSplitVertical={onSplitVertical}
onClose={inWorkspace ? () => onCloseSession?.(sessionId) : undefined}
>
<div className="relative h-full w-full flex overflow-hidden bg-gradient-to-br from-[#050910] via-[#06101a] to-[#0b1220]">
{/* Unified statusbar for both single host and workspace modes */}
<div className="absolute left-0 right-0 top-0 z-20 pointer-events-none">
<div className="flex items-center gap-1 px-2 py-1 bg-black/55 text-white backdrop-blur-md pointer-events-auto min-w-0">
<div className="flex-1 min-w-0 flex items-center gap-1 text-[11px] font-semibold">
<span
className={cn(
"truncate",
inWorkspace ? "max-w-[80px]" : "max-w-[200px]",
)}
>
<Maximize2 size={12} />
</Button>
)}
{renderControls({ showClose: inWorkspace })}
{host.label}
</span>
<span
className={cn(
"inline-block h-2 w-2 rounded-full flex-shrink-0",
statusDotTone,
)}
/>
</div>
<div className="flex items-center gap-0.5 flex-shrink-0">
{/* Expand to focus mode button - only show in workspace split view mode */}
{inWorkspace && !isFocusMode && onExpandToFocus && (
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0 text-white/70 hover:text-white hover:bg-white/10"
onClick={onExpandToFocus}
title="Focus Mode"
>
<Maximize2 size={12} />
</Button>
)}
{renderControls({ showClose: inWorkspace })}
</div>
</div>
</div>
</div>
<div
className="h-full flex-1 min-w-0 transition-all duration-300 relative overflow-hidden pt-8"
style={{ backgroundColor: effectiveTheme.colors.background }}
>
<div
ref={containerRef}
className="absolute inset-x-0 bottom-0"
style={{ top: "40px", paddingLeft: 6, backgroundColor: effectiveTheme.colors.background }}
/>
{error && (
<div className="absolute bottom-3 left-3 text-xs text-destructive bg-background/80 border border-destructive/40 rounded px-3 py-2 shadow-lg">
{error}
</div>
)}
className="h-full flex-1 min-w-0 transition-all duration-300 relative overflow-hidden pt-8"
style={{ backgroundColor: effectiveTheme.colors.background }}
>
<div
ref={containerRef}
className="absolute inset-x-0 bottom-0"
style={{ top: "40px", paddingLeft: 6, backgroundColor: effectiveTheme.colors.background }}
/>
{error && (
<div className="absolute bottom-3 left-3 text-xs text-destructive bg-background/80 border border-destructive/40 rounded px-3 py-2 shadow-lg">
{error}
</div>
)}
{/* Known Host Verification Dialog */}
{needsHostKeyVerification && pendingHostKeyInfo && (
@@ -1524,24 +1592,25 @@ const TerminalComponent: React.FC<TerminalProps> = ({
}}
/>
)}
</div>
</div>
{/* SFTP Modal - rendered outside terminal container to avoid affecting terminal width */}
<SFTPModal
host={host}
credentials={{
username: host.username,
hostname: host.hostname,
port: host.port,
password: host.password, // Always include for fallback
privateKey: host.identityFileId
? keys.find((k) => k.id === host.identityFileId)?.privateKey
: undefined,
}}
open={showSFTP && status === "connected"}
onClose={() => setShowSFTP(false)}
/>
</div>
{/* SFTP Modal - rendered outside terminal container to avoid affecting terminal width */}
<SFTPModal
host={host}
credentials={{
username: host.username,
hostname: host.hostname,
port: host.port,
password: host.password, // Always include for fallback
privateKey: host.identityFileId
? keys.find((k) => k.id === host.identityFileId)?.privateKey
: undefined,
}}
open={showSFTP && status === "connected"}
onClose={() => setShowSFTP(false)}
/>
</div>
</TerminalContextMenu>
);
};
+7 -1
View File
@@ -2,6 +2,7 @@ import { Circle, LayoutGrid, Server } from 'lucide-react';
import React, { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useActiveTabId } from '../application/state/activeTabStore';
import { collectSessionIds } from '../domain/workspace';
import { SplitDirection } from '../domain/workspace';
import { KeyBinding } from '../domain/models';
import { cn } from '../lib/utils';
import { Host, KnownHost, SSHKey, Snippet, TerminalSession, TerminalTheme, Workspace, WorkspaceNode } from '../types';
@@ -53,6 +54,7 @@ interface TerminalLayerProps {
onSetDraggingSessionId: (id: string | null) => void;
onToggleWorkspaceViewMode?: (workspaceId: string) => void;
onSetWorkspaceFocusedSession?: (workspaceId: string, sessionId: string) => void;
onSplitSession?: (sessionId: string, direction: SplitDirection) => void;
}
const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
@@ -80,6 +82,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
onSetDraggingSessionId,
onToggleWorkspaceViewMode,
onSetWorkspaceFocusedSession,
onSplitSession,
}) => {
// Subscribe to activeTabId from external store
const activeTabId = useActiveTabId();
@@ -575,6 +578,8 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
onAddKnownHost={handleAddKnownHost}
onCommandExecuted={handleCommandExecuted}
onExpandToFocus={inActiveWorkspace && !isFocusMode && activeWorkspace ? () => onToggleWorkspaceViewMode?.(activeWorkspace.id) : undefined}
onSplitHorizontal={onSplitSession ? () => onSplitSession(session.id, 'horizontal') : undefined}
onSplitVertical={onSplitSession ? () => onSplitSession(session.id, 'vertical') : undefined}
/>
</div>
);
@@ -649,7 +654,8 @@ const terminalLayerAreEqual = (prev: TerminalLayerProps, next: TerminalLayerProp
prev.fontSize === next.fontSize &&
prev.onUpdateHost === next.onUpdateHost &&
prev.onToggleWorkspaceViewMode === next.onToggleWorkspaceViewMode &&
prev.onSetWorkspaceFocusedSession === next.onSetWorkspaceFocusedSession
prev.onSetWorkspaceFocusedSession === next.onSetWorkspaceFocusedSession &&
prev.onSplitSession === next.onSplitSession
);
};
+123
View File
@@ -0,0 +1,123 @@
/**
* Terminal Context Menu
* Right-click menu for terminal with split, copy/paste, and other actions
*/
import {
Copy,
ClipboardPaste,
SplitSquareHorizontal,
SplitSquareVertical,
Trash2,
Terminal as TerminalIcon,
} from 'lucide-react';
import React from 'react';
import {
ContextMenu,
ContextMenuContent,
ContextMenuItem,
ContextMenuSeparator,
ContextMenuShortcut,
ContextMenuTrigger,
} from '../ui/context-menu';
export interface TerminalContextMenuProps {
children: React.ReactNode;
hasSelection?: boolean;
hotkeyScheme?: 'disabled' | 'mac' | 'pc';
onCopy?: () => void;
onPaste?: () => void;
onSelectAll?: () => void;
onClear?: () => void;
onSplitHorizontal?: () => void;
onSplitVertical?: () => void;
onClose?: () => void;
}
export const TerminalContextMenu: React.FC<TerminalContextMenuProps> = ({
children,
hasSelection = false,
hotkeyScheme = 'mac',
onCopy,
onPaste,
onSelectAll,
onClear,
onSplitHorizontal,
onSplitVertical,
onClose,
}) => {
const isMac = hotkeyScheme === 'mac';
const copyShortcut = isMac ? '⌘C' : 'Ctrl+Shift+C';
const pasteShortcut = isMac ? '⌘V' : 'Ctrl+Shift+V';
const selectAllShortcut = isMac ? '⌘A' : 'Ctrl+Shift+A';
const splitHShortcut = isMac ? '⌘D' : 'Ctrl+Shift+D';
const splitVShortcut = isMac ? '⇧⌘D' : 'Ctrl+Shift+E';
const clearShortcut = isMac ? '⌘K' : 'Ctrl+L';
return (
<ContextMenu>
<ContextMenuTrigger asChild>
{children}
</ContextMenuTrigger>
<ContextMenuContent className="w-56">
{/* Copy/Paste Section */}
<ContextMenuItem
onClick={onCopy}
disabled={!hasSelection}
>
<Copy size={14} className="mr-2" />
复制
<ContextMenuShortcut>{copyShortcut}</ContextMenuShortcut>
</ContextMenuItem>
<ContextMenuItem onClick={onPaste}>
<ClipboardPaste size={14} className="mr-2" />
粘贴
<ContextMenuShortcut>{pasteShortcut}</ContextMenuShortcut>
</ContextMenuItem>
<ContextMenuItem onClick={onSelectAll}>
<TerminalIcon size={14} className="mr-2" />
全选
<ContextMenuShortcut>{selectAllShortcut}</ContextMenuShortcut>
</ContextMenuItem>
<ContextMenuSeparator />
{/* Split Section */}
<ContextMenuItem onClick={onSplitVertical}>
<SplitSquareHorizontal size={14} className="mr-2" />
水平分屏
<ContextMenuShortcut>{splitVShortcut}</ContextMenuShortcut>
</ContextMenuItem>
<ContextMenuItem onClick={onSplitHorizontal}>
<SplitSquareVertical size={14} className="mr-2" />
垂直分屏
<ContextMenuShortcut>{splitHShortcut}</ContextMenuShortcut>
</ContextMenuItem>
<ContextMenuSeparator />
{/* Clear/Close Section */}
<ContextMenuItem onClick={onClear}>
<Trash2 size={14} className="mr-2" />
清除缓冲区
<ContextMenuShortcut>{clearShortcut}</ContextMenuShortcut>
</ContextMenuItem>
{onClose && (
<>
<ContextMenuSeparator />
<ContextMenuItem
onClick={onClose}
className="text-destructive focus:text-destructive"
>
<Trash2 size={14} className="mr-2" />
关闭终端
</ContextMenuItem>
</>
)}
</ContextMenuContent>
</ContextMenu>
);
};
export default TerminalContextMenu;
+3
View File
@@ -14,3 +14,6 @@ export type { TerminalToolbarProps } from './TerminalToolbar';
export { TerminalConnectionDialog } from './TerminalConnectionDialog';
export type { ChainProgress,TerminalConnectionDialogProps } from './TerminalConnectionDialog';
export { TerminalContextMenu } from './TerminalContextMenu';
export type { TerminalContextMenuProps } from './TerminalContextMenu';