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

appearanceFonts.ts

389 lines14.1 KB

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