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