Open History to see the last commit
1import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
3import { RefreshIcon } from "~/components/ui/refresh-icon";
4import { ExternalLinkIcon, PackagePlusIcon, PaletteIcon, SearchIcon } from "lucide-react";
5import { type ReactNode, useState } from "react";
6import {
7 importOpenVsxThemeExtension,
8 searchOpenVsxThemes,
9 type OpenVsxThemeExtension,
10 type OpenVsxThemeSort,
11} from "../../openVsxThemes";
12import {
13 getCustomThemes,
14 getStoredCustomThemeCollection,
15 replaceCustomThemeCollection,
16 type ThemeDefinition,
17} from "../../themePalette";
18import { sourceControlIcon } from "../../sourceControlPresentation";
19import {
20 AlertDialog,
21 AlertDialogClose,
22 AlertDialogDescription,
23 AlertDialogFooter,
24 AlertDialogHeader,
25 AlertDialogPopup,
26 AlertDialogTitle,
27} from "../ui/alert-dialog";
28import { Alert, AlertDescription } from "../ui/alert";
29import { Button } from "../ui/button";
30import { InputGroup, InputGroupAddon, InputGroupInput } from "../ui/input-group";
31import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
32import { Spinner } from "../ui/spinner";
33import { msg, T, useGT, useMessages, Var, plural, part } from "gt-react";
34import { useFormattingLocale } from "../../i18n/I18nProvider";
35import { m } from "../../i18n/messages";
36
37const SUGGESTED_SEARCHES = ["Dracula", "Catppuccin", "Nord", "Tokyo Night"];
38const SORT_OPTIONS: ReadonlyArray<{ value: OpenVsxThemeSort; label: string }> = [
39 { value: "downloadCount", label: msg("Most downloaded") },
40 { value: "rating", label: msg("Best rated") },
41 { value: "timestamp", label: msg("Newest") },
42 { value: "relevance", label: msg("Most relevant") },
43];
44const SEARCH_DEBOUNCE_MS = 350;
45
46function sourceHost(url: string): string | null {
47 try {
48 return new URL(url).hostname.toLowerCase();
49 } catch {
50 return null;
51 }
52}
53
54function sourceLinkIcon(url: string): ReactNode {
55 const host = sourceHost(url);
56 const definition = host === null ? undefined : sourceControlClients.findByPublicDomain(host);
57 const Icon = definition ? sourceControlIcon(definition) : ExternalLinkIcon;
58 return <Icon className="size-3.5" />;
59}
60
61function ThemeExtensionIcon({ extension }: { extension: OpenVsxThemeExtension }) {
62 const [failed, setFailed] = useState(false);
63
64 return (
65 <div className="flex size-10 shrink-0 items-center justify-center overflow-hidden rounded-lg bg-muted text-muted-foreground">
66 {extension.iconUrl && !failed ? (
67 <img
68 alt=""
69 className="size-full object-cover"
70 loading="lazy"
71 referrerPolicy="no-referrer"
72 src={extension.iconUrl}
73 onError={() => setFailed(true)}
74 />
75 ) : (
76 <PaletteIcon className="size-4" />
77 )}
78 </div>
79 );
80}
81
82export interface ThemeSearchView {
83 readonly setResults: (results: ReadonlyArray<OpenVsxThemeExtension> | null) => void;
84 readonly setError: (error: string | null) => void;
85 readonly setIsSearching: (isSearching: boolean) => void;
86}
87
88type SearchThemes = typeof searchOpenVsxThemes;
89
90/**
91 * Owns one dialog session's Open VSX traffic: the input debounce, the request in
92 * flight, and which key the shown results belong to. Aborting `signal` (the
93 * dialog closing) cancels all of it, including an install.
94 */
95export function createThemeSearch(
96 view: ThemeSearchView,
97 signal: AbortSignal,
98 search: SearchThemes = searchOpenVsxThemes,
99) {
100 let query = "";
101 let sortBy: OpenVsxThemeSort = "downloadCount";
102 let debounce: ReturnType<typeof setTimeout> | null = null;
103 let request: AbortController | null = null;
104 let install: AbortController | null = null;
105 // Record successful searches only; rerun after install only for changed query/sort to preserve install
106 // errors.
107 let shownKey: string | null = null;
108 let handledKey: string | null = null;
109 let interrupted = false;
110
111 const keyOf = () => `${query}\u0000${sortBy}`;
112 const abortRequest = () => {
113 request?.abort();
114 request = null;
115 };
116 const cancelDebounce = () => {
117 if (debounce !== null) clearTimeout(debounce);
118 debounce = null;
119 };
120
121 const fetchResults = () => {
122 abortRequest();
123 const controller = new AbortController();
124 request = controller;
125 const key = keyOf();
126 void search(query, { signal: controller.signal, sortBy })
127 .then(
128 (results) => {
129 if (controller.signal.aborted) return;
130 view.setResults(results);
131 shownKey = key;
132 },
133 (cause: unknown) => {
134 if (controller.signal.aborted) return;
135 view.setResults(null);
136 shownKey = null;
137 view.setError(
138 cause instanceof Error
139 ? (thrownErrorMessage(cause, m) ?? cause.message)
140 : m(msg("Open VSX search failed.")),
141 );
142 },
143 )
144 .then(() => {
145 if (request !== controller) return;
146 request = null;
147 view.setIsSearching(false);
148 });
149 };
150
151 const clear = () => {
152 cancelDebounce();
153 abortRequest();
154 shownKey = null;
155 handledKey = null;
156 view.setResults(null);
157 view.setError(null);
158 view.setIsSearching(false);
159 };
160
161 const settle = () => {
162 if (install !== null || signal.aborted || query === "") return;
163 const key = keyOf();
164 const keyChanged = handledKey !== key;
165 if (!keyChanged && !interrupted) return;
166 handledKey = key;
167 interrupted = false;
168 const shouldFetch = shownKey !== key;
169 if (shouldFetch || keyChanged) view.setError(null);
170 view.setIsSearching(shouldFetch);
171 if (shouldFetch) fetchResults();
172 else abortRequest();
173 };
174
175 signal.addEventListener(
176 "abort",
177 () => {
178 cancelDebounce();
179 abortRequest();
180 install?.abort();
181 },
182 { once: true },
183 );
184
185 return {
186 /** An unsettled query would hit Open VSX for text that is no longer visible, so typing waits. */
187 setQuery(nextQuery: string) {
188 const trimmed = nextQuery.trim();
189 if (trimmed === query) return;
190 query = trimmed;
191 cancelDebounce();
192 if (trimmed === "") {
193 if (install === null) clear();
194 return;
195 }
196 debounce = setTimeout(() => {
197 debounce = null;
198 settle();
199 }, SEARCH_DEBOUNCE_MS);
200 },
201 setSortBy(nextSort: OpenVsxThemeSort) {
202 sortBy = nextSort;
203 if (debounce === null) settle();
204 },
205 /** Enter or re-picking the current suggestion searches again even for the shown key. */
206 searchNow() {
207 if (install !== null || signal.aborted || query === "") return;
208 // A pending debounce for the same key would otherwise restart this search.
209 cancelDebounce();
210 handledKey = keyOf();
211 interrupted = false;
212 view.setError(null);
213 view.setIsSearching(true);
214 fetchResults();
215 },
216 beginInstall(): AbortSignal {
217 abortRequest();
218 install?.abort();
219 install = new AbortController();
220 interrupted = true;
221 view.setIsSearching(false);
222 return install.signal;
223 },
224 endInstall(installSignal: AbortSignal): boolean {
225 if (install?.signal !== installSignal) return false;
226 install = null;
227 if (query === "") clear();
228 else if (debounce === null) settle();
229 return true;
230 },
231 };
232}
233
234export function ThemeSearchSection({
235 signal,
236 onInstalled,
237}: {
238 signal: AbortSignal;
239 onInstalled: (themes: ReadonlyArray<ThemeDefinition>, context: { updated: boolean }) => void;
240}) {
241 const messages = useMessages();
242 const gt = useGT();
243 const downloadFormat = new Intl.NumberFormat(useFormattingLocale(), {
244 notation: "compact",
245 maximumFractionDigits: 1,
246 });
247 const [query, setQuery] = useState("");
248 const [sortBy, setSortBy] = useState<OpenVsxThemeSort>("downloadCount");
249 const [results, setResults] = useState<ReadonlyArray<OpenVsxThemeExtension> | null>(null);
250 const [error, setError] = useState<string | null>(null);
251 const [isSearching, setIsSearching] = useState(false);
252 const [installingId, setInstallingId] = useState<string | null>(null);
253 const [pendingUpdate, setPendingUpdate] = useState<OpenVsxThemeExtension | null>(null);
254 const [themeSearch] = useState(() =>
255 createThemeSearch({ setResults, setError, setIsSearching }, signal),
256 );
257
258 const changeQuery = (nextQuery: string) => {
259 setQuery(nextQuery);
260 themeSearch.setQuery(nextQuery);
261 };
262
263 const handleSortChange = (value: OpenVsxThemeSort | null) => {
264 const nextSort = SORT_OPTIONS.find((option) => option.value === value)?.value;
265 if (!nextSort) return;
266 setSortBy(nextSort);
267 themeSearch.setSortBy(nextSort);
268 };
269
270 const handleInstall = async (extension: OpenVsxThemeExtension, allowUpdate: boolean) => {
271 setError(null);
272 let installedCollection: ReadonlyArray<ThemeDefinition>;
273 try {
274 installedCollection = getStoredCustomThemeCollection(extension.collectionId);
275 } catch (cause) {
276 setError(
277 cause instanceof Error
278 ? (thrownErrorMessage(cause, m) ?? cause.message)
279 : gt`Installed themes could not be read.`,
280 );
281 return;
282 }
283 const updated = installedCollection.length > 0;
284 if (updated && !allowUpdate) {
285 setPendingUpdate(extension);
286 return;
287 }
288
289 const installSignal = themeSearch.beginInstall();
290 setInstallingId(extension.id);
291 try {
292 const themes = await importOpenVsxThemeExtension(extension, installSignal);
293 if (!installSignal.aborted) {
294 const imported = replaceCustomThemeCollection(extension.collectionId, themes, {
295 expectedCollection: installedCollection,
296 });
297 onInstalled(imported, { updated });
298 }
299 } catch (cause) {
300 if (!installSignal.aborted) {
301 setError(
302 cause instanceof Error
303 ? (thrownErrorMessage(cause, m) ?? cause.message)
304 : gt`That theme could not be added.`,
305 );
306 }
307 }
308 if (themeSearch.endInstall(installSignal)) setInstallingId(null);
309 };
310
311 return (
312 <section className="space-y-3" aria-labelledby="theme-search-heading">
313 <div>
314 <h3 className="text-sm font-medium" id="theme-search-heading">
315 <T>Search community themes</T>
316 </h3>
317 <p className="mt-0.5 text-muted-foreground text-xs">
318 <T>Find open-source themes from Open VSX.</T>
319 </p>
320 </div>
321 <InputGroup>
322 <InputGroupAddon>
323 {isSearching ? <Spinner aria-hidden /> : <SearchIcon aria-hidden />}
324 </InputGroupAddon>
325 {/* Native search inputs clear on Escape even during IME composition. */}
326 <InputGroupInput
327 aria-label={gt`Search Open VSX themes`}
328 autoFocus
329 onChange={(event) => changeQuery(event.currentTarget.value)}
330 onKeyDown={(event) => {
331 if (event.nativeEvent.isComposing || event.keyCode === 229) return;
332 if (event.key === "Escape" && (query || event.repeat)) {
333 event.preventDefault();
334 event.stopPropagation();
335 changeQuery("");
336 }
337 if (event.key === "Enter" && !isSearching && installingId === null)
338 themeSearch.searchNow();
339 }}
340 placeholder={gt`Search themes...`}
341 role="searchbox"
342 size="lg"
343 type="text"
344 value={query}
345 />
346 </InputGroup>
347
348 {!isSearching || results !== null ? (
349 <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
350 <div className="flex min-w-0 flex-wrap items-center gap-1.5">
351 <p className="text-muted-foreground text-xs">
352 <T>Popular</T>
353 </p>
354 {SUGGESTED_SEARCHES.map((suggestion) => (
355 <Button
356 key={suggestion}
357 disabled={installingId !== null}
358 size="xs"
359 variant="ghost"
360 onClick={() => {
361 if (query.trim() === suggestion) {
362 themeSearch.searchNow();
363 } else {
364 changeQuery(suggestion);
365 }
366 }}
367 >
368 {suggestion}
369 </Button>
370 ))}
371 </div>
372 {results && results.length > 0 ? (
373 <div className="flex shrink-0 items-center justify-end gap-2">
374 <p className="text-muted-foreground text-xs">
375 <T>Sort</T>
376 </p>
377 <Select
378 disabled={installingId !== null}
379 value={sortBy}
380 onValueChange={handleSortChange}
381 >
382 <SelectTrigger size="sm" className="w-40" aria-label={gt`Sort themes`}>
383 <SelectValue>
384 {messages(SORT_OPTIONS.find((option) => option.value === sortBy)?.label ?? "")}
385 </SelectValue>
386 </SelectTrigger>
387 <SelectPopup align="end" alignItemWithTrigger={false}>
388 {SORT_OPTIONS.map((option) => (
389 <SelectItem key={option.value} hideIndicator value={option.value}>
390 {messages(option.label)}
391 </SelectItem>
392 ))}
393 </SelectPopup>
394 </Select>
395 </div>
396 ) : null}
397 </div>
398 ) : null}
399
400 <div className="sr-only" role="status">
401 {isSearching
402 ? gt`Searching themes...`
403 : results
404 ? gt`${plural(
405 { count: results.length },
406 {
407 one: part`${{ count: results.length }} supported theme found.`,
408 other: part`${{ count: results.length }} supported themes found.`,
409 },
410 )}`
411 : ""}
412 </div>
413
414 {error ? (
415 <Alert variant="error" role="status" aria-live="polite">
416 <AlertDescription>{error}</AlertDescription>
417 </Alert>
418 ) : null}
419
420 {isSearching && results === null ? (
421 <div className="flex min-h-20 items-center justify-center gap-2 text-muted-foreground text-sm">
422 <Spinner /> <T>Searching themes...</T>
423 </div>
424 ) : null}
425
426 {results ? (
427 results.length === 0 ? (
428 <div className="flex min-h-40 flex-col items-center justify-center rounded-2xl border border-dashed text-center">
429 <p className="text-sm font-medium">
430 <T>No supported open-source themes found</T>
431 </p>
432 <p className="mt-1 text-muted-foreground text-xs">
433 <T>Try a broader search.</T>
434 </p>
435 </div>
436 ) : (
437 <div className="grid gap-2 sm:grid-cols-2">
438 {results.map((extension) => {
439 const isInstalling = installingId === extension.id;
440 const isInstalled = getCustomThemes().some(
441 (theme) => theme.collection?.id === extension.collectionId,
442 );
443 const action = isInstalled ? gt`Update` : gt`Install`;
444 return (
445 <article
446 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"
447 key={extension.id}
448 >
449 <div className="flex min-w-0 gap-3">
450 <ThemeExtensionIcon key={extension.iconUrl} extension={extension} />
451 <div className="min-w-0 flex-1">
452 <h4 className="truncate text-sm font-medium">{extension.name}</h4>
453 <p className="truncate text-muted-foreground text-xs">
454 {extension.publisher} ·{" "}
455 {gt`${plural(
456 { count: extension.downloadCount },
457 {
458 one: part`${{ formatted: downloadFormat.format(extension.downloadCount) }} download`,
459 other: part`${{ formatted: downloadFormat.format(extension.downloadCount) }} downloads`,
460 },
461 )}`}
462 </p>
463 </div>
464 </div>
465 <p className="line-clamp-2 min-h-8 text-muted-foreground text-xs leading-4">
466 {extension.description || gt`A community color theme for your editor.`}
467 </p>
468 <div className="mt-auto flex items-center justify-between gap-2">
469 <div className="flex min-w-0 items-center gap-2">
470 {extension.sourceUrl ? (
471 <Button
472 aria-label={gt`View source for ${{ name: extension.name }}`}
473 render={<a href={extension.sourceUrl} rel="noreferrer" target="_blank" />}
474 size="icon-micro"
475 variant="ghost-muted"
476 >
477 {sourceLinkIcon(extension.sourceUrl)}
478 </Button>
479 ) : null}
480 </div>
481 <Button
482 aria-label={
483 isInstalled
484 ? isInstalling
485 ? gt`Updating ${{ name: extension.name }}`
486 : gt`Update ${{ name: extension.name }}`
487 : isInstalling
488 ? gt`Installing ${{ name: extension.name }}`
489 : gt`Install ${{ name: extension.name }}`
490 }
491 disabled={installingId !== null}
492 size="xs"
493 variant="outline"
494 onClick={() => void handleInstall(extension, false)}
495 >
496 {isInstalling ? (
497 <Spinner />
498 ) : isInstalled ? (
499 <RefreshIcon />
500 ) : (
501 <PackagePlusIcon />
502 )}
503 {isInstalling ? (isInstalled ? gt`Updating...` : gt`Installing...`) : action}
504 </Button>
505 </div>
506 </article>
507 );
508 })}
509 </div>
510 )
511 ) : null}
512
513 <AlertDialog
514 open={pendingUpdate !== null}
515 onOpenChange={(nextOpen) => {
516 if (!nextOpen) setPendingUpdate(null);
517 }}
518 >
519 <AlertDialogPopup>
520 <AlertDialogHeader>
521 <AlertDialogTitle>
522 <T>
523 Update “<Var>{pendingUpdate?.name}</Var>”?
524 </T>
525 </AlertDialogTitle>
526 <AlertDialogDescription>
527 <T>
528 This replaces its installed variants, including any local edits. Variants no longer
529 in the extension will be removed.
530 </T>
531 </AlertDialogDescription>
532 </AlertDialogHeader>
533 <AlertDialogFooter>
534 <AlertDialogClose render={<Button variant="outline" />}>
535 <T>Cancel</T>
536 </AlertDialogClose>
537 <Button
538 onClick={() => {
539 const extension = pendingUpdate;
540 setPendingUpdate(null);
541 if (extension) void handleInstall(extension, true);
542 }}
543 >
544 <T>Update theme</T>
545 </Button>
546 </AlertDialogFooter>
547 </AlertDialogPopup>
548 </AlertDialog>
549 </section>
550 );
551}