Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThemeSearchSection.tsx

465 lines17.1 KB

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" />;
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 );
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 // `installingId` and `sortBy` are deliberately not dependencies: the
208 // guards above read the current values from the fresh render closure. An
209 // install finishing reruns the search only when the query or sort changed
210 // while it was in flight (checked via lastSearchKeyRef, recorded only
211 // once a search succeeds), so the install error the user needs to see is
212 // preserved across that rerun.
213 // eslint-disable-next-line react-hooks/exhaustive-deps
214 }, [open, query, debouncedQuery, installingId, runSearch]);
215​
216 const handleSortChange = useCallback((value: OpenVsxThemeSort | null) => {
217 const nextSort = SORT_OPTIONS.find((option) => option.value === value)?.value;
218 if (!nextSort) return;
219 setSortBy(nextSort);
220 }, []);
221​
222 const handleInstall = useCallback(
223 async (extension: OpenVsxThemeExtension, allowUpdate: boolean) => {
224 setError(null);
225 let installedCollection: ReadonlyArray<ThemeDefinition>;
226 try {
227 installedCollection = getStoredCustomThemeCollection(extension.collectionId);
228 } catch (cause) {
229 setError(cause instanceof Error ? cause.message : "Installed themes could not be read.");
230 return;
231 }
232 const updated = installedCollection.length > 0;
233 if (updated && !allowUpdate) {
234 setPendingUpdate(extension);
235 return;
236 }
237​
238 requestRef.current?.abort();
239 const controller = new AbortController();
240 requestRef.current = controller;
241 setIsSearching(false);
242 setInstallingId(extension.id);
243 try {
244 const themes = await importOpenVsxThemeExtension(extension, controller.signal);
245 if (!controller.signal.aborted) {
246 const imported = replaceCustomThemeCollection(extension.collectionId, themes, {
247 expectedCollection: installedCollection,
248 });
249 onInstalled(imported, { updated });
250 }
251 } catch (cause) {
252 if (!controller.signal.aborted) {
253 setError(cause instanceof Error ? cause.message : "That theme could not be added.");
254 }
255 }
256 if (requestRef.current === controller) {
257 requestRef.current = null;
258 setInstallingId(null);
259 }
260 },
261 [onInstalled],
262 );
263​
264 return (
265 <section className="space-y-3" aria-labelledby="theme-search-heading">
266 <div>
267 <h3 className="text-sm font-medium" id="theme-search-heading">
268 Search community themes
269 </h3>
270 <p className="mt-0.5 text-muted-foreground text-xs">
271 Find open-source themes from Open VSX.
272 </p>
273 </div>
274 <InputGroup>
275 <InputGroupAddon>
276 {isSearching ? <Spinner aria-hidden /> : <SearchIcon aria-hidden />}
277 </InputGroupAddon>
278 <InputGroupInput
279 aria-label="Search Open VSX themes"
280 autoFocus
281 onChange={(event) => setQuery(event.currentTarget.value)}
282 onKeyDown={(event) => {
283 if (event.nativeEvent.isComposing || event.keyCode === 229) return;
284 if (event.key === "Enter" && !isSearching && installingId === null)
285 void runSearch(query.trim());
286 }}
287 placeholder="Search themes..."
288 size="lg"
289 type="search"
290 value={query}
291 />
292 </InputGroup>
293​
294 {!isSearching || results !== null ? (
295 <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
296 <div className="flex min-w-0 flex-wrap items-center gap-1.5">
297 <p className="text-muted-foreground text-xs">Popular</p>
298 {SUGGESTED_SEARCHES.map((suggestion) => (
299 <Button
300 key={suggestion}
301 disabled={installingId !== null}
302 size="xs"
303 variant="ghost"
304 onClick={() => {
305 if (query.trim() === suggestion) {
306 void runSearch(suggestion);
307 } else {
308 setQuery(suggestion);
309 }
310 }}
311 >
312 {suggestion}
313 </Button>
314 ))}
315 </div>
316 {results && results.length > 0 ? (
317 <div className="flex shrink-0 items-center justify-end gap-2">
318 <p className="text-muted-foreground text-xs">Sort</p>
319 <Select
320 disabled={installingId !== null}
321 value={sortBy}
322 onValueChange={handleSortChange}
323 >
324 <SelectTrigger size="sm" className="w-40" aria-label="Sort themes">
325 <SelectValue>
326 {SORT_OPTIONS.find((option) => option.value === sortBy)?.label}
327 </SelectValue>
328 </SelectTrigger>
329 <SelectPopup align="end" alignItemWithTrigger={false}>
330 {SORT_OPTIONS.map((option) => (
331 <SelectItem key={option.value} hideIndicator value={option.value}>
332 {option.label}
333 </SelectItem>
334 ))}
335 </SelectPopup>
336 </Select>
337 </div>
338 ) : null}
339 </div>
340 ) : null}
341​
342 <div className="sr-only" role="status">
343 {isSearching
344 ? "Searching themes..."
345 : results
346 ? `${results.length} supported ${results.length === 1 ? "theme" : "themes"} found.`
347 : ""}
348 </div>
349​
350 {error ? (
351 <div
352 aria-live="polite"
353 className="rounded-xl border border-destructive/30 bg-destructive/5 px-3 py-2 text-destructive text-sm"
354 >
355 {error}
356 </div>
357 ) : null}
358​
359 {isSearching && results === null ? (
360 <div className="flex min-h-20 items-center justify-center gap-2 text-muted-foreground text-sm">
361 <Spinner /> Searching themes...
362 </div>
363 ) : null}
364​
365 {results ? (
366 results.length === 0 ? (
367 <div className="flex min-h-40 flex-col items-center justify-center rounded-2xl border border-dashed text-center">
368 <p className="text-sm font-medium">No supported open-source themes found</p>
369 <p className="mt-1 text-muted-foreground text-xs">Try a broader search.</p>
370 </div>
371 ) : (
372 <div className="grid gap-2 sm:grid-cols-2">
373 {results.map((extension) => {
374 const isInstalling = installingId === extension.id;
375 const isInstalled = getCustomThemes().some(
376 (theme) => theme.collection?.id === extension.collectionId,
377 );
378 const action = isInstalled ? "Update" : "Install";
379 const progressAction = isInstalled ? "Updating" : "Installing";
380 return (
381 <article
382 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"
383 key={extension.id}
384 >
385 <div className="flex min-w-0 gap-3">
386 <ThemeExtensionIcon key={extension.iconUrl} extension={extension} />
387 <div className="min-w-0 flex-1">
388 <h4 className="truncate text-sm font-medium">{extension.name}</h4>
389 <p className="truncate text-muted-foreground text-xs">
390 {extension.publisher} · {DOWNLOAD_FORMAT.format(extension.downloadCount)}{" "}
391 downloads
392 </p>
393 </div>
394 </div>
395 <p className="line-clamp-2 min-h-8 text-muted-foreground text-xs leading-4">
396 {extension.description || "A community color theme for your editor."}
397 </p>
398 <div className="mt-auto flex items-center justify-between gap-2">
399 <div className="flex min-w-0 items-center gap-2">
400 {extension.sourceUrl ? (
401 <Button
402 aria-label={`View source for ${extension.name}`}
403 render={<a href={extension.sourceUrl} rel="noreferrer" target="_blank" />}
404 size="icon-micro"
405 variant="ghost-muted"
406 >
407 <SourceLinkIcon url={extension.sourceUrl} />
408 </Button>
409 ) : null}
410 </div>
411 <Button
412 aria-label={`${isInstalling ? progressAction : action} ${extension.name}`}
413 disabled={installingId !== null}
414 size="xs"
415 variant="outline"
416 onClick={() => void handleInstall(extension, false)}
417 >
418 {isInstalling ? (
419 <Spinner />
420 ) : isInstalled ? (
421 <RefreshCwIcon />
422 ) : (
423 <PackagePlusIcon />
424 )}
425 {isInstalling ? `${progressAction}...` : action}
426 </Button>
427 </div>
428 </article>
429 );
430 })}
431 </div>
432 )
433 ) : null}
434​
435 <AlertDialog
436 open={pendingUpdate !== null}
437 onOpenChange={(nextOpen) => {
438 if (!nextOpen) setPendingUpdate(null);
439 }}
440 >
441 <AlertDialogPopup>
442 <AlertDialogHeader>
443 <AlertDialogTitle>Update “{pendingUpdate?.name}”?</AlertDialogTitle>
444 <AlertDialogDescription>
445 This replaces its installed variants, including any local edits. Variants no longer in
446 the extension will be removed.
447 </AlertDialogDescription>
448 </AlertDialogHeader>
449 <AlertDialogFooter>
450 <AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
451 <Button
452 onClick={() => {
453 const extension = pendingUpdate;
454 setPendingUpdate(null);
455 if (extension) void handleInstall(extension, true);
456 }}
457 >
458 Update theme
459 </Button>
460 </AlertDialogFooter>
461 </AlertDialogPopup>
462 </AlertDialog>
463 </section>
464 );