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

FontFamilyPicker.tsx

233 lines8.6 KB

1import { LegendList, type LegendListRef } from "@legendapp/list/react";
2import { CheckIcon } from "lucide-react";
3import { useEffect, useMemo, 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";
15​
16const DEFAULT_FONT_VALUE = "__default__";
17​
18function supportsFontEnumeration(): boolean {
19 return (
20 typeof window !== "undefined" &&
21 typeof (window as { queryLocalFonts?: unknown }).queryLocalFonts === "function"
22 );
24​
25type FontEnumerationState =
26 | { readonly status: "unknown" }
27 | { readonly status: "granted"; readonly families: readonly string[] }
28 | { readonly status: "unavailable" };
29​
30// Shared across every row: once one picker learns the fonts (or learns the
31// permission is blocked), the others follow without re-querying — and the
32// rows can swap to the plain-input control together.
33let enumerationState: FontEnumerationState = supportsFontEnumeration()
34 ? { status: "unknown" }
35 : { status: "unavailable" };
36const enumerationListeners = new Set<() => void>();
37​
38function subscribeToEnumeration(listener: () => void): () => void {
39 enumerationListeners.add(listener);
40 return () => enumerationListeners.delete(listener);
42​
43function readEnumerationState(): FontEnumerationState {
44 return enumerationState;
46​
47let enumerationLoad: Promise<void> | null = null;
48​
49/** Query installed fonts; call from a user gesture (the permission prompt needs one). */
50export function discoverInstalledFonts(): void {
51 if (enumerationState.status !== "unknown" || enumerationLoad !== null) return;
52 enumerationLoad = queryInstalledFontFamilies().then((result) => {
53 enumerationState =
54 result.status === "granted"
55 ? { status: "granted", families: result.families }
56 : { status: "unavailable" };
57 enumerationLoad = null;
58 for (const listener of enumerationListeners) listener();
59 });
61​
62let grantedProbeStarted = false;
63​
64/**
65 * Discover eagerly when the permission is already granted, so the picker
66 * renders without waiting for a focus. Electron's default permission handler
67 * approves silently (it has no prompt UI), and a browser that granted once
68 * reports "granted" on later visits — in both, no user gesture is needed.
69 * "prompt" and "denied" states change nothing: the focus-driven flow stays,
70 * because raising the browser prompt still requires a gesture.
71 */
72function probeAlreadyGrantedPermission(): void {
73 if (grantedProbeStarted || enumerationState.status !== "unknown") return;
74 grantedProbeStarted = true;
75 const permissions = typeof navigator !== "undefined" ? navigator.permissions : undefined;
76 if (typeof permissions?.query !== "function") return;
77 permissions.query({ name: "local-fonts" as PermissionName }).then(
78 (status) => {
79 if (status.state === "granted") discoverInstalledFonts();
80 },
81 () => {
82 // The engine does not recognize the permission name; keep the
83 // focus-driven flow.
84 },
85 );
87​
88/**
89 * Whether the engine can list installed fonts (Local Font Access API —
90 * Chromium and Electron). "unknown" until discovery resolves the permission;
91 * rows render a plain family-name input until the state is known granted,
92 * then upgrade to the picker. Where the permission is already granted,
93 * discovery starts at mount and the picker appears without a focus.
94 */
95export function useFontEnumeration(): FontEnumerationState {
96 useEffect(probeAlreadyGrantedPermission, []);
97 return useSyncExternalStore(subscribeToEnumeration, readEnumerationState);
99​
100/**
101 * A searchable picker over every installed family, the way native editors
102 * list system fonts. The trigger always names the font in use: the committed
103 * family, or what the default stack resolves to on this machine.
104 */
105export function FontFamilyPicker({
106 ariaLabel,
107 defaultFamily,
108 selectedFamily,
109 requireMonospace = false,
110 initialOpen = false,
111 onSelect,
112}: {
113 ariaLabel: string;
114 /** What an unset preference renders as, e.g. "Menlo". */
115 defaultFamily: string;
116 /** Committed family name; empty string means the default is in use. */
117 selectedFamily: string;
118 requireMonospace?: boolean;
119 /** Open the popup on mount — set when the control upgrades under focus. */
120 initialOpen?: boolean;
121 onSelect: (family: string) => void;
122}) {
123 const [open, setOpen] = useState(false);
124 const [query, setQuery] = useState("");
125 // Open after mount rather than mounting open: a popup that first renders in
126 // its open state never receives Base UI's entrance style baseline, so the
127 // exit transition on close has no style delta, never fires transitionend,
128 // and the popup lingers on screen forever.
129 useEffect(() => {
130 if (initialOpen) setOpen(true);
131 // The prop is only meaningful at mount - the control just swapped in
132 // under an active focus - so later changes are deliberately ignored.
133 }, []);
134 const listRef = useRef<LegendListRef | null>(null);
135 const enumeration = useFontEnumeration();
136​
137 const handleOpenChange = (nextOpen: boolean) => {
138 setOpen(nextOpen);
139 if (nextOpen) setQuery("");
140 };
141​
142 const families = useMemo(() => {
143 if (enumeration.status !== "granted") return [];
144 return requireMonospace ? enumeration.families.filter(isMonospaceFamily) : enumeration.families;
145 }, [enumeration, requireMonospace]);
146​
147 const items = useMemo(() => {
148 const trimmedQuery = query.trim().toLowerCase();
149 const result: string[] = [];
150 if (trimmedQuery.length === 0) result.push(DEFAULT_FONT_VALUE);
151 result.push(
152 ...families.filter(
153 (family) => trimmedQuery.length === 0 || family.toLowerCase().includes(trimmedQuery),
154 ),
155 );
156 return result;
157 }, [query, families]);
158​
159 const selectedValue = selectedFamily.length === 0 ? DEFAULT_FONT_VALUE : selectedFamily;
160​
161 const handlePick = (value: string) => {
162 setOpen(false);
163 onSelect(value === DEFAULT_FONT_VALUE ? "" : value);
164 };
165​
166 const renderItem = (item: string, index: number) => {
167 const isDefault = item === DEFAULT_FONT_VALUE;
168 const family = isDefault ? defaultFamily : item;
169 return (
170 <ComboboxItem hideIndicator index={index} key={item} value={item}>
171 <div className="flex w-full min-w-0 items-center justify-between gap-2">
172 <span className="min-w-0 truncate" style={{ fontFamily: family }}>
173 {family}
174 </span>
175 <span className="flex shrink-0 items-center gap-1.5">
176 {isDefault ? <span className="text-3xs text-muted-foreground/60">default</span> : null}
177 {item === selectedValue ? (
178 <CheckIcon className="size-3.5 text-muted-foreground" />
179 ) : null}
180 </span>
181 </div>
182 </ComboboxItem>
183 );
184 };
185​
186 return (
187 <Combobox
188 items={items}
189 filteredItems={items}
190 autoHighlight
191 virtualized
192 open={open}
193 onOpenChange={handleOpenChange}
194 value={selectedValue}
195 onValueChange={(next) => {
196 if (typeof next === "string") handlePick(next);
197 }}
198 onItemHighlighted={(_value, eventDetails) => {
199 // Keyboard highlights must pull the virtualized row into view, or
200 // arrow keys walk past the rendered window and navigate blind.
201 if (!open || eventDetails.index < 0 || eventDetails.reason !== "keyboard") return;
202 void listRef.current?.scrollIndexIntoView?.({ index: eventDetails.index, animated: false });
203 }}
204 >
205 <ComboboxTrigger aria-label={ariaLabel} render={<SelectButton size="sm" />}>
206 {selectedFamily.length === 0 ? defaultFamily : selectedFamily}
207 </ComboboxTrigger>
208 <ComboboxPopup align="end" className="flex w-72 flex-col">
209 <ComboboxSearchInput
210 placeholder="Search fonts…"
211 value={query}
212 onChange={(event) => setQuery(event.target.value)}
213 />
214 <div className="flex min-h-0 flex-1 flex-col overflow-hidden">
215 <ComboboxEmpty>No fonts found.</ComboboxEmpty>
216 <div className="relative min-h-0 max-h-72 w-full flex-1 overflow-hidden">
217 <ComboboxListVirtualized>
218 <LegendList<string>
219 ref={listRef}
220 data={items}
221 keyExtractor={(item) => item}
222 renderItem={({ item, index }) => renderItem(item, index)}
223 estimatedItemSize={30}
224 drawDistance={360}
225 style={{ height: Math.min(items.length * 30, 288) }}
226 />
227 </ComboboxListVirtualized>
228 </div>
229 </div>
230 </ComboboxPopup>
231 </Combobox>
232 );