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

FontFamilyPicker.tsx

253 lines9.8 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";
14​
15const DEFAULT_FONT_VALUE = "__default__";
16​
17function supportsFontEnumeration(): boolean {
18 return (
19 typeof window !== "undefined" &&
20 typeof (window as { queryLocalFonts?: unknown }).queryLocalFonts === "function"
21 );
23​
24type FontEnumerationState =
25 | { readonly status: "unknown" }
26 | { readonly status: "granted"; readonly families: readonly string[] }
27 | { readonly status: "unavailable" };
28​
29// Shared across every row: once one picker learns the fonts (or learns the
30// permission is blocked), the others follow without re-querying — and the
31// rows can swap to the plain-input control together.
32let enumerationState: FontEnumerationState = supportsFontEnumeration()
33 ? { status: "unknown" }
34 : { status: "unavailable" };
35const enumerationListeners = new Set<() => void>();
36​
37function subscribeToEnumeration(listener: () => void): () => void {
38 enumerationListeners.add(listener);
39 return () => enumerationListeners.delete(listener);
41​
42function readEnumerationState(): FontEnumerationState {
43 return enumerationState;
45​
46let enumerationLoad: Promise<void> | null = null;
47​
48/** Query installed fonts; call from a user gesture (the permission prompt needs one). */
49export function discoverInstalledFonts(): void {
50 if (enumerationState.status !== "unknown" || enumerationLoad !== null) return;
51 enumerationLoad = queryInstalledFontFamilies().then((result) => {
52 enumerationState =
53 result.status === "granted"
54 ? { status: "granted", families: result.families }
55 : { status: "unavailable" };
56 enumerationLoad = null;
57 for (const listener of enumerationListeners) listener();
58 });
60​
61let 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 */
71function 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 );
86​
87/**
88 * Whether the engine can list installed fonts (Local Font Access API —
89 * Chromium and Electron). "unknown" until discovery resolves the permission;
90 * 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.
93 */
94export function useFontEnumeration(): FontEnumerationState {
95 useEffect(probeAlreadyGrantedPermission, []);
96 return useSyncExternalStore(subscribeToEnumeration, readEnumerationState);
98​
99/**
100 * A searchable picker over every installed family, the way native editors
101 * list system fonts. The trigger always names the font in use: the committed
102 * family, or what the default stack resolves to on this machine.
103 */
104export function FontFamilyPicker({
105 ariaLabel,
106 defaultFamily,
107 selectedFamily,
108 requireMonospace = false,
109 initialOpen = false,
110 onSelect,
111}: {
112 ariaLabel: string;
113 /** What an unset preference renders as, e.g. "Menlo". */
114 defaultFamily: string;
115 /** Committed family name; empty string means the default is in use. */
116 selectedFamily: string;
117 requireMonospace?: boolean;
118 /** Open the popup on mount — set when the control upgrades under focus. */
119 initialOpen?: boolean;
120 onSelect: (family: string) => void;
121}) {
122 const [open, setOpen] = useState(false);
123 const [query, setQuery] = useState("");
124 // Open after mount rather than mounting open: a popup that first renders in
125 // its open state never receives Base UI's entrance style baseline, so the
126 // exit transition on close has no style delta, never fires transitionend,
127 // and the popup lingers on screen forever.
128 useEffect(() => {
129 if (initialOpen) setOpen(true);
130 // The prop is only meaningful at mount - the control just swapped in
131 // under an active focus - so later changes are deliberately ignored.
132 }, []);
133 const listRef = useRef<LegendListRef | null>(null);
134 const enumeration = useFontEnumeration();
135​
136 const handleOpenChange = (nextOpen: boolean) => {
137 setOpen(nextOpen);
138 if (nextOpen) setQuery("");
139 };
140​
141 const families = useMemo(() => {
142 if (enumeration.status !== "granted") return [];
143 return requireMonospace ? enumeration.families.filter(isMonospaceFamily) : enumeration.families;
144 }, [enumeration, requireMonospace]);
145​
146 const items = useMemo(() => {
147 const trimmedQuery = query.trim().toLowerCase();
148 const result: string[] = [];
149 if (trimmedQuery.length === 0) result.push(DEFAULT_FONT_VALUE);
150 result.push(
151 ...families.filter(
152 (family) => trimmedQuery.length === 0 || family.toLowerCase().includes(trimmedQuery),
153 ),
154 );
155 return result;
156 }, [query, families]);
157​
158 const selectedValue = selectedFamily.length === 0 ? DEFAULT_FONT_VALUE : selectedFamily;
159​
160 const handlePick = (value: string) => {
161 setOpen(false);
162 onSelect(value === DEFAULT_FONT_VALUE ? "" : value);
163 };
164​
165 const renderItem = (item: string, index: number) => {
166 const isDefault = item === DEFAULT_FONT_VALUE;
167 const family = isDefault ? defaultFamily : item;
168 return (
169 <ComboboxItem hideIndicator index={index} key={item} value={item}>
170 <div className="flex w-full min-w-0 items-center justify-between gap-2">
171 <span className="min-w-0 truncate" style={{ fontFamily: family }}>
172 {family}
173 </span>
174 <span className="flex shrink-0 items-center gap-1.5">
175 {isDefault ? (
176 <span className="text-[10px] text-muted-foreground/60">default</span>
177 ) : null}
178 {item === selectedValue ? (
179 <CheckIcon className="size-3.5 text-muted-foreground" />
180 ) : null}
181 </span>
182 </div>
183 </ComboboxItem>
184 );
185 };
186​
187 return (
188 <Combobox
189 items={items}
190 filteredItems={items}
191 autoHighlight
192 virtualized
193 open={open}
194 onOpenChange={handleOpenChange}
195 value={selectedValue}
196 onValueChange={(next) => {
197 if (typeof next === "string") handlePick(next);
198 }}
199 onItemHighlighted={(_value, eventDetails) => {
200 // Keyboard highlights must pull the virtualized row into view, or
201 // arrow keys walk past the rendered window and navigate blind.
202 if (!open || eventDetails.index < 0 || eventDetails.reason !== "keyboard") return;
203 void listRef.current?.scrollIndexIntoView?.({ index: eventDetails.index, animated: false });
204 }}
205 >
206 <ComboboxTrigger
207 aria-label={ariaLabel}
208 className="relative inline-flex min-h-9 w-full min-w-36 cursor-pointer select-none items-center justify-between gap-2 rounded-lg border border-input bg-background px-[calc(--spacing(3)-1px)] text-left text-base text-foreground shadow-xs/5 outline-none transition-[color,box-shadow] focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/24 sm:min-h-8 sm:text-sm dark:bg-input/32"
209 >
210 <span className="min-w-0 truncate">
211 {selectedFamily.length === 0 ? defaultFamily : selectedFamily}
212 </span>
213 <ChevronDownIcon className="-me-1 size-3 shrink-0 text-muted-foreground opacity-50" />
214 </ComboboxTrigger>
215 <ComboboxPopup align="end" className="flex w-72 flex-col">
216 <div className="shrink-0 px-3 pt-2.5">
217 <div className="relative -translate-y-px border-b border-border/70 pb-1.5 transition-colors focus-within:border-ring">
218 <SearchIcon
219 aria-hidden="true"
220 className="pointer-events-none absolute top-1.5 left-0 size-4 shrink-0 text-muted-foreground/55"
221 />
222 <ComboboxInput
223 className="[&_input]:h-6.5 [&_input]:ps-5 [&_input]:font-sans [&_input]:leading-6.5"
224 inputClassName="rounded-none bg-transparent text-sm"
225 placeholder="Search fonts…"
226 showTrigger={false}
227 size="sm"
228 unstyled
229 value={query}
230 onChange={(event) => setQuery(event.target.value)}
231 />
232 </div>
233 </div>
234 <div className="flex min-h-0 flex-1 flex-col overflow-hidden">
235 <ComboboxEmpty>No fonts found.</ComboboxEmpty>
236 <div className="relative min-h-0 max-h-72 w-full flex-1 overflow-hidden">
237 <ComboboxListVirtualized className="size-full min-w-0 p-0">
238 <LegendList<string>
239 ref={listRef}
240 data={items}
241 keyExtractor={(item) => item}
242 renderItem={({ item, index }) => renderItem(item, index)}
243 estimatedItemSize={30}
244 drawDistance={360}
245 style={{ height: Math.min(items.length * 30, 288) }}
246 />
247 </ComboboxListVirtualized>
248 </div>
249 </div>
250 </ComboboxPopup>
251 </Combobox>
252 );