The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { thrownErrorMessage } from "@t3tools/client-runtime/errors"; |
| 2 | import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; |
| 3 | import { RefreshIcon } from "~/components/ui/refresh-icon"; |
| 4 | import { ExternalLinkIcon, PackagePlusIcon, PaletteIcon, SearchIcon } from "lucide-react"; |
| 5 | import { type ReactNode, useState } from "react"; |
| 6 | import { |
| 7 | importOpenVsxThemeExtension, |
| 8 | searchOpenVsxThemes, |
| 9 | type OpenVsxThemeExtension, |
| 10 | type OpenVsxThemeSort, |
| 11 | } from "../../openVsxThemes"; |
| 12 | import { |
| 13 | getCustomThemes, |
| 14 | getStoredCustomThemeCollection, |
| 15 | replaceCustomThemeCollection, |
| 16 | type ThemeDefinition, |
| 17 | } from "../../themePalette"; |
| 18 | import { sourceControlIcon } from "../../sourceControlPresentation"; |
| 19 | import { |
| 20 | AlertDialog, |
| 21 | AlertDialogClose, |
| 22 | AlertDialogDescription, |
| 23 | AlertDialogFooter, |
| 24 | AlertDialogHeader, |
| 25 | AlertDialogPopup, |
| 26 | AlertDialogTitle, |
| 27 | } from "../ui/alert-dialog"; |
| 28 | import { Alert, AlertDescription } from "../ui/alert"; |
| 29 | import { Button } from "../ui/button"; |
| 30 | import { InputGroup, InputGroupAddon, InputGroupInput } from "../ui/input-group"; |
| 31 | import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; |
| 32 | import { Spinner } from "../ui/spinner"; |
| 33 | import { msg, T, useGT, useMessages, Var } from "gt-react"; |
| 34 | import { m } from "../../i18n/messages"; |
| 35 | |
| 36 | const DOWNLOAD_FORMAT = new Intl.NumberFormat(undefined, { |
| 37 | notation: "compact", |
| 38 | maximumFractionDigits: 1, |
| 39 | }); |
| 40 | const SUGGESTED_SEARCHES = ["Dracula", "Catppuccin", "Nord", "Tokyo Night"]; |
| 41 | const 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 | ]; |
| 47 | const SEARCH_DEBOUNCE_MS = 350; |
| 48 | |
| 49 | function sourceHost(url: string): string | null { |
| 50 | try { |
| 51 | return new URL(url).hostname.toLowerCase(); |
| 52 | } catch { |
| 53 | return null; |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | function 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" />; |
| 62 | } |
| 63 | |
| 64 | function 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 | ); |
| 83 | } |
| 84 | |
| 85 | export interface ThemeSearchView { |
| 86 | readonly setResults: (results: ReadonlyArray<OpenVsxThemeExtension> | null) => void; |
| 87 | readonly setError: (error: string | null) => void; |
| 88 | readonly setIsSearching: (isSearching: boolean) => void; |
| 89 | } |
| 90 | |
| 91 | type 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 | */ |
| 98 | export 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 | }; |
| 235 | } |
| 236 | |
| 237 | export 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 | <InputGroupInput |
| 325 | aria-label={gt("Search Open VSX themes")} |
| 326 | autoFocus |
| 327 | onChange={(event) => changeQuery(event.currentTarget.value)} |
| 328 | onKeyDown={(event) => { |
| 329 | if (event.nativeEvent.isComposing || event.keyCode === 229) return; |
| 330 | if (event.key === "Enter" && !isSearching && installingId === null) |
| 331 | themeSearch.searchNow(); |
| 332 | }} |
| 333 | placeholder={gt("Search themes...")} |
| 334 | size="lg" |
| 335 | type="search" |
| 336 | value={query} |
| 337 | /> |
| 338 | </InputGroup> |
| 339 | |
| 340 | {!isSearching || results !== null ? ( |
| 341 | <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between"> |
| 342 | <div className="flex min-w-0 flex-wrap items-center gap-1.5"> |
| 343 | <p className="text-muted-foreground text-xs"> |
| 344 | <T>Popular</T> |
| 345 | </p> |
| 346 | {SUGGESTED_SEARCHES.map((suggestion) => ( |
| 347 | <Button |
| 348 | key={suggestion} |
| 349 | disabled={installingId !== null} |
| 350 | size="xs" |
| 351 | variant="ghost" |
| 352 | onClick={() => { |
| 353 | if (query.trim() === suggestion) { |
| 354 | themeSearch.searchNow(); |
| 355 | } else { |
| 356 | changeQuery(suggestion); |
| 357 | } |
| 358 | }} |
| 359 | > |
| 360 | {suggestion} |
| 361 | </Button> |
| 362 | ))} |
| 363 | </div> |
| 364 | {results && results.length > 0 ? ( |
| 365 | <div className="flex shrink-0 items-center justify-end gap-2"> |
| 366 | <p className="text-muted-foreground text-xs"> |
| 367 | <T>Sort</T> |
| 368 | </p> |
| 369 | <Select |
| 370 | disabled={installingId !== null} |
| 371 | value={sortBy} |
| 372 | onValueChange={handleSortChange} |
| 373 | > |
| 374 | <SelectTrigger size="sm" className="w-40" aria-label={gt("Sort themes")}> |
| 375 | <SelectValue> |
| 376 | {messages(SORT_OPTIONS.find((option) => option.value === sortBy)?.label ?? "")} |
| 377 | </SelectValue> |
| 378 | </SelectTrigger> |
| 379 | <SelectPopup align="end" alignItemWithTrigger={false}> |
| 380 | {SORT_OPTIONS.map((option) => ( |
| 381 | <SelectItem key={option.value} hideIndicator value={option.value}> |
| 382 | {messages(option.label)} |
| 383 | </SelectItem> |
| 384 | ))} |
| 385 | </SelectPopup> |
| 386 | </Select> |
| 387 | </div> |
| 388 | ) : null} |
| 389 | </div> |
| 390 | ) : null} |
| 391 | |
| 392 | <div className="sr-only" role="status"> |
| 393 | {isSearching |
| 394 | ? gt("Searching themes...") |
| 395 | : results |
| 396 | ? gt( |
| 397 | "{count, plural, one {{count} supported theme found.} other {{count} supported themes found.}}", |
| 398 | { count: results.length }, |
| 399 | ) |
| 400 | : ""} |
| 401 | </div> |
| 402 | |
| 403 | {error ? ( |
| 404 | <Alert variant="error" role="status" aria-live="polite"> |
| 405 | <AlertDescription>{error}</AlertDescription> |
| 406 | </Alert> |
| 407 | ) : null} |
| 408 | |
| 409 | {isSearching && results === null ? ( |
| 410 | <div className="flex min-h-20 items-center justify-center gap-2 text-muted-foreground text-sm"> |
| 411 | <Spinner /> <T>Searching themes...</T> |
| 412 | </div> |
| 413 | ) : null} |
| 414 | |
| 415 | {results ? ( |
| 416 | results.length === 0 ? ( |
| 417 | <div className="flex min-h-40 flex-col items-center justify-center rounded-2xl border border-dashed text-center"> |
| 418 | <p className="text-sm font-medium"> |
| 419 | <T>No supported open-source themes found</T> |
| 420 | </p> |
| 421 | <p className="mt-1 text-muted-foreground text-xs"> |
| 422 | <T>Try a broader search.</T> |
| 423 | </p> |
| 424 | </div> |
| 425 | ) : ( |
| 426 | <div className="grid gap-2 sm:grid-cols-2"> |
| 427 | {results.map((extension) => { |
| 428 | const isInstalling = installingId === extension.id; |
| 429 | const isInstalled = getCustomThemes().some( |
| 430 | (theme) => theme.collection?.id === extension.collectionId, |
| 431 | ); |
| 432 | const action = isInstalled ? gt("Update") : gt("Install"); |
| 433 | return ( |
| 434 | <article |
| 435 | 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" |
| 436 | key={extension.id} |
| 437 | > |
| 438 | <div className="flex min-w-0 gap-3"> |
| 439 | <ThemeExtensionIcon key={extension.iconUrl} extension={extension} /> |
| 440 | <div className="min-w-0 flex-1"> |
| 441 | <h4 className="truncate text-sm font-medium">{extension.name}</h4> |
| 442 | <p className="truncate text-muted-foreground text-xs"> |
| 443 | {extension.publisher} · {DOWNLOAD_FORMAT.format(extension.downloadCount)}{" "} |
| 444 | downloads |
| 445 | </p> |
| 446 | </div> |
| 447 | </div> |
| 448 | <p className="line-clamp-2 min-h-8 text-muted-foreground text-xs leading-4"> |
| 449 | {extension.description || gt("A community color theme for your editor.")} |
| 450 | </p> |
| 451 | <div className="mt-auto flex items-center justify-between gap-2"> |
| 452 | <div className="flex min-w-0 items-center gap-2"> |
| 453 | {extension.sourceUrl ? ( |
| 454 | <Button |
| 455 | aria-label={gt("View source for {name}", { name: extension.name })} |
| 456 | render={<a href={extension.sourceUrl} rel="noreferrer" target="_blank" />} |
| 457 | size="icon-micro" |
| 458 | variant="ghost-muted" |
| 459 | > |
| 460 | {sourceLinkIcon(extension.sourceUrl)} |
| 461 | </Button> |
| 462 | ) : null} |
| 463 | </div> |
| 464 | <Button |
| 465 | aria-label={ |
| 466 | isInstalled |
| 467 | ? isInstalling |
| 468 | ? gt("Updating {name}", { name: extension.name }) |
| 469 | : gt("Update {name}", { name: extension.name }) |
| 470 | : isInstalling |
| 471 | ? gt("Installing {name}", { name: extension.name }) |
| 472 | : gt("Install {name}", { name: extension.name }) |
| 473 | } |
| 474 | disabled={installingId !== null} |
| 475 | size="xs" |
| 476 | variant="outline" |
| 477 | onClick={() => void handleInstall(extension, false)} |
| 478 | > |
| 479 | {isInstalling ? ( |
| 480 | <Spinner /> |
| 481 | ) : isInstalled ? ( |
| 482 | <RefreshIcon /> |
| 483 | ) : ( |
| 484 | <PackagePlusIcon /> |
| 485 | )} |
| 486 | {isInstalling |
| 487 | ? isInstalled |
| 488 | ? gt("Updating...") |
| 489 | : gt("Installing...") |
| 490 | : action} |
| 491 | </Button> |
| 492 | </div> |
| 493 | </article> |
| 494 | ); |
| 495 | })} |
| 496 | </div> |
| 497 | ) |
| 498 | ) : null} |
| 499 | |
| 500 | <AlertDialog |
| 501 | open={pendingUpdate !== null} |
| 502 | onOpenChange={(nextOpen) => { |
| 503 | if (!nextOpen) setPendingUpdate(null); |
| 504 | }} |
| 505 | > |
| 506 | <AlertDialogPopup> |
| 507 | <AlertDialogHeader> |
| 508 | <AlertDialogTitle> |
| 509 | <T> |
| 510 | Update “<Var>{pendingUpdate?.name}</Var>”? |
| 511 | </T> |
| 512 | </AlertDialogTitle> |
| 513 | <AlertDialogDescription> |
| 514 | <T> |
| 515 | This replaces its installed variants, including any local edits. Variants no longer |
| 516 | in the extension will be removed. |
| 517 | </T> |
| 518 | </AlertDialogDescription> |
| 519 | </AlertDialogHeader> |
| 520 | <AlertDialogFooter> |
| 521 | <AlertDialogClose render={<Button variant="outline" />}> |
| 522 | <T>Cancel</T> |
| 523 | </AlertDialogClose> |
| 524 | <Button |
| 525 | onClick={() => { |
| 526 | const extension = pendingUpdate; |
| 527 | setPendingUpdate(null); |
| 528 | if (extension) void handleInstall(extension, true); |
| 529 | }} |
| 530 | > |
| 531 | <T>Update theme</T> |
| 532 | </Button> |
| 533 | </AlertDialogFooter> |
| 534 | </AlertDialogPopup> |
| 535 | </AlertDialog> |
| 536 | </section> |
| 537 | ); |
| 538 | } |