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

ThemeSearchSection.tsx

476 lines16.9 KB

1import { RefreshIcon } from "~/components/ui/refresh-icon";
2import { ExternalLinkIcon, PackagePlusIcon, PaletteIcon, SearchIcon } from "lucide-react";
3import { useEffect, useEffectEvent, useRef, useState } from "react";
4import {
5 importOpenVsxThemeExtension,
6 searchOpenVsxThemes,
7 type OpenVsxThemeExtension,
8 type OpenVsxThemeSort,
9} from "../../openVsxThemes";
10import { useDebouncedValue } from "../../state/queries";
11import {
12 getCustomThemes,
13 getStoredCustomThemeCollection,
14 replaceCustomThemeCollection,
15 type ThemeDefinition,
16} from "../../themePalette";
17import { GitHubIcon, GitLabIcon } from "../Icons";
18import {
19 AlertDialog,
20 AlertDialogClose,
21 AlertDialogDescription,
22 AlertDialogFooter,
23 AlertDialogHeader,
24 AlertDialogPopup,
25 AlertDialogTitle,
26} from "../ui/alert-dialog";
27import { Alert, AlertDescription } from "../ui/alert";
28import { Button } from "../ui/button";
29import { InputGroup, InputGroupAddon, InputGroupInput } from "../ui/input-group";
30import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
31import { Spinner } from "../ui/spinner";
32​
33const DOWNLOAD_FORMAT = new Intl.NumberFormat(undefined, {
34 notation: "compact",
35 maximumFractionDigits: 1,
36});
37const SUGGESTED_SEARCHES = ["Dracula", "Catppuccin", "Nord", "Tokyo Night"];
38const SORT_OPTIONS: ReadonlyArray<{ value: OpenVsxThemeSort; label: string }> = [
39 { value: "downloadCount", label: "Most downloaded" },
40 { value: "rating", label: "Best rated" },
41 { value: "timestamp", label: "Newest" },
42 { value: "relevance", label: "Most relevant" },
43];
44const SEARCH_DEBOUNCE_MS = 350;
45​
46function sourceHost(url: string): string | null {
47 try {
48 return new URL(url).hostname.toLowerCase();
49 } catch {
50 return null;
51 }
53​
54function SourceLinkIcon({ url }: { url: string }) {
55 const host = sourceHost(url);
56 if (host === "github.com" || host?.endsWith(".github.com"))
57 return <GitHubIcon className="size-3.5" />;
58 if (host === "gitlab.com" || host?.endsWith(".gitlab.com"))
59 return <GitLabIcon className="size-3.5" monochrome />;
60 return <ExternalLinkIcon className="size-3.5" />;
62​
63function ThemeExtensionIcon({ extension }: { extension: OpenVsxThemeExtension }) {
64 const [failed, setFailed] = useState(false);
65​
66 return (
67 <div className="flex size-10 shrink-0 items-center justify-center overflow-hidden rounded-lg bg-muted text-muted-foreground">
68 {extension.iconUrl && !failed ? (
69 <img
70 alt=""
71 className="size-full object-cover"
72 loading="lazy"
73 referrerPolicy="no-referrer"
74 src={extension.iconUrl}
75 onError={() => setFailed(true)}
76 />
77 ) : (
78 <PaletteIcon className="size-4" />
79 )}
80 </div>
81 );
83​
84export function ThemeSearchSection({
85 open,
86 onInstalled,
87}: {
88 open: boolean;
89 onInstalled: (themes: ReadonlyArray<ThemeDefinition>, context: { updated: boolean }) => void;
90}) {
91 const [query, setQuery] = useState("");
92 const [sortBy, setSortBy] = useState<OpenVsxThemeSort>("downloadCount");
93 const [results, setResults] = useState<ReadonlyArray<OpenVsxThemeExtension> | null>(null);
94 const [error, setError] = useState<string | null>(null);
95 const [isSearching, setIsSearching] = useState(false);
96 const [installingId, setInstallingId] = useState<string | null>(null);
97 const [pendingUpdate, setPendingUpdate] = useState<OpenVsxThemeExtension | null>(null);
98 const requestRef = useRef<AbortController | null>(null);
99 // Recorded only once a search succeeds, so a finished install reruns the
100 // search only when the query or sort changed while it was in flight, and the
101 // install error the user needs to see survives.
102 const [lastSearchKey, setLastSearchKey] = useState<string | null>(null);
103 const [handledSearch, setHandledSearch] = useState<{
104 key: string;
105 query: string;
106 fetch: boolean;
107 } | null>(null);
108 // An install aborts any search, so once it ends the current key is checked
109 // again even though it has not changed.
110 const [searchInterrupted, setSearchInterrupted] = useState(false);
111​
112 const [wasOpen, setWasOpen] = useState(open);
113 if (open !== wasOpen) {
114 setWasOpen(open);
115 if (open) {
116 setQuery("");
117 setSortBy("downloadCount");
118 setResults(null);
119 setError(null);
120 setIsSearching(false);
121 setInstallingId(null);
122 setPendingUpdate(null);
123 setLastSearchKey(null);
124 setHandledSearch(null);
125 setSearchInterrupted(false);
126 }
127 }
128​
129 useEffect(() => {
130 if (!open) return;
131 return () => {
132 requestRef.current?.abort();
133 requestRef.current = null;
134 };
135 }, [open]);
136​
137 const queryCleared = !query.trim() && installingId === null;
138 if (
139 queryCleared &&
140 (results !== null ||
141 error !== null ||
142 isSearching ||
143 lastSearchKey !== null ||
144 handledSearch !== null)
145 ) {
146 setResults(null);
147 setError(null);
148 setIsSearching(false);
149 setLastSearchKey(null);
150 setHandledSearch(null);
151 }
152​
153 useEffect(() => {
154 if (!queryCleared) return;
155 requestRef.current?.abort();
156 requestRef.current = null;
157 }, [queryCleared]);
158​
159 const startRequest = () => {
160 requestRef.current?.abort();
161 const controller = new AbortController();
162 requestRef.current = controller;
163 return controller;
164 };
165​
166 const fetchResults = (trimmed: string, controller: AbortController) => {
167 const key = `${trimmed}\u0000${sortBy}`;
168 void searchOpenVsxThemes(trimmed, { signal: controller.signal, sortBy })
169 .then(
170 (nextResults) => {
171 if (controller.signal.aborted) return;
172 setResults(nextResults);
173 setLastSearchKey(key);
174 },
175 (cause: unknown) => {
176 if (controller.signal.aborted) return;
177 setResults(null);
178 setLastSearchKey(null);
179 setError(cause instanceof Error ? cause.message : "Open VSX search failed.");
180 },
181 )
182 .then(() => {
183 if (requestRef.current !== controller) return;
184 requestRef.current = null;
185 setIsSearching(false);
186 });
187 };
188​
189 const runSearch = (searchText: string) => {
190 const trimmed = searchText.trim();
191 if (!trimmed) return;
192 setError(null);
193 setIsSearching(true);
194 fetchResults(trimmed, startRequest());
195 };
196​
197 const debouncedQuery = useDebouncedValue(query.trim(), SEARCH_DEBOUNCE_MS);
198 const searchKey = `${debouncedQuery}\u0000${sortBy}`;
199 // An unsettled query would hit Open VSX for text that is no longer visible;
200 // wait for the debounce to catch up to the current input instead.
201 const searchSettled =
202 open && installingId === null && debouncedQuery !== "" && debouncedQuery === query.trim();
203​
204 const keyChanged = handledSearch?.key !== searchKey;
205 if (searchSettled && (keyChanged || searchInterrupted)) {
206 // Typing and then undoing lands back on the key already shown; keep those
207 // results instead of searching again.
208 const fetch = lastSearchKey !== searchKey;
209 setHandledSearch({ key: searchKey, query: debouncedQuery, fetch });
210 setSearchInterrupted(false);
211 // An install error on an unchanged, already-shown query stays visible.
212 if (fetch || keyChanged) setError(null);
213 setIsSearching(fetch);
214 }
215​
216 const fetchHandledSearch = useEffectEvent((searchText: string) => {
217 fetchResults(searchText, startRequest());
218 });
219​
220 useEffect(() => {
221 if (!handledSearch) return;
222 if (handledSearch.fetch) {
223 fetchHandledSearch(handledSearch.query);
224 return;
225 }
226 // A request for a newer key may still be in flight; abort it so it cannot
227 // overwrite the results being kept.
228 requestRef.current?.abort();
229 requestRef.current = null;
230 }, [handledSearch]);
231​
232 const handleSortChange = (value: OpenVsxThemeSort | null) => {
233 const nextSort = SORT_OPTIONS.find((option) => option.value === value)?.value;
234 if (!nextSort) return;
235 setSortBy(nextSort);
236 };
237​
238 const handleInstall = async (extension: OpenVsxThemeExtension, allowUpdate: boolean) => {
239 setError(null);
240 let installedCollection: ReadonlyArray<ThemeDefinition>;
241 try {
242 installedCollection = getStoredCustomThemeCollection(extension.collectionId);
243 } catch (cause) {
244 setError(cause instanceof Error ? cause.message : "Installed themes could not be read.");
245 return;
246 }
247 const updated = installedCollection.length > 0;
248 if (updated && !allowUpdate) {
249 setPendingUpdate(extension);
250 return;
251 }
252​
253 requestRef.current?.abort();
254 const controller = new AbortController();
255 requestRef.current = controller;
256 setIsSearching(false);
257 setSearchInterrupted(true);
258 setInstallingId(extension.id);
259 try {
260 const themes = await importOpenVsxThemeExtension(extension, controller.signal);
261 if (!controller.signal.aborted) {
262 const imported = replaceCustomThemeCollection(extension.collectionId, themes, {
263 expectedCollection: installedCollection,
264 });
265 onInstalled(imported, { updated });
266 }
267 } catch (cause) {
268 if (!controller.signal.aborted) {
269 setError(cause instanceof Error ? cause.message : "That theme could not be added.");
270 }
271 }
272 if (requestRef.current === controller) {
273 requestRef.current = null;
274 setInstallingId(null);
275 }
276 };
277​
278 return (
279 <section className="space-y-3" aria-labelledby="theme-search-heading">
280 <div>
281 <h3 className="text-sm font-medium" id="theme-search-heading">
282 Search community themes
283 </h3>
284 <p className="mt-0.5 text-muted-foreground text-xs">
285 Find open-source themes from Open VSX.
286 </p>
287 </div>
288 <InputGroup>
289 <InputGroupAddon>
290 {isSearching ? <Spinner aria-hidden /> : <SearchIcon aria-hidden />}
291 </InputGroupAddon>
292 <InputGroupInput
293 aria-label="Search Open VSX themes"
294 autoFocus
295 onChange={(event) => setQuery(event.currentTarget.value)}
296 onKeyDown={(event) => {
297 if (event.nativeEvent.isComposing || event.keyCode === 229) return;
298 if (event.key === "Enter" && !isSearching && installingId === null)
299 runSearch(query.trim());
300 }}
301 placeholder="Search themes..."
302 size="lg"
303 type="search"
304 value={query}
305 />
306 </InputGroup>
307​
308 {!isSearching || results !== null ? (
309 <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
310 <div className="flex min-w-0 flex-wrap items-center gap-1.5">
311 <p className="text-muted-foreground text-xs">Popular</p>
312 {SUGGESTED_SEARCHES.map((suggestion) => (
313 <Button
314 key={suggestion}
315 disabled={installingId !== null}
316 size="xs"
317 variant="ghost"
318 onClick={() => {
319 if (query.trim() === suggestion) {
320 runSearch(suggestion);
321 } else {
322 setQuery(suggestion);
323 }
324 }}
325 >
326 {suggestion}
327 </Button>
328 ))}
329 </div>
330 {results && results.length > 0 ? (
331 <div className="flex shrink-0 items-center justify-end gap-2">
332 <p className="text-muted-foreground text-xs">Sort</p>
333 <Select
334 disabled={installingId !== null}
335 value={sortBy}
336 onValueChange={handleSortChange}
337 >
338 <SelectTrigger size="sm" className="w-40" aria-label="Sort themes">
339 <SelectValue>
340 {SORT_OPTIONS.find((option) => option.value === sortBy)?.label}
341 </SelectValue>
342 </SelectTrigger>
343 <SelectPopup align="end" alignItemWithTrigger={false}>
344 {SORT_OPTIONS.map((option) => (
345 <SelectItem key={option.value} hideIndicator value={option.value}>
346 {option.label}
347 </SelectItem>
348 ))}
349 </SelectPopup>
350 </Select>
351 </div>
352 ) : null}
353 </div>
354 ) : null}
355​
356 <div className="sr-only" role="status">
357 {isSearching
358 ? "Searching themes..."
359 : results
360 ? `${results.length} supported ${results.length === 1 ? "theme" : "themes"} found.`
361 : ""}
362 </div>
363​
364 {error ? (
365 <Alert variant="error" role="status" aria-live="polite">
366 <AlertDescription>{error}</AlertDescription>
367 </Alert>
368 ) : null}
369​
370 {isSearching && results === null ? (
371 <div className="flex min-h-20 items-center justify-center gap-2 text-muted-foreground text-sm">
372 <Spinner /> Searching themes...
373 </div>
374 ) : null}
375​
376 {results ? (
377 results.length === 0 ? (
378 <div className="flex min-h-40 flex-col items-center justify-center rounded-2xl border border-dashed text-center">
379 <p className="text-sm font-medium">No supported open-source themes found</p>
380 <p className="mt-1 text-muted-foreground text-xs">Try a broader search.</p>
381 </div>
382 ) : (
383 <div className="grid gap-2 sm:grid-cols-2">
384 {results.map((extension) => {
385 const isInstalling = installingId === extension.id;
386 const isInstalled = getCustomThemes().some(
387 (theme) => theme.collection?.id === extension.collectionId,
388 );
389 const action = isInstalled ? "Update" : "Install";
390 const progressAction = isInstalled ? "Updating" : "Installing";
391 return (
392 <article
393 className="group flex min-w-0 flex-col gap-3 rounded-xl border border-border/70 bg-card/60 p-3 transition-colors hover:bg-accent/20"
394 key={extension.id}
395 >
396 <div className="flex min-w-0 gap-3">
397 <ThemeExtensionIcon key={extension.iconUrl} extension={extension} />
398 <div className="min-w-0 flex-1">
399 <h4 className="truncate text-sm font-medium">{extension.name}</h4>
400 <p className="truncate text-muted-foreground text-xs">
401 {extension.publisher} · {DOWNLOAD_FORMAT.format(extension.downloadCount)}{" "}
402 downloads
403 </p>
404 </div>
405 </div>
406 <p className="line-clamp-2 min-h-8 text-muted-foreground text-xs leading-4">
407 {extension.description || "A community color theme for your editor."}
408 </p>
409 <div className="mt-auto flex items-center justify-between gap-2">
410 <div className="flex min-w-0 items-center gap-2">
411 {extension.sourceUrl ? (
412 <Button
413 aria-label={`View source for ${extension.name}`}
414 render={<a href={extension.sourceUrl} rel="noreferrer" target="_blank" />}
415 size="icon-micro"
416 variant="ghost-muted"
417 >
418 <SourceLinkIcon url={extension.sourceUrl} />
419 </Button>
420 ) : null}
421 </div>
422 <Button
423 aria-label={`${isInstalling ? progressAction : action} ${extension.name}`}
424 disabled={installingId !== null}
425 size="xs"
426 variant="outline"
427 onClick={() => void handleInstall(extension, false)}
428 >
429 {isInstalling ? (
430 <Spinner />
431 ) : isInstalled ? (
432 <RefreshIcon />
433 ) : (
434 <PackagePlusIcon />
435 )}
436 {isInstalling ? `${progressAction}...` : action}
437 </Button>
438 </div>
439 </article>
440 );
441 })}
442 </div>
443 )
444 ) : null}
445​
446 <AlertDialog
447 open={pendingUpdate !== null}
448 onOpenChange={(nextOpen) => {
449 if (!nextOpen) setPendingUpdate(null);
450 }}
451 >
452 <AlertDialogPopup>
453 <AlertDialogHeader>
454 <AlertDialogTitle>Update “{pendingUpdate?.name}”?</AlertDialogTitle>
455 <AlertDialogDescription>
456 This replaces its installed variants, including any local edits. Variants no longer in
457 the extension will be removed.
458 </AlertDialogDescription>
459 </AlertDialogHeader>
460 <AlertDialogFooter>
461 <AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
462 <Button
463 onClick={() => {
464 const extension = pendingUpdate;
465 setPendingUpdate(null);
466 if (extension) void handleInstall(extension, true);
467 }}
468 >
469 Update theme
470 </Button>
471 </AlertDialogFooter>
472 </AlertDialogPopup>
473 </AlertDialog>
474 </section>
475 );