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

FontFamilyPicker.tsx

251 lines9.5 KB

1import { LegendList, type LegendListRef } from "@legendapp/list/react";
2import { CheckIcon, ChevronDownIcon, SearchIcon } from "lucide-react";
3import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
4import { isMonospaceFamily, queryInstalledFontFamilies } from "../../appearanceFonts";
5import {
6 Combobox,
7 ComboboxEmpty,
8 ComboboxInput,
9 ComboboxItem,
10 ComboboxListVirtualized,
11 ComboboxPopup,
12 ComboboxTrigger,
13} from "../ui/combobox";
14import { selectTriggerVariants } 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 ? (
177 <span className="text-[10px] text-muted-foreground/60">default</span>
178 ) : null}
179 {item === selectedValue ? (
180 <CheckIcon className="size-3.5 text-muted-foreground" />
181 ) : null}
182 </span>
183 </div>
184 </ComboboxItem>
185 );
186 };
187​
188 return (
189 <Combobox
190 items={items}
191 filteredItems={items}
192 autoHighlight
193 virtualized
194 open={open}
195 onOpenChange={handleOpenChange}
196 value={selectedValue}
197 onValueChange={(next) => {
198 if (typeof next === "string") handlePick(next);
199 }}
200 onItemHighlighted={(_value, eventDetails) => {
201 // Keyboard highlights must pull the virtualized row into view, or
202 // arrow keys walk past the rendered window and navigate blind.
203 if (!open || eventDetails.index < 0 || eventDetails.reason !== "keyboard") return;
204 void listRef.current?.scrollIndexIntoView?.({ index: eventDetails.index, animated: false });
205 }}
206 >
207 <ComboboxTrigger aria-label={ariaLabel} className={selectTriggerVariants({ size: "sm" })}>
208 <span className="min-w-0 truncate">
209 {selectedFamily.length === 0 ? defaultFamily : selectedFamily}
210 </span>
211 <ChevronDownIcon className="-me-1 size-3 opacity-50" />
212 </ComboboxTrigger>
213 <ComboboxPopup align="end" className="flex w-72 flex-col">
214 <div className="shrink-0 px-3 pt-2.5">
215 <div className="relative -translate-y-px border-b border-border/70 pb-1.5 transition-colors focus-within:border-ring">
216 <SearchIcon
217 aria-hidden="true"
218 className="pointer-events-none absolute top-1.5 left-0 size-4 shrink-0 text-muted-foreground/55"
219 />
220 <ComboboxInput
221 className="[&_input]:h-6.5 [&_input]:ps-5 [&_input]:font-sans [&_input]:leading-6.5"
222 inputClassName="rounded-none bg-transparent text-sm"
223 placeholder="Search fonts…"
224 showTrigger={false}
225 size="sm"
226 unstyled
227 value={query}
228 onChange={(event) => setQuery(event.target.value)}
229 />
230 </div>
231 </div>
232 <div className="flex min-h-0 flex-1 flex-col overflow-hidden">
233 <ComboboxEmpty>No fonts found.</ComboboxEmpty>
234 <div className="relative min-h-0 max-h-72 w-full flex-1 overflow-hidden">
235 <ComboboxListVirtualized className="size-full min-w-0 p-0">
236 <LegendList<string>
237 ref={listRef}
238 data={items}
239 keyExtractor={(item) => item}
240 renderItem={({ item, index }) => renderItem(item, index)}
241 estimatedItemSize={30}
242 drawDistance={360}
243 style={{ height: Math.min(items.length * 30, 288) }}
244 />
245 </ComboboxListVirtualized>
246 </div>
247 </div>
248 </ComboboxPopup>
249 </Combobox>
250 );