Open History to see the last commit
1import { LegendList, type LegendListRef } from "@legendapp/list/react";
2import { CheckIcon } from "lucide-react";
3import { useEffect, useRef, useState, useSyncExternalStore } from "react";
4import { isMonospaceFamily, queryInstalledFontFamilies } from "../../appearanceFonts";
5import {
6 Combobox,
7 ComboboxEmpty,
8 ComboboxSearchInput,
9 ComboboxItem,
10 ComboboxListVirtualized,
11 ComboboxPopup,
12 ComboboxTrigger,
13} from "../ui/combobox";
14import { SelectButton } from "../ui/select";
15import { stackedThreadToast, toastManager } from "../ui/toast";
16
17const DEFAULT_FONT_VALUE = "__default__";
18
19function supportsFontEnumeration(): boolean {
20 return (
21 typeof window !== "undefined" &&
22 typeof (window as { queryLocalFonts?: unknown }).queryLocalFonts === "function"
23 );
24}
25
26type FontEnumerationState =
27 | { readonly status: "unknown" }
28 | { readonly status: "granted"; readonly families: readonly string[] }
29 | { readonly status: "unavailable" };
30
31let enumerationState: FontEnumerationState = supportsFontEnumeration()
32 ? { status: "unknown" }
33 : { status: "unavailable" };
34const enumerationListeners = new Set<() => void>();
35
36function subscribeToEnumeration(listener: () => void): () => void {
37 enumerationListeners.add(listener);
38 return () => enumerationListeners.delete(listener);
39}
40
41function readEnumerationState(): FontEnumerationState {
42 return enumerationState;
43}
44
45let enumerationLoad: Promise<void> | null = null;
46
47/** Query installed fonts; call from a user gesture (the permission prompt needs one). */
48export function discoverInstalledFonts(): void {
49 if (enumerationState.status !== "unknown" || enumerationLoad !== null) return;
50 enumerationLoad = queryInstalledFontFamilies().then((result) => {
51 enumerationState =
52 result.status === "granted"
53 ? { status: "granted", families: result.families }
54 : { status: "unavailable" };
55 enumerationLoad = null;
56 for (const listener of enumerationListeners) listener();
57 });
58}
59
60let grantedProbeStarted = false;
61
62/** Electron and previously granted browsers need no user gesture to enumerate fonts. */
63function probeAlreadyGrantedPermission(): void {
64 if (grantedProbeStarted || enumerationState.status !== "unknown") return;
65 grantedProbeStarted = true;
66 const permissions = typeof navigator !== "undefined" ? navigator.permissions : undefined;
67 if (typeof permissions?.query !== "function") return;
68 permissions.query({ name: "local-fonts" as PermissionName }).then(
69 (status) => {
70 if (status.state === "granted") discoverInstalledFonts();
71 },
72 () => {},
73 );
74}
75
76export function useFontEnumeration(): FontEnumerationState {
77 useEffect(probeAlreadyGrantedPermission, []);
78 return useSyncExternalStore(subscribeToEnumeration, readEnumerationState);
79}
80
81export function FontFamilyPicker({
82 ariaLabel,
83 defaultFamily,
84 selectedFamily,
85 requireMonospace = false,
86 initialOpen = false,
87 onSelect,
88}: {
89 ariaLabel: string;
90 defaultFamily: string;
91 selectedFamily: string;
92 requireMonospace?: boolean;
93 initialOpen?: boolean;
94 onSelect: (family: string) => void;
95}) {
96 const [open, setOpen] = useState(false);
97 const [query, setQuery] = useState("");
98 // Base UI needs an initial closed commit; mounting open loses exit transitionend and leaves the popup
99 // stuck.
100 const [openAfterMount] = useState(initialOpen);
101 useEffect(() => {
102 // oxlint-disable-next-line react/set-state-in-effect -- Base UI needs one closed commit first to record the popup's entrance style.
103 if (openAfterMount) setOpen(true);
104 }, [openAfterMount]);
105 const listRef = useRef<LegendListRef | null>(null);
106 const enumeration = useFontEnumeration();
107
108 const handleOpenChange = (nextOpen: boolean) => {
109 setOpen(nextOpen);
110 if (nextOpen) setQuery("");
111 };
112
113 const families = enumeration.status === "granted" ? enumeration.families : [];
114
115 const items = (() => {
116 const trimmedQuery = query.trim().toLowerCase();
117 const result: string[] = [];
118 if (trimmedQuery.length === 0) result.push(DEFAULT_FONT_VALUE);
119 result.push(
120 ...families.filter(
121 (family) => trimmedQuery.length === 0 || family.toLowerCase().includes(trimmedQuery),
122 ),
123 );
124 return result;
125 })();
126
127 const selectedValue = selectedFamily.length === 0 ? DEFAULT_FONT_VALUE : selectedFamily;
128
129 const handlePick = (value: string) => {
130 setOpen(false);
131 if (value !== DEFAULT_FONT_VALUE && requireMonospace && !isMonospaceFamily(value)) {
132 toastManager.add(
133 stackedThreadToast({
134 type: "error",
135 title: `"${value}" isn't monospace`,
136 description: "Code and terminal need a fixed-width font, so the current font was kept.",
137 }),
138 );
139 return;
140 }
141 onSelect(value === DEFAULT_FONT_VALUE ? "" : value);
142 };
143
144 const renderItem = (item: string, index: number) => {
145 const isDefault = item === DEFAULT_FONT_VALUE;
146 const family = isDefault ? defaultFamily : item;
147 return (
148 <ComboboxItem hideIndicator index={index} key={item} value={item}>
149 <div className="flex w-full min-w-0 items-center justify-between gap-2">
150 <span className="min-w-0 truncate" style={{ fontFamily: family }}>
151 {family}
152 </span>
153 <span className="flex shrink-0 items-center gap-1.5">
154 {isDefault ? <span className="text-3xs text-muted-foreground/60">default</span> : null}
155 {item === selectedValue ? (
156 <CheckIcon className="size-3.5 text-muted-foreground" />
157 ) : null}
158 </span>
159 </div>
160 </ComboboxItem>
161 );
162 };
163
164 return (
165 <Combobox
166 items={items}
167 filteredItems={items}
168 autoHighlight
169 virtualized
170 open={open}
171 onOpenChange={handleOpenChange}
172 value={selectedValue}
173 onValueChange={(next) => {
174 if (typeof next === "string") handlePick(next);
175 }}
176 onItemHighlighted={(_value, eventDetails) => {
177 if (!open || eventDetails.index < 0 || eventDetails.reason !== "keyboard") return;
178 void listRef.current?.scrollIndexIntoView?.({ index: eventDetails.index, animated: false });
179 }}
180 >
181 <ComboboxTrigger aria-label={ariaLabel} render={<SelectButton size="sm" />}>
182 {selectedFamily.length === 0 ? defaultFamily : selectedFamily}
183 </ComboboxTrigger>
184 <ComboboxPopup align="end" className="flex w-72 flex-col">
185 <ComboboxSearchInput
186 placeholder="Search fonts…"
187 value={query}
188 onChange={(event) => setQuery(event.target.value)}
189 />
190 <div className="flex min-h-0 flex-1 flex-col overflow-hidden">
191 <ComboboxEmpty>No fonts found.</ComboboxEmpty>
192 <div className="relative min-h-0 max-h-72 w-full flex-1 overflow-hidden">
193 <ComboboxListVirtualized>
194 <LegendList<string>
195 ref={listRef}
196 data={items}
197 // Base UI selects virtualized rows by index; rerender surviving items when filtering changes
198 // their indices.
199 extraData={items}
200 keyExtractor={(item) => item}
201 renderItem={({ item, index }) => renderItem(item, index)}
202 estimatedItemSize={30}
203 drawDistance={360}
204 style={{ height: Math.min(items.length * 30, 288) }}
205 />
206 </ComboboxListVirtualized>
207 </div>
208 </div>
209 </ComboboxPopup>
210 </Combobox>
211 );
212}