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

ThemeSearchSection.tsx

545 lines18.8 KB

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