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

appearanceFonts.ts

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