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

FontFamilyPicker.tsx

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