diff --git a/src/renderer/src/components/settings/SettingsFormControls.tsx b/src/renderer/src/components/settings/SettingsFormControls.tsx index 27685dbc3..1f45f6489 100644 --- a/src/renderer/src/components/settings/SettingsFormControls.tsx +++ b/src/renderer/src/components/settings/SettingsFormControls.tsx @@ -259,6 +259,11 @@ type FontAutocompleteProps = { suggestions: string[] onChange: (value: string) => void placeholder?: string + /** Fires with whichever option the user is currently highlighting in the + * dropdown (via mouse hover or keyboard arrow), or null when nothing is + * highlighted / the dropdown is closed. Lets a consumer show a live + * preview of the font without committing the selection. */ + onPreviewFontFamily?: (font: string | null) => void } export function ThemePicker({ @@ -435,7 +440,8 @@ export function FontAutocomplete({ value, suggestions, onChange, - placeholder = 'SF Mono' + placeholder = 'SF Mono', + onPreviewFontFamily }: FontAutocompleteProps): React.JSX.Element { const [query, setQuery] = useState(value) const [prevValue, setPrevValue] = useState(value) @@ -512,6 +518,31 @@ export function FontAutocomplete({ optionRefs.current.get(highlightedFont)?.scrollIntoView({ block: 'nearest' }) }, [filteredSuggestions, highlightedIndex, open]) + // Why: notify the consumer of the currently-highlighted font so it can + // render a live preview. Closing the dropdown or moving past all options + // clears the preview back to the committed value. + useEffect(() => { + if (!onPreviewFontFamily) { + return + } + if (!open || highlightedIndex < 0) { + onPreviewFontFamily(null) + return + } + onPreviewFontFamily(filteredSuggestions[highlightedIndex] ?? null) + }, [filteredSuggestions, highlightedIndex, onPreviewFontFamily, open]) + + // Why: clear the live preview if this autocomplete is unmounted while a + // hovered preview is still active (e.g. the section is filtered out by + // settings search) — otherwise the consumer keeps showing a stale font. + useEffect( + () => () => { + onPreviewFontFamily?.(null) + }, + // oxlint-disable-next-line react-hooks/exhaustive-deps + [] + ) + const commitValue = (nextValue: string): void => { setQuery(nextValue) onChange(nextValue) diff --git a/src/renderer/src/components/settings/TerminalPane.tsx b/src/renderer/src/components/settings/TerminalPane.tsx index 2c6eb01e2..c856c822e 100644 --- a/src/renderer/src/components/settings/TerminalPane.tsx +++ b/src/renderer/src/components/settings/TerminalPane.tsx @@ -19,11 +19,7 @@ import { Input } from '../ui/input' import { Separator } from '../ui/separator' import { ToggleGroup, ToggleGroupItem } from '../ui/toggle-group' import { Minus, Plus } from 'lucide-react' -import { - clampNumber, - resolveEffectiveTerminalAppearance, - resolvePaneStyleOptions -} from '@/lib/terminal-theme' +import { clampNumber, resolvePaneStyleOptions } from '@/lib/terminal-theme' import { FontAutocomplete, NumberField, @@ -62,6 +58,7 @@ import { TerminalWindowSection } from './TerminalWindowSection' import { GhosttyImportModal } from './GhosttyImportModal' import type { UseGhosttyImportReturn } from './useGhosttyImport' import { ManageSessionsSection } from './ManageSessionsSection' +import { TerminalSettingsPreview } from './TerminalSettingsPreview' type TerminalPaneProps = { settings: GlobalSettings @@ -96,15 +93,9 @@ export function TerminalPane({ const isMac = isMacUserAgent() const [themeSearchDark, setThemeSearchDark] = useState('') const [themeSearchLight, setThemeSearchLight] = useState('') + // Why: hover preview lets the font picker update the sample without committing a setting. + const [previewFontFamily, setPreviewFontFamily] = useState(null) - const darkPreviewAppearance = resolveEffectiveTerminalAppearance( - { ...settings, theme: 'dark' }, - systemPrefersDark - ) - const lightPreviewAppearance = resolveEffectiveTerminalAppearance( - { ...settings, theme: 'light' }, - systemPrefersDark - ) const paneStyleOptions = resolvePaneStyleOptions(settings) const detectedLayout = useDetectedOptionAsAlt() const detectedLayoutLabel = @@ -166,183 +157,193 @@ export function TerminalPane({ ) : null, matchesSettingsSearch(searchQuery, TERMINAL_TYPOGRAPHY_SEARCH_ENTRIES) ? ( -
- +
+
+ -
- - + - - { - const value = parseInt(e.target.value, 10) - if (!Number.isNaN(value) && value >= 10 && value <= 24) { - updateSettings({ terminalFontSize: value }) - } - }} - className="w-14 text-center tabular-nums" - /> - - px -
- } - /> - + keywords={['terminal', 'typography', 'text size']} + > + + + { + const value = parseInt(e.target.value, 10) + if (!Number.isNaN(value) && value >= 10 && value <= 24) { + updateSettings({ terminalFontSize: value }) + } + }} + className="w-14 text-center tabular-nums" + /> + + px +
+ } + /> + - - updateSettings({ terminalFontFamily: value })} - /> - } - /> - + keywords={['terminal', 'typography', 'font']} + > + updateSettings({ terminalFontFamily: value })} + onPreviewFontFamily={setPreviewFontFamily} + /> + } + /> + - - - updateSettings({ - terminalFontWeight: normalizeTerminalFontWeight(value) - }) - } - /> - + keywords={['terminal', 'typography', 'weight']} + > + + updateSettings({ + terminalFontWeight: normalizeTerminalFontWeight(value) + }) + } + /> + - - - updateSettings({ - terminalLineHeight: clampNumber(value, 1, 3) - }) - } - /> - + keywords={['terminal', 'typography', 'line height', 'spacing']} + > + + updateSettings({ + terminalLineHeight: clampNumber(value, 1, 3) + }) + } + /> + - - updateSettings({ terminalLigatures: option })} - options={[ - { value: 'auto', label: 'Auto' }, - { value: 'on', label: 'On' }, - { value: 'off', label: 'Off' } - ]} - /> - } - /> - {/* Why: surface the resolved state explicitly so the "Auto" label - isn't ambiguous when a user is staring at it. */} -

