Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

SettingsFontPreviews.tsx

273 lines10.5 KB

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