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