Open History to see the last commit
1import {
2 ExternalLinkIcon,
3 PaletteIcon,
4 PlusIcon,
5 RefreshCwIcon,
6 SearchIcon,
7 ShieldCheckIcon,
8} from "lucide-react";
9import type { FormEvent } from "react";
10import { useCallback, useEffect, useRef, useState } from "react";
11import {
12 importOpenVsxThemeExtension,
13 searchOpenVsxThemes,
14 type OpenVsxThemeExtension,
15 type OpenVsxThemeSort,
16} from "../../openVsxThemes";
17import {
18 getCustomThemes,
19 getStoredCustomThemeCollection,
20 replaceCustomThemeCollection,
21 type ThemeDefinition,
22} from "../../themePalette";
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 { Input } from "../ui/input";
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];
48
49function ThemeExtensionIcon({ extension }: { extension: OpenVsxThemeExtension }) {
50 const [failed, setFailed] = useState(false);
51
52 return (
53 <div className="flex size-10 shrink-0 items-center justify-center overflow-hidden rounded-lg bg-muted text-muted-foreground">
54 {extension.iconUrl && !failed ? (
55 <img
56 alt=""
57 className="size-full object-cover"
58 loading="lazy"
59 referrerPolicy="no-referrer"
60 src={extension.iconUrl}
61 onError={() => setFailed(true)}
62 />
63 ) : (
64 <PaletteIcon className="size-4" />
65 )}
66 </div>
67 );
68}
69
70export function ThemeSearchSection({
71 open,
72 onInstalled,
73}: {
74 open: boolean;
75 onInstalled: (themes: ReadonlyArray<ThemeDefinition>, context: { updated: boolean }) => void;
76}) {
77 const [query, setQuery] = useState("");
78 const [sortBy, setSortBy] = useState<OpenVsxThemeSort>("downloadCount");
79 const [results, setResults] = useState<ReadonlyArray<OpenVsxThemeExtension> | null>(null);
80 const [error, setError] = useState<string | null>(null);
81 const [isSearching, setIsSearching] = useState(false);
82 const [installingId, setInstallingId] = useState<string | null>(null);
83 const [pendingUpdate, setPendingUpdate] = useState<OpenVsxThemeExtension | null>(null);
84 const requestRef = useRef<AbortController | null>(null);
85
86 useEffect(() => {
87 requestRef.current?.abort();
88 requestRef.current = null;
89 if (open) {
90 setQuery("");
91 setSortBy("downloadCount");
92 setResults(null);
93 setError(null);
94 setIsSearching(false);
95 setInstallingId(null);
96 setPendingUpdate(null);
97 }
98 return () => {
99 requestRef.current?.abort();
100 requestRef.current = null;
101 };
102 }, [open]);
103
104 const runSearch = useCallback(
105 async (searchText: string, nextSort = sortBy) => {
106 const trimmed = searchText.trim();
107 if (!trimmed) return;
108 requestRef.current?.abort();
109 const controller = new AbortController();
110 requestRef.current = controller;
111 setQuery(trimmed);
112 setIsSearching(true);
113 setError(null);
114 setResults(null);
115 try {
116 const nextResults = await searchOpenVsxThemes(trimmed, {
117 signal: controller.signal,
118 sortBy: nextSort,
119 });
120 if (!controller.signal.aborted) setResults(nextResults);
121 } catch (cause) {
122 if (!controller.signal.aborted) {
123 setError(cause instanceof Error ? cause.message : "Open VSX search failed.");
124 }
125 }
126 if (requestRef.current === controller) {
127 requestRef.current = null;
128 setIsSearching(false);
129 }
130 },
131 [sortBy],
132 );
133
134 const handleSearch = useCallback(
135 (event: FormEvent<HTMLFormElement>) => {
136 event.preventDefault();
137 void runSearch(query);
138 },
139 [query, runSearch],
140 );
141
142 const handleSortChange = useCallback(
143 (value: OpenVsxThemeSort | null) => {
144 const nextSort = SORT_OPTIONS.find((option) => option.value === value)?.value;
145 if (!nextSort) return;
146 setSortBy(nextSort);
147 if ((results !== null || isSearching) && query.trim()) {
148 void runSearch(query, nextSort);
149 }
150 },
151 [isSearching, query, results, runSearch],
152 );
153
154 const handleInstall = useCallback(
155 async (extension: OpenVsxThemeExtension, allowUpdate: boolean) => {
156 setError(null);
157 let installedCollection: ReadonlyArray<ThemeDefinition>;
158 try {
159 installedCollection = getStoredCustomThemeCollection(extension.collectionId);
160 } catch (cause) {
161 setError(cause instanceof Error ? cause.message : "Installed themes could not be read.");
162 return;
163 }
164 const updated = installedCollection.length > 0;
165 if (updated && !allowUpdate) {
166 setPendingUpdate(extension);
167 return;
168 }
169
170 requestRef.current?.abort();
171 const controller = new AbortController();
172 requestRef.current = controller;
173 setInstallingId(extension.id);
174 try {
175 const themes = await importOpenVsxThemeExtension(extension, controller.signal);
176 if (!controller.signal.aborted) {
177 const imported = replaceCustomThemeCollection(extension.collectionId, themes, {
178 expectedCollection: installedCollection,
179 });
180 onInstalled(imported, { updated });
181 }
182 } catch (cause) {
183 if (!controller.signal.aborted) {
184 setError(cause instanceof Error ? cause.message : "That theme could not be added.");
185 }
186 }
187 if (requestRef.current === controller) {
188 requestRef.current = null;
189 setInstallingId(null);
190 }
191 },
192 [onInstalled],
193 );
194
195 return (
196 <section className="space-y-3" aria-labelledby="theme-search-heading">
197 <div>
198 <h3 className="text-sm font-medium" id="theme-search-heading">
199 Search community themes
200 </h3>
201 <p className="mt-0.5 text-muted-foreground text-xs">
202 Find open-source themes from Open VSX.
203 </p>
204 </div>
205 <form className="relative flex gap-2" onSubmit={handleSearch}>
206 <SearchIcon className="pointer-events-none absolute left-3 top-1/2 z-10 size-4 -translate-y-1/2 text-muted-foreground" />
207 <Input
208 aria-label="Search Open VSX themes"
209 className="rounded-xl [&_input]:pl-9"
210 autoFocus
211 onChange={(event) => setQuery(event.currentTarget.value)}
212 placeholder="try dracula, nord, catppuccin..."
213 size="lg"
214 type="search"
215 value={query}
216 />
217 <Button
218 disabled={!query.trim() || isSearching || installingId !== null}
219 type="submit"
220 variant="outline"
221 >
222 {isSearching ? <Spinner /> : <SearchIcon />}
223 Search
224 </Button>
225 </form>
226
227 {!isSearching ? (
228 <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
229 <div className="flex min-w-0 flex-wrap items-center gap-1.5">
230 <p className="text-muted-foreground text-xs">Popular</p>
231 {SUGGESTED_SEARCHES.map((suggestion) => (
232 <Button
233 key={suggestion}
234 size="xs"
235 variant="ghost"
236 onClick={() => void runSearch(suggestion)}
237 >
238 {suggestion}
239 </Button>
240 ))}
241 </div>
242 {results && results.length > 0 ? (
243 <div className="flex shrink-0 items-center justify-end gap-2">
244 <p className="text-muted-foreground text-xs">Sort</p>
245 <Select
246 disabled={installingId !== null}
247 value={sortBy}
248 onValueChange={handleSortChange}
249 >
250 <SelectTrigger size="sm" className="w-40" aria-label="Sort themes">
251 <SelectValue>
252 {SORT_OPTIONS.find((option) => option.value === sortBy)?.label}
253 </SelectValue>
254 </SelectTrigger>
255 <SelectPopup align="end" alignItemWithTrigger={false}>
256 {SORT_OPTIONS.map((option) => (
257 <SelectItem key={option.value} hideIndicator value={option.value}>
258 {option.label}
259 </SelectItem>
260 ))}
261 </SelectPopup>
262 </Select>
263 </div>
264 ) : null}
265 </div>
266 ) : null}
267
268 <div className="sr-only" role="status">
269 {isSearching
270 ? "Finding themes..."
271 : results
272 ? `${results.length} supported ${results.length === 1 ? "theme" : "themes"} found.`
273 : ""}
274 </div>
275
276 {error ? (
277 <div
278 aria-live="polite"
279 className="rounded-xl border border-destructive/30 bg-destructive/5 px-3 py-2 text-destructive text-sm"
280 >
281 {error}
282 </div>
283 ) : null}
284
285 {isSearching ? (
286 <div className="flex min-h-20 items-center justify-center gap-2 text-muted-foreground text-sm">
287 <Spinner /> Finding themes...
288 </div>
289 ) : null}
290
291 {results ? (
292 results.length === 0 ? (
293 <div className="flex min-h-40 flex-col items-center justify-center rounded-2xl border border-dashed text-center">
294 <p className="text-sm font-medium">No supported open-source themes found</p>
295 <p className="mt-1 text-muted-foreground text-xs">Try a broader search.</p>
296 </div>
297 ) : (
298 <div className="grid gap-2 sm:grid-cols-2">
299 {results.map((extension) => {
300 const isInstalling = installingId === extension.id;
301 const isInstalled = getCustomThemes().some(
302 (theme) => theme.collection?.id === extension.collectionId,
303 );
304 const action = isInstalled ? "Update" : "Add";
305 const progressAction = isInstalled ? "Updating" : "Adding";
306 return (
307 <article
308 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"
309 key={extension.id}
310 >
311 <div className="flex min-w-0 gap-3">
312 <ThemeExtensionIcon key={extension.iconUrl} extension={extension} />
313 <div className="min-w-0 flex-1">
314 <h4 className="truncate text-sm font-medium">{extension.name}</h4>
315 <p className="truncate text-muted-foreground text-xs">
316 {extension.publisher} · {DOWNLOAD_FORMAT.format(extension.downloadCount)}{" "}
317 downloads
318 </p>
319 </div>
320 </div>
321 <p className="line-clamp-2 min-h-8 text-muted-foreground text-xs leading-4">
322 {extension.description || "A community color theme for your editor."}
323 </p>
324 <div className="mt-auto flex items-center justify-between gap-2">
325 <div className="flex min-w-0 items-center gap-2">
326 <span className="inline-flex items-center gap-1 text-muted-foreground text-[11px]">
327 <ShieldCheckIcon className="size-3" /> {extension.license}
328 </span>
329 {extension.sourceUrl ? (
330 <a
331 aria-label={`View source for ${extension.name}`}
332 className="inline-flex items-center gap-1 text-muted-foreground text-[11px] hover:text-foreground"
333 href={extension.sourceUrl}
334 rel="noreferrer"
335 target="_blank"
336 >
337 Source <ExternalLinkIcon className="size-3" />
338 </a>
339 ) : null}
340 </div>
341 <Button
342 aria-label={`${isInstalling ? progressAction : action} ${extension.name}`}
343 disabled={installingId !== null}
344 size="xs"
345 variant="outline"
346 onClick={() => void handleInstall(extension, false)}
347 >
348 {isInstalling ? <Spinner /> : isInstalled ? <RefreshCwIcon /> : <PlusIcon />}
349 {isInstalling ? `${progressAction}...` : action}
350 </Button>
351 </div>
352 </article>
353 );
354 })}
355 </div>
356 )
357 ) : null}
358
359 <AlertDialog
360 open={pendingUpdate !== null}
361 onOpenChange={(nextOpen) => {
362 if (!nextOpen) setPendingUpdate(null);
363 }}
364 >
365 <AlertDialogPopup>
366 <AlertDialogHeader>
367 <AlertDialogTitle>Update “{pendingUpdate?.name}”?</AlertDialogTitle>
368 <AlertDialogDescription>
369 This replaces its installed variants, including any local edits. Variants no longer in
370 the extension will be removed.
371 </AlertDialogDescription>
372 </AlertDialogHeader>
373 <AlertDialogFooter>
374 <AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
375 <Button
376 onClick={() => {
377 const extension = pendingUpdate;
378 setPendingUpdate(null);
379 if (extension) void handleInstall(extension, true);
380 }}
381 >
382 Update theme
383 </Button>
384 </AlertDialogFooter>
385 </AlertDialogPopup>
386 </AlertDialog>
387 </section>
388 );
389}