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

FontFamilyPicker.tsx

216 lines7.3 KB

1import { LegendList, type LegendListRef } from "@legendapp/list/react";
2import { CheckIcon } from "lucide-react";
3import { useEffect, useMemo, 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 useEffect(() => {
107 if (initialOpen) setOpen(true);
108 }, []);
109 const listRef = useRef<LegendListRef | null>(null);
110 const enumeration = useFontEnumeration();
111​
112 const handleOpenChange = (nextOpen: boolean) => {
113 setOpen(nextOpen);
114 if (nextOpen) setQuery("");
115 };
116​
117 const families = useMemo(() => {
118 if (enumeration.status !== "granted") return [];
119 return enumeration.families;
120 }, [enumeration]);
121​
122 const items = useMemo(() => {
123 const trimmedQuery = query.trim().toLowerCase();
124 const result: string[] = [];
125 if (trimmedQuery.length === 0) result.push(DEFAULT_FONT_VALUE);
126 result.push(
127 ...families.filter(
128 (family) => trimmedQuery.length === 0 || family.toLowerCase().includes(trimmedQuery),
129 ),
130 );
131 return result;
132 }, [query, families]);
133​
134 const selectedValue = selectedFamily.length === 0 ? DEFAULT_FONT_VALUE : selectedFamily;
135​
136 const handlePick = (value: string) => {
137 setOpen(false);
138 if (value !== DEFAULT_FONT_VALUE && requireMonospace && !isMonospaceFamily(value)) {
139 toastManager.add(
140 stackedThreadToast({
141 type: "error",
142 title: `"${value}" isn't monospace`,
143 description: "Code and terminal need a fixed-width font, so the current font was kept.",
144 }),
145 );
146 return;
147 }
148 onSelect(value === DEFAULT_FONT_VALUE ? "" : value);
149 };
150​
151 const renderItem = (item: string, index: number) => {
152 const isDefault = item === DEFAULT_FONT_VALUE;
153 const family = isDefault ? defaultFamily : item;
154 return (
155 <ComboboxItem hideIndicator index={index} key={item} value={item}>
156 <div className="flex w-full min-w-0 items-center justify-between gap-2">
157 <span className="min-w-0 truncate" style={{ fontFamily: family }}>
158 {family}
159 </span>
160 <span className="flex shrink-0 items-center gap-1.5">
161 {isDefault ? <span className="text-3xs text-muted-foreground/60">default</span> : null}
162 {item === selectedValue ? (
163 <CheckIcon className="size-3.5 text-muted-foreground" />
164 ) : null}
165 </span>
166 </div>
167 </ComboboxItem>
168 );
169 };
170​
171 return (
172 <Combobox
173 items={items}
174 filteredItems={items}
175 autoHighlight
176 virtualized
177 open={open}
178 onOpenChange={handleOpenChange}
179 value={selectedValue}
180 onValueChange={(next) => {
181 if (typeof next === "string") handlePick(next);
182 }}
183 onItemHighlighted={(_value, eventDetails) => {
184 if (!open || eventDetails.index < 0 || eventDetails.reason !== "keyboard") return;
185 void listRef.current?.scrollIndexIntoView?.({ index: eventDetails.index, animated: false });
186 }}
187 >
188 <ComboboxTrigger aria-label={ariaLabel} render={<SelectButton size="sm" />}>
189 {selectedFamily.length === 0 ? defaultFamily : selectedFamily}
190 </ComboboxTrigger>
191 <ComboboxPopup align="end" className="flex w-72 flex-col">
192 <ComboboxSearchInput
193 placeholder="Search fonts…"
194 value={query}
195 onChange={(event) => setQuery(event.target.value)}
196 />
197 <div className="flex min-h-0 flex-1 flex-col overflow-hidden">
198 <ComboboxEmpty>No fonts found.</ComboboxEmpty>
199 <div className="relative min-h-0 max-h-72 w-full flex-1 overflow-hidden">
200 <ComboboxListVirtualized>
201 <LegendList<string>
202 ref={listRef}
203 data={items}
204 keyExtractor={(item) => item}
205 renderItem={({ item, index }) => renderItem(item, index)}
206 estimatedItemSize={30}
207 drawDistance={360}
208 style={{ height: Math.min(items.length * 30, 288) }}
209 />
210 </ComboboxListVirtualized>
211 </div>
212 </div>
213 </ComboboxPopup>
214 </Combobox>
215 );