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 { 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];
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="flex gap-2" onSubmit={handleSearch}>
206 <InputGroup>
207 <InputGroupAddon>
208 <SearchIcon />
209 </InputGroupAddon>
210 <InputGroupInput
211 aria-label="Search Open VSX themes"
212 autoFocus
213 onChange={(event) => setQuery(event.currentTarget.value)}
214 placeholder="try dracula, nord, catppuccin..."
215 size="lg"
216 type="search"
217 value={query}
218 />
219 </InputGroup>
220 <Button
221 disabled={!query.trim() || isSearching || installingId !== null}
222 size="lg"
223 type="submit"
224 variant="outline"
225 >
226 {isSearching ? <Spinner /> : <SearchIcon />}
227 Search
228 </Button>
229 </form>
230
231 {!isSearching ? (
232 <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
233 <div className="flex min-w-0 flex-wrap items-center gap-1.5">
234 <p className="text-muted-foreground text-xs">Popular</p>
235 {SUGGESTED_SEARCHES.map((suggestion) => (
236 <Button
237 key={suggestion}
238 size="xs"
239 variant="ghost"
240 onClick={() => void runSearch(suggestion)}
241 >
242 {suggestion}
243 </Button>
244 ))}
245 </div>
246 {results && results.length > 0 ? (
247 <div className="flex shrink-0 items-center justify-end gap-2">
248 <p className="text-muted-foreground text-xs">Sort</p>
249 <Select
250 disabled={installingId !== null}
251 value={sortBy}
252 onValueChange={handleSortChange}
253 >
254 <SelectTrigger size="sm" className="w-40" aria-label="Sort themes">
255 <SelectValue>
256 {SORT_OPTIONS.find((option) => option.value === sortBy)?.label}
257 </SelectValue>
258 </SelectTrigger>
259 <SelectPopup align="end" alignItemWithTrigger={false}>
260 {SORT_OPTIONS.map((option) => (
261 <SelectItem key={option.value} hideIndicator value={option.value}>
262 {option.label}
263 </SelectItem>
264 ))}
265 </SelectPopup>
266 </Select>
267 </div>
268 ) : null}
269 </div>
270 ) : null}
271
272 <div className="sr-only" role="status">
273 {isSearching
274 ? "Finding themes..."
275 : results
276 ? `${results.length} supported ${results.length === 1 ? "theme" : "themes"} found.`
277 : ""}
278 </div>
279
280 {error ? (
281 <div
282 aria-live="polite"
283 className="rounded-xl border border-destructive/30 bg-destructive/5 px-3 py-2 text-destructive text-sm"
284 >
285 {error}
286 </div>
287 ) : null}
288
289 {isSearching ? (
290 <div className="flex min-h-20 items-center justify-center gap-2 text-muted-foreground text-sm">
291 <Spinner /> Finding themes...
292 </div>
293 ) : null}
294
295 {results ? (
296 results.length === 0 ? (
297 <div className="flex min-h-40 flex-col items-center justify-center rounded-2xl border border-dashed text-center">
298 <p className="text-sm font-medium">No supported open-source themes found</p>
299 <p className="mt-1 text-muted-foreground text-xs">Try a broader search.</p>
300 </div>
301 ) : (
302 <div className="grid gap-2 sm:grid-cols-2">
303 {results.map((extension) => {
304 const isInstalling = installingId === extension.id;
305 const isInstalled = getCustomThemes().some(
306 (theme) => theme.collection?.id === extension.collectionId,
307 );
308 const action = isInstalled ? "Update" : "Add";
309 const progressAction = isInstalled ? "Updating" : "Adding";
310 return (
311 <article
312 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"
313 key={extension.id}
314 >
315 <div className="flex min-w-0 gap-3">
316 <ThemeExtensionIcon key={extension.iconUrl} extension={extension} />
317 <div className="min-w-0 flex-1">
318 <h4 className="truncate text-sm font-medium">{extension.name}</h4>
319 <p className="truncate text-muted-foreground text-xs">
320 {extension.publisher} · {DOWNLOAD_FORMAT.format(extension.downloadCount)}{" "}
321 downloads
322 </p>
323 </div>
324 </div>
325 <p className="line-clamp-2 min-h-8 text-muted-foreground text-xs leading-4">
326 {extension.description || "A community color theme for your editor."}
327 </p>
328 <div className="mt-auto flex items-center justify-between gap-2">
329 <div className="flex min-w-0 items-center gap-2">
330 <span className="inline-flex items-center gap-1 text-muted-foreground text-[11px]">
331 <ShieldCheckIcon className="size-3" /> {extension.license}
332 </span>
333 {extension.sourceUrl ? (
334 <a
335 aria-label={`View source for ${extension.name}`}
336 className="inline-flex items-center gap-1 text-muted-foreground text-[11px] hover:text-foreground"
337 href={extension.sourceUrl}
338 rel="noreferrer"
339 target="_blank"
340 >
341 Source <ExternalLinkIcon className="size-3" />
342 </a>
343 ) : null}
344 </div>
345 <Button
346 aria-label={`${isInstalling ? progressAction : action} ${extension.name}`}
347 disabled={installingId !== null}
348 size="xs"
349 variant="outline"
350 onClick={() => void handleInstall(extension, false)}
351 >
352 {isInstalling ? <Spinner /> : isInstalled ? <RefreshCwIcon /> : <PlusIcon />}
353 {isInstalling ? `${progressAction}...` : action}
354 </Button>
355 </div>
356 </article>
357 );
358 })}
359 </div>
360 )
361 ) : null}
362
363 <AlertDialog
364 open={pendingUpdate !== null}
365 onOpenChange={(nextOpen) => {
366 if (!nextOpen) setPendingUpdate(null);
367 }}
368 >
369 <AlertDialogPopup>
370 <AlertDialogHeader>
371 <AlertDialogTitle>Update “{pendingUpdate?.name}”?</AlertDialogTitle>
372 <AlertDialogDescription>
373 This replaces its installed variants, including any local edits. Variants no longer in
374 the extension will be removed.
375 </AlertDialogDescription>
376 </AlertDialogHeader>
377 <AlertDialogFooter>
378 <AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
379 <Button
380 onClick={() => {
381 const extension = pendingUpdate;
382 setPendingUpdate(null);
383 if (extension) void handleInstall(extension, true);
384 }}
385 >
386 Update theme
387 </Button>
388 </AlertDialogFooter>
389 </AlertDialogPopup>
390 </AlertDialog>
391 </section>
392 );
393}