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
88function StaticDiffHtml({ html }: { html: string }) {
89 const hostRef = useRef<HTMLDivElement | null>(null);
90 useEffect(() => {
91 const host = hostRef.current;
92 if (host === null) return;
93 const shadow = host.shadowRoot ?? host.attachShadow({ mode: "open" });
94 shadow.innerHTML = html;
95 }, [html]);
96 return <div ref={hostRef} />;
97}
98
99/** The diff panel's file diff, statically rendered by its real pipeline. */
100export function CodeFontPreview() {
101 const { resolvedTheme } = useTheme();
102 const themeName = resolveDiffThemeName(resolvedTheme);
103 const [htmlByFile, setHtmlByFile] = useState<readonly string[] | null>(null);
104 useEffect(() => {
105 let cancelled = false;
106 void loadDiffPreviewHtml(themeName).then((html) => {
107 if (!cancelled) setHtmlByFile(html);
108 });
109 return () => {
110 cancelled = true;
111 };
112 }, [themeName]);
113 if (htmlByFile === null) return null;
114 return (
115 <div className="mt-1 mb-2 space-y-2">
116 {htmlByFile.map((html) => (
117 <StaticDiffHtml key={html} html={html} />
118 ))}
119 </div>
120 );
121}
122
123// A zsh-style prompt: green arrow, cyan project, blue/red git segment,
124// yellow dirty marker. It doubles as the echo loop's fresh-line prompt.
125const TERMINAL_PROMPT =
126 "\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 ";
127// A dev-server startup: brand line, addresses, a test summary, and a READY
128// badge. Together the lines cover bold, dim, underline, the six accent
129// colors, and a background cell, so a font choice shows every SGR the
130// terminal actually renders.
131const TERMINAL_PREVIEW_TRANSCRIPT =
132 `${TERMINAL_PROMPT}vpr dev\r\n` +
133 "\r\n" +
134 " \x1b[1;32mVITE\x1b[0m \x1b[32mv7.1.1\x1b[0m \x1b[2mready in\x1b[0m \x1b[1m1.24s\x1b[0m\r\n" +
135 "\r\n" +
136 " \x1b[32m→\x1b[0m \x1b[2mLocal:\x1b[0m \x1b[4;36mhttp://127.0.0.1:5173/\x1b[0m\r\n" +
137 " \x1b[32m→\x1b[0m \x1b[2mNetwork:\x1b[0m \x1b[4;36mhttp://192.168.1.24:5173/\x1b[0m\r\n" +
138 "\r\n" +
139 " \x1b[32m✓ 85 passed\x1b[0m \x1b[33m△ 2 warnings\x1b[0m \x1b[31m✗ 0 failed\x1b[0m\r\n" +
140 "\r\n" +
141 " \x1b[42;30m READY \x1b[0m \x1b[2mwatching for changes — press\x1b[0m \x1b[1mq\x1b[0m \x1b[2mto quit\x1b[0m\r\n" +
142 "\r\n" +
143 TERMINAL_PROMPT;
144
145/** The surface treats an omitted family or size as "use the built-in default". */
146function previewTerminalFont(family: string, size: number): { family?: string; size: number } {
147 const trimmed = family.trim();
148 return trimmed.length > 0 ? { family: trimmed, size } : { size };
149}
150
151/**
152 * The real Ghostty canvas renderer against a local echo loop instead of a
153 * PTY: keys print, Enter starts a new prompt line, Backspace erases. That
154 * exercises the same glyph atlas, cell metrics, and monospace gate the
155 * terminal drawer uses.
156 */
157export function TerminalFontPreview({ family, size }: { family: string; size: number }) {
158 const mountRef = useRef<HTMLDivElement>(null);
159 const surfaceRef = useRef<GhosttyTerminalSurface | null>(null);
160 const fontRef = useRef({ family, size });
161 const { resolvedTheme } = useTheme();
162
163 useEffect(() => {
164 const current = fontRef.current;
165 if (current.family === family && current.size === size) return;
166 fontRef.current = { family, size };
167 void surfaceRef.current?.setFont(previewTerminalFont(family, size));
168 }, [family, size]);
169
170 useEffect(() => {
171 const mount = mountRef.current;
172 const surface = surfaceRef.current;
173 if (!mount || !surface) return;
174 surface.setTheme(terminalThemeFromApp(mount));
175 }, [resolvedTheme]);
176
177 useEffect(() => {
178 const mount = mountRef.current;
179 if (!mount) return;
180 let cancelled = false;
181 // Column of the caret on the current input line, so Backspace stops at
182 // the prompt instead of eating it.
183 let lineLength = 0;
184
185 const echo = (data: string) => {
186 const surface = surfaceRef.current;
187 if (!surface) return;
188 if (data === "\r") {
189 surface.write(`\r\n${TERMINAL_PROMPT}`);
190 lineLength = 0;
191 return;
192 }
193 if (data === "\x7f" || data === "\b") {
194 if (lineLength > 0) {
195 surface.write("\b \b");
196 lineLength -= 1;
197 }
198 return;
199 }
200 // Arrow keys and other escape reports have no cursor to move here.
201 if (data.startsWith("\x1b")) return;
202 const printable = [...data]
203 .filter((character) => character >= " " && character !== "\x7f")
204 .join("");
205 if (printable.length === 0) return;
206 surface.write(printable);
207 lineLength += printable.length;
208 };
209
210 void GhosttyTerminalSurface.create(mount, {
211 theme: terminalThemeFromApp(mount),
212 font: previewTerminalFont(fontRef.current.family, fontRef.current.size),
213 onData: echo,
214 onResize: noop,
215 onSelectionChange: noop,
216 onCopy: (text) => void navigator.clipboard?.writeText(text).catch(noop),
217 // Tab keeps walking the settings page instead of feeding the echo loop.
218 beforeKey: (event) => event.key !== "Tab",
219 onLinkActivate: noop,
220 }).then((surface) => {
221 if (cancelled) {
222 surface.dispose();
223 return;
224 }
225 surfaceRef.current = surface;
226 // The theme and font may both have changed while the WASM surface loaded.
227 surface.setTheme(terminalThemeFromApp(mount));
228 const font = fontRef.current;
229 void surface.setFont(previewTerminalFont(font.family, font.size));
230 surface.write(TERMINAL_PREVIEW_TRANSCRIPT);
231 });
232
233 return () => {
234 cancelled = true;
235 surfaceRef.current?.dispose();
236 surfaceRef.current = null;
237 };
238 }, []);
239
240 return (
241 <div
242 ref={mountRef}
243 className="relative mt-1 mb-2 h-52 overflow-hidden rounded-lg border border-border"
244 aria-label="Terminal font preview"
245 />
246 );
247}