Open History to see the last commit
1import {
2 DEFAULT_CODE_FONT_SIZE,
3 DEFAULT_INTERFACE_FONT_SIZE,
4 DEFAULT_PROMPT_FONT_SIZE,
5 MAX_CODE_FONT_SIZE,
6 MAX_INTERFACE_FONT_SIZE,
7 MAX_PROMPT_FONT_SIZE,
8 MIN_CODE_FONT_SIZE,
9 MIN_INTERFACE_FONT_SIZE,
10 MIN_PROMPT_FONT_SIZE,
11} from "@t3tools/contracts";
12
13export const DEFAULT_SANS_FONT_STACK =
14 '-apple-system, BlinkMacSystemFont, "Inter Variable", "Segoe UI", system-ui, sans-serif';
15
16// Some engines map `ui-monospace` to a proportional font, so prefer concrete names.
17export const DEFAULT_CODE_FONT_STACK =
18 '"SF Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", monospace';
19
20export const TYPOGRAPHY_ADVANCED_STORAGE_KEY = "t3code:typography-advanced";
21
22export function resolveTerminalFontPreference(input: {
23 readonly advanced: boolean;
24 readonly code: string;
25 readonly terminal: string;
26}): string {
27 if (input.advanced) return input.terminal;
28 return input.code;
29}
30
31export function resolveTerminalFontSizePreference(input: {
32 readonly advanced: boolean;
33 readonly code: number;
34 readonly terminal: number;
35}): number {
36 if (input.advanced) return input.terminal;
37 return input.code;
38}
39
40function quoteFontFamilyName(name: string): string {
41 const bare = name.trim();
42 if (bare.length === 0) return "";
43 if (/^(['"]).*\1$/.test(bare)) return bare;
44 if (/^[a-zA-Z][a-zA-Z0-9-]*$/.test(bare)) return bare;
45 return `"${bare.replaceAll('"', "")}"`;
46}
47
48function cssFontFamilies(input: string): string | null {
49 const families = input
50 .split(",")
51 .map(quoteFontFamilyName)
52 .filter((name) => name.length > 0);
53 return families.length > 0 ? families.join(", ") : null;
54}
55
56export function appearanceFontStack(custom: string, defaultStack: string): string {
57 const families = cssFontFamilies(custom);
58 return families === null ? defaultStack : `${families}, ${defaultStack}`;
59}
60
61export interface AppearanceFontPreferences {
62 readonly sans: string;
63 readonly code: string;
64 readonly composer: string;
65 readonly sizeInterface: number;
66 readonly sizePrompt: number;
67 readonly sizeCode: number;
68 readonly smoothing: boolean;
69}
70
71/** Always writes sizes: interface size sets the root; prompt and code use pixels to avoid double scaling. */
72export function applyAppearanceFontVariables(
73 root: HTMLElement,
74 preferences: AppearanceFontPreferences,
75): void {
76 const families: ReadonlyArray<readonly [variable: string, custom: string, fallback: string]> = [
77 ["--font-sans", preferences.sans, DEFAULT_SANS_FONT_STACK],
78 ["--font-mono", preferences.code, DEFAULT_CODE_FONT_STACK],
79 ["--font-composer", preferences.composer, "var(--font-sans)"],
80 ];
81 for (const [variable, custom, fallback] of families) {
82 const list = cssFontFamilies(custom);
83 if (list === null) {
84 root.style.removeProperty(variable);
85 } else {
86 root.style.setProperty(variable, `${list}, ${fallback}`);
87 }
88 }
89
90 root.style.fontSize = `${clampInterfaceFontSize(preferences.sizeInterface)}px`;
91 root.style.setProperty("--font-size-prompt", `${clampPromptFontSize(preferences.sizePrompt)}px`);
92 const code = clampCodeFontSize(preferences.sizeCode);
93 root.style.setProperty("--font-size-code", `${code}px`);
94 root.style.setProperty("--diffs-font-size", `${code}px`);
95
96 if (preferences.smoothing) {
97 root.style.setProperty("-webkit-font-smoothing", "antialiased");
98 } else {
99 root.style.removeProperty("-webkit-font-smoothing");
100 }
101}
102
103function clampFontSize(value: number, minimum: number, maximum: number, fallback: number): number {
104 if (!Number.isFinite(value)) return fallback;
105 return Math.min(maximum, Math.max(minimum, Math.round(value)));
106}
107
108function clampInterfaceFontSize(value: number): number {
109 return clampFontSize(
110 value,
111 MIN_INTERFACE_FONT_SIZE,
112 MAX_INTERFACE_FONT_SIZE,
113 DEFAULT_INTERFACE_FONT_SIZE,
114 );
115}
116
117function clampPromptFontSize(value: number): number {
118 return clampFontSize(value, MIN_PROMPT_FONT_SIZE, MAX_PROMPT_FONT_SIZE, DEFAULT_PROMPT_FONT_SIZE);
119}
120
121function clampCodeFontSize(value: number): number {
122 return clampFontSize(value, MIN_CODE_FONT_SIZE, MAX_CODE_FONT_SIZE, DEFAULT_CODE_FONT_SIZE);
123}
124
125const FONT_PROBE_TEXT = "mmmmmmmmMMWli1O0@# fjord";
126let fontProbeContext: CanvasRenderingContext2D | null | undefined;
127
128function probeWidth(fontList: string): number | null {
129 if (fontProbeContext === undefined) {
130 fontProbeContext = document.createElement("canvas").getContext("2d");
131 }
132 if (fontProbeContext === null) return null;
133 fontProbeContext.font = `16px ${fontList}`;
134 return fontProbeContext.measureText(FONT_PROBE_TEXT).width;
135}
136
137/** Probes canvas metrics because document.fonts.check() accepts uninstalled families. */
138export function isFontFamilyAvailable(family: string): boolean {
139 const families = cssFontFamilies(family);
140 if (families === null) return false;
141 if (/^(system-ui|sans-serif|serif|monospace|ui-monospace)$/i.test(families)) return true;
142 try {
143 for (const generic of ["monospace", "serif", "sans-serif"]) {
144 const baseline = probeWidth(generic);
145 const candidate = probeWidth(`${families}, ${generic}`);
146 if (baseline === null || candidate === null) return false;
147 if (candidate !== baseline) return true;
148 }
149 return false;
150 } catch {
151 return false;
152 }
153}
154
155const MONOSPACE_PROBE_VARIANTS = ["normal 400", "normal 700", "italic 400", "italic 700"] as const;
156const MONOSPACE_PROBE_GLYPHS = ["i", "M", "W", "0", "@", "#", ".", " "] as const;
157const MONOSPACE_ADVANCE_TOLERANCE = 0.01;
158
159function areFontAdvancesMonospace(advances: readonly number[]): boolean {
160 const reference = advances[0];
161 if (
162 reference === undefined ||
163 reference <= 0 ||
164 advances.some((advance) => !Number.isFinite(advance) || advance <= 0)
165 ) {
166 return true;
167 }
168 return advances.every((advance) => Math.abs(advance - reference) < MONOSPACE_ADVANCE_TOLERANCE);
169}
170
171export function isMonospaceFamily(family: string): boolean {
172 const families = cssFontFamilies(family);
173 if (families === null) return true;
174 try {
175 if (fontProbeContext === undefined) {
176 fontProbeContext = document.createElement("canvas").getContext("2d");
177 }
178 if (fontProbeContext === null) return true;
179 const context = fontProbeContext;
180 for (const variant of MONOSPACE_PROBE_VARIANTS) {
181 context.font = `${variant} 32px ${families}, monospace`;
182 const advances = MONOSPACE_PROBE_GLYPHS.map((glyph) => context.measureText(glyph).width);
183 if (!areFontAdvancesMonospace(advances)) return false;
184 }
185 return true;
186 } catch {
187 return true;
188 }
189}
190
191const SANS_GENERIC_CANDIDATES = [
192 "Segoe UI",
193 "Roboto",
194 "Noto Sans",
195 "Ubuntu",
196 "Cantarell",
197 "DejaVu Sans",
198 "Liberation Sans",
199 "Helvetica Neue",
200 "Arial",
201] as const;
202const MONO_GENERIC_CANDIDATES = [
203 "Menlo",
204 "Consolas",
205 "Cascadia Mono",
206 "DejaVu Sans Mono",
207 "Ubuntu Mono",
208 "Liberation Mono",
209 "Noto Sans Mono",
210 "Roboto Mono",
211 "Monaco",
212 "Courier New",
213] as const;
214
215const GENERIC_PROBE_TEXT = "RagIl10O@ fjord quiz";
216
217// Canvas generic-family mappings can differ from CSS, so measure the DOM.
218function measureDomProbeWidth(fontFamily: string): number | null {
219 try {
220 const body = document.body;
221 if (!body) return null;
222 const span = document.createElement("span");
223 span.style.cssText =
224 "position:absolute;left:-9999px;top:0;visibility:hidden;white-space:pre;font-size:100px;";
225 span.style.fontFamily = fontFamily;
226 span.textContent = GENERIC_PROBE_TEXT;
227 body.appendChild(span);
228 const width = span.getBoundingClientRect().width;
229 span.remove();
230 return width > 0 ? width : null;
231 } catch {
232 return null;
233 }
234}
235
236function widthsMatch(left: number, right: number): boolean {
237 return Math.abs(left - right) < 0.01;
238}
239
240function resolveGenericFamilyLabel(generic: string): string | null {
241 const lower = generic.toLowerCase();
242 if (lower === "serif") return null;
243 const monoLike = lower === "ui-monospace" || lower === "monospace";
244 const genericWidth = measureDomProbeWidth(generic);
245 if (genericWidth === null) return null;
246 for (const candidate of monoLike ? MONO_GENERIC_CANDIDATES : SANS_GENERIC_CANDIDATES) {
247 if (!isFontFamilyAvailable(candidate)) continue;
248 const candidateWidth = measureDomProbeWidth(`"${candidate}"`);
249 if (candidateWidth !== null && widthsMatch(genericWidth, candidateWidth)) {
250 return candidate;
251 }
252 }
253 // Unnameable Apple faces need -apple-system metrics to distinguish the UI face from SF Mono.
254 if (/mac|iphone|ipad|ipod/i.test(navigator.platform)) {
255 const systemWidth = measureDomProbeWidth("-apple-system");
256 if (systemWidth !== null && widthsMatch(genericWidth, systemWidth)) return "SF Pro";
257 return monoLike ? "SF Mono" : "SF Pro";
258 }
259 return null;
260}
261
262export function resolveDefaultFamilyLabel(stack: string): string | null {
263 for (const raw of stack.split(",")) {
264 const family = raw.trim().replace(/^(['"])(.*)\1$/, "$2");
265 if (family.length === 0) continue;
266 if (
267 /^(system-ui|sans-serif|serif|monospace|ui-monospace|-apple-system|BlinkMacSystemFont)$/i.test(
268 family,
269 )
270 ) {
271 const resolved = resolveGenericFamilyLabel(family);
272 if (resolved !== null) return resolved;
273 continue;
274 }
275 if (isFontFamilyAvailable(family)) return family;
276 }
277 return null;
278}
279
280export interface InstalledFontFamiliesResult {
281 readonly families: readonly string[];
282 readonly status: "granted" | "denied" | "unsupported";
283}
284
285let installedFamiliesCache: InstalledFontFamiliesResult | null = null;
286
287/** Call from a user gesture; the first call prompts for local-fonts permission. */
288export async function queryInstalledFontFamilies(): Promise<InstalledFontFamiliesResult> {
289 if (installedFamiliesCache !== null) return installedFamiliesCache;
290 const query = (
291 window as Window & {
292 queryLocalFonts?: () => Promise<ReadonlyArray<{ readonly family: string }>>;
293 }
294 ).queryLocalFonts;
295 if (typeof query !== "function") {
296 installedFamiliesCache = { families: [], status: "unsupported" };
297 return installedFamiliesCache;
298 }
299 try {
300 const fonts = await query.call(window);
301 const families = [...new Set(fonts.map((font) => font.family))]
302 // Dot-prefixed macOS UI faces often refuse to render in web content.
303 .filter((family) => !family.startsWith("."))
304 .sort((left, right) => left.localeCompare(right));
305 // Denied access can return an empty list instead of throwing.
306 if (families.length === 0) return { families: [], status: "denied" };
307 installedFamiliesCache = { families, status: "granted" };
308 return installedFamiliesCache;
309 } catch {
310 return { families: [], status: "denied" };
311 }
312}