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

appearanceFonts.ts

332 lines11.1 KB

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, "Segoe UI", system-ui, sans-serif';
15​
16// Concrete names first: some engines alias `ui-monospace` to the
17// proportional system UI font, which would break every code surface.
18export const DEFAULT_CODE_FONT_STACK =
19 '"SF Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", monospace';
20​
21export const TYPOGRAPHY_ADVANCED_STORAGE_KEY = "t3code:typography-advanced";
22​
23export function resolveTerminalFontPreference(input: {
24 readonly advanced: boolean;
25 readonly code: string;
26 readonly terminal: string;
27}): string {
28 if (input.advanced) return input.terminal;
29 return input.code;
31​
32export function resolveTerminalFontSizePreference(input: {
33 readonly advanced: boolean;
34 readonly code: number;
35 readonly terminal: number;
36}): number {
37 if (input.advanced) return input.terminal;
38 return input.code;
40​
41function quoteFontFamilyName(name: string): string {
42 const bare = name.trim();
43 if (bare.length === 0) return "";
44 if (/^(['"]).*\1$/.test(bare)) return bare;
45 if (/^[a-zA-Z][a-zA-Z0-9-]*$/.test(bare)) return bare;
46 return `"${bare.replaceAll('"', "")}"`;
48​
49export function cssFontFamilies(input: string): string | null {
50 const families = input
51 .split(",")
52 .map(quoteFontFamilyName)
53 .filter((name) => name.length > 0);
54 return families.length > 0 ? families.join(", ") : null;
56​
57export function appearanceFontStack(custom: string, defaultStack: string): string {
58 const families = cssFontFamilies(custom);
59 return families === null ? defaultStack : `${families}, ${defaultStack}`;
61​
62export interface AppearanceFontPreferences {
63 readonly sans: string;
64 readonly code: string;
65 readonly composer: string;
66 readonly sizeInterface: number;
67 readonly sizePrompt: number;
68 readonly sizeCode: number;
69 readonly smoothing: boolean;
71​
72/**
73 * Sizes are always written: the interface size drives the root font size (and
74 * with it every rem-based dimension), while the prompt and code sizes stay in
75 * absolute pixels so they do not scale twice.
76 */
77export function applyAppearanceFontVariables(
78 root: HTMLElement,
79 preferences: AppearanceFontPreferences,
80): void {
81 const families: ReadonlyArray<readonly [variable: string, custom: string, fallback: string]> = [
82 ["--font-sans", preferences.sans, DEFAULT_SANS_FONT_STACK],
83 ["--font-mono", preferences.code, DEFAULT_CODE_FONT_STACK],
84 ["--font-composer", preferences.composer, "var(--font-sans)"],
85 ];
86 for (const [variable, custom, fallback] of families) {
87 const list = cssFontFamilies(custom);
88 if (list === null) {
89 root.style.removeProperty(variable);
90 } else {
91 root.style.setProperty(variable, `${list}, ${fallback}`);
92 }
93 }
94​
95 root.style.fontSize = `${clampInterfaceFontSize(preferences.sizeInterface)}px`;
96 root.style.setProperty("--font-size-prompt", `${clampPromptFontSize(preferences.sizePrompt)}px`);
97 const code = clampCodeFontSize(preferences.sizeCode);
98 root.style.setProperty("--font-size-code", `${code}px`);
99 root.style.setProperty("--diffs-font-size", `${code}px`);
100​
101 if (preferences.smoothing) {
102 root.style.setProperty("-webkit-font-smoothing", "antialiased");
103 } else {
104 root.style.removeProperty("-webkit-font-smoothing");
105 }
107​
108function clampFontSize(value: number, minimum: number, maximum: number, fallback: number): number {
109 if (!Number.isFinite(value)) return fallback;
110 return Math.min(maximum, Math.max(minimum, Math.round(value)));
112​
113export function clampInterfaceFontSize(value: number): number {
114 return clampFontSize(
115 value,
116 MIN_INTERFACE_FONT_SIZE,
117 MAX_INTERFACE_FONT_SIZE,
118 DEFAULT_INTERFACE_FONT_SIZE,
119 );
121​
122export function clampPromptFontSize(value: number): number {
123 return clampFontSize(value, MIN_PROMPT_FONT_SIZE, MAX_PROMPT_FONT_SIZE, DEFAULT_PROMPT_FONT_SIZE);
125​
126export function clampCodeFontSize(value: number): number {
127 return clampFontSize(value, MIN_CODE_FONT_SIZE, MAX_CODE_FONT_SIZE, DEFAULT_CODE_FONT_SIZE);
129​
130const FONT_PROBE_TEXT = "mmmmmmmmMMWli1O0@# fjord";
131let fontProbeContext: CanvasRenderingContext2D | null | undefined;
132​
133function probeWidth(fontList: string): number | null {
134 if (fontProbeContext === undefined) {
135 fontProbeContext = document.createElement("canvas").getContext("2d");
136 }
137 if (fontProbeContext === null) return null;
138 fontProbeContext.font = `16px ${fontList}`;
139 return fontProbeContext.measureText(FONT_PROBE_TEXT).width;
141​
142/**
143 * Canvas metric probing instead of document.fonts.check(): check() reports true
144 * for families that are not installed at all (nothing needs loading), so it
145 * cannot filter the dropdown.
146 */
147export function isFontFamilyAvailable(family: string): boolean {
148 const families = cssFontFamilies(family);
149 if (families === null) return false;
150 if (/^(system-ui|sans-serif|serif|monospace|ui-monospace)$/i.test(families)) return true;
151 try {
152 for (const generic of ["monospace", "serif", "sans-serif"]) {
153 const baseline = probeWidth(generic);
154 const candidate = probeWidth(`${families}, ${generic}`);
155 if (baseline === null || candidate === null) return false;
156 if (candidate !== baseline) return true;
157 }
158 return false;
159 } catch {
160 return false;
161 }
163​
164const MONOSPACE_PROBE_VARIANTS = ["normal 400", "normal 700", "italic 400", "italic 700"] as const;
165const MONOSPACE_PROBE_GLYPHS = ["i", "M", "W", "0", "@", "#", ".", " "] as const;
166const MONOSPACE_ADVANCE_TOLERANCE = 0.01;
167​
168export function areFontAdvancesMonospace(advances: readonly number[]): boolean {
169 const reference = advances[0];
170 if (
171 reference === undefined ||
172 reference <= 0 ||
173 advances.some((advance) => !Number.isFinite(advance) || advance <= 0)
174 ) {
175 return true;
176 }
177 return advances.every((advance) => Math.abs(advance - reference) < MONOSPACE_ADVANCE_TOLERANCE);
179​
180export function isMonospaceFamily(family: string): boolean {
181 const families = cssFontFamilies(family);
182 if (families === null) return true;
183 try {
184 if (fontProbeContext === undefined) {
185 fontProbeContext = document.createElement("canvas").getContext("2d");
186 }
187 if (fontProbeContext === null) return true;
188 const context = fontProbeContext;
189 for (const variant of MONOSPACE_PROBE_VARIANTS) {
190 context.font = `${variant} 32px ${families}, monospace`;
191 const advances = MONOSPACE_PROBE_GLYPHS.map((glyph) => context.measureText(glyph).width);
192 if (!areFontAdvancesMonospace(advances)) return false;
193 }
194 return true;
195 } catch {
196 return true;
197 }
199​
200const SANS_GENERIC_CANDIDATES = [
201 "Segoe UI",
202 "Roboto",
203 "Noto Sans",
204 "Ubuntu",
205 "Cantarell",
206 "DejaVu Sans",
207 "Liberation Sans",
208 "Helvetica Neue",
209 "Arial",
210] as const;
211const MONO_GENERIC_CANDIDATES = [
212 "Menlo",
213 "Consolas",
214 "Cascadia Mono",
215 "DejaVu Sans Mono",
216 "Ubuntu Mono",
217 "Liberation Mono",
218 "Noto Sans Mono",
219 "Roboto Mono",
220 "Monaco",
221 "Courier New",
222] as const;
223​
224const GENERIC_PROBE_TEXT = "RagIl10O@ fjord quiz";
225​
226/**
227 * Advance width of the probe text laid out by the DOM - not canvas, whose
228 * generic-family mapping diverges from real rendering (this engine draws
229 * `ui-monospace` as the proportional UI font on canvas but not in CSS).
230 */
231function measureDomProbeWidth(fontFamily: string): number | null {
232 try {
233 const body = document.body;
234 if (!body) return null;
235 const span = document.createElement("span");
236 span.style.cssText =
237 "position:absolute;left:-9999px;top:0;visibility:hidden;white-space:pre;font-size:100px;";
238 span.style.fontFamily = fontFamily;
239 span.textContent = GENERIC_PROBE_TEXT;
240 body.appendChild(span);
241 const width = span.getBoundingClientRect().width;
242 span.remove();
243 return width > 0 ? width : null;
244 } catch {
245 return null;
246 }
248​
249function widthsMatch(left: number, right: number): boolean {
250 return Math.abs(left - right) < 0.01;
252​
253function resolveGenericFamilyLabel(generic: string): string | null {
254 const lower = generic.toLowerCase();
255 if (lower === "serif") return null;
256 const monoLike = lower === "ui-monospace" || lower === "monospace";
257 const genericWidth = measureDomProbeWidth(generic);
258 if (genericWidth === null) return null;
259 for (const candidate of monoLike ? MONO_GENERIC_CANDIDATES : SANS_GENERIC_CANDIDATES) {
260 if (!isFontFamilyAvailable(candidate)) continue;
261 const candidateWidth = measureDomProbeWidth(`"${candidate}"`);
262 if (candidateWidth !== null && widthsMatch(genericWidth, candidateWidth)) {
263 return candidate;
264 }
265 }
266 // No nameable face matched; on Apple platforms that means one of the San
267 // Francisco faces, which CSS cannot name. Comparing against -apple-system
268 // tells the UI face apart from SF Mono.
269 if (/mac|iphone|ipad|ipod/i.test(navigator.platform)) {
270 const systemWidth = measureDomProbeWidth("-apple-system");
271 if (systemWidth !== null && widthsMatch(genericWidth, systemWidth)) return "SF Pro";
272 return monoLike ? "SF Mono" : "SF Pro";
273 }
274 return null;
276​
277export function resolveDefaultFamilyLabel(stack: string): string | null {
278 for (const raw of stack.split(",")) {
279 const family = raw.trim().replace(/^(['"])(.*)\1$/, "$2");
280 if (family.length === 0) continue;
281 if (
282 /^(system-ui|sans-serif|serif|monospace|ui-monospace|-apple-system|BlinkMacSystemFont)$/i.test(
283 family,
284 )
285 ) {
286 const resolved = resolveGenericFamilyLabel(family);
287 if (resolved !== null) return resolved;
288 continue;
289 }
290 if (isFontFamilyAvailable(family)) return family;
291 }
292 return null;
294​
295export interface InstalledFontFamiliesResult {
296 readonly families: readonly string[];
297 readonly status: "granted" | "denied" | "unsupported";
299​
300let installedFamiliesCache: InstalledFontFamiliesResult | null = null;
301​
302/**
303 * Call from a user gesture: the first call raises the browser's local-fonts
304 * permission prompt.
305 */
306export async function queryInstalledFontFamilies(): Promise<InstalledFontFamiliesResult> {
307 if (installedFamiliesCache !== null) return installedFamiliesCache;
308 const query = (
309 window as Window & {
310 queryLocalFonts?: () => Promise<ReadonlyArray<{ readonly family: string }>>;
311 }
312 ).queryLocalFonts;
313 if (typeof query !== "function") {
314 installedFamiliesCache = { families: [], status: "unsupported" };
315 return installedFamiliesCache;
316 }
317 try {
318 const fonts = await query.call(window);
319 const families = [...new Set(fonts.map((font) => font.family))]
320 // Dot-prefixed families are macOS-internal UI faces; selecting one is
321 // never intended and most refuse to render for web content anyway.
322 .filter((family) => !family.startsWith("."))
323 .sort((left, right) => left.localeCompare(right));
324 // A denied permission check resolves with an empty list instead of
325 // throwing; no machine has zero fonts, so treat empty as denied.
326 if (families.length === 0) return { families: [], status: "denied" };
327 installedFamiliesCache = { families, status: "granted" };
328 return installedFamiliesCache;
329 } catch {
330 return { families: [], status: "denied" };
331 }