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 // Record successful searches only; rerun after install only for changed query/sort to preserve install
99 // errors.
100 const [lastSearchKey, setLastSearchKey] = useState<string | null>(null);
101 const [handledSearch, setHandledSearch] = useState<{
102 key: string;
103 query: string;
104 fetch: boolean;
105 } | null>(null);
106 const [searchInterrupted, setSearchInterrupted] = useState(false);
107
108 const [wasOpen, setWasOpen] = useState(open);
109 if (open !== wasOpen) {
110 setWasOpen(open);
111 if (open) {
112 setQuery("");
113 setSortBy("downloadCount");
114 setResults(null);
115 setError(null);
116 setIsSearching(false);
117 setInstallingId(null);
118 setPendingUpdate(null);
119 setLastSearchKey(null);
120 setHandledSearch(null);
121 setSearchInterrupted(false);
122 }
123 }
124
125 useEffect(() => {
126 if (!open) return;
127 return () => {
128 requestRef.current?.abort();
129 requestRef.current = null;
130 };
131 }, [open]);
132
133 const queryCleared = !query.trim() && installingId === null;
134 if (
135 queryCleared &&
136 (results !== null ||
137 error !== null ||
138 isSearching ||
139 lastSearchKey !== null ||
140 handledSearch !== null)
141 ) {
142 setResults(null);
143 setError(null);
144 setIsSearching(false);
145 setLastSearchKey(null);
146 setHandledSearch(null);
147 }
148
149 useEffect(() => {
150 if (!queryCleared) return;
151 requestRef.current?.abort();
152 requestRef.current = null;
153 }, [queryCleared]);
154
155 const startRequest = () => {
156 requestRef.current?.abort();
157 const controller = new AbortController();
158 requestRef.current = controller;
159 return controller;
160 };
161
162 const fetchResults = (trimmed: string, controller: AbortController) => {
163 const key = `${trimmed}\u0000${sortBy}`;
164 void searchOpenVsxThemes(trimmed, { signal: controller.signal, sortBy })
165 .then(
166 (nextResults) => {
167 if (controller.signal.aborted) return;
168 setResults(nextResults);
169 setLastSearchKey(key);
170 },
171 (cause: unknown) => {
172 if (controller.signal.aborted) return;
173 setResults(null);
174 setLastSearchKey(null);
175 setError(cause instanceof Error ? cause.message : "Open VSX search failed.");
176 },
177 )
178 .then(() => {
179 if (requestRef.current !== controller) return;
180 requestRef.current = null;
181 setIsSearching(false);
182 });
183 };
184
185 const runSearch = (searchText: string) => {
186 const trimmed = searchText.trim();
187 if (!trimmed) return;
188 setError(null);
189 setIsSearching(true);
190 fetchResults(trimmed, startRequest());
191 };
192
193 const debouncedQuery = useDebouncedValue(query.trim(), SEARCH_DEBOUNCE_MS);
194 const searchKey = `${debouncedQuery}\u0000${sortBy}`;
195 const searchSettled =
196 open && installingId === null && debouncedQuery !== "" && debouncedQuery === query.trim();
197
198 const keyChanged = handledSearch?.key !== searchKey;
199 if (searchSettled && (keyChanged || searchInterrupted)) {
200 const fetch = lastSearchKey !== searchKey;
201 setHandledSearch({ key: searchKey, query: debouncedQuery, fetch });
202 setSearchInterrupted(false);
203 if (fetch || keyChanged) setError(null);
204 setIsSearching(fetch);
205 }
206
207 const fetchHandledSearch = useEffectEvent((searchText: string) => {
208 fetchResults(searchText, startRequest());
209 });
210
211 useEffect(() => {
212 if (!handledSearch) return;
213 if (handledSearch.fetch) {
214 fetchHandledSearch(handledSearch.query);
215 return;
216 }
217 requestRef.current?.abort();
218 requestRef.current = null;
219 }, [handledSearch]);
220
221 const handleSortChange = (value: OpenVsxThemeSort | null) => {
222 const nextSort = SORT_OPTIONS.find((option) => option.value === value)?.value;
223 if (!nextSort) return;
224 setSortBy(nextSort);
225 };
226
227 const handleInstall = async (extension: OpenVsxThemeExtension, allowUpdate: boolean) => {
228 setError(null);
229 let installedCollection: ReadonlyArray<ThemeDefinition>;
230 try {
231 installedCollection = getStoredCustomThemeCollection(extension.collectionId);
232 } catch (cause) {
233 setError(cause instanceof Error ? cause.message : "Installed themes could not be read.");
234 return;
235 }
236 const updated = installedCollection.length > 0;
237 if (updated && !allowUpdate) {
238 setPendingUpdate(extension);
239 return;
240 }
241
242 requestRef.current?.abort();
243 const controller = new AbortController();
244 requestRef.current = controller;
245 setIsSearching(false);
246 setSearchInterrupted(true);
247 setInstallingId(extension.id);
248 try {
249 const themes = await importOpenVsxThemeExtension(extension, controller.signal);
250 if (!controller.signal.aborted) {
251 const imported = replaceCustomThemeCollection(extension.collectionId, themes, {
252 expectedCollection: installedCollection,
253 });
254 onInstalled(imported, { updated });
255 }
256 } catch (cause) {
257 if (!controller.signal.aborted) {
258 setError(cause instanceof Error ? cause.message : "That theme could not be added.");
259 }
260 }
261 if (requestRef.current === controller) {
262 requestRef.current = null;
263 setInstallingId(null);
264 }
265 };
266
267 return (
268 <section className="space-y-3" aria-labelledby="theme-search-heading">
269 <div>
270 <h3 className="text-sm font-medium" id="theme-search-heading">
271 Search community themes
272 </h3>
273 <p className="mt-0.5 text-muted-foreground text-xs">
274 Find open-source themes from Open VSX.
275 </p>
276 </div>
277 <InputGroup>
278 <InputGroupAddon>
279 {isSearching ? <Spinner aria-hidden /> : <SearchIcon aria-hidden />}
280 </InputGroupAddon>
281 <InputGroupInput
282 aria-label="Search Open VSX themes"
283 autoFocus
284 onChange={(event) => setQuery(event.currentTarget.value)}
285 onKeyDown={(event) => {
286 if (event.nativeEvent.isComposing || event.keyCode === 229) return;
287 if (event.key === "Enter" && !isSearching && installingId === null)
288 runSearch(query.trim());
289 }}
290 placeholder="Search themes..."
291 size="lg"
292 type="search"
293 value={query}
294 />
295 </InputGroup>
296
297 {!isSearching || results !== null ? (
298 <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
299 <div className="flex min-w-0 flex-wrap items-center gap-1.5">
300 <p className="text-muted-foreground text-xs">Popular</p>
301 {SUGGESTED_SEARCHES.map((suggestion) => (
302 <Button
303 key={suggestion}
304 disabled={installingId !== null}
305 size="xs"
306 variant="ghost"
307 onClick={() => {
308 if (query.trim() === suggestion) {
309 runSearch(suggestion);
310 } else {
311 setQuery(suggestion);
312 }
313 }}
314 >
315 {suggestion}
316 </Button>
317 ))}
318 </div>
319 {results && results.length > 0 ? (
320 <div className="flex shrink-0 items-center justify-end gap-2">
321 <p className="text-muted-foreground text-xs">Sort</p>
322 <Select
323 disabled={installingId !== null}
324 value={sortBy}
325 onValueChange={handleSortChange}
326 >
327 <SelectTrigger size="sm" className="w-40" aria-label="Sort themes">
328 <SelectValue>
329 {SORT_OPTIONS.find((option) => option.value === sortBy)?.label}
330 </SelectValue>
331 </SelectTrigger>
332 <SelectPopup align="end" alignItemWithTrigger={false}>
333 {SORT_OPTIONS.map((option) => (
334 <SelectItem key={option.value} hideIndicator value={option.value}>
335 {option.label}
336 </SelectItem>
337 ))}
338 </SelectPopup>
339 </Select>
340 </div>
341 ) : null}
342 </div>
343 ) : null}
344
345 <div className="sr-only" role="status">
346 {isSearching
347 ? "Searching themes..."
348 : results
349 ? `${results.length} supported ${results.length === 1 ? "theme" : "themes"} found.`
350 : ""}
351 </div>
352
353 {error ? (
354 <Alert variant="error" role="status" aria-live="polite">
355 <AlertDescription>{error}</AlertDescription>
356 </Alert>
357 ) : null}
358
359 {isSearching && results === null ? (
360 <div className="flex min-h-20 items-center justify-center gap-2 text-muted-foreground text-sm">
361 <Spinner /> Searching themes...
362 </div>
363 ) : null}
364
365 {results ? (
366 results.length === 0 ? (
367 <div className="flex min-h-40 flex-col items-center justify-center rounded-2xl border border-dashed text-center">
368 <p className="text-sm font-medium">No supported open-source themes found</p>
369 <p className="mt-1 text-muted-foreground text-xs">Try a broader search.</p>
370 </div>
371 ) : (
372 <div className="grid gap-2 sm:grid-cols-2">
373 {results.map((extension) => {
374 const isInstalling = installingId === extension.id;
375 const isInstalled = getCustomThemes().some(
376 (theme) => theme.collection?.id === extension.collectionId,
377 );
378 const action = isInstalled ? "Update" : "Install";
379 const progressAction = isInstalled ? "Updating" : "Installing";
380 return (
381 <article
382 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"
383 key={extension.id}
384 >
385 <div className="flex min-w-0 gap-3">
386 <ThemeExtensionIcon key={extension.iconUrl} extension={extension} />
387 <div className="min-w-0 flex-1">
388 <h4 className="truncate text-sm font-medium">{extension.name}</h4>
389 <p className="truncate text-muted-foreground text-xs">
390 {extension.publisher} · {DOWNLOAD_FORMAT.format(extension.downloadCount)}{" "}
391 downloads
392 </p>
393 </div>
394 </div>
395 <p className="line-clamp-2 min-h-8 text-muted-foreground text-xs leading-4">
396 {extension.description || "A community color theme for your editor."}
397 </p>
398 <div className="mt-auto flex items-center justify-between gap-2">
399 <div className="flex min-w-0 items-center gap-2">
400 {extension.sourceUrl ? (
401 <Button
402 aria-label={`View source for ${extension.name}`}
403 render={<a href={extension.sourceUrl} rel="noreferrer" target="_blank" />}
404 size="icon-micro"
405 variant="ghost-muted"
406 >
407 {sourceLinkIcon(extension.sourceUrl)}
408 </Button>
409 ) : null}
410 </div>
411 <Button
412 aria-label={`${isInstalling ? progressAction : action} ${extension.name}`}
413 disabled={installingId !== null}
414 size="xs"
415 variant="outline"
416 onClick={() => void handleInstall(extension, false)}
417 >
418 {isInstalling ? (
419 <Spinner />
420 ) : isInstalled ? (
421 <RefreshIcon />
422 ) : (
423 <PackagePlusIcon />
424 )}
425 {isInstalling ? `${progressAction}...` : action}
426 </Button>
427 </div>
428 </article>
429 );
430 })}
431 </div>
432 )
433 ) : null}
434
435 <AlertDialog
436 open={pendingUpdate !== null}
437 onOpenChange={(nextOpen) => {
438 if (!nextOpen) setPendingUpdate(null);
439 }}
440 >
441 <AlertDialogPopup>
442 <AlertDialogHeader>
443 <AlertDialogTitle>Update “{pendingUpdate?.name}”?</AlertDialogTitle>
444 <AlertDialogDescription>
445 This replaces its installed variants, including any local edits. Variants no longer in
446 the extension will be removed.
447 </AlertDialogDescription>
448 </AlertDialogHeader>
449 <AlertDialogFooter>
450 <AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
451 <Button
452 onClick={() => {
453 const extension = pendingUpdate;
454 setPendingUpdate(null);
455 if (extension) void handleInstall(extension, true);
456 }}
457 >
458 Update theme
459 </Button>
460 </AlertDialogFooter>
461 </AlertDialogPopup>
462 </AlertDialog>
463 </section>
464 );
465}