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