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