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