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

FontFamilyPicker.tsx

219 lines7.6 KB

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 );
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);
40​
41function readEnumerationState(): FontEnumerationState {
42 return enumerationState;
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 });
59​
60let grantedProbeStarted = false;
61​
62/**
63 * Electron's default permission handler approves silently (it has no prompt
64 * UI), and a browser that granted once reports "granted" on later visits — in
65 * both, no user gesture is needed.
66 */
67function probeAlreadyGrantedPermission(): void {
68 if (grantedProbeStarted || enumerationState.status !== "unknown") return;
69 grantedProbeStarted = true;
70 const permissions = typeof navigator !== "undefined" ? navigator.permissions : undefined;
71 if (typeof permissions?.query !== "function") return;
72 permissions.query({ name: "local-fonts" as PermissionName }).then(
73 (status) => {
74 if (status.state === "granted") discoverInstalledFonts();
75 },
76 () => {},
77 );
79​
80export function useFontEnumeration(): FontEnumerationState {
81 useEffect(probeAlreadyGrantedPermission, []);
82 return useSyncExternalStore(subscribeToEnumeration, readEnumerationState);
84​
85export function FontFamilyPicker({
86 ariaLabel,
87 defaultFamily,
88 selectedFamily,
89 requireMonospace = false,
90 initialOpen = false,
91 onSelect,
92}: {
93 ariaLabel: string;
94 defaultFamily: string;
95 selectedFamily: string;
96 requireMonospace?: boolean;
97 initialOpen?: boolean;
98 onSelect: (family: string) => void;
99}) {
100 const [open, setOpen] = useState(false);
101 const [query, setQuery] = useState("");
102 // Open after mount rather than mounting open: a popup that first renders in
103 // its open state never receives Base UI's entrance style baseline, so the
104 // exit transition on close has no style delta, never fires transitionend,
105 // and the popup lingers on screen forever.
106 const [openAfterMount] = useState(initialOpen);
107 useEffect(() => {
108 // oxlint-disable-next-line react/set-state-in-effect -- Base UI needs one closed commit first to record the popup's entrance style.
109 if (openAfterMount) setOpen(true);
110 }, [openAfterMount]);
111 const listRef = useRef<LegendListRef | null>(null);
112 const enumeration = useFontEnumeration();
113​
114 const handleOpenChange = (nextOpen: boolean) => {
115 setOpen(nextOpen);
116 if (nextOpen) setQuery("");
117 };
118​
119 const families = enumeration.status === "granted" ? enumeration.families : [];
120​
121 const items = (() => {
122 const trimmedQuery = query.trim().toLowerCase();
123 const result: string[] = [];
124 if (trimmedQuery.length === 0) result.push(DEFAULT_FONT_VALUE);
125 result.push(
126 ...families.filter(
127 (family) => trimmedQuery.length === 0 || family.toLowerCase().includes(trimmedQuery),
128 ),
129 );
130 return result;
131 })();
132​
133 const selectedValue = selectedFamily.length === 0 ? DEFAULT_FONT_VALUE : selectedFamily;
134​
135 const handlePick = (value: string) => {
136 setOpen(false);
137 if (value !== DEFAULT_FONT_VALUE && requireMonospace && !isMonospaceFamily(value)) {
138 toastManager.add(
139 stackedThreadToast({
140 type: "error",
141 title: `"${value}" isn't monospace`,
142 description: "Code and terminal need a fixed-width font, so the current font was kept.",
143 }),
144 );
145 return;
146 }
147 onSelect(value === DEFAULT_FONT_VALUE ? "" : value);
148 };
149​
150 const renderItem = (item: string, index: number) => {
151 const isDefault = item === DEFAULT_FONT_VALUE;
152 const family = isDefault ? defaultFamily : item;
153 return (
154 <ComboboxItem hideIndicator index={index} key={item} value={item}>
155 <div className="flex w-full min-w-0 items-center justify-between gap-2">
156 <span className="min-w-0 truncate" style={{ fontFamily: family }}>
157 {family}
158 </span>
159 <span className="flex shrink-0 items-center gap-1.5">
160 {isDefault ? <span className="text-3xs text-muted-foreground/60">default</span> : null}
161 {item === selectedValue ? (
162 <CheckIcon className="size-3.5 text-muted-foreground" />
163 ) : null}
164 </span>
165 </div>
166 </ComboboxItem>
167 );
168 };
169​
170 return (
171 <Combobox
172 items={items}
173 filteredItems={items}
174 autoHighlight
175 virtualized
176 open={open}
177 onOpenChange={handleOpenChange}
178 value={selectedValue}
179 onValueChange={(next) => {
180 if (typeof next === "string") handlePick(next);
181 }}
182 onItemHighlighted={(_value, eventDetails) => {
183 if (!open || eventDetails.index < 0 || eventDetails.reason !== "keyboard") return;
184 void listRef.current?.scrollIndexIntoView?.({ index: eventDetails.index, animated: false });
185 }}
186 >
187 <ComboboxTrigger aria-label={ariaLabel} render={<SelectButton size="sm" />}>
188 {selectedFamily.length === 0 ? defaultFamily : selectedFamily}
189 </ComboboxTrigger>
190 <ComboboxPopup align="end" className="flex w-72 flex-col">
191 <ComboboxSearchInput
192 placeholder="Search fonts…"
193 value={query}
194 onChange={(event) => setQuery(event.target.value)}
195 />
196 <div className="flex min-h-0 flex-1 flex-col overflow-hidden">
197 <ComboboxEmpty>No fonts found.</ComboboxEmpty>
198 <div className="relative min-h-0 max-h-72 w-full flex-1 overflow-hidden">
199 <ComboboxListVirtualized>
200 <LegendList<string>
201 ref={listRef}
202 data={items}
203 // Rows are memoized by item, but Base UI highlights and selects
204 // virtualized rows by index. Re-render them when filtering moves
205 // a surviving item to a new index.
206 extraData={items}
207 keyExtractor={(item) => item}
208 renderItem={({ item, index }) => renderItem(item, index)}
209 estimatedItemSize={30}
210 drawDistance={360}
211 style={{ height: Math.min(items.length * 30, 288) }}
212 />
213 </ComboboxListVirtualized>
214 </div>
215 </div>
216 </ComboboxPopup>
217 </Combobox>
218 );