Open History to see the last commit
1import { preloadPatchFile } from "@pierre/diffs/ssr";
2import { useCallback, useEffect, useRef, useState } from "react";
3import { ComposerPromptEditor, type ComposerPromptEditorHandle } from "../ComposerPromptEditor";
4import { terminalThemeFromApp } from "../ThreadTerminalDrawer";
5import { useTheme } from "../../hooks/useTheme";
6import { DISCONNECTED_COMPOSER_PLACEHOLDER } from "../../composerPlaceholder";
7import { resolveDiffThemeName, type DiffThemeName } from "../../lib/diffRendering";
8import { GhosttyTerminalSurface } from "~/terminal/ghostty/surface";
9
10// The font previews are the real surfaces, not lookalikes: the composer's
11// Lexical editor, the diff panel's file diff, and the Ghostty canvas
12// renderer. Each already consumes the appearance font tokens (or, for the
13// terminal, the settings passed down as props), so what the row shows is
14// exactly what the app renders.
15
16const EMPTY_TERMINAL_CONTEXTS: ReadonlyArray<never> = [];
17const EMPTY_SKILLS: ReadonlyArray<never> = [];
18
19// Serialized the way the composer stores inline tokens: the $skill and the
20// markdown-style file links render as chips, so the preview shows prompt
21// text and pills exactly as the real composer draws them.
22const PROMPT_PREVIEW_TEXT =
23 "Use $frontend-design to fix the flaky test in " +
24 "[surface.test.ts](apps/web/src/terminal/ghostty/surface.test.ts) and align the header with " +
25 "[SettingsPanels.tsx](apps/web/src/components/settings/SettingsPanels.tsx) before shipping.";
26
27function noop() {}
28
29/** A live composer editor: type in it to feel the family and size. */
30export function PromptFontPreview() {
31 const editorRef = useRef<ComposerPromptEditorHandle>(null);
32 const [prompt, setPrompt] = useState(PROMPT_PREVIEW_TEXT);
33 const [cursor, setCursor] = useState(PROMPT_PREVIEW_TEXT.length);
34 const onChange = useCallback((nextValue: string, nextCursor: number) => {
35 setPrompt(nextValue);
36 setCursor(nextCursor);
37 }, []);
38 return (
39 <div className="mt-1 mb-2 rounded-lg border border-border bg-background px-3 py-2">
40 <ComposerPromptEditor
41 editorRef={editorRef}
42 value={prompt}
43 cursor={cursor}
44 terminalContexts={EMPTY_TERMINAL_CONTEXTS}
45 skills={EMPTY_SKILLS}
46 disabled={false}
47 placeholder={DISCONNECTED_COMPOSER_PLACEHOLDER}
48 className="max-h-40 min-h-12"
49 onRemoveTerminalContext={noop}
50 onChange={onChange}
51 onPaste={noop}
52 />
53 </div>
54 );
55}
56
57const DIFF_PREVIEW_PATCH = [
58 "diff --git a/src/formatUser.ts b/src/formatUser.ts",
59 "--- a/src/formatUser.ts",
60 "+++ b/src/formatUser.ts",
61 "@@ -1,3 +1,3 @@",
62 " export function formatUser(user: User) {",
63 "- return user.name.toUpperCase();",
64 "+ return `${user.name} <${user.email}>`; // 0O 1lI",
65 " }",
66 "",
67].join("\n");
68
69// Rendered once per theme through the SSR pipeline, which always awaits the
70// shared highlighter before producing HTML. The interactive FileDiff's mount
71// lifecycle can race that highlighter when the typography views remount it
72// (toggling Advanced) and lock in an unhighlighted frame; a static preview
73// needs none of that lifecycle, so it uses the deterministic renderer and
74// injects the finished HTML into a shadow root, exactly as FileDiff would.
75const diffPreviewHtmlByTheme = new Map<DiffThemeName, Promise<readonly string[]>>();
76
77function loadDiffPreviewHtml(theme: DiffThemeName): Promise<readonly string[]> {
78 let promise = diffPreviewHtmlByTheme.get(theme);
79 if (promise === undefined) {
80 promise = preloadPatchFile({
81 patch: DIFF_PREVIEW_PATCH,
82 options: { diffStyle: "unified", theme },
83 }).then((results) => results.map((result) => result.prerenderedHTML));
84 diffPreviewHtmlByTheme.set(theme, promise);
85 }
86 return promise;
87}
88
89// Pierre's prerendered stylesheet bakes its own light/dark surface colors
90// into the shadow root's @layer rules. These unlayered rules win the cascade
91// without !important and re-point the surfaces at the app's code tokens
92// (custom properties inherit across the shadow boundary), so the preview
93// follows the active theme exactly like the real diff panel does.
94const DIFF_PREVIEW_THEME_BRIDGE = `
95 :host {
96 color: var(--code-foreground);
97 background-color: var(--code-background);
98 --diffs-fg: var(--code-foreground);
99 --diffs-bg: var(--code-background);
100 --diffs-light-bg: var(--code-background);
101 --diffs-dark-bg: var(--code-background);
102 }
103 [data-diffs-header] {
104 background-color: var(--code-background);
105 color: var(--code-foreground);
106 }
107`;
108
109function StaticDiffHtml({ html }: { html: string }) {
110 const hostRef = useRef<HTMLDivElement | null>(null);
111 useEffect(() => {
112 const host = hostRef.current;
113 if (host === null) return;
114 const shadow = host.shadowRoot ?? host.attachShadow({ mode: "open" });
115 shadow.innerHTML = html;
116 const bridge = document.createElement("style");
117 bridge.textContent = DIFF_PREVIEW_THEME_BRIDGE;
118 shadow.append(bridge);
119 }, [html]);
120 return <div ref={hostRef} />;
121}
122
123/** The diff panel's file diff, statically rendered by its real pipeline. */
124export function CodeFontPreview() {
125 const { resolvedTheme } = useTheme();
126 const themeName = resolveDiffThemeName(resolvedTheme);
127 const [htmlByFile, setHtmlByFile] = useState<readonly string[] | null>(null);
128 useEffect(() => {
129 let cancelled = false;
130 void loadDiffPreviewHtml(themeName).then((html) => {
131 if (!cancelled) setHtmlByFile(html);
132 });
133 return () => {
134 cancelled = true;
135 };
136 }, [themeName]);
137 if (htmlByFile === null) return null;
138 return (
139 <div className="mt-1 mb-2 space-y-2">
140 {htmlByFile.map((html) => (
141 <StaticDiffHtml key={html} html={html} />
142 ))}
143 </div>
144 );
145}
146
147// A zsh-style prompt: green arrow, cyan project, blue/red git segment,
148// yellow dirty marker. It doubles as the echo loop's fresh-line prompt.
149const TERMINAL_PROMPT =
150 "\x1b[1;32m→\x1b[0m \x1b[1;36mt3code\x1b[0m \x1b[1;34mgit:(\x1b[1;31mmain\x1b[1;34m)\x1b[0m \x1b[1;33m✗\x1b[0m ";
151// A dev-server startup: brand line, addresses, a test summary, and a READY
152// badge. Together the lines cover bold, dim, underline, the six accent
153// colors, and a background cell, so a font choice shows every SGR the
154// terminal actually renders.
155const TERMINAL_PREVIEW_TRANSCRIPT =
156 `${TERMINAL_PROMPT}vpr dev\r\n` +
157 "\r\n" +
158 " \x1b[1;32mVITE\x1b[0m \x1b[32mv7.1.1\x1b[0m \x1b[2mready in\x1b[0m \x1b[1m1.24s\x1b[0m\r\n" +
159 "\r\n" +
160 " \x1b[32m→\x1b[0m \x1b[2mLocal:\x1b[0m \x1b[4;36mhttp://127.0.0.1:5173/\x1b[0m\r\n" +
161 " \x1b[32m→\x1b[0m \x1b[2mNetwork:\x1b[0m \x1b[4;36mhttp://192.168.1.24:5173/\x1b[0m\r\n" +
162 "\r\n" +
163 " \x1b[32m✓ 85 passed\x1b[0m \x1b[33m△ 2 warnings\x1b[0m \x1b[31m✗ 0 failed\x1b[0m\r\n" +
164 "\r\n" +
165 " \x1b[42;30m READY \x1b[0m \x1b[2mwatching for changes — press\x1b[0m \x1b[1mq\x1b[0m \x1b[2mto quit\x1b[0m\r\n" +
166 "\r\n" +
167 TERMINAL_PROMPT;
168
169/** The surface treats an omitted family or size as "use the built-in default". */
170function previewTerminalFont(family: string, size: number): { family?: string; size: number } {
171 const trimmed = family.trim();
172 return trimmed.length > 0 ? { family: trimmed, size } : { size };
173}
174
175/**
176 * The real Ghostty canvas renderer against a local echo loop instead of a
177 * PTY: keys print, Enter starts a new prompt line, Backspace erases. That
178 * exercises the same glyph atlas, cell metrics, and monospace gate the
179 * terminal drawer uses.
180 */
181export function TerminalFontPreview({ family, size }: { family: string; size: number }) {
182 const mountRef = useRef<HTMLDivElement>(null);
183 const surfaceRef = useRef<GhosttyTerminalSurface | null>(null);
184 const fontRef = useRef({ family, size });
185 const { theme, resolvedTheme } = useTheme();
186
187 useEffect(() => {
188 const current = fontRef.current;
189 if (current.family === family && current.size === size) return;
190 fontRef.current = { family, size };
191 void surfaceRef.current?.setFont(previewTerminalFont(family, size));
192 }, [family, size]);
193
194 // Re-read the terminal tokens on any theme change — switching between two
195 // palettes can leave resolvedTheme (light/dark) untouched.
196 useEffect(() => {
197 const mount = mountRef.current;
198 const surface = surfaceRef.current;
199 if (!mount || !surface) return;
200 surface.setTheme(terminalThemeFromApp(mount));
201 }, [theme, resolvedTheme]);
202
203 useEffect(() => {
204 const mount = mountRef.current;
205 if (!mount) return;
206 let cancelled = false;
207 // Column of the caret on the current input line, so Backspace stops at
208 // the prompt instead of eating it.
209 let lineLength = 0;
210
211 const echo = (data: string) => {
212 const surface = surfaceRef.current;
213 if (!surface) return;
214 if (data === "\r") {
215 surface.write(`\r\n${TERMINAL_PROMPT}`);
216 lineLength = 0;
217 return;
218 }
219 if (data === "\x7f" || data === "\b") {
220 if (lineLength > 0) {
221 surface.write("\b \b");
222 lineLength -= 1;
223 }
224 return;
225 }
226 // Arrow keys and other escape reports have no cursor to move here.
227 if (data.startsWith("\x1b")) return;
228 const printable = [...data]
229 .filter((character) => character >= " " && character !== "\x7f")
230 .join("");
231 if (printable.length === 0) return;
232 surface.write(printable);
233 lineLength += printable.length;
234 };
235
236 void GhosttyTerminalSurface.create(mount, {
237 theme: terminalThemeFromApp(mount),
238 font: previewTerminalFont(fontRef.current.family, fontRef.current.size),
239 onData: echo,
240 onResize: noop,
241 onSelectionChange: noop,
242 // Tab keeps walking the settings page instead of feeding the echo loop.
243 beforeKey: (event) => event.key !== "Tab",
244 onLinkActivate: noop,
245 }).then((surface) => {
246 if (cancelled) {
247 surface.dispose();
248 return;
249 }
250 surfaceRef.current = surface;
251 // The theme and font may both have changed while the WASM surface loaded.
252 surface.setTheme(terminalThemeFromApp(mount));
253 const font = fontRef.current;
254 void surface.setFont(previewTerminalFont(font.family, font.size));
255 surface.write(TERMINAL_PREVIEW_TRANSCRIPT);
256 });
257
258 return () => {
259 cancelled = true;
260 surfaceRef.current?.dispose();
261 surfaceRef.current = null;
262 };
263 }, []);
264
265 return (
266 <div
267 ref={mountRef}
268 className="relative mt-1 mb-2 h-52 overflow-hidden rounded-lg border border-border"
269 aria-label="Terminal font preview"
270 />
271 );
272}