- Ligatures are currently{' '} - {resolveTerminalLigaturesEnabled( - settings.terminalLigatures, - settings.terminalFontFamily - ) - ? 'enabled' - : 'disabled'} - . -

-
+ + updateSettings({ terminalLigatures: option })} + options={[ + { value: 'auto', label: 'Auto' }, + { value: 'on', label: 'On' }, + { value: 'off', label: 'Off' } + ]} + /> + } + /> + {/* Why: surface the resolved state explicitly so the "Auto" label + isn't ambiguous when a user is staring at it. */} +

+ Ligatures are currently{' '} + {resolveTerminalLigaturesEnabled( + settings.terminalLigatures, + settings.terminalFontFamily + ) + ? 'enabled' + : 'disabled'} + . +

+
+ +
) : null, matchesSettingsSearch(searchQuery, TERMINAL_RENDERING_SEARCH_ENTRIES) ? ( @@ -627,8 +628,7 @@ export function TerminalPane({ themeSearchDark={themeSearchDark} setThemeSearchDark={setThemeSearchDark} updateSettings={updateSettings} - previewProps={paneStyleOptions} - darkPreviewAppearance={darkPreviewAppearance} + previewFontFamily={previewFontFamily} /> ) : null, matchesSettingsSearch(searchQuery, TERMINAL_LIGHT_THEME_SEARCH_ENTRIES) ? ( @@ -638,8 +638,7 @@ export function TerminalPane({ themeSearchLight={themeSearchLight} setThemeSearchLight={setThemeSearchLight} updateSettings={updateSettings} - previewProps={paneStyleOptions} - lightPreviewAppearance={lightPreviewAppearance} + previewFontFamily={previewFontFamily} /> ) : null, matchesSettingsSearch(searchQuery, TERMINAL_SETUP_SCRIPT_SEARCH_ENTRIES) ? ( diff --git a/src/renderer/src/components/settings/TerminalSettingsPreview.lifecycle.test.tsx b/src/renderer/src/components/settings/TerminalSettingsPreview.lifecycle.test.tsx new file mode 100644 index 000000000..01dbca718 --- /dev/null +++ b/src/renderer/src/components/settings/TerminalSettingsPreview.lifecycle.test.tsx @@ -0,0 +1,266 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { Mock } from 'vitest' +import type { GlobalSettings } from '../../../../shared/types' + +type Cleanup = () => void + +type MockTerminalInstance = { + options: Record + open: Mock + write: Mock + reset: Mock + dispose: Mock + loadAddon: Mock +} + +type MockLigaturesAddonInstance = { + dispose: Mock +} + +const mockReactRuntime = vi.hoisted(() => ({ + cleanups: [] as Cleanup[], + container: { nodeName: 'PREVIEW' }, + refCallIndex: 0 +})) + +const mockXterm = vi.hoisted(() => ({ + instances: [] as MockTerminalInstance[], + nextLoadAddonError: null as Error | null, + nextOpenError: null as Error | null +})) + +const mockLigaturesAddon = vi.hoisted(() => ({ + enabled: false, + instances: [] as MockLigaturesAddonInstance[] +})) + +vi.mock('react', async () => { + const actual = await vi.importActual('react') // eslint-disable-line @typescript-eslint/consistent-type-imports -- vi.importActual requires inline import() + return { + ...actual, + useEffect: (effect: () => void | Cleanup) => { + const cleanup = effect() + if (typeof cleanup === 'function') { + mockReactRuntime.cleanups.push(cleanup) + } + }, + useMemo: (factory: () => unknown) => factory(), + useRef: (initialValue: unknown) => { + const ref = { current: initialValue } + if (mockReactRuntime.refCallIndex === 0) { + ref.current = mockReactRuntime.container + } + mockReactRuntime.refCallIndex += 1 + return ref + }, + useState: (initialValue: unknown) => [ + typeof initialValue === 'function' ? (initialValue as () => unknown)() : initialValue, + vi.fn() + ] + } +}) + +vi.mock('@xterm/xterm', () => ({ + Terminal: class Terminal { + options: Record + open: Mock + write: Mock + reset: Mock + dispose: Mock + loadAddon: Mock + + constructor(options: Record) { + this.options = { ...options } + this.open = vi.fn(() => { + if (mockXterm.nextOpenError) { + throw mockXterm.nextOpenError + } + }) + this.write = vi.fn() + this.reset = vi.fn() + this.dispose = vi.fn() + this.loadAddon = vi.fn(() => { + if (mockXterm.nextLoadAddonError) { + throw mockXterm.nextLoadAddonError + } + }) + mockXterm.instances.push(this) + } + } +})) + +vi.mock('@xterm/addon-ligatures', () => ({ + LigaturesAddon: class LigaturesAddon { + dispose: Mock + + constructor() { + this.dispose = vi.fn() + mockLigaturesAddon.instances.push(this) + } + } +})) + +vi.mock('@/components/ui/card', () => ({ + Card: 'Card', + CardContent: 'CardContent', + CardDescription: 'CardDescription', + CardHeader: 'CardHeader', + CardTitle: 'CardTitle' +})) + +vi.mock('@/lib/pane-manager/pane-terminal-options', () => ({ + buildDefaultTerminalOptions: () => ({ scrollback: 0 }) +})) + +vi.mock('@/components/terminal-pane/layout-serialization', () => ({ + buildFontFamily: (font: string) => `built:${font}` +})) + +vi.mock('@/components/terminal-pane/terminal-appearance', () => ({ + composeActiveTerminalTheme: () => ({ background: '#111111', foreground: '#eeeeee' }) +})) + +vi.mock('@/lib/terminal-theme', () => ({ + clampNumber: (value: number, min: number, max: number) => Math.max(min, Math.min(max, value)), + resolveEffectiveTerminalAppearance: () => ({ + dividerColor: '#333333', + theme: { background: '#000000' } + }) +})) + +vi.mock('../../../../shared/terminal-fonts', () => ({ + resolveTerminalFontWeights: () => ({ fontWeight: 500, fontWeightBold: 700 }) +})) + +vi.mock('../../../../shared/terminal-ligatures', () => ({ + resolveTerminalLigaturesEnabled: () => mockLigaturesAddon.enabled +})) + +import { TerminalSettingsPreview } from './TerminalSettingsPreview' + +function makeSettings(overrides: Partial = {}): GlobalSettings { + return { + theme: 'dark', + terminalFontFamily: 'SF Mono', + terminalFontSize: 14, + terminalFontWeight: 400, + terminalLineHeight: 1, + terminalCursorStyle: 'bar', + terminalCursorBlink: true, + terminalLigatures: 'off', + terminalThemeDark: 'Dark', + terminalThemeLight: 'Light', + terminalUseSeparateLightTheme: true, + terminalDividerColorDark: '#333333', + terminalDividerColorLight: '#dddddd', + terminalColorOverrides: {}, + terminalBackgroundOpacity: 1, + terminalCursorOpacity: 1, + terminalDividerThicknessPx: 3, + terminalInactivePaneOpacity: 0.6, + ...overrides + } as GlobalSettings +} + +function renderPreview(settings = makeSettings()): void { + TerminalSettingsPreview({ + title: 'Preview', + description: 'Preview description', + settings, + systemPrefersDark: true + }) +} + +function runCleanups(): void { + for (const cleanup of [...mockReactRuntime.cleanups].reverse()) { + cleanup() + } + mockReactRuntime.cleanups.length = 0 +} + +describe('TerminalSettingsPreview terminal lifecycle', () => { + beforeEach(() => { + mockReactRuntime.cleanups.length = 0 + mockReactRuntime.refCallIndex = 0 + mockXterm.instances.length = 0 + mockXterm.nextLoadAddonError = null + mockXterm.nextOpenError = null + mockLigaturesAddon.enabled = false + mockLigaturesAddon.instances.length = 0 + }) + + it('initializes once, writes once on mount, and disposes on unmount', () => { + renderPreview() + + expect(mockXterm.instances).toHaveLength(1) + const terminal = mockXterm.instances[0] + expect(terminal.open).toHaveBeenCalledOnce() + expect(terminal.open).toHaveBeenCalledWith(mockReactRuntime.container) + expect(terminal.write).toHaveBeenCalledOnce() + expect(terminal.reset).not.toHaveBeenCalled() + expect(terminal.options).toMatchObject({ + allowTransparency: false, + cols: 36, + cursorBlink: true, + cursorInactiveStyle: 'bar', + cursorStyle: 'bar', + disableStdin: true, + fontFamily: 'built:SF Mono', + fontSize: 14, + fontWeight: 500, + fontWeightBold: 700, + lineHeight: 1, + rows: 15, + scrollback: 0, + theme: { background: '#111111', foreground: '#eeeeee' } + }) + + runCleanups() + expect(terminal.dispose).toHaveBeenCalledOnce() + }) + + it('disposes the ligatures addon before disposing the terminal', () => { + mockLigaturesAddon.enabled = true + + renderPreview() + + const terminal = mockXterm.instances[0] + const addon = mockLigaturesAddon.instances[0] + expect(terminal.loadAddon).toHaveBeenCalledOnce() + expect(terminal.loadAddon).toHaveBeenCalledWith(addon) + + runCleanups() + expect(addon.dispose).toHaveBeenCalledOnce() + expect(terminal.dispose).toHaveBeenCalledOnce() + }) + + it('disposes the ligatures addon if loading it fails', () => { + mockLigaturesAddon.enabled = true + mockXterm.nextLoadAddonError = new Error('load addon failed') + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) + + try { + renderPreview() + + const addon = mockLigaturesAddon.instances[0] + expect(addon.dispose).toHaveBeenCalledOnce() + expect(mockXterm.instances[0].dispose).not.toHaveBeenCalled() + + runCleanups() + expect(mockXterm.instances[0].dispose).toHaveBeenCalledOnce() + } finally { + warnSpy.mockRestore() + } + }) + + it('disposes a partially created terminal if open fails', () => { + const openError = new Error('open failed') + mockXterm.nextOpenError = openError + + expect(() => renderPreview()).toThrow(openError) + + expect(mockXterm.instances).toHaveLength(1) + expect(mockXterm.instances[0].dispose).toHaveBeenCalledOnce() + expect(mockReactRuntime.cleanups).toHaveLength(0) + }) +}) diff --git a/src/renderer/src/components/settings/TerminalSettingsPreview.tsx b/src/renderer/src/components/settings/TerminalSettingsPreview.tsx new file mode 100644 index 000000000..3462ca5e1 --- /dev/null +++ b/src/renderer/src/components/settings/TerminalSettingsPreview.tsx @@ -0,0 +1,353 @@ +import { useEffect, useMemo, useRef, useState } from 'react' +import { Terminal } from '@xterm/xterm' +import { LigaturesAddon } from '@xterm/addon-ligatures' +import { Moon, Sun } from 'lucide-react' +import '@xterm/xterm/css/xterm.css' +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card' +import { buildDefaultTerminalOptions } from '@/lib/pane-manager/pane-terminal-options' +import { buildFontFamily } from '@/components/terminal-pane/layout-serialization' +import { composeActiveTerminalTheme } from '@/components/terminal-pane/terminal-appearance' +import { clampNumber, resolveEffectiveTerminalAppearance } from '@/lib/terminal-theme' +import { resolveTerminalFontWeights } from '../../../../shared/terminal-fonts' +import { resolveTerminalLigaturesEnabled } from '../../../../shared/terminal-ligatures' +import { PREVIEW_BUFFER } from './terminal-preview-content' +import { SettingsSwitch } from './SettingsFormControls' +import type { GlobalSettings } from '../../../../shared/types' + +// Why: pin cols/rows so PREVIEW_BUFFER never wraps. Sized so the longest +// line (the def total signature, 32 chars) plus a few cols of margin fits +// the xterm canvas in the xl right-column at the default 14px font with +// the divider + stub pane carved off the right side. Larger fonts will +// extend past the xterm box's right edge — the box clips, which is +// preferable to wrapping mid-content. +const PREVIEW_COLS = 36 +const PREVIEW_ROWS = 15 + +// Why: the old TerminalThemePreview rendered two side-by-side panes so the +// user could see the divider + inactive opacity in context. Keep that +// affordance with a real xterm on the left and a small color-only stub on +// the right. 40px is wide enough to read the inactive opacity dim against +// the active xterm, narrow enough not to crowd content. +const STUB_PANE_PX = 40 + +type PreviewMode = 'dark' | 'light' + +type TerminalSettingsPreviewProps = { + title: string + description?: string + settings: GlobalSettings + systemPrefersDark: boolean + /** Optional override for `settings.terminalFontFamily`. Set by the font + * picker while the user hovers a dropdown option so they can preview a + * font without committing the selection. */ + previewFontFamily?: string | null + /** Force the preview into this mode regardless of app settings. Used by + * the Dark/Light theme sections so each pins its own theme. When set, + * the in-header theme toggle is hidden. */ + modeOverride?: PreviewMode + /** When true, render a Moon/Sun toggle in the card header so the user + * can flip the preview between dark and light themes without changing + * the app theme. Initial mode follows the active app theme. Ignored + * when `modeOverride` is set. */ + showThemeToggle?: boolean +} + +function resolveAppMode( + settings: Pick, + systemPrefersDark: boolean +): PreviewMode { + if (settings.theme === 'system') { + return systemPrefersDark ? 'dark' : 'light' + } + return settings.theme +} + +export function TerminalSettingsPreview({ + title, + description, + settings, + systemPrefersDark, + previewFontFamily, + modeOverride, + showThemeToggle +}: TerminalSettingsPreviewProps): React.JSX.Element { + const containerRef = useRef(null) + const terminalRef = useRef(null) + const ligaturesAddonRef = useRef(null) + const skipInitialOptionMutationRef = useRef(false) + const skipInitialThemeRewriteRef = useRef(false) + + const effectiveFontFamily = previewFontFamily || settings.terminalFontFamily + + // Why: lazy-init from the active app theme so the toggle starts in the + // user's current mode. After init the toggle is independent — flipping + // it doesn't change app settings, and changing the app theme later + // doesn't reset the toggle. + const [togglePreviewMode, setTogglePreviewMode] = useState(() => + resolveAppMode(settings, systemPrefersDark) + ) + const [previewPaneDividerVisible, setPreviewPaneDividerVisible] = useState(false) + + // Why: precedence — modeOverride pins the mode; otherwise the in-header + // toggle drives it; otherwise follow whatever the app is set to right + // now (recomputed each render so plain previews track app theme changes). + const effectiveMode: PreviewMode = + modeOverride ?? + (showThemeToggle ? togglePreviewMode : resolveAppMode(settings, systemPrefersDark)) + + // Why: reuse the live-pane resolver so divider color, theme palette, and + // the dark/light variant rules (e.g. `useSeparateLightTheme`) stay in + // lockstep with what real terminal panes render. + // Why: list each property resolveEffectiveTerminalAppearance reads instead + // of the whole settings object so unrelated changes (font, cursor) don't + // re-derive the appearance. The lint can't see that settings flows through + // the helper to those specific properties. + const appearance = useMemo( + () => + resolveEffectiveTerminalAppearance({ ...settings, theme: effectiveMode }, systemPrefersDark), + // oxlint-disable-next-line react-hooks/exhaustive-deps + [ + effectiveMode, + settings.terminalThemeDark, + settings.terminalThemeLight, + settings.terminalUseSeparateLightTheme, + settings.terminalDividerColorDark, + settings.terminalDividerColorLight, + systemPrefersDark + ] + ) + + // Why: same — list the composeActiveTerminalTheme inputs explicitly so font + // and cursor option changes don't trigger a buffer rewrite. + const composedTheme = useMemo( + () => composeActiveTerminalTheme(appearance.theme, settings), + // oxlint-disable-next-line react-hooks/exhaustive-deps + [ + appearance, + settings.terminalColorOverrides, + settings.terminalBackgroundOpacity, + settings.terminalCursorOpacity + ] + ) + + const dividerThicknessPx = clampNumber(settings.terminalDividerThicknessPx, 1, 32) + const inactivePaneOpacity = clampNumber(settings.terminalInactivePaneOpacity, 0, 1) + const paneBackground = composedTheme?.background ?? '#000' + + useEffect(() => { + const container = containerRef.current + if (!container) { + return + } + const weights = resolveTerminalFontWeights(settings.terminalFontWeight) + skipInitialOptionMutationRef.current = true + skipInitialThemeRewriteRef.current = true + // Why: DOM renderer only — multiple previews can mount at once and + // WebGL contexts are scarce. + // Why disableStdin: read-only preview. tabIndex/aria-hidden on the + // wrapper don't reach xterm's internal textarea; disableStdin does. + const terminal = new Terminal({ + ...buildDefaultTerminalOptions(), + disableStdin: true, + // Why mirror cursorInactiveStyle: xterm renders the cursor as a hollow + // outline when the terminal is not focused. The preview is read-only and + // never gets focused, so without mirroring the user wouldn't see their + // selected cursor shape on the trailing prompt. + cursorInactiveStyle: settings.terminalCursorStyle, + cursorStyle: settings.terminalCursorStyle, + cursorBlink: settings.terminalCursorBlink, + fontSize: settings.terminalFontSize, + fontFamily: buildFontFamily(effectiveFontFamily), + fontWeight: weights.fontWeight, + fontWeightBold: weights.fontWeightBold, + lineHeight: settings.terminalLineHeight, + theme: composedTheme ?? undefined, + allowTransparency: + settings.terminalBackgroundOpacity !== undefined && settings.terminalBackgroundOpacity < 1, + cols: PREVIEW_COLS, + rows: PREVIEW_ROWS + }) + terminalRef.current = terminal + + try { + terminal.open(container) + terminal.write(PREVIEW_BUFFER) + } catch (err) { + terminalRef.current = null + terminal.dispose() + throw err + } + + return () => { + ligaturesAddonRef.current?.dispose() + ligaturesAddonRef.current = null + terminal.dispose() + terminalRef.current = null + } + // Why empty deps: mount effect intentionally runs once. Subsequent + // setting changes (including cursor style) flow through the dedicated + // option-mutation effects below. + // oxlint-disable-next-line react-hooks/exhaustive-deps + }, []) + + // Why: font/cursor options are mutated directly so the preview repaints in + // xterm's normal cycle. No fit/refit needed since cols/rows are pinned. + useEffect(() => { + const terminal = terminalRef.current + if (!terminal) { + return + } + if (skipInitialOptionMutationRef.current) { + skipInitialOptionMutationRef.current = false + return + } + const weights = resolveTerminalFontWeights(settings.terminalFontWeight) + terminal.options.fontSize = settings.terminalFontSize + terminal.options.fontFamily = buildFontFamily(effectiveFontFamily) + terminal.options.fontWeight = weights.fontWeight + terminal.options.fontWeightBold = weights.fontWeightBold + terminal.options.lineHeight = settings.terminalLineHeight + terminal.options.cursorStyle = settings.terminalCursorStyle + // Why: see constructor — mirror so the unfocused cursor reflects the + // user's chosen shape (xterm defaults inactive to 'outline'). + terminal.options.cursorInactiveStyle = settings.terminalCursorStyle + terminal.options.cursorBlink = settings.terminalCursorBlink + }, [ + settings.terminalFontSize, + effectiveFontFamily, + settings.terminalFontWeight, + settings.terminalLineHeight, + settings.terminalCursorStyle, + settings.terminalCursorBlink + ]) + + useEffect(() => { + const terminal = terminalRef.current + if (!terminal || !composedTheme) { + return + } + terminal.options.theme = composedTheme + // Why: matches the live pane policy in applyTerminalAppearance — without + // this, an opacity < 1 background renders opaque inside xterm even though + // the theme color carries an alpha channel. + terminal.options.allowTransparency = + settings.terminalBackgroundOpacity !== undefined && settings.terminalBackgroundOpacity < 1 + if (skipInitialThemeRewriteRef.current) { + skipInitialThemeRewriteRef.current = false + return + } + // Why reset() not clear(): clear() keeps the row the cursor sits on, and + // our buffer ends mid-line on the prompt — so a follow-up clear+write + // would leave the trailing prompt fragment and append the new buffer + // beneath it, producing the duplicated content seen during font swaps. + // reset() restores cursor home + wipes the buffer so the rewrite starts + // from a clean slate. + terminal.reset() + terminal.write(PREVIEW_BUFFER) + }, [composedTheme, settings.terminalBackgroundOpacity]) + + useEffect(() => { + const terminal = terminalRef.current + if (!terminal) { + return + } + const enabled = resolveTerminalLigaturesEnabled(settings.terminalLigatures, effectiveFontFamily) + const current = ligaturesAddonRef.current + if (enabled && !current) { + const addon = new LigaturesAddon() + try { + terminal.loadAddon(addon) + ligaturesAddonRef.current = addon + } catch (err) { + addon.dispose() + console.warn('[settings preview] ligatures addon failed to attach', err) + ligaturesAddonRef.current = null + } + } else if (!enabled && current) { + current.dispose() + ligaturesAddonRef.current = null + } + }, [settings.terminalLigatures, effectiveFontFamily]) + + const showToggle = showThemeToggle && modeOverride === undefined + + return ( + + +
+
+ {title} + {description ? {description} : null} +
+
+
+ Pane divider + setPreviewPaneDividerVisible((visible) => !visible)} + ariaLabel="Show pane divider in preview" + /> +
+ {showToggle ? ( +
+ {(['dark', 'light'] as const).map((mode) => ( + + ))} +
+ ) : null} +
+
+
+ + {/* Why: flex layout with xterm on the left and a stub pane on the + right keeps inactive-pane opacity visible. The divider stays + preview-only and opt-in so the default preview remains clean. */} +
+
) @@ -100,8 +85,7 @@ export function LightTerminalThemeSection({ themeSearchLight, setThemeSearchLight, updateSettings, - previewProps, - lightPreviewAppearance + previewFontFamily }: LightTerminalThemeSectionProps): React.JSX.Element { return (
@@ -137,15 +121,9 @@ export function LightTerminalThemeSection({ -
-
-
+ {settings.terminalUseSeparateLightTheme ? ( +
+

Light Theme

@@ -184,17 +162,16 @@ export function LightTerminalThemeSection({
-
-
+ ) : null}
) } diff --git a/src/renderer/src/components/settings/__snapshots__/terminal-preview-content.test.ts.snap b/src/renderer/src/components/settings/__snapshots__/terminal-preview-content.test.ts.snap new file mode 100644 index 000000000..1c8628b31 --- /dev/null +++ b/src/renderer/src/components/settings/__snapshots__/terminal-preview-content.test.ts.snap @@ -0,0 +1,19 @@ +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html + +exports[`PREVIEW_BUFFER > matches the locked snapshot 1`] = ` +"~/orca main * $ npm test +  PASS  src/preview.test.ts + ✓ renders sample output (3ms) + ✗ ligatures: => != >= <= === + +def total(xs: list[int]) -> int: + """Sum the values.""" + return sum(x for x in xs) + +~/orca main * $ git diff +@@ -1,2 +1,3 @@ +-const size = 13 ++const size = 14 + +~/orca main * $ " +`; diff --git a/src/renderer/src/components/settings/terminal-preview-content.test.ts b/src/renderer/src/components/settings/terminal-preview-content.test.ts new file mode 100644 index 000000000..510bc43eb --- /dev/null +++ b/src/renderer/src/components/settings/terminal-preview-content.test.ts @@ -0,0 +1,26 @@ +import { describe, expect, it } from 'vitest' +import { PREVIEW_BUFFER } from './terminal-preview-content' + +describe('PREVIEW_BUFFER', () => { + it('contains the canonical content markers', () => { + // Why: strip ANSI before matching so re-coloring a marker (e.g. splitting + // "def render" into separate keyword/identifier spans) doesn't break this + // test — what matters is the visible text the user reads. + // eslint-disable-next-line no-control-regex + const stripped = PREVIEW_BUFFER.replace(/\x1b\[[0-9;]*m/g, '') + expect(stripped).toContain('npm test') + expect(stripped).toContain('PASS') + expect(stripped).toContain('ligatures: => != >= <= ===') + expect(stripped).toContain('git diff') + expect(stripped).toContain('def total') + }) + + it('ends without a trailing newline so the cursor parks on the prompt', () => { + expect(PREVIEW_BUFFER.endsWith('\n')).toBe(false) + expect(PREVIEW_BUFFER).toMatch(/\$ $/) + }) + + it('matches the locked snapshot', () => { + expect(PREVIEW_BUFFER).toMatchSnapshot() + }) +}) diff --git a/src/renderer/src/components/settings/terminal-preview-content.ts b/src/renderer/src/components/settings/terminal-preview-content.ts new file mode 100644 index 000000000..8f301b1b3 --- /dev/null +++ b/src/renderer/src/components/settings/terminal-preview-content.ts @@ -0,0 +1,45 @@ +// SGR escape helpers — keep tiny and local; xterm interprets these as ANSI. +const RESET = '\x1b[0m' +const DIM = '\x1b[2m' +const ITALIC = '\x1b[3m' +const RED = '\x1b[31m' +const GREEN = '\x1b[32m' +const YELLOW = '\x1b[33m' +const BLUE = '\x1b[34m' +const MAGENTA = '\x1b[35m' +const CYAN = '\x1b[36m' +const BG_GREEN = '\x1b[42m' +const FG_BLACK = '\x1b[30m' + +function prompt(): string { + // Why: short two-segment prompt — cwd + branch — so the preview reads as a + // real shell line without using too many columns. + return `${BLUE}~/orca${RESET} ${MAGENTA}main${RESET} ${YELLOW}*${RESET} $ ` +} + +// Why: every line must fit in PREVIEW_COLS (see TerminalSettingsPreview) so +// xterm doesn't wrap mid-content at the default 14px font. Longest visible +// line below is the def total signature at 32 chars. +const lines: string[] = [ + `${prompt()}npm test`, + ` ${BG_GREEN}${FG_BLACK} PASS ${RESET} src/preview.test.ts`, + ` ${GREEN}✓${RESET} renders sample output ${DIM}(3ms)${RESET}`, + ` ${RED}✗ ligatures: => != >= <= ===${RESET}`, + ``, + `${YELLOW}def${RESET} ${CYAN}total${RESET}(xs: list[${CYAN}int${RESET}]) -> ${CYAN}int${RESET}:`, + ` ${ITALIC}${GREEN}"""Sum the values."""${RESET}`, + ` ${YELLOW}return${RESET} ${CYAN}sum${RESET}(x ${YELLOW}for${RESET} x ${YELLOW}in${RESET} xs)`, + ``, + `${prompt()}git diff`, + `${CYAN}@@ -1,2 +1,3 @@${RESET}`, + `${RED}-const size = 13${RESET}`, + `${GREEN}+const size = 14${RESET}`, + ``, + `${prompt()}` +] + +// Why: xterm interprets `\n` as line-feed only (no carriage return) by default +// for `term.write`. We need `\r\n` between visual lines so the cursor returns +// to column 0; otherwise each subsequent line starts where the previous one +// ended. +export const PREVIEW_BUFFER = lines.join('\r\n') diff --git a/src/renderer/src/components/tab-group/TabGroupPanel.tsx b/src/renderer/src/components/tab-group/TabGroupPanel.tsx index f5ff12e78..672efc87b 100644 --- a/src/renderer/src/components/tab-group/TabGroupPanel.tsx +++ b/src/renderer/src/components/tab-group/TabGroupPanel.tsx @@ -171,7 +171,6 @@ export default function TabGroupPanel({ const actionChromeClassName = `flex shrink-0 items-center gap-0.5 overflow-hidden transition-[opacity] duration-150 ${ isFocused ? 'ml-1.5 pointer-events-auto opacity-100' : 'pointer-events-none opacity-0 w-0' }` - return (
{ + function settingsWith(partial: Partial): GlobalSettings { + return { + terminalColorOverrides: undefined, + terminalCursorOpacity: undefined, + terminalBackgroundOpacity: undefined, + ...partial + } as GlobalSettings + } + + it('returns the base theme when no overrides apply', () => { + const base = { background: '#101010', foreground: '#fafafa', cursor: '#fafafa' } + const result = composeActiveTerminalTheme(base, settingsWith({})) + expect(result).toEqual(base) + }) + + it('layers terminalColorOverrides on top of the base theme', () => { + const base = { background: '#101010', foreground: '#fafafa' } + const result = composeActiveTerminalTheme( + base, + settingsWith({ terminalColorOverrides: { foreground: '#00ff00' } }) + ) + expect(result!.foreground).toBe('#00ff00') + expect(result!.background).toBe('#101010') + }) + + it('applies background opacity by converting the hex background to rgba', () => { + const base = { background: '#112233' } + const result = composeActiveTerminalTheme( + base, + settingsWith({ terminalBackgroundOpacity: 0.5 }) + ) + expect(result!.background).toBe('rgba(17, 34, 51, 0.5)') + }) + + it('honors a zero background opacity', () => { + // Why: pin against a regression where the guard becomes truthy-only + // (e.g. `if (settings.terminalBackgroundOpacity)`) and silently drops + // the user's intent to make the background fully transparent. + const base = { background: '#112233' } + const result = composeActiveTerminalTheme(base, settingsWith({ terminalBackgroundOpacity: 0 })) + expect(result!.background).toBe('rgba(17, 34, 51, 0)') + }) + + it('applies cursor opacity only when the cursor is a hex color', () => { + const base = { cursor: '#ffffff' } + const result = composeActiveTerminalTheme(base, settingsWith({ terminalCursorOpacity: 0.3 })) + expect(result!.cursor).toBe('rgba(255, 255, 255, 0.3)') + }) + + it('leaves named CSS cursor colors untouched when applying opacity', () => { + const base = { cursor: 'red' } + const result = composeActiveTerminalTheme(base, settingsWith({ terminalCursorOpacity: 0.3 })) + expect(result!.cursor).toBe('red') + }) + + it('returns null when given a null base theme', () => { + expect(composeActiveTerminalTheme(null, settingsWith({}))).toBeNull() + }) +}) diff --git a/src/renderer/src/components/terminal-pane/terminal-appearance.ts b/src/renderer/src/components/terminal-pane/terminal-appearance.ts index 7985d67d4..e9b8d6267 100644 --- a/src/renderer/src/components/terminal-pane/terminal-appearance.ts +++ b/src/renderer/src/components/terminal-pane/terminal-appearance.ts @@ -145,10 +145,50 @@ export function hexToRgba(hex: string, alpha: number): string { return `rgba(${r}, ${g}, ${b}, ${alpha})` } -function isHexColor(value: string): boolean { +export function isHexColor(value: string): boolean { return HEX_COLOR_RE.test(value) } +// Why: extracted from applyTerminalAppearance so the settings preview can +// derive the same composed theme without depending on PaneManager. Keep +// pure — no DOM, no manager, no side effects. +export function composeActiveTerminalTheme( + baseTheme: ITheme | null, + settings: Pick< + GlobalSettings, + 'terminalColorOverrides' | 'terminalBackgroundOpacity' | 'terminalCursorOpacity' + > +): ITheme | null { + if (!baseTheme) { + return null + } + let theme: ITheme = { ...baseTheme } + // Why: merge user-imported Ghostty color overrides on top of the resolved + // base theme so individual colors can be tweaked without losing the rest. + if (settings.terminalColorOverrides) { + theme = { ...theme, ...settings.terminalColorOverrides } + } + // Why: Ghostty's background-opacity controls the terminal's base alpha. + // Convert the hex background to rgba so xterm honors it when allowTransparency + // is also set on the Terminal instance. + if (settings.terminalBackgroundOpacity !== undefined && theme.background) { + theme = { + ...theme, + background: hexToRgba(theme.background, settings.terminalBackgroundOpacity) + } + } + // Why: Ghostty's cursor-opacity applies alpha to the cursor color. Only + // converted when the resolved cursor is a hex value; named CSS colors are + // left untouched because hexToRgba expects a hex input. + if (settings.terminalCursorOpacity !== undefined && theme.cursor && isHexColor(theme.cursor)) { + theme = { + ...theme, + cursor: hexToRgba(theme.cursor, settings.terminalCursorOpacity) + } + } + return theme +} + export function applyTerminalAppearance( manager: PaneManager, settings: GlobalSettings, @@ -161,29 +201,9 @@ export function applyTerminalAppearance( ): void { const appearance = resolveEffectiveTerminalAppearance(settings, systemPrefersDark) const paneStyles = resolvePaneStyleOptions(settings) - let theme: ITheme | null = appearance.theme ?? getBuiltinTheme(appearance.themeName) - - // Why: merge user-imported Ghostty color overrides on top of the resolved - // base theme so individual colors can be tweaked without losing the rest. - if (theme && settings.terminalColorOverrides) { - theme = { ...theme, ...settings.terminalColorOverrides } - } - - let paneBackground = theme?.background ?? '#000000' - - // Why: Ghostty's background-opacity controls the terminal's base alpha. - // We convert the hex background to rgba and enable xterm transparency. - if (settings.terminalBackgroundOpacity !== undefined && theme?.background) { - paneBackground = hexToRgba(theme.background, settings.terminalBackgroundOpacity) - theme = { ...theme, background: paneBackground } - } - - // Why: Ghostty's cursor-opacity applies alpha to the cursor color. We only - // convert when the resolved cursor is a hex value; named CSS colors are - // left untouched because hexToRgba expects a hex input. - if (settings.terminalCursorOpacity !== undefined && theme?.cursor && isHexColor(theme.cursor)) { - theme = { ...theme, cursor: hexToRgba(theme.cursor, settings.terminalCursorOpacity) } - } + const baseTheme: ITheme | null = appearance.theme ?? getBuiltinTheme(appearance.themeName) + const theme = composeActiveTerminalTheme(baseTheme, settings) + const paneBackground = theme?.background ?? '#000000' const terminalFontWeights = resolveTerminalFontWeights(settings.terminalFontWeight) const ligaturesEnabled = resolveTerminalLigaturesEnabled(