Open History to see the last commit
1/**
2 * Font preferences from Settings → Appearance, applied as CSS custom
3 * properties. The default stacks mirror the `--font-sans` / `--font-mono`
4 * definitions in `index.css`; a custom family is always prepended to the
5 * matching default stack so glyph coverage never regresses.
6 */
7
8import {
9 DEFAULT_CODE_FONT_SIZE,
10 DEFAULT_INTERFACE_FONT_SIZE,
11 DEFAULT_PROMPT_FONT_SIZE,
12 MAX_CODE_FONT_SIZE,
13 MAX_INTERFACE_FONT_SIZE,
14 MAX_PROMPT_FONT_SIZE,
15 MIN_CODE_FONT_SIZE,
16 MIN_INTERFACE_FONT_SIZE,
17 MIN_PROMPT_FONT_SIZE,
18} from "@t3tools/contracts";
19
20export const DEFAULT_SANS_FONT_STACK =
21 '-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif';
22
23// Concrete names first: some engines alias `ui-monospace` to the
24// proportional system UI font, which would break every code surface.
25export const DEFAULT_CODE_FONT_STACK =
26 '"SF Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", monospace';
27
28export const TYPOGRAPHY_ADVANCED_STORAGE_KEY = "t3code:typography-advanced";
29
30/**
31 * Simple typography treats the terminal as another monospace surface. In
32 * Advanced mode an empty terminal preference means the terminal default,
33 * keeping later code-font changes isolated to code surfaces.
34 */
35export function resolveTerminalFontPreference(input: {
36 readonly advanced: boolean;
37 readonly code: string;
38 readonly terminal: string;
39}): string {
40 if (input.advanced) return input.terminal;
41 return input.code;
42}
43
44function quoteFontFamilyName(name: string): string {
45 const bare = name.trim();
46 if (bare.length === 0) return "";
47 // Already quoted, or a single ident that needs no quoting.
48 if (/^(['"]).*\1$/.test(bare)) return bare;
49 if (/^[a-zA-Z][a-zA-Z0-9-]*$/.test(bare)) return bare;
50 return `"${bare.replaceAll('"', "")}"`;
51}
52
53/**
54 * Normalize a user-entered family (single name or comma-separated list) into a
55 * safe CSS font-family list, or null when the input is effectively empty.
56 */
57export function cssFontFamilies(input: string): string | null {
58 const families = input
59 .split(",")
60 .map(quoteFontFamilyName)
61 .filter((name) => name.length > 0);
62 return families.length > 0 ? families.join(", ") : null;
63}
64
65/** The full stack a preference resolves to: custom families before the default. */
66export function appearanceFontStack(custom: string, defaultStack: string): string {
67 const families = cssFontFamilies(custom);
68 return families === null ? defaultStack : `${families}, ${defaultStack}`;
69}
70
71export interface AppearanceFontPreferences {
72 readonly sans: string;
73 readonly code: string;
74 readonly composer: string;
75 readonly sizeInterface: number;
76 readonly sizePrompt: number;
77 readonly sizeCode: number;
78 /** Grayscale `antialiased` rendering; false keeps the heavier platform default. */
79 readonly smoothing: boolean;
80}
81
82/**
83 * Apply the preferences to the root element. Unset families remove the
84 * override so the stylesheet defaults (and theme changes) stay in charge.
85 *
86 * Sizes are always written: the interface size drives the root font size (and
87 * with it every rem-based dimension), while the prompt and code sizes stay in
88 * absolute pixels so they do not scale twice.
89 */
90export function applyAppearanceFontVariables(
91 root: HTMLElement,
92 preferences: AppearanceFontPreferences,
93): void {
94 const families: ReadonlyArray<readonly [variable: string, custom: string, fallback: string]> = [
95 ["--font-sans", preferences.sans, DEFAULT_SANS_FONT_STACK],
96 ["--font-mono", preferences.code, DEFAULT_CODE_FONT_STACK],
97 // The composer falls back to whatever the sans preference resolves to.
98 ["--font-composer", preferences.composer, "var(--font-sans)"],
99 ];
100 for (const [variable, custom, fallback] of families) {
101 const list = cssFontFamilies(custom);
102 if (list === null) {
103 root.style.removeProperty(variable);
104 } else {
105 root.style.setProperty(variable, `${list}, ${fallback}`);
106 }
107 }
108
109 root.style.fontSize = `${clampInterfaceFontSize(preferences.sizeInterface)}px`;
110 root.style.setProperty("--font-size-prompt", `${clampPromptFontSize(preferences.sizePrompt)}px`);
111 const code = clampCodeFontSize(preferences.sizeCode);
112 root.style.setProperty("--font-size-code", `${code}px`);
113 // The @pierre/diffs surfaces read their own hook for code text.
114 root.style.setProperty("--diffs-font-size", `${code}px`);
115
116 // Inherited from the root; only macOS engines honor the property, so no
117 // platform gate is needed here. Smoothing on means grayscale `antialiased`
118 // (thinner strokes); off restores the platform default, which macOS renders
119 // with heavier stem darkening.
120 if (preferences.smoothing) {
121 root.style.setProperty("-webkit-font-smoothing", "antialiased");
122 } else {
123 root.style.removeProperty("-webkit-font-smoothing");
124 }
125}
126
127function clampFontSize(value: number, minimum: number, maximum: number, fallback: number): number {
128 if (!Number.isFinite(value)) return fallback;
129 return Math.min(maximum, Math.max(minimum, Math.round(value)));
130}
131
132export function clampInterfaceFontSize(value: number): number {
133 return clampFontSize(
134 value,
135 MIN_INTERFACE_FONT_SIZE,
136 MAX_INTERFACE_FONT_SIZE,
137 DEFAULT_INTERFACE_FONT_SIZE,
138 );
139}
140
141export function clampPromptFontSize(value: number): number {
142 return clampFontSize(value, MIN_PROMPT_FONT_SIZE, MAX_PROMPT_FONT_SIZE, DEFAULT_PROMPT_FONT_SIZE);
143}
144
145export function clampCodeFontSize(value: number): number {
146 return clampFontSize(value, MIN_CODE_FONT_SIZE, MAX_CODE_FONT_SIZE, DEFAULT_CODE_FONT_SIZE);
147}
148
149const FONT_PROBE_TEXT = "mmmmmmmmMMWli1O0@# fjord";
150let fontProbeContext: CanvasRenderingContext2D | null | undefined;
151
152function probeWidth(fontList: string): number | null {
153 if (fontProbeContext === undefined) {
154 fontProbeContext = document.createElement("canvas").getContext("2d");
155 }
156 if (fontProbeContext === null) return null;
157 fontProbeContext.font = `16px ${fontList}`;
158 return fontProbeContext.measureText(FONT_PROBE_TEXT).width;
159}
160
161/**
162 * Canvas metric probing instead of document.fonts.check(): check() reports
163 * true for families that are not installed at all (nothing needs loading), so
164 * it cannot filter the dropdown. A family exists when falling back to at
165 * least one generic changes the measured advance.
166 */
167export function isFontFamilyAvailable(family: string): boolean {
168 const families = cssFontFamilies(family);
169 if (families === null) return false;
170 if (/^(system-ui|sans-serif|serif|monospace|ui-monospace)$/i.test(families)) return true;
171 try {
172 for (const generic of ["monospace", "serif", "sans-serif"]) {
173 const baseline = probeWidth(generic);
174 const candidate = probeWidth(`${families}, ${generic}`);
175 if (baseline === null || candidate === null) return false;
176 if (candidate !== baseline) return true;
177 }
178 return false;
179 } catch {
180 return false;
181 }
182}
183
184const MONOSPACE_PROBE_VARIANTS = ["normal 400", "normal 700", "italic 400", "italic 700"] as const;
185const MONOSPACE_PROBE_GLYPHS = ["i", "M", "W", "0", "@", "#", ".", " "] as const;
186const MONOSPACE_ADVANCE_TOLERANCE = 0.01;
187
188export function areFontAdvancesMonospace(advances: readonly number[]): boolean {
189 const reference = advances[0];
190 if (
191 reference === undefined ||
192 reference <= 0 ||
193 advances.some((advance) => !Number.isFinite(advance) || advance <= 0)
194 ) {
195 return true;
196 }
197 return advances.every((advance) => Math.abs(advance - reference) < MONOSPACE_ADVANCE_TOLERANCE);
198}
199
200/**
201 * Whether a family renders every character on the same advance. Cell-grid
202 * surfaces (the terminal) require this: a proportional face draws its text
203 * narrower than the lattice the cursor and selection are placed on, which
204 * reads as ragged gaps and a cursor stranded to the right of the text.
205 *
206 * Unmeasurable environments answer true, so a missing canvas never blocks a
207 * legitimate font.
208 */
209export function isMonospaceFamily(family: string): boolean {
210 const families = cssFontFamilies(family);
211 if (families === null) return true;
212 try {
213 if (fontProbeContext === undefined) {
214 fontProbeContext = document.createElement("canvas").getContext("2d");
215 }
216 if (fontProbeContext === null) return true;
217 const context = fontProbeContext;
218 // Fall back to a generic mono so an absent face measures as monospace and
219 // is left for the normal fallback chain to resolve.
220 for (const variant of MONOSPACE_PROBE_VARIANTS) {
221 context.font = `${variant} 32px ${families}, monospace`;
222 const advances = MONOSPACE_PROBE_GLYPHS.map((glyph) => context.measureText(glyph).width);
223 if (!areFontAdvancesMonospace(advances)) return false;
224 }
225 return true;
226 } catch {
227 return true;
228 }
229}
230
231// Nameable faces the platform generics commonly map to, likeliest first.
232// Pixel-comparing a generic against these names the actual face; Apple's own
233// UI fonts are deliberately not CSS-nameable, so a miss on an Apple platform
234// identifies San Francisco itself.
235const SANS_GENERIC_CANDIDATES = [
236 "Segoe UI",
237 "Roboto",
238 "Noto Sans",
239 "Ubuntu",
240 "Cantarell",
241 "DejaVu Sans",
242 "Liberation Sans",
243 "Helvetica Neue",
244 "Arial",
245] as const;
246const MONO_GENERIC_CANDIDATES = [
247 "Menlo",
248 "Consolas",
249 "Cascadia Mono",
250 "DejaVu Sans Mono",
251 "Ubuntu Mono",
252 "Liberation Mono",
253 "Noto Sans Mono",
254 "Roboto Mono",
255 "Monaco",
256 "Courier New",
257] as const;
258
259const GENERIC_PROBE_TEXT = "RagIl10O@ fjord quiz";
260
261/**
262 * Advance width of the probe text laid out by the DOM - not canvas, whose
263 * generic-family mapping diverges from real rendering (this engine draws
264 * `ui-monospace` as the proportional UI font on canvas but not in CSS).
265 * Identical widths at this size mean the same face for practical purposes.
266 */
267function measureDomProbeWidth(fontFamily: string): number | null {
268 try {
269 const body = document.body;
270 if (!body) return null;
271 const span = document.createElement("span");
272 span.style.cssText =
273 "position:absolute;left:-9999px;top:0;visibility:hidden;white-space:pre;font-size:100px;";
274 span.style.fontFamily = fontFamily;
275 span.textContent = GENERIC_PROBE_TEXT;
276 body.appendChild(span);
277 const width = span.getBoundingClientRect().width;
278 span.remove();
279 return width > 0 ? width : null;
280 } catch {
281 return null;
282 }
283}
284
285function widthsMatch(left: number, right: number): boolean {
286 return Math.abs(left - right) < 0.01;
287}
288
289/**
290 * Name the concrete face a generic keyword renders as, by measuring the
291 * generic against nameable candidates. Null when the face cannot be
292 * identified (and the platform gives no definitional answer).
293 */
294function resolveGenericFamilyLabel(generic: string): string | null {
295 const lower = generic.toLowerCase();
296 if (lower === "serif") return null;
297 const monoLike = lower === "ui-monospace" || lower === "monospace";
298 const genericWidth = measureDomProbeWidth(generic);
299 if (genericWidth === null) return null;
300 for (const candidate of monoLike ? MONO_GENERIC_CANDIDATES : SANS_GENERIC_CANDIDATES) {
301 if (!isFontFamilyAvailable(candidate)) continue;
302 const candidateWidth = measureDomProbeWidth(`"${candidate}"`);
303 if (candidateWidth !== null && widthsMatch(genericWidth, candidateWidth)) {
304 return candidate;
305 }
306 }
307 // No nameable face matched; on Apple platforms that means one of the San
308 // Francisco faces, which CSS cannot name. Comparing against -apple-system
309 // tells the UI face apart from SF Mono.
310 if (/mac|iphone|ipad|ipod/i.test(navigator.platform)) {
311 const systemWidth = measureDomProbeWidth("-apple-system");
312 if (systemWidth !== null && widthsMatch(genericWidth, systemWidth)) return "SF Pro";
313 return monoLike ? "SF Mono" : "SF Pro";
314 }
315 return null;
316}
317
318/**
319 * The first family of a default stack that will actually render - what the
320 * "Default" choice means on this machine. Concrete names are probed for
321 * availability; generic keywords are resolved to the face they draw with
322 * where identifiable. Null when nothing can be named.
323 */
324export function resolveDefaultFamilyLabel(stack: string): string | null {
325 for (const raw of stack.split(",")) {
326 const family = raw.trim().replace(/^(['"])(.*)\1$/, "$2");
327 if (family.length === 0) continue;
328 if (
329 /^(system-ui|sans-serif|serif|monospace|ui-monospace|-apple-system|BlinkMacSystemFont)$/i.test(
330 family,
331 )
332 ) {
333 const resolved = resolveGenericFamilyLabel(family);
334 if (resolved !== null) return resolved;
335 continue;
336 }
337 if (isFontFamilyAvailable(family)) return family;
338 }
339 return null;
340}
341
342export interface InstalledFontFamiliesResult {
343 readonly families: readonly string[];
344 /**
345 * "unsupported" - the engine has no Local Font Access API (Safari,
346 * Firefox); "denied" - the API exists but the user declined the permission
347 * prompt. Both fall back to the curated catalog.
348 */
349 readonly status: "granted" | "denied" | "unsupported";
350}
351
352let installedFamiliesCache: InstalledFontFamiliesResult | null = null;
353
354/**
355 * Every installed family via the Local Font Access API (Chromium and
356 * Electron). Call from a user gesture: the first call raises the browser's
357 * local-fonts permission prompt. A denial is not cached, so reopening the
358 * picker can ask again after the user changes the site setting.
359 */
360export async function queryInstalledFontFamilies(): Promise<InstalledFontFamiliesResult> {
361 if (installedFamiliesCache !== null) return installedFamiliesCache;
362 const query = (
363 window as Window & {
364 queryLocalFonts?: () => Promise<ReadonlyArray<{ readonly family: string }>>;
365 }
366 ).queryLocalFonts;
367 if (typeof query !== "function") {
368 installedFamiliesCache = { families: [], status: "unsupported" };
369 return installedFamiliesCache;
370 }
371 try {
372 const fonts = await query.call(window);
373 const families = [...new Set(fonts.map((font) => font.family))]
374 // Dot-prefixed families are macOS-internal UI faces; selecting one is
375 // never intended and most refuse to render for web content anyway.
376 .filter((family) => !family.startsWith("."))
377 .sort((left, right) => left.localeCompare(right));
378 // A denied permission check resolves with an empty list instead of
379 // throwing; no machine has zero fonts, so treat empty as denied.
380 if (families.length === 0) return { families: [], status: "denied" };
381 installedFamiliesCache = { families, status: "granted" };
382 return installedFamiliesCache;
383 } catch {
384 return { families: [], status: "denied" };
385 }
386}