Skip to content

Commit 726671d

Browse files
committed
fix(web): avoid freezing appearance font settings
1 parent a20923c commit 726671d

3 files changed

Lines changed: 118 additions & 32 deletions

File tree

‎apps/web/src/appearanceFonts.test.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
DEFAULT_SANS_FONT_STACK,
1010
appearanceFontStack,
1111
cssFontFamilies,
12+
filterFontFamiliesWithoutBlocking,
1213
resolveDefaultFamilyLabel,
1314
resolveTerminalFontPreference,
1415
resolveTerminalFontSizePreference,
@@ -27,6 +28,36 @@ describe("areFontAdvancesMonospace", () => {
2728
});
2829
});
2930

31+
describe("filterFontFamiliesWithoutBlocking", () => {
32+
it("yields when the time budget is exhausted and preserves accepted-family order", async () => {
33+
let elapsed = 0;
34+
const evaluated: string[] = [];
35+
const yieldedAfter: string[][] = [];
36+
37+
const result = await filterFontFamiliesWithoutBlocking(
38+
["Alpha", "Beta", "Gamma", "Delta"],
39+
(family) => {
40+
evaluated.push(family);
41+
elapsed += 5;
42+
return family !== "Beta";
43+
},
44+
{
45+
timeBudgetMs: 8,
46+
now: () => elapsed,
47+
yieldControl: async () => {
48+
yieldedAfter.push([...evaluated]);
49+
},
50+
},
51+
);
52+
53+
expect(result).toEqual(["Alpha", "Gamma", "Delta"]);
54+
expect(yieldedAfter).toEqual([
55+
["Alpha", "Beta"],
56+
["Alpha", "Beta", "Gamma", "Delta"],
57+
]);
58+
});
59+
});
60+
3061
describe("cssFontFamilies", () => {
3162
it("returns null for effectively empty input", () => {
3263
expect(cssFontFamilies("")).toBeNull();

‎apps/web/src/appearanceFonts.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,46 @@ export function areFontAdvancesMonospace(advances: readonly number[]): boolean {
206206
return advances.every((advance) => Math.abs(advance - reference) < MONOSPACE_ADVANCE_TOLERANCE);
207207
}
208208

209+
type NonBlockingFilterOptions = {
210+
readonly timeBudgetMs?: number;
211+
readonly now?: () => number;
212+
readonly yieldControl?: () => Promise<void>;
213+
};
214+
215+
function currentTime(): number {
216+
return typeof performance === "undefined" ? Date.now() : performance.now();
217+
}
218+
219+
function yieldToMainThread(): Promise<void> {
220+
return new Promise((resolve) => setTimeout(resolve, 0));
221+
}
222+
223+
/**
224+
* Filter expensive font probes without monopolizing the browser's main
225+
* thread. The time budget adapts to the cost of each family's canvas probes,
226+
* unlike a fixed item count.
227+
*/
228+
export async function filterFontFamiliesWithoutBlocking(
229+
families: readonly string[],
230+
acceptsFamily: (family: string) => boolean,
231+
options: NonBlockingFilterOptions = {},
232+
): Promise<readonly string[]> {
233+
const now = options.now ?? currentTime;
234+
const yieldControl = options.yieldControl ?? yieldToMainThread;
235+
const timeBudgetMs = options.timeBudgetMs ?? 8;
236+
let nextYieldAt = now() + timeBudgetMs;
237+
const accepted: string[] = [];
238+
239+
for (const family of families) {
240+
if (acceptsFamily(family)) accepted.push(family);
241+
if (now() < nextYieldAt) continue;
242+
await yieldControl();
243+
nextYieldAt = now() + timeBudgetMs;
244+
}
245+
246+
return accepted;
247+
}
248+
209249
/**
210250
* Whether a family renders every character on the same advance. Cell-grid
211251
* surfaces (the terminal) require this: a proportional face draws its text

‎apps/web/src/components/settings/FontFamilyPicker.tsx‎

Lines changed: 47 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
11
import { LegendList, type LegendListRef } from "@legendapp/list/react";
22
import { CheckIcon, ChevronDownIcon, SearchIcon } from "lucide-react";
33
import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
4-
import { isMonospaceFamily, queryInstalledFontFamilies } from "../../appearanceFonts";
4+
import {
5+
filterFontFamiliesWithoutBlocking,
6+
isMonospaceFamily,
7+
queryInstalledFontFamilies,
8+
} from "../../appearanceFonts";
59
import {
610
Combobox,
711
ComboboxEmpty,
@@ -58,44 +62,27 @@ export function discoverInstalledFonts(): void {
5862
});
5963
}
6064

61-
let grantedProbeStarted = false;
62-
63-
/**
64-
* Discover eagerly when the permission is already granted, so the picker
65-
* renders without waiting for a focus. Electron's default permission handler
66-
* approves silently (it has no prompt UI), and a browser that granted once
67-
* reports "granted" on later visits — in both, no user gesture is needed.
68-
* "prompt" and "denied" states change nothing: the focus-driven flow stays,
69-
* because raising the browser prompt still requires a gesture.
70-
*/
71-
function probeAlreadyGrantedPermission(): void {
72-
if (grantedProbeStarted || enumerationState.status !== "unknown") return;
73-
grantedProbeStarted = true;
74-
const permissions = typeof navigator !== "undefined" ? navigator.permissions : undefined;
75-
if (typeof permissions?.query !== "function") return;
76-
permissions.query({ name: "local-fonts" as PermissionName }).then(
77-
(status) => {
78-
if (status.state === "granted") discoverInstalledFonts();
79-
},
80-
() => {
81-
// The engine does not recognize the permission name; keep the
82-
// focus-driven flow.
83-
},
84-
);
85-
}
86-
8765
/**
8866
* Whether the engine can list installed fonts (Local Font Access API —
8967
* Chromium and Electron). "unknown" until discovery resolves the permission;
9068
* rows render a plain family-name input until the state is known granted,
91-
* then upgrade to the picker. Where the permission is already granted,
92-
* discovery starts at mount and the picker appears without a focus.
69+
* then upgrade to the picker. Discovery only starts from the plain input's
70+
* focus gesture, so opening Appearance never scans the machine's font catalog.
9371
*/
9472
export function useFontEnumeration(): FontEnumerationState {
95-
useEffect(probeAlreadyGrantedPermission, []);
9673
return useSyncExternalStore(subscribeToEnumeration, readEnumerationState);
9774
}
9875

76+
const monospaceFamiliesCache = new WeakMap<readonly string[], Promise<readonly string[]>>();
77+
78+
function readMonospaceFamilies(families: readonly string[]): Promise<readonly string[]> {
79+
const cached = monospaceFamiliesCache.get(families);
80+
if (cached !== undefined) return cached;
81+
const pending = filterFontFamiliesWithoutBlocking(families, isMonospaceFamily);
82+
monospaceFamiliesCache.set(families, pending);
83+
return pending;
84+
}
85+
9986
/**
10087
* A searchable picker over every installed family, the way native editors
10188
* list system fonts. The trigger always names the font in use: the committed
@@ -132,6 +119,22 @@ export function FontFamilyPicker({
132119
}, []);
133120
const listRef = useRef<LegendListRef | null>(null);
134121
const enumeration = useFontEnumeration();
122+
const [monospaceClassification, setMonospaceClassification] = useState<{
123+
readonly source: readonly string[];
124+
readonly families: readonly string[];
125+
} | null>(null);
126+
127+
useEffect(() => {
128+
if (!requireMonospace || enumeration.status !== "granted") return;
129+
const source = enumeration.families;
130+
let cancelled = false;
131+
void readMonospaceFamilies(source).then((families) => {
132+
if (!cancelled) setMonospaceClassification({ source, families });
133+
});
134+
return () => {
135+
cancelled = true;
136+
};
137+
}, [enumeration, requireMonospace]);
135138

136139
const handleOpenChange = (nextOpen: boolean) => {
137140
setOpen(nextOpen);
@@ -140,8 +143,15 @@ export function FontFamilyPicker({
140143

141144
const families = useMemo(() => {
142145
if (enumeration.status !== "granted") return [];
143-
return requireMonospace ? enumeration.families.filter(isMonospaceFamily) : enumeration.families;
144-
}, [enumeration, requireMonospace]);
146+
if (!requireMonospace) return enumeration.families;
147+
return monospaceClassification?.source === enumeration.families
148+
? monospaceClassification.families
149+
: [];
150+
}, [enumeration, monospaceClassification, requireMonospace]);
151+
const classifyingMonospaceFamilies =
152+
requireMonospace &&
153+
enumeration.status === "granted" &&
154+
monospaceClassification?.source !== enumeration.families;
145155

146156
const items = useMemo(() => {
147157
const trimmedQuery = query.trim().toLowerCase();
@@ -232,6 +242,11 @@ export function FontFamilyPicker({
232242
</div>
233243
</div>
234244
<div className="flex min-h-0 flex-1 flex-col overflow-hidden">
245+
{classifyingMonospaceFamilies ? (
246+
<div className="px-3 py-2 text-xs text-muted-foreground" role="status">
247+
Checking installed fonts…
248+
</div>
249+
) : null}
235250
<ComboboxEmpty>No fonts found.</ComboboxEmpty>
236251
<div className="relative min-h-0 max-h-72 w-full flex-1 overflow-hidden">
237252
<ComboboxListVirtualized className="size-full min-w-0 p-0">

0 commit comments

Comments
 (0)