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