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