Squashed commits (#2049)
- feat(settings): restore divider + inactive pane stub in preview The new xterm-based preview lost the visual feedback for terminal divider color/thickness and inactive pane opacity that the old TerminalThemePreview used to give. Bring back the same two-pane shape — real xterm on the left, configurable-width divider in the middle, small color-only stub on the right — so changing divider color, divider thickness, or inactive pane opacity has immediate visible feedback in the Dark/Light theme previews and the Typography preview. Switch the preview prop from themeOverride: ITheme to modeOverride: 'dark' | 'light' so the preview can derive both the theme and the matching divider color from a single resolveEffectiveTerminalAppearance call — keeps the dark/light variant rules in lockstep with live panes. - feat(settings): drop cursor preview; add dark/light toggle to typography preview Cursor preview was high-friction (xterm cursor blink only animates on focus, and every workaround for that was either intrusive or fragile) and low-value — the bar/block/underline toggle is visually obvious from the controls themselves. Remove it. The Cursor section is back to a single-column layout. Add a Moon/Sun toggle to the Typography preview's card header so users can flip the preview between dark and light themes without changing the app theme. Toggle is hidden when themeOverride is set (Dark/Light theme sections already pin a specific theme). Initial mode follows the active app theme; flipping it doesn't change app settings. - fix(settings): defer cursor preview focus by one frame Use terminal.focus() (which already uses preventScroll: true internally) and defer it via requestAnimationFrame. Focusing synchronously inside a React effect can land before xterm finishes wiring the textarea focus subscription, leaving _isFocused stale and the blink interval paused even though the textarea has DOM focus. One frame is enough for xterm's setup to complete. - fix(settings): blink cursor preview as soon as Settings opens Drop the first-render guard so the cursor preview blinks immediately on mount, not just after a cursor setting change. Switch to focusing the xterm helper textarea directly with preventScroll: true so the page doesn't jump to the preview when Settings first opens — the preview can be below the fold and a scroll-into-view would be jarring. - fix(settings): focus preview on cursor changes so blink demonstrates xterm only animates cursor blink when the terminal has focus, so the Cursor section's blink toggle had no visible effect unless the user clicked into the preview. Add an opt-in autoFocusOnCursorChange prop that focuses the preview whenever cursorStyle/Blink/Opacity changes — the user is interacting with cursor controls so a brief focus snap is expected. Skip the first run so opening Settings doesn't steal initial focus from elsewhere on the page. Only the Cursor preview opts in; Typography and theme previews keep natural focus behavior. - fix(settings): fit preview at default font, mirror cursor inactive style, share with theme sections Three follow-ups from visual testing: 1. Trim preview content and pin cols=36 so PREVIEW_BUFFER fits in the ~312px-wide xterm canvas at the default 14px font. Larger fonts still extend past the right edge (clipped, not wrapped) — same behavior as before, just with the default size now on the right side of "fits". 2. Mirror cursorInactiveStyle to cursorStyle so the cursor shape always reflects the user's choice. xterm renders an outline cursor when unfocused by default, which masked shape changes in the preview because it's read-only and never gets focus. Blink still requires focus — same as a real terminal pane. 3. Replace TerminalThemePreview with TerminalSettingsPreview in the dark and light theme sections. Adds a themeOverride prop on the preview so each section can pin a specific theme regardless of the active app theme. Drops the static two-pane mock + palette grid in favor of the richer code/test/diff buffer the user prefers. - fix(settings): preview lifecycle and font hover preview Three issues from initial visual testing: 1. Buffer accumulated on theme/settings changes. terminal.clear() keeps the row the cursor sits on, and PREVIEW_BUFFER ends mid-line on the prompt — so a follow-up clear+write left the trailing prompt fragment and appended the new buffer beneath it. Switch to terminal.reset() which restores cursor home and wipes the buffer. 2. Long lines wrapped because FitAddon shrunk cols to fit the 360px container. Drop FitAddon (and the resize observer that supported it), pin cols=50 / rows=15 in the constructor, and let the container clip horizontal overflow at large fonts. Lines never break mid-content now. 3. Add hover-to-preview to the font picker. FontAutocomplete fires a new onPreviewFontFamily callback as the user moves through dropdown options; TerminalPane lifts a previewFontFamily state and hands it to both Typography and Cursor previews so users see each font without committing the selection. - fix(settings): preserve Ghostty context and honor opacity in preview Per final review: the original Ghostty rationale comments inside applyTerminalAppearance were lost when the composition was extracted — restore them on each branch of composeActiveTerminalTheme. And the preview needs allowTransparency true when the user has set a sub-1 background opacity, otherwise xterm renders the rgba background fully opaque. - feat(settings): show live preview in Typography and Cursor sections - fix(settings): make preview read-only via xterm and track theme bg Per code review: tabIndex/aria-hidden on the wrapper don't reach xterm's internal textarea — disableStdin does. And bg-black on the wrapper showed a stark black ring around light-mode previews; track the composed theme's background instead so the padding band always matches the canvas. - fix(settings): suppress false-positive exhaustive-deps warning - feat(settings): add TerminalSettingsPreview component Implements Tasks 3-7 of the terminal-settings-preview plan: a live read-only xterm.js preview card (DOM renderer) that mutates font/cursor options directly, repaints the ANSI buffer on theme changes, manages the LigaturesAddon on toggle, and refits on ResizeObserver events. - fix(terminal): tighten composeActiveTerminalTheme docs + cover zero opacity Per code review: lead the JSDoc with the why (preview reuse) instead of narrating the merge steps, and add a test that pins zero-background-opacity behavior so a future truthy-only guard refactor doesn't silently drop it. - refactor(terminal): extract composeActiveTerminalTheme helper - fix(settings): split def/render syntax colors and harden marker test Per code review: the prompt() comment leaked a layout detail (360px), and def/render were collapsed into a single yellow span — losing the function- name color distinction the preview is meant to demonstrate. Strip ANSI in the marker test so future re-coloring doesn't break it. - feat(settings): add terminal preview content module Co-authored-by: Neil <4138956+nwparker@users.noreply.github.com>
This commit is contained in:
@@ -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)
|
||||
|
||||
@@ -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<string | null>(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({
|
||||
</section>
|
||||
) : null,
|
||||
matchesSettingsSearch(searchQuery, TERMINAL_TYPOGRAPHY_SEARCH_ENTRIES) ? (
|
||||
<section key="typography" className="space-y-3">
|
||||
<SettingsSubsectionHeader
|
||||
title="Typography"
|
||||
description="Default terminal typography for new panes and live updates."
|
||||
/>
|
||||
<section key="typography" className="grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]">
|
||||
<div className="min-w-0 space-y-3">
|
||||
<SettingsSubsectionHeader
|
||||
title="Typography"
|
||||
description="Default terminal typography for new panes and live updates."
|
||||
/>
|
||||
|
||||
<div className="divide-y divide-border/40">
|
||||
<SearchableSetting
|
||||
title="Font Size"
|
||||
description="Default terminal font size for new panes and live updates."
|
||||
keywords={['terminal', 'typography', 'text size']}
|
||||
>
|
||||
<SettingsRow
|
||||
label="Font Size"
|
||||
<div className="divide-y divide-border/40">
|
||||
<SearchableSetting
|
||||
title="Font Size"
|
||||
description="Default terminal font size for new panes and live updates."
|
||||
control={
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon-sm"
|
||||
onClick={() => {
|
||||
const next = Math.max(10, settings.terminalFontSize - 1)
|
||||
updateSettings({ terminalFontSize: next })
|
||||
}}
|
||||
disabled={settings.terminalFontSize <= 10}
|
||||
>
|
||||
<Minus className="size-3" />
|
||||
</Button>
|
||||
<Input
|
||||
type="number"
|
||||
min={10}
|
||||
max={24}
|
||||
value={settings.terminalFontSize}
|
||||
onChange={(e) => {
|
||||
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"
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon-sm"
|
||||
onClick={() => {
|
||||
const next = Math.min(24, settings.terminalFontSize + 1)
|
||||
updateSettings({ terminalFontSize: next })
|
||||
}}
|
||||
disabled={settings.terminalFontSize >= 24}
|
||||
>
|
||||
<Plus className="size-3" />
|
||||
</Button>
|
||||
<span className="text-xs text-muted-foreground">px</span>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
</SearchableSetting>
|
||||
keywords={['terminal', 'typography', 'text size']}
|
||||
>
|
||||
<SettingsRow
|
||||
label="Font Size"
|
||||
description="Default terminal font size for new panes and live updates."
|
||||
control={
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon-sm"
|
||||
onClick={() => {
|
||||
const next = Math.max(10, settings.terminalFontSize - 1)
|
||||
updateSettings({ terminalFontSize: next })
|
||||
}}
|
||||
disabled={settings.terminalFontSize <= 10}
|
||||
>
|
||||
<Minus className="size-3" />
|
||||
</Button>
|
||||
<Input
|
||||
type="number"
|
||||
min={10}
|
||||
max={24}
|
||||
value={settings.terminalFontSize}
|
||||
onChange={(e) => {
|
||||
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"
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon-sm"
|
||||
onClick={() => {
|
||||
const next = Math.min(24, settings.terminalFontSize + 1)
|
||||
updateSettings({ terminalFontSize: next })
|
||||
}}
|
||||
disabled={settings.terminalFontSize >= 24}
|
||||
>
|
||||
<Plus className="size-3" />
|
||||
</Button>
|
||||
<span className="text-xs text-muted-foreground">px</span>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
</SearchableSetting>
|
||||
|
||||
<SearchableSetting
|
||||
title="Font Family"
|
||||
description="Default terminal font family for new panes and live updates."
|
||||
keywords={['terminal', 'typography', 'font']}
|
||||
>
|
||||
<SettingsRow
|
||||
alignTop
|
||||
label="Font Family"
|
||||
<SearchableSetting
|
||||
title="Font Family"
|
||||
description="Default terminal font family for new panes and live updates."
|
||||
control={
|
||||
<FontAutocomplete
|
||||
value={settings.terminalFontFamily}
|
||||
suggestions={terminalFontSuggestions}
|
||||
onChange={(value) => updateSettings({ terminalFontFamily: value })}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</SearchableSetting>
|
||||
keywords={['terminal', 'typography', 'font']}
|
||||
>
|
||||
<SettingsRow
|
||||
alignTop
|
||||
label="Font Family"
|
||||
description="Default terminal font family for new panes and live updates."
|
||||
control={
|
||||
<FontAutocomplete
|
||||
value={settings.terminalFontFamily}
|
||||
suggestions={terminalFontSuggestions}
|
||||
onChange={(value) => updateSettings({ terminalFontFamily: value })}
|
||||
onPreviewFontFamily={setPreviewFontFamily}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</SearchableSetting>
|
||||
|
||||
<SearchableSetting
|
||||
title="Font Weight"
|
||||
description="Controls the terminal text font weight."
|
||||
keywords={['terminal', 'typography', 'weight']}
|
||||
>
|
||||
<NumberField
|
||||
label="Font Weight"
|
||||
<SearchableSetting
|
||||
title="Font Weight"
|
||||
description="Controls the terminal text font weight."
|
||||
value={normalizeTerminalFontWeight(settings.terminalFontWeight)}
|
||||
defaultValue={DEFAULT_TERMINAL_FONT_WEIGHT}
|
||||
min={TERMINAL_FONT_WEIGHT_MIN}
|
||||
max={TERMINAL_FONT_WEIGHT_MAX}
|
||||
step={TERMINAL_FONT_WEIGHT_STEP}
|
||||
suffix="100–900"
|
||||
onChange={(value) =>
|
||||
updateSettings({
|
||||
terminalFontWeight: normalizeTerminalFontWeight(value)
|
||||
})
|
||||
}
|
||||
/>
|
||||
</SearchableSetting>
|
||||
keywords={['terminal', 'typography', 'weight']}
|
||||
>
|
||||
<NumberField
|
||||
label="Font Weight"
|
||||
description="Controls the terminal text font weight."
|
||||
value={normalizeTerminalFontWeight(settings.terminalFontWeight)}
|
||||
defaultValue={DEFAULT_TERMINAL_FONT_WEIGHT}
|
||||
min={TERMINAL_FONT_WEIGHT_MIN}
|
||||
max={TERMINAL_FONT_WEIGHT_MAX}
|
||||
step={TERMINAL_FONT_WEIGHT_STEP}
|
||||
suffix="100–900"
|
||||
onChange={(value) =>
|
||||
updateSettings({
|
||||
terminalFontWeight: normalizeTerminalFontWeight(value)
|
||||
})
|
||||
}
|
||||
/>
|
||||
</SearchableSetting>
|
||||
|
||||
<SearchableSetting
|
||||
title="Line Height"
|
||||
description="Controls the terminal line height multiplier."
|
||||
keywords={['terminal', 'typography', 'line height', 'spacing']}
|
||||
>
|
||||
<NumberField
|
||||
label="Line Height"
|
||||
<SearchableSetting
|
||||
title="Line Height"
|
||||
description="Controls the terminal line height multiplier."
|
||||
value={settings.terminalLineHeight}
|
||||
defaultValue={1}
|
||||
min={1}
|
||||
max={3}
|
||||
step={0.1}
|
||||
suffix="1–3"
|
||||
onChange={(value) =>
|
||||
updateSettings({
|
||||
terminalLineHeight: clampNumber(value, 1, 3)
|
||||
})
|
||||
}
|
||||
/>
|
||||
</SearchableSetting>
|
||||
keywords={['terminal', 'typography', 'line height', 'spacing']}
|
||||
>
|
||||
<NumberField
|
||||
label="Line Height"
|
||||
description="Controls the terminal line height multiplier."
|
||||
value={settings.terminalLineHeight}
|
||||
defaultValue={1}
|
||||
min={1}
|
||||
max={3}
|
||||
step={0.1}
|
||||
suffix="1–3"
|
||||
onChange={(value) =>
|
||||
updateSettings({
|
||||
terminalLineHeight: clampNumber(value, 1, 3)
|
||||
})
|
||||
}
|
||||
/>
|
||||
</SearchableSetting>
|
||||
|
||||
<SearchableSetting
|
||||
title="Font Ligatures"
|
||||
description='Render programming ligatures (e.g. =>, !=, ===) for fonts that ship them. "Auto" enables ligatures only for known ligature fonts (Fira Code, JetBrains Mono, Cascadia Code, Iosevka, etc.).'
|
||||
keywords={[
|
||||
'terminal',
|
||||
'typography',
|
||||
'ligatures',
|
||||
'ligature',
|
||||
'fira code',
|
||||
'jetbrains mono',
|
||||
'cascadia code',
|
||||
'iosevka',
|
||||
'calt',
|
||||
'font features'
|
||||
]}
|
||||
>
|
||||
<SettingsRow
|
||||
label="Font Ligatures"
|
||||
description={
|
||||
settings.terminalLigatures === 'on'
|
||||
? 'Always on. Fonts without ligatures simply render as-is.'
|
||||
: settings.terminalLigatures === 'off'
|
||||
? 'Always off, even for fonts that ship them.'
|
||||
: fontFamilyHasKnownLigatures(settings.terminalFontFamily)
|
||||
? `Auto — enabled for "${settings.terminalFontFamily}".`
|
||||
: `Auto — disabled for "${
|
||||
settings.terminalFontFamily || 'the current font'
|
||||
}".`
|
||||
}
|
||||
control={
|
||||
<SettingsSegmentedControl
|
||||
ariaLabel="Font Ligatures"
|
||||
value={settings.terminalLigatures ?? 'auto'}
|
||||
onChange={(option) => 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. */}
|
||||
<p className="sr-only" aria-live="polite">
|
||||
Ligatures are currently{' '}
|
||||
{resolveTerminalLigaturesEnabled(
|
||||
settings.terminalLigatures,
|
||||
settings.terminalFontFamily
|
||||
)
|
||||
? 'enabled'
|
||||
: 'disabled'}
|
||||
.
|
||||
</p>
|
||||
</SearchableSetting>
|
||||
<SearchableSetting
|
||||
title="Font Ligatures"
|
||||
description='Render programming ligatures (e.g. =>, !=, ===) for fonts that ship them. "Auto" enables ligatures only for known ligature fonts (Fira Code, JetBrains Mono, Cascadia Code, Iosevka, etc.).'
|
||||
keywords={[
|
||||
'terminal',
|
||||
'typography',
|
||||
'ligatures',
|
||||
'ligature',
|
||||
'fira code',
|
||||
'jetbrains mono',
|
||||
'cascadia code',
|
||||
'iosevka',
|
||||
'calt',
|
||||
'font features'
|
||||
]}
|
||||
>
|
||||
<SettingsRow
|
||||
label="Font Ligatures"
|
||||
description={
|
||||
settings.terminalLigatures === 'on'
|
||||
? 'Always on. Fonts without ligatures simply render as-is.'
|
||||
: settings.terminalLigatures === 'off'
|
||||
? 'Always off, even for fonts that ship them.'
|
||||
: fontFamilyHasKnownLigatures(settings.terminalFontFamily)
|
||||
? `Auto — enabled for "${settings.terminalFontFamily}".`
|
||||
: `Auto — disabled for "${
|
||||
settings.terminalFontFamily || 'the current font'
|
||||
}".`
|
||||
}
|
||||
control={
|
||||
<SettingsSegmentedControl
|
||||
ariaLabel="Font Ligatures"
|
||||
value={settings.terminalLigatures ?? 'auto'}
|
||||
onChange={(option) => 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. */}
|
||||
<p className="sr-only" aria-live="polite">
|
||||
Ligatures are currently{' '}
|
||||
{resolveTerminalLigaturesEnabled(
|
||||
settings.terminalLigatures,
|
||||
settings.terminalFontFamily
|
||||
)
|
||||
? 'enabled'
|
||||
: 'disabled'}
|
||||
.
|
||||
</p>
|
||||
</SearchableSetting>
|
||||
</div>
|
||||
</div>
|
||||
<TerminalSettingsPreview
|
||||
title="Preview"
|
||||
settings={settings}
|
||||
systemPrefersDark={systemPrefersDark}
|
||||
previewFontFamily={previewFontFamily}
|
||||
showThemeToggle
|
||||
/>
|
||||
</section>
|
||||
) : 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) ? (
|
||||
|
||||
@@ -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<string, unknown>
|
||||
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<typeof import('react')>('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<string, unknown>
|
||||
open: Mock
|
||||
write: Mock
|
||||
reset: Mock
|
||||
dispose: Mock
|
||||
loadAddon: Mock
|
||||
|
||||
constructor(options: Record<string, unknown>) {
|
||||
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> = {}): 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)
|
||||
})
|
||||
})
|
||||
@@ -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<GlobalSettings, 'theme'>,
|
||||
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<HTMLDivElement | null>(null)
|
||||
const terminalRef = useRef<Terminal | null>(null)
|
||||
const ligaturesAddonRef = useRef<LigaturesAddon | null>(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<PreviewMode>(() =>
|
||||
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 (
|
||||
<Card className="gap-4 overflow-hidden py-0">
|
||||
<CardHeader className="gap-0 border-b border-border/50 px-4 py-3 !pb-3">
|
||||
<div className="flex min-h-7 items-center justify-between gap-3">
|
||||
<div className="min-w-0 space-y-1">
|
||||
<CardTitle className="text-sm">{title}</CardTitle>
|
||||
{description ? <CardDescription>{description}</CardDescription> : null}
|
||||
</div>
|
||||
<div className="flex shrink-0 flex-wrap items-center justify-end gap-2">
|
||||
<div className="flex items-center gap-2 rounded-md border border-border/50 bg-background/40 px-2 py-1">
|
||||
<span className="text-xs font-medium text-muted-foreground">Pane divider</span>
|
||||
<SettingsSwitch
|
||||
checked={previewPaneDividerVisible}
|
||||
onChange={() => setPreviewPaneDividerVisible((visible) => !visible)}
|
||||
ariaLabel="Show pane divider in preview"
|
||||
/>
|
||||
</div>
|
||||
{showToggle ? (
|
||||
<div
|
||||
className="flex gap-0.5 rounded-md border border-border/50 p-0.5"
|
||||
role="group"
|
||||
aria-label="Preview theme"
|
||||
>
|
||||
{(['dark', 'light'] as const).map((mode) => (
|
||||
<button
|
||||
key={mode}
|
||||
type="button"
|
||||
onClick={() => setTogglePreviewMode(mode)}
|
||||
aria-pressed={togglePreviewMode === mode}
|
||||
aria-label={`Preview ${mode} theme`}
|
||||
title={`Preview ${mode} theme`}
|
||||
className={`rounded-sm p-1 transition-colors ${
|
||||
togglePreviewMode === mode
|
||||
? 'bg-accent text-accent-foreground'
|
||||
: 'text-muted-foreground hover:text-foreground'
|
||||
}`}
|
||||
>
|
||||
{mode === 'dark' ? <Moon className="size-3.5" /> : <Sun className="size-3.5" />}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="px-4 pb-4">
|
||||
{/* 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. */}
|
||||
<div className="flex h-[300px] flex-col overflow-hidden rounded-md border border-border/50">
|
||||
<div className="flex min-h-0 flex-1 overflow-hidden" aria-hidden="true">
|
||||
<div
|
||||
ref={containerRef}
|
||||
className="min-w-0 flex-1 overflow-hidden p-2"
|
||||
style={{ backgroundColor: paneBackground }}
|
||||
tabIndex={-1}
|
||||
/>
|
||||
{previewPaneDividerVisible ? (
|
||||
<div
|
||||
className="shrink-0"
|
||||
style={{
|
||||
width: `${dividerThicknessPx}px`,
|
||||
backgroundColor: appearance.dividerColor
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
<div
|
||||
className="shrink-0"
|
||||
style={{
|
||||
width: `${STUB_PANE_PX}px`,
|
||||
backgroundColor: paneBackground,
|
||||
opacity: inactivePaneOpacity
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -1,116 +0,0 @@
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { terminalPalettePreview, type EffectiveTerminalAppearance } from '@/lib/terminal-theme'
|
||||
|
||||
type TerminalThemePreviewProps = {
|
||||
title: string
|
||||
description: string
|
||||
appearance: EffectiveTerminalAppearance
|
||||
dividerThicknessPx?: number
|
||||
inactivePaneOpacity?: number
|
||||
activePaneOpacity?: number
|
||||
}
|
||||
|
||||
export function TerminalThemePreview({
|
||||
title,
|
||||
description,
|
||||
appearance,
|
||||
dividerThicknessPx = 3,
|
||||
inactivePaneOpacity = 0.9,
|
||||
activePaneOpacity = 1
|
||||
}: TerminalThemePreviewProps): React.JSX.Element {
|
||||
const background =
|
||||
appearance.theme?.background ?? (appearance.mode === 'light' ? '#f8fafc' : '#09090b')
|
||||
const foreground =
|
||||
appearance.theme?.foreground ?? (appearance.mode === 'light' ? '#111827' : '#f4f4f5')
|
||||
const cursor = appearance.theme?.cursor ?? foreground
|
||||
const selection =
|
||||
appearance.theme?.selectionBackground ??
|
||||
(appearance.mode === 'light' ? 'rgba(59, 130, 246, 0.18)' : 'rgba(148, 163, 184, 0.22)')
|
||||
const palette = terminalPalettePreview(appearance.theme)
|
||||
|
||||
return (
|
||||
<Card className="gap-4 overflow-hidden py-0">
|
||||
<CardHeader className="gap-1 border-b border-border/50 py-4">
|
||||
<CardTitle className="text-sm">{title}</CardTitle>
|
||||
<CardDescription>{description}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4 px-4 pb-4">
|
||||
<div className="flex items-center justify-between rounded-md border border-border/50 bg-muted/40 px-3 py-2 text-xs">
|
||||
<div className="min-w-0">
|
||||
<p className="font-medium text-foreground">{appearance.themeName}</p>
|
||||
<p className="text-muted-foreground">
|
||||
{appearance.sourceTheme === 'system'
|
||||
? `System mode, currently ${appearance.systemPrefersDark ? 'Dark' : 'Light'}`
|
||||
: `${appearance.mode === 'dark' ? 'Dark' : 'Light'} mode`}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-muted-foreground">Divider</span>
|
||||
<span
|
||||
className="size-4 rounded-sm border border-border/50"
|
||||
style={{ backgroundColor: appearance.dividerColor }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className="overflow-hidden rounded-lg border border-border/50"
|
||||
style={{ backgroundColor: appearance.dividerColor }}
|
||||
>
|
||||
<div className="flex min-h-[220px]">
|
||||
<div
|
||||
className="flex-1 p-3 font-mono text-[12px] leading-6"
|
||||
style={{ backgroundColor: background, color: foreground, opacity: activePaneOpacity }}
|
||||
>
|
||||
<div className="flex items-center gap-2 text-[11px] opacity-70">
|
||||
<span className="size-2 rounded-full bg-emerald-500" />
|
||||
<span>orca preview</span>
|
||||
</div>
|
||||
<div className="mt-3">$ git status --short</div>
|
||||
<div style={{ color: palette[1] ?? foreground }}>
|
||||
M src/renderer/src/components/Settings.tsx
|
||||
</div>
|
||||
<div style={{ color: palette[2] ?? foreground }}>
|
||||
A src/renderer/src/lib/terminal-theme.ts
|
||||
</div>
|
||||
<div className="mt-3">
|
||||
<span style={{ backgroundColor: selection }}>theme preview selected text</span>
|
||||
</div>
|
||||
<div className="mt-3 flex items-center gap-2">
|
||||
<span>$</span>
|
||||
<span>echo "cursor"</span>
|
||||
<span
|
||||
className="inline-block h-[1.1em] w-[0.6ch] align-middle"
|
||||
style={{ backgroundColor: cursor }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
className="shrink-0"
|
||||
style={{ width: `${dividerThicknessPx}px`, backgroundColor: appearance.dividerColor }}
|
||||
/>
|
||||
<div
|
||||
className="w-[38%] p-3 font-mono text-[12px] leading-6"
|
||||
style={{
|
||||
backgroundColor: background,
|
||||
color: foreground,
|
||||
opacity: inactivePaneOpacity
|
||||
}}
|
||||
>
|
||||
<div className="opacity-70">palette</div>
|
||||
<div className="mt-3 grid grid-cols-4 gap-2">
|
||||
{(palette.length ? palette : [foreground]).map((swatch, index) => (
|
||||
<div
|
||||
key={`${swatch}-${index}`}
|
||||
className="h-6 rounded-sm border border-black/10"
|
||||
style={{ backgroundColor: swatch }}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type { GlobalSettings } from '../../../../shared/types'
|
||||
|
||||
vi.mock('./TerminalSettingsPreview', () => ({
|
||||
TerminalSettingsPreview: function TerminalSettingsPreview() {
|
||||
return null
|
||||
}
|
||||
}))
|
||||
|
||||
import { LightTerminalThemeSection } from './TerminalThemeSections'
|
||||
|
||||
type ReactElementLike = {
|
||||
type: unknown
|
||||
props?: Record<string, unknown>
|
||||
}
|
||||
|
||||
function makeSettings(overrides: Partial<GlobalSettings> = {}): GlobalSettings {
|
||||
return {
|
||||
terminalUseSeparateLightTheme: false,
|
||||
terminalThemeLight: 'Builtin Tango Light',
|
||||
terminalDividerColorLight: '#d4d4d8',
|
||||
...overrides
|
||||
} as GlobalSettings
|
||||
}
|
||||
|
||||
function countElementsByTypeName(node: unknown, typeName: string): number {
|
||||
if (node == null || typeof node === 'string' || typeof node === 'number') {
|
||||
return 0
|
||||
}
|
||||
if (Array.isArray(node)) {
|
||||
return node.reduce((total, child) => total + countElementsByTypeName(child, typeName), 0)
|
||||
}
|
||||
|
||||
const element = node as ReactElementLike
|
||||
const currentTypeName =
|
||||
typeof element.type === 'function' ? element.type.name : String(element.type)
|
||||
const childCount = countElementsByTypeName(element.props?.children, typeName)
|
||||
return currentTypeName === typeName ? childCount + 1 : childCount
|
||||
}
|
||||
|
||||
function renderLightSection(settings: GlobalSettings): React.JSX.Element {
|
||||
return LightTerminalThemeSection({
|
||||
settings,
|
||||
themeSearchLight: '',
|
||||
setThemeSearchLight: () => {},
|
||||
updateSettings: () => {},
|
||||
previewFontFamily: null
|
||||
})
|
||||
}
|
||||
|
||||
describe('LightTerminalThemeSection preview lifecycle', () => {
|
||||
it('does not mount the terminal preview while separate light theme is disabled', () => {
|
||||
const element = renderLightSection(makeSettings({ terminalUseSeparateLightTheme: false }))
|
||||
|
||||
expect(countElementsByTypeName(element, 'TerminalSettingsPreview')).toBe(0)
|
||||
})
|
||||
|
||||
it('mounts the terminal preview when separate light theme is enabled', () => {
|
||||
const element = renderLightSection(makeSettings({ terminalUseSeparateLightTheme: true }))
|
||||
|
||||
expect(countElementsByTypeName(element, 'TerminalSettingsPreview')).toBe(1)
|
||||
})
|
||||
})
|
||||
@@ -1,15 +1,8 @@
|
||||
import type { Dispatch, SetStateAction } from 'react'
|
||||
import type { GlobalSettings } from '../../../../shared/types'
|
||||
import type { EffectiveTerminalAppearance } from '@/lib/terminal-theme'
|
||||
import { ColorField, ThemePicker } from './SettingsFormControls'
|
||||
import { SearchableSetting } from './SearchableSetting'
|
||||
import { TerminalThemePreview } from './TerminalThemePreview'
|
||||
|
||||
type ThemePreviewProps = {
|
||||
dividerThicknessPx: number
|
||||
inactivePaneOpacity: number
|
||||
activePaneOpacity: number
|
||||
}
|
||||
import { TerminalSettingsPreview } from './TerminalSettingsPreview'
|
||||
|
||||
type DarkTerminalThemeSectionProps = {
|
||||
settings: GlobalSettings
|
||||
@@ -17,8 +10,7 @@ type DarkTerminalThemeSectionProps = {
|
||||
themeSearchDark: string
|
||||
setThemeSearchDark: Dispatch<SetStateAction<string>>
|
||||
updateSettings: (updates: Partial<GlobalSettings>) => void
|
||||
previewProps: ThemePreviewProps
|
||||
darkPreviewAppearance: EffectiveTerminalAppearance
|
||||
previewFontFamily: string | null
|
||||
}
|
||||
|
||||
type LightTerminalThemeSectionProps = {
|
||||
@@ -26,8 +18,7 @@ type LightTerminalThemeSectionProps = {
|
||||
themeSearchLight: string
|
||||
setThemeSearchLight: Dispatch<SetStateAction<string>>
|
||||
updateSettings: (updates: Partial<GlobalSettings>) => void
|
||||
previewProps: ThemePreviewProps
|
||||
lightPreviewAppearance: EffectiveTerminalAppearance
|
||||
previewFontFamily: string | null
|
||||
}
|
||||
|
||||
export function DarkTerminalThemeSection({
|
||||
@@ -36,8 +27,7 @@ export function DarkTerminalThemeSection({
|
||||
themeSearchDark,
|
||||
setThemeSearchDark,
|
||||
updateSettings,
|
||||
previewProps,
|
||||
darkPreviewAppearance
|
||||
previewFontFamily
|
||||
}: DarkTerminalThemeSectionProps): React.JSX.Element {
|
||||
return (
|
||||
<section className="grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]">
|
||||
@@ -79,17 +69,12 @@ export function DarkTerminalThemeSection({
|
||||
</SearchableSetting>
|
||||
</div>
|
||||
|
||||
<TerminalThemePreview
|
||||
<TerminalSettingsPreview
|
||||
title="Dark Mode Preview"
|
||||
description={
|
||||
settings.theme === 'system'
|
||||
? `System mode is currently ${systemPrefersDark ? 'Dark' : 'Light'}.`
|
||||
: `Orca is currently in ${settings.theme} mode.`
|
||||
}
|
||||
appearance={darkPreviewAppearance}
|
||||
dividerThicknessPx={previewProps.dividerThicknessPx}
|
||||
inactivePaneOpacity={previewProps.inactivePaneOpacity}
|
||||
activePaneOpacity={previewProps.activePaneOpacity}
|
||||
settings={settings}
|
||||
systemPrefersDark={systemPrefersDark}
|
||||
previewFontFamily={previewFontFamily}
|
||||
modeOverride="dark"
|
||||
/>
|
||||
</section>
|
||||
)
|
||||
@@ -100,8 +85,7 @@ export function LightTerminalThemeSection({
|
||||
themeSearchLight,
|
||||
setThemeSearchLight,
|
||||
updateSettings,
|
||||
previewProps,
|
||||
lightPreviewAppearance
|
||||
previewFontFamily
|
||||
}: LightTerminalThemeSectionProps): React.JSX.Element {
|
||||
return (
|
||||
<section className="space-y-4">
|
||||
@@ -137,15 +121,9 @@ export function LightTerminalThemeSection({
|
||||
</button>
|
||||
</SearchableSetting>
|
||||
|
||||
<div
|
||||
className={`grid overflow-hidden transition-all duration-300 ease-out ${
|
||||
settings.terminalUseSeparateLightTheme
|
||||
? 'grid-rows-[1fr] opacity-100'
|
||||
: 'grid-rows-[0fr] opacity-0'
|
||||
}`}
|
||||
>
|
||||
<div className="min-h-0">
|
||||
<div className="grid gap-6 pt-2 xl:grid-cols-[minmax(0,1fr)_360px]">
|
||||
{settings.terminalUseSeparateLightTheme ? (
|
||||
<div className="grid overflow-hidden pt-2">
|
||||
<div className="grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]">
|
||||
<div className="space-y-6">
|
||||
<div className="space-y-1">
|
||||
<h3 className="text-sm font-semibold">Light Theme</h3>
|
||||
@@ -184,17 +162,16 @@ export function LightTerminalThemeSection({
|
||||
</SearchableSetting>
|
||||
</div>
|
||||
|
||||
<TerminalThemePreview
|
||||
<TerminalSettingsPreview
|
||||
title="Light Mode Preview"
|
||||
description="Updates live as you change the light theme or divider color."
|
||||
appearance={lightPreviewAppearance}
|
||||
dividerThicknessPx={previewProps.dividerThicknessPx}
|
||||
inactivePaneOpacity={previewProps.inactivePaneOpacity}
|
||||
activePaneOpacity={previewProps.activePaneOpacity}
|
||||
settings={settings}
|
||||
systemPrefersDark={false}
|
||||
previewFontFamily={previewFontFamily}
|
||||
modeOverride="light"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
|
||||
|
||||
exports[`PREVIEW_BUFFER > matches the locked snapshot 1`] = `
|
||||
"[34m~/orca[0m [35mmain[0m [33m*[0m $ npm test
|
||||
[42m[30m PASS [0m src/preview.test.ts
|
||||
[32m✓[0m renders sample output [2m(3ms)[0m
|
||||
[31m✗ ligatures: => != >= <= ===[0m
|
||||
|
||||
[33mdef[0m [36mtotal[0m(xs: list[[36mint[0m]) -> [36mint[0m:
|
||||
[3m[32m"""Sum the values."""[0m
|
||||
[33mreturn[0m [36msum[0m(x [33mfor[0m x [33min[0m xs)
|
||||
|
||||
[34m~/orca[0m [35mmain[0m [33m*[0m $ git diff
|
||||
[36m@@ -1,2 +1,3 @@[0m
|
||||
[31m-const size = 13[0m
|
||||
[32m+const size = 14[0m
|
||||
|
||||
[34m~/orca[0m [35mmain[0m [33m*[0m $ "
|
||||
`;
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
@@ -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')
|
||||
@@ -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 (
|
||||
<div
|
||||
// Why: vertical borders are always `border-border` so the focus
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { composeActiveTerminalTheme } from './terminal-appearance'
|
||||
import type { GlobalSettings } from '../../../../shared/types'
|
||||
|
||||
describe('composeActiveTerminalTheme', () => {
|
||||
function settingsWith(partial: Partial<GlobalSettings>): 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()
|
||||
})
|
||||
})
|
||||
@@ -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(
|
||||
|
||||
Reference in New Issue
Block a user