Enhances terminal customization and accessibility options

Expands terminal settings with advanced customization such as emulation type, font weights, line padding, keyword highlighting, link modifiers, and middle-click behavior.
Adds support for clickable URLs, cross-window settings sync, and context-aware right-click actions.
Improves accessibility with minimum contrast ratio controls and allows keyword-based output highlighting.
Refines theme/font selection UI for performance and clarity.
This commit is contained in:
LAPTOP-O016UC3M\Qi Chen committed 2025-12-12 22:06:03 +08:00
1 parent 8b3d53bb90
commit 43154e7992
15 files changed
+977 -263

No files matched your search

+1
View File
@@ -476,6 +476,7 @@ function App() {
knownHosts={knownHosts}
draggingSessionId={draggingSessionId}
terminalTheme={currentTerminalTheme}
terminalSettings={terminalSettings}
fontSize={terminalFontSize}
hotkeyScheme={hotkeyScheme}
keyBindings={keyBindings}
+29 -1
View File
@@ -108,11 +108,39 @@ export const useSettingsState = () => {
// ignore parse errors
}
}
// Sync terminal settings from other windows
if (e.key === STORAGE_KEY_TERM_SETTINGS && e.newValue) {
try {
const newSettings = JSON.parse(e.newValue) as TerminalSettings;
setTerminalSettings(prev => ({ ...DEFAULT_TERMINAL_SETTINGS, ...newSettings }));
} catch {
// ignore parse errors
}
}
// Sync terminal theme from other windows
if (e.key === STORAGE_KEY_TERM_THEME && e.newValue) {
if (e.newValue !== terminalThemeId) {
setTerminalThemeId(e.newValue);
}
}
// Sync terminal font family from other windows
if (e.key === STORAGE_KEY_TERM_FONT_FAMILY && e.newValue) {
if (e.newValue !== terminalFontFamilyId) {
setTerminalFontFamilyId(e.newValue);
}
}
// Sync terminal font size from other windows
if (e.key === STORAGE_KEY_TERM_FONT_SIZE && e.newValue) {
const newSize = parseInt(e.newValue, 10);
if (!isNaN(newSize) && newSize !== terminalFontSize) {
setTerminalFontSize(newSize);
}
}
};
window.addEventListener('storage', handleStorageChange);
return () => window.removeEventListener('storage', handleStorageChange);
}, [theme, primaryColor, customCSS, hotkeyScheme]);
}, [theme, primaryColor, customCSS, hotkeyScheme, terminalThemeId, terminalFontFamilyId, terminalFontSize]);
useEffect(() => {
localStorageAdapter.writeString(STORAGE_KEY_TERM_THEME, terminalThemeId);
+268 -19
View File
@@ -8,8 +8,10 @@ import {
Download,
Keyboard,
Loader2,
Minus,
Moon,
Palette,
Plus,
RotateCcw,
Sun,
TerminalSquare,
@@ -21,6 +23,9 @@ import {
CursorShape,
RightClickBehavior,
HotkeyScheme,
TerminalEmulationType,
LinkModifier,
DEFAULT_KEYWORD_HIGHLIGHT_RULES,
keyEventToString,
} from "../domain/models";
import { TERMINAL_THEMES } from "../infrastructure/config/terminalThemes";
@@ -604,21 +609,33 @@ export default function SettingsPage() {
/>
</SettingRow>
<SettingRow label="Font size">
<div className="flex items-center gap-2">
<Input
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) {
setTerminalFontSize(val);
<SettingRow label="Text Size">
<div className="flex items-center gap-1">
<button
onClick={() => {
if (terminalFontSize > MIN_FONT_SIZE) {
setTerminalFontSize(terminalFontSize - 1);
}
}}
className="w-20 text-center"
/>
className="w-8 h-8 flex items-center justify-center rounded-md bg-muted hover:bg-muted/80 transition-colors"
disabled={terminalFontSize <= MIN_FONT_SIZE}
>
<Minus size={14} />
</button>
<div className="w-10 h-8 flex items-center justify-center text-sm font-medium">
{terminalFontSize}
</div>
<button
onClick={() => {
if (terminalFontSize < MAX_FONT_SIZE) {
setTerminalFontSize(terminalFontSize + 1);
}
}}
className="w-8 h-8 flex items-center justify-center rounded-md bg-muted hover:bg-muted/80 transition-colors"
disabled={terminalFontSize >= MAX_FONT_SIZE}
>
<Plus size={14} />
</button>
</div>
</SettingRow>
@@ -631,6 +648,94 @@ export default function SettingsPage() {
onChange={(v) => updateTerminalSetting("fontLigatures", v)}
/>
</SettingRow>
<SettingRow
label="Use bright colours for bold text"
>
<Toggle
checked={terminalSettings.drawBoldInBrightColors}
onChange={(v) => updateTerminalSetting("drawBoldInBrightColors", v)}
/>
</SettingRow>
<SettingRow
label="Font weight"
description="Weight for normal text (100-900)"
>
<Select
value={String(terminalSettings.fontWeight)}
options={[
{ value: "100", label: "100 - Thin" },
{ value: "200", label: "200 - Extra Light" },
{ value: "300", label: "300 - Light" },
{ value: "400", label: "400 - Normal" },
{ value: "500", label: "500 - Medium" },
{ value: "600", label: "600 - Semi Bold" },
{ value: "700", label: "700 - Bold" },
{ value: "800", label: "800 - Extra Bold" },
{ value: "900", label: "900 - Black" },
]}
onChange={(v) => updateTerminalSetting("fontWeight", parseInt(v))}
className="w-40"
/>
</SettingRow>
<SettingRow
label="Bold font weight"
description="Weight for bold text (100-900)"
>
<Select
value={String(terminalSettings.fontWeightBold)}
options={[
{ value: "100", label: "100 - Thin" },
{ value: "200", label: "200 - Extra Light" },
{ value: "300", label: "300 - Light" },
{ value: "400", label: "400 - Normal" },
{ value: "500", label: "500 - Medium" },
{ value: "600", label: "600 - Semi Bold" },
{ value: "700", label: "700 - Bold" },
{ value: "800", label: "800 - Extra Bold" },
{ value: "900", label: "900 - Black" },
]}
onChange={(v) => updateTerminalSetting("fontWeightBold", parseInt(v))}
className="w-40"
/>
</SettingRow>
<SettingRow
label="Line padding"
description="Additional space between lines (0-10)"
>
<div className="flex items-center gap-2">
<input
type="range"
min={0}
max={10}
step={1}
value={terminalSettings.linePadding}
onChange={(e) => updateTerminalSetting("linePadding", parseInt(e.target.value))}
className="w-24 accent-primary"
/>
<span className="text-sm text-muted-foreground w-6 text-center">
{terminalSettings.linePadding}
</span>
</div>
</SettingRow>
<SettingRow label="Terminal emulation type">
<Select
value={terminalSettings.terminalEmulationType}
options={[
{ value: "xterm-256color", label: "xterm-256color" },
{ value: "xterm-16color", label: "xterm-16color" },
{ value: "xterm", label: "xterm" },
]}
onChange={(v) =>
updateTerminalSetting("terminalEmulationType", v as TerminalEmulationType)
}
className="w-36"
/>
</SettingRow>
</div>
<SectionHeader title="Cursor" />
@@ -658,6 +763,42 @@ export default function SettingsPage() {
</SettingRow>
</div>
<SectionHeader title="Keyboard" />
<div className="space-y-0 divide-y divide-border rounded-lg border bg-card px-4">
<SettingRow
label="Use Option as Meta key"
description="Use ⌥ Option (Alt) as the Meta key instead of for special characters"
>
<Toggle
checked={terminalSettings.altAsMeta}
onChange={(v) => updateTerminalSetting("altAsMeta", v)}
/>
</SettingRow>
</div>
<SectionHeader title="Accessibility" />
<div className="space-y-0 divide-y divide-border rounded-lg border bg-card px-4">
<SettingRow
label="Minimum contrast ratio"
description="Adjust colors to meet contrast requirements (1 = disabled, 21 = max)"
>
<div className="flex items-center gap-2">
<input
type="range"
min={1}
max={21}
step={1}
value={terminalSettings.minimumContrastRatio}
onChange={(e) => updateTerminalSetting("minimumContrastRatio", parseInt(e.target.value))}
className="w-24 accent-primary"
/>
<span className="text-sm text-muted-foreground w-6 text-center">
{terminalSettings.minimumContrastRatio}
</span>
</div>
</SettingRow>
</div>
<SectionHeader title="Behavior" />
<div className="space-y-0 divide-y divide-border rounded-lg border bg-card px-4">
<SettingRow
@@ -692,23 +833,131 @@ export default function SettingsPage() {
</SettingRow>
<SettingRow
label="Scrollback lines"
description="Number of lines to keep in history"
label="Middle-click paste"
description="Paste clipboard content on middle-click"
>
<Toggle
checked={terminalSettings.middleClickPaste}
onChange={(v) => updateTerminalSetting("middleClickPaste", v)}
/>
</SettingRow>
<SettingRow
label="Scroll on input"
description="Scroll terminal to bottom when typing"
>
<Toggle
checked={terminalSettings.scrollOnInput}
onChange={(v) => updateTerminalSetting("scrollOnInput", v)}
/>
</SettingRow>
<SettingRow
label="Word separators"
description="Characters used to separate words for double-click selection"
>
<Input
value={terminalSettings.wordSeparators}
onChange={(e) => updateTerminalSetting("wordSeparators", e.target.value)}
className="w-32 text-center font-mono"
placeholder=" ()[]{}'&quot;"
/>
</SettingRow>
<SettingRow
label="Link modifier key"
description="Hold this key to click on links in terminal"
>
<Select
value={terminalSettings.linkModifier}
options={[
{ value: "none", label: "None (click directly)" },
{ value: "ctrl", label: "Ctrl" },
{ value: "alt", label: "Alt / Option" },
{ value: "meta", label: "Cmd / Win" },
]}
onChange={(v) => updateTerminalSetting("linkModifier", v as LinkModifier)}
className="w-40"
/>
</SettingRow>
</div>
<SectionHeader title="Scrollback" />
<div className="rounded-lg border bg-card p-4">
<p className="text-sm text-muted-foreground mb-3">
Limit number of terminal rows. Set to 0 to maximum limit size.
</p>
<div className="space-y-1">
<Label className="text-xs">Number of rows *</Label>
<Input
type="number"
min={1000}
min={0}
max={100000}
value={terminalSettings.scrollback}
onChange={(e) => {
const val = parseInt(e.target.value);
if (val >= 1000 && val <= 100000) {
if (!isNaN(val) && val >= 0 && val <= 100000) {
updateTerminalSetting("scrollback", val);
}
}}
className="w-24 text-center"
className="w-full"
/>
</SettingRow>
</div>
</div>
<SectionHeader title="Keyword highlighting" />
<div className="rounded-lg border bg-card p-4">
<div className="flex items-center justify-between mb-4">
<span className="text-sm font-medium">Keyword highlighting</span>
<Toggle
checked={terminalSettings.keywordHighlightEnabled}
onChange={(v) => updateTerminalSetting("keywordHighlightEnabled", v)}
/>
</div>
{terminalSettings.keywordHighlightEnabled && (
<div className="space-y-2.5">
{terminalSettings.keywordHighlightRules.map((rule) => (
<div key={rule.id} className="flex items-center justify-between">
<span className="text-sm" style={{ color: rule.color }}>
{rule.label}
</span>
<label className="relative">
<input
type="color"
value={rule.color}
onChange={(e) => {
const newRules = terminalSettings.keywordHighlightRules.map(r =>
r.id === rule.id ? { ...r, color: e.target.value } : r
);
updateTerminalSetting("keywordHighlightRules", newRules);
}}
className="sr-only"
/>
<span
className="block w-10 h-6 rounded-md cursor-pointer border border-border/50 hover:border-border transition-colors"
style={{ backgroundColor: rule.color }}
/>
</label>
</div>
))}
<Button
variant="ghost"
size="sm"
className="w-full mt-3 text-muted-foreground hover:text-foreground"
onClick={() => {
// Reset colors to default values
const resetRules = terminalSettings.keywordHighlightRules.map(rule => {
const defaultRule = DEFAULT_KEYWORD_HIGHLIGHT_RULES.find(r => r.id === rule.id);
return defaultRule ? { ...rule, color: defaultRule.color } : rule;
});
updateTerminalSetting("keywordHighlightRules", resetRules);
}}
>
<RotateCcw size={14} className="mr-2" />
Reset to default colors
</Button>
</div>
)}
</div>
</SettingsTabContent>
+218 -45
View File
@@ -2,6 +2,7 @@ import { Terminal as XTerm } from "@xterm/xterm";
import { FitAddon } from "@xterm/addon-fit";
import { SerializeAddon } from "@xterm/addon-serialize";
import { WebglAddon } from "@xterm/addon-webgl";
import { WebLinksAddon } from "@xterm/addon-web-links";
import "@xterm/xterm/css/xterm.css";
import { Maximize2 } from "lucide-react";
import React, { memo, useEffect, useMemo, useRef, useState } from "react";
@@ -13,6 +14,7 @@ import {
Snippet,
TerminalSession,
TerminalTheme,
TerminalSettings,
KeyBinding,
} from "../types";
import { checkAppShortcut, getAppLevelActions, getTerminalPassthroughActions } from "../application/state/useGlobalHotkeys";
@@ -26,6 +28,7 @@ import { TERMINAL_THEMES } from "../infrastructure/config/terminalThemes";
import { TerminalConnectionDialog } from "./terminal/TerminalConnectionDialog";
import { TerminalToolbar } from "./terminal/TerminalToolbar";
import { TerminalContextMenu } from "./terminal/TerminalContextMenu";
import { createHighlightProcessor } from "./terminal/keywordHighlight";
import {
XTERM_PERFORMANCE_CONFIG,
type XTermPlatform,
@@ -45,6 +48,7 @@ interface TerminalProps {
isFocused?: boolean; // Whether this terminal should have keyboard focus (for split views)
fontSize: number;
terminalTheme: TerminalTheme;
terminalSettings?: TerminalSettings; // Global terminal settings
sessionId: string;
startupCommand?: string; // Command to run after connection (for snippet runner)
// Hotkey configuration
@@ -88,6 +92,7 @@ const TerminalComponent: React.FC<TerminalProps> = ({
isFocused,
fontSize,
terminalTheme,
terminalSettings,
sessionId,
startupCommand,
hotkeyScheme = 'disabled',
@@ -116,6 +121,21 @@ const TerminalComponent: React.FC<TerminalProps> = ({
const hasRunStartupCommandRef = useRef(false); // Track if startup command has been executed
const commandBufferRef = useRef<string>(""); // Buffer for tracking typed commands
// Ref to store latest terminalSettings for use in boot function (avoids stale closure)
const terminalSettingsRef = useRef(terminalSettings);
terminalSettingsRef.current = terminalSettings;
// Keyword highlight processor - processes terminal output for keyword highlighting
const highlightProcessorRef = useRef<(text: string) => string>((t) => t);
// Update highlight processor when settings change
useEffect(() => {
highlightProcessorRef.current = createHighlightProcessor(
terminalSettings?.keywordHighlightRules ?? [],
terminalSettings?.keywordHighlightEnabled ?? false
);
}, [terminalSettings?.keywordHighlightEnabled, terminalSettings?.keywordHighlightRules]);
// Refs to store latest hotkey config for use in keyboard handler
const hotkeySchemeRef = useRef(hotkeyScheme);
const keyBindingsRef = useRef(keyBindings);
@@ -287,10 +307,38 @@ const TerminalComponent: React.FC<TerminalProps> = ({
// Use host-specific font size if available, otherwise use the global fontSize prop
const effectiveFontSize = host.fontSize || fontSize;
// Apply terminal settings with defaults (use ref to get latest values)
const settings = terminalSettingsRef.current;
const cursorStyle = settings?.cursorShape ?? 'block';
const cursorBlink = settings?.cursorBlink ?? true;
const scrollback = settings?.scrollback ?? 10000;
const fontLigatures = settings?.fontLigatures ?? true;
const drawBoldTextInBrightColors = settings?.drawBoldInBrightColors ?? true;
const fontWeight = settings?.fontWeight ?? 400;
const fontWeightBold = settings?.fontWeightBold ?? 700;
// linePadding 0-10 maps to lineHeight 1.0-2.0
const lineHeight = 1 + (settings?.linePadding ?? 0) / 10;
const minimumContrastRatio = settings?.minimumContrastRatio ?? 1;
const scrollOnUserInput = settings?.scrollOnInput ?? true;
const altIsMeta = settings?.altAsMeta ?? false;
const wordSeparator = settings?.wordSeparators ?? " ()[]{}'\"";
const term = new XTerm({
...performanceConfig.options,
fontSize: effectiveFontSize,
fontFamily: fontFamily,
fontWeight: fontWeight as 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | 'normal' | 'bold',
fontWeightBold: fontWeightBold as 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | 'normal' | 'bold',
lineHeight,
cursorStyle,
cursorBlink,
scrollback,
allowProposedApi: fontLigatures, // Required for font ligatures
drawBoldTextInBrightColors,
minimumContrastRatio,
scrollOnUserInput,
altClickMovesCursor: !altIsMeta, // If altAsMeta is true, don't use alt for cursor movement
wordSeparator,
theme: {
...terminalTheme.colors,
selectionBackground: terminalTheme.colors.selection,
@@ -397,6 +445,36 @@ const TerminalComponent: React.FC<TerminalProps> = ({
scopedWindow.__xtermWebGLLoaded = webglLoaded;
scopedWindow.__xtermRendererPreference = performanceConfig.preferCanvasRenderer ? "canvas" : "webgl";
// Load web links addon for clickable URLs
const webLinksAddon = new WebLinksAddon((event, uri) => {
// Check if the required modifier key is held (read from ref for real-time updates)
const currentLinkModifier = terminalSettingsRef.current?.linkModifier ?? 'none';
let shouldOpen = false;
switch (currentLinkModifier) {
case 'none':
shouldOpen = true;
break;
case 'ctrl':
shouldOpen = event.ctrlKey;
break;
case 'alt':
shouldOpen = event.altKey;
break;
case 'meta':
shouldOpen = event.metaKey;
break;
}
if (shouldOpen) {
// Open URL in default browser
if (window.netcatty?.openExternal) {
window.netcatty.openExternal(uri);
} else {
window.open(uri, '_blank');
}
}
});
term.loadAddon(webLinksAddon);
logRenderer();
// Attach custom key event handler to intercept app-level shortcuts
@@ -488,6 +566,34 @@ const TerminalComponent: React.FC<TerminalProps> = ({
return true; // Let xterm handle other keys
});
// Add middle-click paste support
const middleClickPaste = settings?.middleClickPaste ?? true;
if (middleClickPaste && containerRef.current) {
const handleMiddleClick = async (e: MouseEvent) => {
if (e.button === 1) { // Middle mouse button
e.preventDefault();
try {
const text = await navigator.clipboard.readText();
if (text && sessionRef.current && window.netcatty?.writeToSession) {
window.netcatty.writeToSession(sessionRef.current, text);
}
} catch (err) {
console.warn('[Terminal] Failed to paste from clipboard:', err);
}
}
};
containerRef.current.addEventListener('auxclick', handleMiddleClick);
// Store cleanup function
const container = containerRef.current;
const cleanup = () => container.removeEventListener('auxclick', handleMiddleClick);
// Add to disposal - we'll handle this in the main cleanup
const originalDispose = disposeDataRef.current;
disposeDataRef.current = () => {
cleanup();
originalDispose?.();
};
}
fitAddon.fit();
term.focus();
} catch (openErr) {
@@ -668,20 +774,47 @@ const TerminalComponent: React.FC<TerminalProps> = ({
}
};
// Effect for global fontSize/terminalTheme changes (from Settings)
// Effect for global fontSize/terminalTheme/terminalSettings changes (from Settings)
useEffect(() => {
if (termRef.current) {
// Only apply global settings if host doesn't have specific overrides
const effectiveFontSize = host.fontSize || fontSize;
termRef.current.options.fontSize = effectiveFontSize;
// Use effectiveTheme which respects host-specific theme override
termRef.current.options.theme = {
...terminalTheme.colors,
selectionBackground: terminalTheme.colors.selection,
...effectiveTheme.colors,
selectionBackground: effectiveTheme.colors.selection,
};
// Refit after font size change
// Apply all terminal settings for real-time updates
if (terminalSettings) {
// Cursor settings
termRef.current.options.cursorStyle = terminalSettings.cursorShape;
termRef.current.options.cursorBlink = terminalSettings.cursorBlink;
// Buffer settings
termRef.current.options.scrollback = terminalSettings.scrollback;
// Font settings
termRef.current.options.fontWeight = terminalSettings.fontWeight as 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900;
termRef.current.options.fontWeightBold = terminalSettings.fontWeightBold as 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900;
termRef.current.options.lineHeight = 1 + terminalSettings.linePadding / 10;
termRef.current.options.drawBoldTextInBrightColors = terminalSettings.drawBoldInBrightColors;
// Accessibility
termRef.current.options.minimumContrastRatio = terminalSettings.minimumContrastRatio;
// Input behavior
termRef.current.options.scrollOnUserInput = terminalSettings.scrollOnInput;
termRef.current.options.altClickMovesCursor = !terminalSettings.altAsMeta;
termRef.current.options.wordSeparator = terminalSettings.wordSeparators;
}
// Refit after settings change (especially important for lineHeight changes)
setTimeout(() => safeFit(), 50);
}
}, [fontSize, terminalTheme, host.fontSize]);
}, [fontSize, effectiveTheme, terminalSettings, host.fontSize]);
// Effect for host-specific font/theme changes (from ThemeCustomizeModal)
useEffect(() => {
@@ -695,21 +828,16 @@ const TerminalComponent: React.FC<TerminalProps> = ({
const fontObj = TERMINAL_FONTS.find(f => f.id === hostFontId) || TERMINAL_FONTS[0];
termRef.current.options.fontFamily = fontObj.family;
// Apply host-specific theme if set
if (host.theme) {
const hostTheme = TERMINAL_THEMES.find(t => t.id === host.theme);
if (hostTheme) {
termRef.current.options.theme = {
...hostTheme.colors,
selectionBackground: hostTheme.colors.selection,
};
}
}
// Apply effective theme (host-specific or global)
termRef.current.options.theme = {
...effectiveTheme.colors,
selectionBackground: effectiveTheme.colors.selection,
};
// Refit after changes
setTimeout(() => safeFit(), 50);
}
}, [host.fontSize, host.fontFamily, host.theme, fontSize]);
}, [host.fontSize, host.fontFamily, host.theme, fontSize, effectiveTheme]);
// Separate effect for visibility-triggered fit (less frequent)
useEffect(() => {
@@ -844,19 +972,27 @@ const TerminalComponent: React.FC<TerminalProps> = ({
}
}, [isFocused, isVisible, sessionId]);
// Track terminal selection for context menu
// Track terminal selection for context menu and copyOnSelect
useEffect(() => {
const term = termRef.current;
if (!term) return;
const onSelectionChange = () => {
const selection = term.getSelection();
setHasSelection(!!selection && selection.length > 0);
const hasText = !!selection && selection.length > 0;
setHasSelection(hasText);
// Copy on select if enabled
if (hasText && terminalSettings?.copyOnSelect) {
navigator.clipboard.writeText(selection).catch(err => {
console.warn('Copy on select failed:', err);
});
}
};
term.onSelectionChange(onSelectionChange);
// No need to return cleanup as xterm handles it when disposed
}, []);
}, [terminalSettings?.copyOnSelect]);
useEffect(() => {
let resizeTimeout: ReturnType<typeof setTimeout> | null = null;
@@ -970,6 +1106,18 @@ const TerminalComponent: React.FC<TerminalProps> = ({
}
try {
// Build environment variables, including TERM from settings
const termEnv: Record<string, string> = {
TERM: terminalSettings?.terminalEmulationType ?? 'xterm-256color',
};
// Add host-specific environment variables
if (host.environmentVariables) {
for (const { name, value } of host.environmentVariables) {
if (name) termEnv[name] = value;
}
}
const id = await window.netcatty.startSSHSession({
sessionId,
hostname: host.hostname,
@@ -982,14 +1130,8 @@ const TerminalComponent: React.FC<TerminalProps> = ({
cols: term.cols,
rows: term.rows,
charset: host.charset,
// Environment variables
env: host.environmentVariables?.reduce(
(acc, { name, value }) => {
if (name) acc[name] = value;
return acc;
},
{} as Record<string, string>,
),
// Environment variables including TERM
env: termEnv,
// New: proxy and jump host configuration
proxy: proxyConfig,
jumpHosts: jumpHosts.length > 0 ? jumpHosts : undefined,
@@ -1003,7 +1145,8 @@ const TerminalComponent: React.FC<TerminalProps> = ({
sessionRef.current = id;
disposeDataRef.current = window.netcatty.onSessionData(id, (chunk) => {
term.write(chunk);
// Apply keyword highlighting before writing to terminal
term.write(highlightProcessorRef.current(chunk));
if (!hasConnectedRef.current) {
updateStatus("connected");
setChainProgress(null); // Clear chain progress on connect
@@ -1113,6 +1256,18 @@ const TerminalComponent: React.FC<TerminalProps> = ({
}
try {
// Build environment variables, including TERM from settings
const telnetEnv: Record<string, string> = {
TERM: terminalSettings?.terminalEmulationType ?? 'xterm-256color',
};
// Add host-specific environment variables
if (host.environmentVariables) {
for (const { name, value } of host.environmentVariables) {
if (name) telnetEnv[name] = value;
}
}
const id = await startTelnetSession({
sessionId,
hostname: host.hostname,
@@ -1120,19 +1275,14 @@ const TerminalComponent: React.FC<TerminalProps> = ({
cols: term.cols,
rows: term.rows,
charset: host.charset,
env: host.environmentVariables?.reduce(
(acc, { name, value }) => {
if (name) acc[name] = value;
return acc;
},
{} as Record<string, string>,
),
env: telnetEnv,
});
sessionRef.current = id;
disposeDataRef.current = window.netcatty?.onSessionData(id, (chunk) => {
term.write(chunk);
// Apply keyword highlighting before writing to terminal
term.write(highlightProcessorRef.current(chunk));
if (!hasConnectedRef.current) {
updateStatus("connected");
setTimeout(() => {
@@ -1187,6 +1337,18 @@ const TerminalComponent: React.FC<TerminalProps> = ({
}
try {
// Build environment variables, including TERM from settings
const moshEnv: Record<string, string> = {
TERM: terminalSettings?.terminalEmulationType ?? 'xterm-256color',
};
// Add host-specific environment variables
if (host.environmentVariables) {
for (const { name, value } of host.environmentVariables) {
if (name) moshEnv[name] = value;
}
}
const id = await startMoshSession({
sessionId,
hostname: host.hostname,
@@ -1197,19 +1359,14 @@ const TerminalComponent: React.FC<TerminalProps> = ({
cols: term.cols,
rows: term.rows,
charset: host.charset,
env: host.environmentVariables?.reduce(
(acc, { name, value }) => {
if (name) acc[name] = value;
return acc;
},
{} as Record<string, string>,
),
env: moshEnv,
});
sessionRef.current = id;
disposeDataRef.current = window.netcatty?.onSessionData(id, (chunk) => {
term.write(chunk);
// Apply keyword highlighting before writing to terminal
term.write(highlightProcessorRef.current(chunk));
if (!hasConnectedRef.current) {
updateStatus("connected");
setTimeout(() => {
@@ -1285,10 +1442,14 @@ const TerminalComponent: React.FC<TerminalProps> = ({
sessionId,
cols: term.cols,
rows: term.rows,
env: {
TERM: terminalSettings?.terminalEmulationType ?? 'xterm-256color',
},
});
sessionRef.current = id;
disposeDataRef.current = window.netcatty?.onSessionData(id, (chunk) => {
term.write(chunk);
// Apply keyword highlighting before writing to terminal
term.write(highlightProcessorRef.current(chunk));
if (!hasConnectedRef.current) {
updateStatus("connected");
// Trigger fit after connection to ensure proper terminal size
@@ -1491,6 +1652,16 @@ const TerminalComponent: React.FC<TerminalProps> = ({
term.clear();
};
const handleContextSelectWord = () => {
const term = termRef.current;
if (!term) return;
// xterm.js selectWord selects the word under cursor
// Since we don't have a cursor position from right-click, we can select all as fallback
// A proper implementation would require tracking the click position
term.selectAll();
setHasSelection(true);
};
const renderControls = (opts?: { showClose?: boolean }) => (
<TerminalToolbar
status={status}
@@ -1520,10 +1691,12 @@ const TerminalComponent: React.FC<TerminalProps> = ({
<TerminalContextMenu
hasSelection={hasSelection}
hotkeyScheme={hotkeyScheme}
rightClickBehavior={terminalSettings?.rightClickBehavior}
onCopy={handleContextCopy}
onPaste={handleContextPaste}
onSelectAll={handleContextSelectAll}
onClear={handleContextClear}
onSelectWord={handleContextSelectWord}
onSplitHorizontal={onSplitHorizontal}
onSplitVertical={onSplitVertical}
onClose={inWorkspace ? () => onCloseSession?.(sessionId) : undefined}
+5 -1
View File
@@ -3,7 +3,7 @@ import React, { memo, useCallback, useEffect, useMemo, useRef, useState } from '
import { useActiveTabId } from '../application/state/activeTabStore';
import { collectSessionIds } from '../domain/workspace';
import { SplitDirection } from '../domain/workspace';
import { KeyBinding } from '../domain/models';
import { KeyBinding, TerminalSettings } from '../domain/models';
import { cn } from '../lib/utils';
import { Host, KnownHost, SSHKey, Snippet, TerminalSession, TerminalTheme, Workspace, WorkspaceNode } from '../types';
import { DistroAvatar } from './DistroAvatar';
@@ -38,6 +38,7 @@ interface TerminalLayerProps {
knownHosts?: KnownHost[];
draggingSessionId: string | null;
terminalTheme: TerminalTheme;
terminalSettings?: TerminalSettings;
fontSize?: number;
hotkeyScheme?: 'disabled' | 'mac' | 'pc';
keyBindings?: KeyBinding[];
@@ -66,6 +67,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
knownHosts = [],
draggingSessionId,
terminalTheme,
terminalSettings,
fontSize = 14,
hotkeyScheme = 'disabled',
keyBindings = [],
@@ -631,6 +633,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
isFocused={isFocusedPane}
fontSize={fontSize}
terminalTheme={terminalTheme}
terminalSettings={terminalSettings}
sessionId={session.id}
startupCommand={session.startupCommand}
hotkeyScheme={hotkeyScheme}
@@ -717,6 +720,7 @@ const terminalLayerAreEqual = (prev: TerminalLayerProps, next: TerminalLayerProp
prev.workspaces === next.workspaces &&
prev.draggingSessionId === next.draggingSessionId &&
prev.terminalTheme === next.terminalTheme &&
prev.terminalSettings === next.terminalSettings &&
prev.fontSize === next.fontSize &&
prev.onUpdateHost === next.onUpdateHost &&
prev.onToggleWorkspaceViewMode === next.onToggleWorkspaceViewMode &&
+29 -1
View File
@@ -10,7 +10,8 @@ import {
Trash2,
Terminal as TerminalIcon,
} from 'lucide-react';
import React from 'react';
import React, { useCallback } from 'react';
import { RightClickBehavior } from '../../domain/models';
import {
ContextMenu,
ContextMenuContent,
@@ -24,6 +25,7 @@ export interface TerminalContextMenuProps {
children: React.ReactNode;
hasSelection?: boolean;
hotkeyScheme?: 'disabled' | 'mac' | 'pc';
rightClickBehavior?: RightClickBehavior;
onCopy?: () => void;
onPaste?: () => void;
onSelectAll?: () => void;
@@ -31,12 +33,14 @@ export interface TerminalContextMenuProps {
onSplitHorizontal?: () => void;
onSplitVertical?: () => void;
onClose?: () => void;
onSelectWord?: () => void;
}
export const TerminalContextMenu: React.FC<TerminalContextMenuProps> = ({
children,
hasSelection = false,
hotkeyScheme = 'mac',
rightClickBehavior = 'context-menu',
onCopy,
onPaste,
onSelectAll,
@@ -44,6 +48,7 @@ export const TerminalContextMenu: React.FC<TerminalContextMenuProps> = ({
onSplitHorizontal,
onSplitVertical,
onClose,
onSelectWord,
}) => {
const isMac = hotkeyScheme === 'mac';
@@ -54,6 +59,29 @@ export const TerminalContextMenu: React.FC<TerminalContextMenuProps> = ({
const splitVShortcut = isMac ? '⇧⌘D' : 'Ctrl+Shift+E';
const clearShortcut = isMac ? '⌘K' : 'Ctrl+L';
// Handle right-click based on behavior setting
const handleRightClick = useCallback((e: React.MouseEvent) => {
if (rightClickBehavior === 'paste') {
e.preventDefault();
e.stopPropagation();
onPaste?.();
} else if (rightClickBehavior === 'select-word') {
e.preventDefault();
e.stopPropagation();
onSelectWord?.();
}
// For 'context-menu', let the default behavior happen (menu shows)
}, [rightClickBehavior, onPaste, onSelectWord]);
// If not using context menu behavior, wrap children with a div that intercepts right-click
if (rightClickBehavior !== 'context-menu') {
return (
<div onContextMenu={handleRightClick} className="contents">
{children}
</div>
);
}
return (
<ContextMenu>
<ContextMenuTrigger asChild>
+236 -195
View File
@@ -9,7 +9,7 @@
* - Cancel: reverts to the original settings when modal was opened
*/
import React, { useEffect, useMemo, useState, useCallback, useRef } from 'react';
import React, { useEffect, useMemo, useState, useCallback, useRef, memo } from 'react';
import { createPortal } from 'react-dom';
import { Check, Minus, Palette, Plus, Type, X } from 'lucide-react';
import { TERMINAL_THEMES, TerminalThemeConfig } from '../../infrastructure/config/terminalThemes';
@@ -19,6 +19,82 @@ import { cn } from '../../lib/utils';
type TabType = 'theme' | 'font';
// Memoized theme item component to prevent unnecessary re-renders
const ThemeItem = memo(({
theme,
isSelected,
onSelect
}: {
theme: TerminalThemeConfig;
isSelected: boolean;
onSelect: (id: string) => void;
}) => (
<button
onClick={() => onSelect(theme.id)}
className={cn(
'w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-left transition-all',
isSelected
? 'bg-primary/15 ring-1 ring-primary'
: 'hover:bg-muted'
)}
>
{/* Color swatch */}
<div
className="w-8 h-8 rounded-md flex-shrink-0 flex flex-col justify-center items-start pl-1 gap-0.5 border border-border/50"
style={{ backgroundColor: theme.colors.background }}
>
<div className="h-1 w-3 rounded-full" style={{ backgroundColor: theme.colors.green }} />
<div className="h-1 w-5 rounded-full" style={{ backgroundColor: theme.colors.blue }} />
<div className="h-1 w-2 rounded-full" style={{ backgroundColor: theme.colors.yellow }} />
</div>
<div className="flex-1 min-w-0">
<div className={cn('text-xs font-medium truncate', isSelected ? 'text-primary' : 'text-foreground')}>
{theme.name}
</div>
<div className="text-[10px] text-muted-foreground capitalize">{theme.type}</div>
</div>
{isSelected && (
<Check size={14} className="text-primary flex-shrink-0" />
)}
</button>
));
ThemeItem.displayName = 'ThemeItem';
// Memoized font item component
const FontItem = memo(({
font,
isSelected,
onSelect
}: {
font: TerminalFont;
isSelected: boolean;
onSelect: (id: string) => void;
}) => (
<button
onClick={() => onSelect(font.id)}
className={cn(
'w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-left transition-all',
isSelected
? 'bg-primary/15 ring-1 ring-primary'
: 'hover:bg-muted'
)}
>
<div className="flex-1 min-w-0">
<div
className={cn('text-sm truncate', isSelected ? 'text-primary' : 'text-foreground')}
style={{ fontFamily: font.family }}
>
{font.name}
</div>
<div className="text-[10px] text-muted-foreground truncate">{font.description}</div>
</div>
{isSelected && (
<Check size={14} className="text-primary flex-shrink-0" />
)}
</button>
));
FontItem.displayName = 'FontItem';
interface ThemeCustomizeModalProps {
open: boolean;
onClose: () => void;
@@ -35,6 +111,147 @@ interface ThemeCustomizeModalProps {
onSave?: () => void;
}
// Memoized preview component to avoid re-rendering on every state change
const TerminalPreview = memo(({
theme,
font,
fontSize
}: {
theme: TerminalThemeConfig;
font: TerminalFont;
fontSize: number;
}) => (
<div
className="flex-1 rounded-xl overflow-hidden border border-border flex flex-col"
style={{ backgroundColor: theme.colors.background }}
>
{/* Fake title bar */}
<div
className="flex items-center gap-2 px-3 py-2 border-b shrink-0"
style={{
backgroundColor: theme.colors.background,
borderColor: `${theme.colors.foreground}15`
}}
>
<div className="flex gap-1.5">
<div className="w-3 h-3 rounded-full bg-red-500/80" />
<div className="w-3 h-3 rounded-full bg-yellow-500/80" />
<div className="w-3 h-3 rounded-full bg-green-500/80" />
</div>
<div
className="flex-1 text-center text-xs"
style={{ color: theme.colors.foreground, opacity: 0.5, fontFamily: font.family }}
>
user@server — bash
</div>
</div>
{/* Terminal content */}
<div
className="flex-1 p-4 font-mono overflow-auto"
style={{
color: theme.colors.foreground,
fontFamily: font.family,
fontSize: `${fontSize}px`,
lineHeight: 1.5,
}}
>
<div className="space-y-1">
<div>
<span style={{ color: theme.colors.green }}>user@server</span>
<span style={{ color: theme.colors.foreground }}>:</span>
<span style={{ color: theme.colors.blue }}>~</span>
<span style={{ color: theme.colors.foreground }}>$ </span>
<span>neofetch</span>
</div>
<div style={{ color: theme.colors.cyan }}>
{' _,met$$$$$gg. '}
</div>
<div style={{ color: theme.colors.cyan }}>
{' ,g$$$$$$$$$$$$$$$P. '}
<span style={{ color: theme.colors.foreground }}>user</span>
<span style={{ color: theme.colors.yellow }}>@</span>
<span style={{ color: theme.colors.foreground }}>server</span>
</div>
<div style={{ color: theme.colors.cyan }}>
{' ,g$$P" """Y$$.". '}
<span style={{ color: theme.colors.foreground }}>-----------</span>
</div>
<div style={{ color: theme.colors.cyan }}>
{' ,$$P\' `$$$. '}
<span style={{ color: theme.colors.blue }}>OS</span>
<span style={{ color: theme.colors.foreground }}>: Ubuntu 22.04 LTS</span>
</div>
<div style={{ color: theme.colors.cyan }}>
{'\',$$P ,ggs. `$$b: '}
<span style={{ color: theme.colors.blue }}>Kernel</span>
<span style={{ color: theme.colors.foreground }}>: 5.15.0-generic</span>
</div>
<div style={{ color: theme.colors.cyan }}>
{'`d$$\' ,$P"\' . $$$ '}
<span style={{ color: theme.colors.blue }}>Uptime</span>
<span style={{ color: theme.colors.foreground }}>: 42 days, 3 hours</span>
</div>
<div style={{ color: theme.colors.cyan }}>
{' $$P d$\' , $$P '}
<span style={{ color: theme.colors.blue }}>Shell</span>
<span style={{ color: theme.colors.foreground }}>: bash 5.1.16</span>
</div>
<div style={{ color: theme.colors.cyan }}>
{' $$: $$. - ,d$$\' '}
<span style={{ color: theme.colors.blue }}>Memory</span>
<span style={{ color: theme.colors.foreground }}>: 4.2G / 16G (26%)</span>
</div>
<div>&nbsp;</div>
<div>
<span style={{ color: theme.colors.green }}>user@server</span>
<span style={{ color: theme.colors.foreground }}>:</span>
<span style={{ color: theme.colors.blue }}>~</span>
<span style={{ color: theme.colors.foreground }}>$ </span>
<span>ls -la</span>
</div>
<div>
<span style={{ color: theme.colors.blue }}>drwxr-xr-x</span>
<span style={{ color: theme.colors.foreground }}> 5 user group </span>
<span style={{ color: theme.colors.yellow }}>4.0K</span>
<span style={{ color: theme.colors.foreground }}> Dec 12 10:30 </span>
<span style={{ color: theme.colors.blue }}>.config</span>
</div>
<div>
<span style={{ color: theme.colors.magenta }}>-rwxr-xr-x</span>
<span style={{ color: theme.colors.foreground }}> 1 user group </span>
<span style={{ color: theme.colors.yellow }}>2.1K</span>
<span style={{ color: theme.colors.foreground }}> Dec 11 15:22 </span>
<span style={{ color: theme.colors.green }}>deploy.sh</span>
</div>
<div>
<span style={{ color: theme.colors.cyan }}>lrwxrwxrwx</span>
<span style={{ color: theme.colors.foreground }}> 1 user group </span>
<span style={{ color: theme.colors.yellow }}> 24</span>
<span style={{ color: theme.colors.foreground }}> Dec 10 09:15 </span>
<span style={{ color: theme.colors.cyan }}>logs</span>
<span style={{ color: theme.colors.foreground }}> -{'>'} </span>
<span style={{ color: theme.colors.foreground }}>/var/log/app</span>
</div>
<div>&nbsp;</div>
<div>
<span style={{ color: theme.colors.green }}>user@server</span>
<span style={{ color: theme.colors.foreground }}>:</span>
<span style={{ color: theme.colors.blue }}>~</span>
<span style={{ color: theme.colors.foreground }}>$ </span>
<span
style={{
backgroundColor: theme.colors.cursor || theme.colors.foreground,
color: theme.colors.background
}}
>▋</span>
</div>
</div>
</div>
</div>
));
TerminalPreview.displayName = 'TerminalPreview';
export const ThemeCustomizeModal: React.FC<ThemeCustomizeModalProps> = ({
open,
onClose,
@@ -137,66 +354,6 @@ export const ThemeCustomizeModal: React.FC<ThemeCustomizeModalProps> = ({
if (!open) return null;
// Render theme item
const renderThemeItem = (theme: TerminalThemeConfig) => (
<button
key={theme.id}
onClick={() => handleThemeSelect(theme.id)}
className={cn(
'w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-left transition-all',
selectedTheme === theme.id
? 'bg-primary/15 ring-1 ring-primary'
: 'hover:bg-muted'
)}
>
{/* Color swatch */}
<div
className="w-8 h-8 rounded-md flex-shrink-0 flex flex-col justify-center items-start pl-1 gap-0.5 border border-border/50"
style={{ backgroundColor: theme.colors.background }}
>
<div className="h-1 w-3 rounded-full" style={{ backgroundColor: theme.colors.green }} />
<div className="h-1 w-5 rounded-full" style={{ backgroundColor: theme.colors.blue }} />
<div className="h-1 w-2 rounded-full" style={{ backgroundColor: theme.colors.yellow }} />
</div>
<div className="flex-1 min-w-0">
<div className={cn('text-xs font-medium truncate', selectedTheme === theme.id ? 'text-primary' : 'text-foreground')}>
{theme.name}
</div>
<div className="text-[10px] text-muted-foreground capitalize">{theme.type}</div>
</div>
{selectedTheme === theme.id && (
<Check size={14} className="text-primary flex-shrink-0" />
)}
</button>
);
// Render font item
const renderFontItem = (font: TerminalFont) => (
<button
key={font.id}
onClick={() => handleFontSelect(font.id)}
className={cn(
'w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-left transition-all',
selectedFont === font.id
? 'bg-primary/15 ring-1 ring-primary'
: 'hover:bg-muted'
)}
>
<div className="flex-1 min-w-0">
<div
className={cn('text-sm truncate', selectedFont === font.id ? 'text-primary' : 'text-foreground')}
style={{ fontFamily: font.family }}
>
{font.name}
</div>
<div className="text-[10px] text-muted-foreground truncate">{font.description}</div>
</div>
{selectedFont === font.id && (
<Check size={14} className="text-primary flex-shrink-0" />
)}
</button>
);
const modalContent = (
<div
className="fixed inset-0 flex items-center justify-center bg-black/60"
@@ -213,10 +370,7 @@ export const ThemeCustomizeModal: React.FC<ThemeCustomizeModalProps> = ({
<div className="w-8 h-8 rounded-lg flex items-center justify-center bg-primary/10">
<Palette size={16} className="text-primary" />
</div>
<div>
<h2 className="text-sm font-semibold text-foreground">Terminal Appearance</h2>
<p className="text-xs text-muted-foreground">Changes apply in real-time</p>
</div>
<h2 className="text-sm font-semibold text-foreground">Terminal Appearance</h2>
</div>
<button
onClick={handleCancel}
@@ -262,12 +416,26 @@ export const ThemeCustomizeModal: React.FC<ThemeCustomizeModalProps> = ({
<div className="flex-1 min-h-0 overflow-y-auto p-2">
{activeTab === 'theme' && (
<div className="space-y-1">
{TERMINAL_THEMES.map(renderThemeItem)}
{TERMINAL_THEMES.map(theme => (
<ThemeItem
key={theme.id}
theme={theme}
isSelected={selectedTheme === theme.id}
onSelect={handleThemeSelect}
/>
))}
</div>
)}
{activeTab === 'font' && (
<div className="space-y-1">
{TERMINAL_FONTS.map(renderFontItem)}
{TERMINAL_FONTS.map(font => (
<FontItem
key={font.id}
font={font}
isSelected={selectedFont === font.id}
onSelect={handleFontSelect}
/>
))}
</div>
)}
</div>
@@ -303,134 +471,7 @@ export const ThemeCustomizeModal: React.FC<ThemeCustomizeModalProps> = ({
{/* Right Panel - Large Preview */}
<div className="flex-1 flex flex-col min-w-0 p-4">
<div className="text-[10px] uppercase tracking-wider text-muted-foreground mb-3 font-semibold">Live Preview</div>
<div
className="flex-1 rounded-xl overflow-hidden border border-border flex flex-col"
style={{ backgroundColor: currentTheme.colors.background }}
>
{/* Fake title bar */}
<div
className="flex items-center gap-2 px-3 py-2 border-b shrink-0"
style={{
backgroundColor: currentTheme.colors.background,
borderColor: `${currentTheme.colors.foreground}15`
}}
>
<div className="flex gap-1.5">
<div className="w-3 h-3 rounded-full bg-red-500/80" />
<div className="w-3 h-3 rounded-full bg-yellow-500/80" />
<div className="w-3 h-3 rounded-full bg-green-500/80" />
</div>
<div
className="flex-1 text-center text-xs"
style={{ color: currentTheme.colors.foreground, opacity: 0.5, fontFamily: currentFont.family }}
>
user@server — bash
</div>
</div>
{/* Terminal content */}
<div
className="flex-1 p-4 font-mono overflow-auto"
style={{
color: currentTheme.colors.foreground,
fontFamily: currentFont.family,
fontSize: `${fontSize}px`,
lineHeight: 1.5,
}}
>
<div className="space-y-1">
<div>
<span style={{ color: currentTheme.colors.green }}>user@server</span>
<span style={{ color: currentTheme.colors.foreground }}>:</span>
<span style={{ color: currentTheme.colors.blue }}>~</span>
<span style={{ color: currentTheme.colors.foreground }}>$ </span>
<span>neofetch</span>
</div>
<div style={{ color: currentTheme.colors.cyan }}>
{' _,met$$$$$gg. '}
</div>
<div style={{ color: currentTheme.colors.cyan }}>
{' ,g$$$$$$$$$$$$$$$P. '}
<span style={{ color: currentTheme.colors.foreground }}>user</span>
<span style={{ color: currentTheme.colors.yellow }}>@</span>
<span style={{ color: currentTheme.colors.foreground }}>server</span>
</div>
<div style={{ color: currentTheme.colors.cyan }}>
{' ,g$$P" """Y$$.". '}
<span style={{ color: currentTheme.colors.foreground }}>-----------</span>
</div>
<div style={{ color: currentTheme.colors.cyan }}>
{' ,$$P\' `$$$. '}
<span style={{ color: currentTheme.colors.blue }}>OS</span>
<span style={{ color: currentTheme.colors.foreground }}>: Ubuntu 22.04 LTS</span>
</div>
<div style={{ color: currentTheme.colors.cyan }}>
{'\',$$P ,ggs. `$$b: '}
<span style={{ color: currentTheme.colors.blue }}>Kernel</span>
<span style={{ color: currentTheme.colors.foreground }}>: 5.15.0-generic</span>
</div>
<div style={{ color: currentTheme.colors.cyan }}>
{'`d$$\' ,$P"\' . $$$ '}
<span style={{ color: currentTheme.colors.blue }}>Uptime</span>
<span style={{ color: currentTheme.colors.foreground }}>: 42 days, 3 hours</span>
</div>
<div style={{ color: currentTheme.colors.cyan }}>
{' $$P d$\' , $$P '}
<span style={{ color: currentTheme.colors.blue }}>Shell</span>
<span style={{ color: currentTheme.colors.foreground }}>: bash 5.1.16</span>
</div>
<div style={{ color: currentTheme.colors.cyan }}>
{' $$: $$. - ,d$$\' '}
<span style={{ color: currentTheme.colors.blue }}>Memory</span>
<span style={{ color: currentTheme.colors.foreground }}>: 4.2G / 16G (26%)</span>
</div>
<div>&nbsp;</div>
<div>
<span style={{ color: currentTheme.colors.green }}>user@server</span>
<span style={{ color: currentTheme.colors.foreground }}>:</span>
<span style={{ color: currentTheme.colors.blue }}>~</span>
<span style={{ color: currentTheme.colors.foreground }}>$ </span>
<span>ls -la</span>
</div>
<div>
<span style={{ color: currentTheme.colors.blue }}>drwxr-xr-x</span>
<span style={{ color: currentTheme.colors.foreground }}> 5 user group </span>
<span style={{ color: currentTheme.colors.yellow }}>4.0K</span>
<span style={{ color: currentTheme.colors.foreground }}> Dec 12 10:30 </span>
<span style={{ color: currentTheme.colors.blue }}>.config</span>
</div>
<div>
<span style={{ color: currentTheme.colors.magenta }}>-rwxr-xr-x</span>
<span style={{ color: currentTheme.colors.foreground }}> 1 user group </span>
<span style={{ color: currentTheme.colors.yellow }}>2.1K</span>
<span style={{ color: currentTheme.colors.foreground }}> Dec 11 15:22 </span>
<span style={{ color: currentTheme.colors.green }}>deploy.sh</span>
</div>
<div>
<span style={{ color: currentTheme.colors.cyan }}>lrwxrwxrwx</span>
<span style={{ color: currentTheme.colors.foreground }}> 1 user group </span>
<span style={{ color: currentTheme.colors.yellow }}> 24</span>
<span style={{ color: currentTheme.colors.foreground }}> Dec 10 09:15 </span>
<span style={{ color: currentTheme.colors.cyan }}>logs</span>
<span style={{ color: currentTheme.colors.foreground }}> -{'>'} </span>
<span style={{ color: currentTheme.colors.foreground }}>/var/log/app</span>
</div>
<div>&nbsp;</div>
<div>
<span style={{ color: currentTheme.colors.green }}>user@server</span>
<span style={{ color: currentTheme.colors.foreground }}>:</span>
<span style={{ color: currentTheme.colors.blue }}>~</span>
<span style={{ color: currentTheme.colors.foreground }}>$ </span>
<span
style={{
backgroundColor: currentTheme.colors.cursor || currentTheme.colors.foreground,
color: currentTheme.colors.background
}}
>▋</span>
</div>
</div>
</div>
</div>
<TerminalPreview theme={currentTheme} font={currentFont} fontSize={fontSize} />
{/* Info line */}
<div className="mt-3 text-xs text-muted-foreground flex items-center justify-between">
+2
View File
@@ -17,3 +17,5 @@ export type { ChainProgress,TerminalConnectionDialogProps } from './TerminalConn
export { TerminalContextMenu } from './TerminalContextMenu';
export type { TerminalContextMenuProps } from './TerminalContextMenu';
export { createHighlightProcessor, highlightKeywords, compileHighlightRules } from './keywordHighlight';
+136
View File
@@ -0,0 +1,136 @@
import { KeywordHighlightRule } from "../../types";
// ESC character as unicode escape for ESLint compatibility
const ESC = "\u001b";
/**
* Convert a hex color to ANSI 24-bit true color escape sequence
* Format: ESC[38;2;R;G;Bm for foreground color
*/
function hexToAnsi(hex: string): string {
// Remove # if present
const cleanHex = hex.replace("#", "");
const r = parseInt(cleanHex.slice(0, 2), 16);
const g = parseInt(cleanHex.slice(2, 4), 16);
const b = parseInt(cleanHex.slice(4, 6), 16);
return `${ESC}[38;2;${r};${g};${b}m`;
}
const ANSI_RESET = `${ESC}[0m`;
// Regex to match ANSI escape sequences (to skip them during highlighting)
// Using RegExp constructor to avoid ESLint control character warning
// eslint-disable-next-line no-control-regex
const ANSI_ESCAPE_REGEX = /\u001b\[[0-9;]*[a-zA-Z]/g;
interface CompiledRule {
regex: RegExp;
ansiColor: string;
}
/**
* Pre-compile keyword highlight rules for better performance
*/
export function compileHighlightRules(
rules: KeywordHighlightRule[],
enabled: boolean
): CompiledRule[] {
if (!enabled) return [];
return rules
.filter((rule) => rule.enabled && rule.patterns.length > 0)
.map((rule) => {
// Combine all patterns with OR, case-insensitive
const combinedPattern = rule.patterns.join("|");
return {
regex: new RegExp(`(${combinedPattern})`, "gi"),
ansiColor: hexToAnsi(rule.color),
};
});
}
/**
* Apply keyword highlighting to terminal output
* This processes text and adds ANSI color codes for matched keywords
*
* Note: This is a simplified approach that works well for most cases.
* It processes the text while preserving existing ANSI escape sequences.
*/
export function highlightKeywords(
text: string,
compiledRules: CompiledRule[]
): string {
if (compiledRules.length === 0 || !text) {
return text;
}
// Split text into segments: ANSI sequences and regular text
const segments: Array<{ isAnsi: boolean; content: string }> = [];
let lastIndex = 0;
// Find all ANSI escape sequences
let match: RegExpExecArray | null;
const ansiRegex = new RegExp(ANSI_ESCAPE_REGEX.source, "g");
while ((match = ansiRegex.exec(text)) !== null) {
// Add text before this ANSI sequence
if (match.index > lastIndex) {
segments.push({
isAnsi: false,
content: text.slice(lastIndex, match.index),
});
}
// Add the ANSI sequence itself
segments.push({
isAnsi: true,
content: match[0],
});
lastIndex = match.index + match[0].length;
}
// Add remaining text after last ANSI sequence
if (lastIndex < text.length) {
segments.push({
isAnsi: false,
content: text.slice(lastIndex),
});
}
// Process only non-ANSI segments
const processedSegments = segments.map((segment) => {
if (segment.isAnsi) {
return segment.content;
}
let processed = segment.content;
// Apply each rule
for (const rule of compiledRules) {
processed = processed.replace(rule.regex, (matched) => {
return `${rule.ansiColor}${matched}${ANSI_RESET}`;
});
}
return processed;
});
return processedSegments.join("");
}
/**
* Create a highlight processor function with pre-compiled rules
* Use this for better performance when processing multiple chunks
*/
export function createHighlightProcessor(
rules: KeywordHighlightRule[],
enabled: boolean
): (text: string) => string {
const compiledRules = compileHighlightRules(rules, enabled);
if (compiledRules.length === 0) {
// Return identity function if no rules are enabled
return (text: string) => text;
}
return (text: string) => highlightKeywords(text, compiledRules);
}
+27
View File
@@ -311,11 +311,22 @@ export const DEFAULT_KEY_BINDINGS: KeyBinding[] = [
export type CursorShape = 'block' | 'bar' | 'underline';
export type RightClickBehavior = 'context-menu' | 'paste' | 'select-word';
export type LinkModifier = 'none' | 'ctrl' | 'alt' | 'meta';
export type TerminalEmulationType = 'xterm-256color' | 'xterm-16color' | 'xterm';
// Keyword highlighting configuration
export interface KeywordHighlightRule {
id: string;
label: string; // Display name (e.g., "Error", "Warning", "OK")
patterns: string[]; // Regex patterns to match
color: string; // Highlight color (hex)
enabled: boolean;
}
export interface TerminalSettings {
// Rendering
scrollback: number; // Number of lines kept in buffer
drawBoldInBrightColors: boolean; // Draw bold text in bright colors
terminalEmulationType: TerminalEmulationType; // Terminal emulation type (TERM env var)
// Font
fontLigatures: boolean; // Enable font ligatures
@@ -341,11 +352,25 @@ export interface TerminalSettings {
middleClickPaste: boolean; // Paste on middle-click
wordSeparators: string; // Characters for word selection
linkModifier: LinkModifier; // Modifier key to click links
// Keyword Highlighting
keywordHighlightEnabled: boolean;
keywordHighlightRules: KeywordHighlightRule[];
}
export const DEFAULT_KEYWORD_HIGHLIGHT_RULES: KeywordHighlightRule[] = [
{ id: 'error', label: 'Error', patterns: ['\\[error\\]', '\\[err\\]', '\\berror\\b', '\\bfail(ed)?\\b', '\\bfatal\\b', '\\bcritical\\b', '\\bexception\\b'], color: '#F87171', enabled: true },
{ id: 'warning', label: 'Warning', patterns: ['\\[warn(ing)?\\]', '\\bwarn(ing)?\\b', '\\bcaution\\b', '\\bdeprecated\\b'], color: '#FBBF24', enabled: true },
{ id: 'ok', label: 'OK', patterns: ['\\[ok\\]', '\\bok\\b', '\\bsuccess(ful)?\\b', '\\bpassed\\b', '\\bcompleted\\b', '\\bdone\\b'], color: '#34D399', enabled: true },
{ id: 'info', label: 'Info', patterns: ['\\[info\\]', '\\[notice\\]', '\\[note\\]', '\\bnotice\\b', '\\bnote\\b'], color: '#3B82F6', enabled: true },
{ id: 'debug', label: 'Debug', patterns: ['\\[debug\\]', '\\[trace\\]', '\\[verbose\\]', '\\bdebug\\b', '\\btrace\\b', '\\bverbose\\b'], color: '#A78BFA', enabled: true },
{ id: 'ip-mac', label: 'IP address & MAC', patterns: ['\\b(?:\\d{1,3}\\.){3}\\d{1,3}\\b', '\\b([0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}\\b'], color: '#EC4899', enabled: true },
];
export const DEFAULT_TERMINAL_SETTINGS: TerminalSettings = {
scrollback: 10000,
drawBoldInBrightColors: true,
terminalEmulationType: 'xterm-256color',
fontLigatures: true,
fontWeight: 400,
fontWeightBold: 700,
@@ -361,6 +386,8 @@ export const DEFAULT_TERMINAL_SETTINGS: TerminalSettings = {
middleClickPaste: true,
wordSeparators: ' ()[]{}\'"',
linkModifier: 'none',
keywordHighlightEnabled: true,
keywordHighlightRules: DEFAULT_KEYWORD_HIGHLIGHT_RULES,
};
export interface TerminalTheme {
+8
View File
@@ -173,6 +173,14 @@ const registerBridges = (win) => {
return true;
});
// Open external URL in default browser
ipcMain.handle("netcatty:openExternal", async (_event, url) => {
const { shell } = electronModule;
if (url && typeof url === 'string' && (url.startsWith('http://') || url.startsWith('https://'))) {
await shell.openExternal(url);
}
});
console.log('[Main] All bridges registered successfully');
};
+3
View File
@@ -325,6 +325,9 @@ const api = {
openSettingsWindow: () => ipcRenderer.invoke("netcatty:settings:open"),
closeSettingsWindow: () => ipcRenderer.invoke("netcatty:settings:close"),
// Open URL in default browser
openExternal: (url) => ipcRenderer.invoke("netcatty:openExternal", url),
// Port Forwarding API
startPortForward: async (options) => {
return ipcRenderer.invoke("netcatty:portforward:start", options);
Vendored
+3
View File
@@ -230,6 +230,9 @@ interface NetcattyBridge {
// Known Hosts
readKnownHosts?(): Promise<string | null>;
// Open URL in default browser
openExternal?(url: string): Promise<void>;
// Chain progress listener for jump host connections
// Callback receives: (currentHop: number, totalHops: number, hostLabel: string, status: string)
onChainProgress?(cb: (hop: number, total: number, label: string, status: string) => void): () => void;
+10
View File
@@ -20,6 +20,7 @@
"@radix-ui/react-tabs": "1.1.13",
"@xterm/addon-fit": "^0.10.0",
"@xterm/addon-serialize": "^0.13.0",
"@xterm/addon-web-links": "^0.11.0",
"@xterm/addon-webgl": "^0.18.0",
"@xterm/xterm": "^5.5.0",
"clsx": "2.1.1",
@@ -3298,6 +3299,15 @@
"@xterm/xterm": "^5.0.0"
}
},
"node_modules/@xterm/addon-web-links": {
"version": "0.11.0",
"resolved": "https://registry.npmmirror.com/@xterm/addon-web-links/-/addon-web-links-0.11.0.tgz",
"integrity": "sha512-nIHQ38pQI+a5kXnRaTgwqSHnX7KE6+4SVoceompgHL26unAxdfP6IPqUTSYPQgSwM56hsElfoNrrW5V7BUED/Q==",
"license": "MIT",
"peerDependencies": {
"@xterm/xterm": "^5.0.0"
}
},
"node_modules/@xterm/addon-webgl": {
"version": "0.18.0",
"resolved": "https://registry.npmmirror.com/@xterm/addon-webgl/-/addon-webgl-0.18.0.tgz",
+2 -1
View File
@@ -27,6 +27,7 @@
"@radix-ui/react-tabs": "1.1.13",
"@xterm/addon-fit": "^0.10.0",
"@xterm/addon-serialize": "^0.13.0",
"@xterm/addon-web-links": "^0.11.0",
"@xterm/addon-webgl": "^0.18.0",
"@xterm/xterm": "^5.5.0",
"clsx": "2.1.1",
@@ -59,4 +60,4 @@
"vite": "^7.2.7",
"wait-on": "^9.0.3"
}
}
}