feat(web): add Open VSX theme search #5654
Mergedt3-code-bot[bot](GitHub profile, opens in a new tab)merged 31 commits into
main fromrefs/pull/5654/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/web/src/openVsxThemes.ts lines 142 to 144OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +124,21 @@124+ "Open VSX returned an unexpectedly large response.",125+ );126+ let value: unknown;127+ try {128+ value = JSON.parse(new TextDecoder().decode(searchBytes));129+ } catch {130+ throw new Error("Open VSX returned an unreadable response.");131+ }132+ const candidates = isRecord(value) && Array.isArray(value.extensions) ? value.extensions : [];133+ const identities = candidates.flatMap((candidate): Array<[string, string]> => {134+ if (!isRecord(candidate)) return [];135+ const namespace = typeof candidate.namespace === "string" ? candidate.namespace : "";136+ const name = typeof candidate.name === "string" ? candidate.name : "";137+ return namespace && name ? [[namespace, name]] : [];138+ });139+ const details = await Promise.allSettled(140+ identities.slice(0, 16).map(async ([namespace, name]) => {141+ const detailUrl = `https://open-vsx.org/api/${encodeURIComponent(namespace)}/${encodeURIComponent(name)}`;142+ const detailResponse = await fetch(detailUrl, signal ? { signal } : {});143+ if (!detailResponse.ok) return null;144+ return extensionFromDetail(await detailResponse.json());apps/web/src/openVsxThemes.ts lines 395 to 403Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +185,21 @@185+}186+187+type ZipEntrySizes = {188+ compressedSize?: unknown;189+ uncompressedSize?: unknown;190+};191+192+type InspectableZipObject = JSZip.JSZipObject & {193+ _data?: ZipEntrySizes;194+ unsafeOriginalName?: string;195+ internalStream?: (type: "uint8array") => JSZip.JSZipStreamHelper<Uint8Array>;196+};197+198+function inspectZipDirectory(bytes: Uint8Array): void {199+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);200+ const minimumOffset = Math.max(0, bytes.byteLength - 65_557);201+ let endOffset = bytes.byteLength - 22;202+ while (endOffset >= minimumOffset && view.getUint32(endOffset, true) !== 0x06054b50) {203+ endOffset -= 1;204+ }205+ if (endOffset < minimumOffset) throw new Error("That extension package has no ZIP directory.");
- apps/web/src/openVsxThemes.ts line 160OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +140,21 @@140+ const details = await Promise.allSettled(141+ identities.slice(0, 16).map(async ([namespace, name]) => {142+ const detailUrl = `https://open-vsx.org/api/${encodeURIComponent(namespace)}/${encodeURIComponent(name)}`;143+ const detailResponse = await fetch(detailUrl, signal ? { signal } : {});144+ if (!detailResponse.ok) return null;145+ const detailBytes = await readCappedResponse(146+ detailResponse,147+ MAX_DETAIL_BYTES,148+ "Open VSX returned an unexpectedly large detail response.",149+ );150+ try {151+ return extensionFromDetail(JSON.parse(new TextDecoder().decode(detailBytes)));152+ } catch {153+ return null;154+ }155+ }),156+ );157+ if (signal?.aborted) throw new DOMException("The operation was aborted.", "AbortError");158+ return details159+ .flatMap((result) => (result.status === "fulfilled" && result.value ? [result.value] : []))160+ .slice(0, 8);
- apps/web/src/openVsxThemes.ts lines 317 to 320Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +201,21 @@201+ if (!manifestResponse.ok) throw new Error("manifest unavailable");202+ const manifestBytes = await readCappedResponse(203+ manifestResponse,204+ MAX_MANIFEST_BYTES,205+ "Open VSX returned an unexpectedly large manifest.",206+ );207+ const manifest = parseJsoncObject(208+ new TextDecoder().decode(manifestBytes),209+ "Extension manifest",210+ );211+ return themeContributions(manifest).length > 0 ? extension : null;212+ } catch {213+ throw new Error("Open VSX returned unreadable theme details.");214+ }215+ }),216+ );217+ if (signal?.aborted) throw new DOMException("The operation was aborted.", "AbortError");218+ const completedDetails = details.filter((result) => result.status === "fulfilled");219+ if (identities.length > 0 && completedDetails.length === 0) {220+ throw new Error("Open VSX theme details are unavailable right now.");221+ }
- apps/web/src/openVsxThemes.ts line 211OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +191,21 @@191+ if (!detailResponse.ok) throw new Error("Open VSX theme details are unavailable.");192+ const detailBytes = await readCappedResponse(193+ detailResponse,194+ MAX_DETAIL_BYTES,195+ "Open VSX returned an unexpectedly large detail response.",196+ );197+ try {198+ const extension = extensionFromDetail(JSON.parse(new TextDecoder().decode(detailBytes)));199+ if (!extension) return null;200+ const manifestResponse = await fetch(extension.manifestUrl, signal ? { signal } : {});201+ if (!manifestResponse.ok) throw new Error("manifest unavailable");202+ const manifestBytes = await readCappedResponse(203+ manifestResponse,204+ MAX_MANIFEST_BYTES,205+ "Open VSX returned an unexpectedly large manifest.",206+ );207+ const manifest = parseJsoncObject(208+ new TextDecoder().decode(manifestBytes),209+ "Extension manifest",210+ );211+ return themeContributions(manifest).length > 0 ? extension : null;@@ -0,0 +556,21 @@556+ "That Open VSX checksum response is invalid.",557+ ),558+ )559+ .trim()560+ .split(/\s+/)[0];561+ if (!expectedChecksum || !/^[a-f\d]{64}$/i.test(expectedChecksum)) {562+ throw new Error("That Open VSX theme has an invalid checksum.");563+ }564+ signal?.throwIfAborted();565+ const actualChecksum = [...sha256(packageBytes)]566+ .map((byte) => byte.toString(16).padStart(2, "0"))567+ .join("");568+ if (actualChecksum.toLowerCase() !== expectedChecksum.toLowerCase()) {569+ throw new Error("That Open VSX theme failed its integrity check.");570+ }571+ signal?.throwIfAborted();572+ let zip: JSZip;573+ try {574+ const inspectedPackageBytes = inspectZipDirectory(packageBytes);575+ zip = await JSZip.loadAsync(inspectedPackageBytes);576+ signal?.throwIfAborted();
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- @@ -0,0 +699,21 @@699+ theme: parseVsCodeThemeFile(decorated),700+ sourceName: path.split("/").at(-1)!,701+ sourcePath: path,702+ });703+ } catch (cause) {704+ signal?.throwIfAborted();705+ failures.push(cause instanceof Error ? cause.message : "theme could not be read");706+ }707+ }708+ if (parsed.length === 0) {709+ throw new Error(failures[0] ?? "That extension has no compatible color themes.");710+ }711+ const extensionId = extension.id.toLowerCase();712+ const resolved = resolveThemeLabelCollisions(parsed).map((theme, index) => ({713+ ...theme,714+ id: openVsxThemeId(extensionId, parsed[index]!.sourcePath),715+ }));716+ const paired = pairVsCodeThemes(resolved, {717+ pairedId: (light, dark) => openVsxThemeId(extensionId, [light.id, dark.id].sort().join(":")),718+ });719+ const themes = resolveThemeLabelCollisions(paired.map((theme) => ({ theme })));
- apps/web/src/openVsxThemes.ts lines 264 to 264OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +244,21 @@244+ url.searchParams.set("category", "Themes");245+ url.searchParams.set("sortBy", sortBy);246+ url.searchParams.set("sortOrder", "desc");247+ // Ask for a few extras because results without a supported SPDX license248+ // are intentionally omitted.249+ url.searchParams.set("size", "16");250+ const value = await withSearchTimeout(async (requestSignal) => {251+ const response = await fetch(url, { signal: requestSignal });252+ if (!response.ok) throw new Error("Open VSX search is unavailable right now.");253+ const searchBytes = await readCappedResponse(254+ response,255+ MAX_SEARCH_BYTES,256+ "Open VSX returned an unexpectedly large response.",257+ );258+ try {259+ return JSON.parse(new TextDecoder().decode(searchBytes)) as unknown;260+ } catch {261+ throw new Error("Open VSX returned an unreadable response.");262+ }263+ }, signal);264+ const candidates = isRecord(value) && Array.isArray(value.extensions) ? value.extensions : [];apps/web/src/components/settings/ThemeSearchSection.tsx lines 225 to 225OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +205,21 @@205+ className="rounded-xl [&_input]:pl-9"206+ autoFocus207+ onChange={(event) => setQuery(event.currentTarget.value)}208+ placeholder="try dracula, nord, catppuccin..."209+ size="lg"210+ type="search"211+ value={query}212+ />213+ <Button214+ disabled={!query.trim() || isSearching || installingId !== null}215+ type="submit"216+ variant="outline"217+ >218+ {isSearching ? <Spinner /> : <SearchIcon />}219+ Search220+ </Button>221+ </form>222+223+ <div className="flex items-center justify-end gap-2">224+ <span className="text-muted-foreground text-xs">Sort</span>225+ <Select value={sortBy} onValueChange={handleSortChange}>
- apps/web/src/components/settings/ThemeSearchSection.tsx line 152Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +134,21 @@134+ );135+136+ const handleSearch = useCallback(137+ (event: FormEvent<HTMLFormElement>) => {138+ event.preventDefault();139+ void runSearch(query);140+ },141+ [query, runSearch],142+ );143+144+ const handleSortChange = useCallback(145+ (value: OpenVsxThemeSort | null) => {146+ const nextSort = SORT_OPTIONS.find((option) => option.value === value)?.value;147+ if (!nextSort) return;148+ setSortBy(nextSort);149+ if ((results !== null || isSearching) && query.trim()) {150+ void runSearch(query, nextSort);151+ }152+ },153+ [isSearching, query, results, runSearch],154+ );apps/web/src/openVsxThemes.ts line 84Resolvedby t3-code-bot[bot](GitHub profile, opens in a new tab)@@ -0,0 +64,21 @@64+ "list.activeSelectionBackground",65+ "list.hoverBackground",66+ "list.inactiveSelectionBackground",67+ "menu.background",68+ "panel.background",69+ "panel.border",70+ "progressBar.background",71+ "quickInput.background",72+ "scrollbarSlider.background",73+ "sideBar.background",74+ "sideBar.border",75+ "sideBar.foreground",76+ "terminal.background",77+ "terminal.foreground",78+ "terminal.selectionBackground",79+ "terminalCursor.foreground",80+ "textCodeBlock.background",81+ "textLink.foreground",82+]);83+84+export type OpenVsxThemeSort = "downloadCount" | "rating" | "timestamp" | "relevance";
- apps/web/src/openVsxThemes.ts line 292OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +272,21 @@272+ });273+ const details = await Promise.allSettled(274+ identities.slice(0, 16).map(([namespace, name]) =>275+ withSearchTimeout(async (requestSignal) => {276+ const detailUrl = `https://open-vsx.org/api/${encodeURIComponent(namespace)}/${encodeURIComponent(name)}`;277+ const detailResponse = await fetch(detailUrl, { signal: requestSignal });278+ if (!detailResponse.ok) throw new Error("Open VSX theme details are unavailable.");279+ const detailBytes = await readCappedResponse(280+ detailResponse,281+ MAX_DETAIL_BYTES,282+ "Open VSX returned an unexpectedly large detail response.",283+ );284+ try {285+ const extension = extensionFromDetail(JSON.parse(new TextDecoder().decode(detailBytes)));286+ if (!extension) return null;287+ const [manifestResponse, packageResponse] = await Promise.all([288+ fetch(extension.manifestUrl, { signal: requestSignal }),289+ fetch(extension.vsixUrl, { method: "HEAD", signal: requestSignal }),290+ ]);291+ if (!manifestResponse.ok) throw new Error("manifest unavailable");292+ if (!packageResponse.ok) throw new Error("package unavailable");
- apps/web/src/components/settings/ThemeSettings.tsx line 751Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -460,3 +579,6 @@460579 </div>461580 );462581582+ const customThemeCollections = [583+ ...customThemes584+ .reduce((groups, customTheme) => {
- apps/web/src/components/settings/ThemeSearchSection.tsx line 168Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +142,21 @@142+143+ const handleSortChange = useCallback(144+ (value: OpenVsxThemeSort | null) => {145+ const nextSort = SORT_OPTIONS.find((option) => option.value === value)?.value;146+ if (!nextSort) return;147+ setSortBy(nextSort);148+ if ((results !== null || isSearching) && query.trim()) {149+ void runSearch(query, nextSort);150+ }151+ },152+ [isSearching, query, results, runSearch],153+ );154+155+ const handleInstall = useCallback(156+ async (extension: OpenVsxThemeExtension, allowUpdate: boolean) => {157+ const installedCollection = getStoredCustomThemeCollection(extension.collectionId);158+ const updated = installedCollection.length > 0;159+ if (updated && !allowUpdate) {160+ setPendingUpdate(extension);161+ return;162+ }apps/web/src/components/settings/ThemeSettings.tsx line 309Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -124,4 +176,4 @@124176 onUse();125177 }}126178 >127- {theme.label}179+ {variantNavigation?.collectionLabel ?? theme.label}
- apps/web/src/components/settings/ThemeSettings.tsx line 475OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -226,0 +455,21 @@455+456+ return (457+ <ThemeLibraryCard458+ activeModes={activeModesFor(theme.id)}459+ isActive={false}460+ onDownload={() => onDownload(theme)}461+ onDuplicate={() => onDuplicate(theme)}462+ onEdit={() => onEdit(theme)}463+ onRemove={() => onRemove(theme)}464+ onUse={selectCollectionDefaults}465+ onUseMode={(mode) => onUseMode(theme, mode)}466+ theme={getThemeCardDefinition(theme)}467+ {...(themes.length > 1468+ ? {469+ variantNavigation: {470+ collectionLabel,471+ options: themes.map((variant, index) => ({472+ label: variantLabels[index] ?? variant.label,473+ activeModes: activeModesFor(variant.id),474+ preview: getThemeCardDefinition(variant).previews[0],475+ })),
- apps/web/src/openVsxThemes.ts line 120Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +100,21 @@100+};101+102+export type OpenVsxThemeSearchOptions = {103+ signal?: AbortSignal;104+ sortBy?: OpenVsxThemeSort;105+};106+107+type ThemeContribution = { label?: unknown; uiTheme?: unknown; path?: unknown };108+109+function isRecord(value: unknown): value is Record<string, unknown> {110+ return typeof value === "object" && value !== null && !Array.isArray(value);111+}112+113+function shortHash(value: string): string {114+ return [...sha256(new TextEncoder().encode(value))]115+ .slice(0, 6)116+ .map((byte) => byte.toString(16).padStart(2, "0"))117+ .join("");118+}119+120+function openVsxThemeId(extensionId: string, source: string): string {apps/web/src/themePalette.ts line 1738Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1664,0 +1714,21 @@1714+ const validated = themes.map((theme) => parseStoredTheme(theme));1715+ if (1716+ validated.some((theme) => theme === null || theme.collection?.id !== collectionId) ||1717+ new Set(validated.map((theme) => theme?.id)).size !== validated.length1718+ ) {1719+ throw new Error("That theme collection is invalid.");1720+ }1721+ const replacement = validated as ThemeDefinition[];1722+ const library = readWritableCustomThemeLibrary();1723+ const current = library.themes;1724+ const currentCollection = current.filter((theme) => theme.collection?.id === collectionId);1725+ if (1726+ options?.expectedCollection &&1727+ JSON.stringify(currentCollection) !== JSON.stringify(options.expectedCollection)1728+ ) {1729+ throw new Error("Your installed themes changed while this package was downloading. Try again.");1730+ }1731+ const occupiedIds = new Set(BUILT_IN_THEME_DEFINITIONS.map((theme) => theme.id));1732+ for (const storedTheme of library.storedThemes) {1733+ if (1734+ !storedThemeHasCollectionId(storedTheme, collectionId) &&apps/web/src/components/settings/ThemeSettings.tsx line 474OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -226,0 +454,21 @@454+ };455+456+ return (457+ <ThemeLibraryCard458+ activeModes={activeModesFor(theme.id)}459+ isActive={false}460+ onDownload={() => onDownload(theme)}461+ onDuplicate={() => onDuplicate(theme)}462+ onEdit={() => onEdit(theme)}463+ onRemove={() => onRemove(theme)}464+ onUse={selectCollectionDefaults}465+ onUseMode={(mode) => onUseMode(theme, mode)}466+ theme={getThemeCardDefinition(theme)}467+ {...(themes.length > 1468+ ? {469+ variantNavigation: {470+ collectionLabel,471+ options: themes.map((variant, index) => ({472+ label: variantLabels[index] ?? variant.label,473+ activeModes: activeModesFor(variant.id),474+ preview: getThemeCardDefinition(variant).previews[0],
- apps/web/src/components/settings/ThemeSettings.tsx line 241Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -113,0 +220,21 @@220+ <SunIcon className="size-2.5" />221+ ) : (222+ <MoonIcon className="size-2.5" />223+ )}224+ </span>225+ ) : null}226+ </button>227+ </ThemeVariantTooltip>228+ <span229+ className="pointer-events-none absolute bottom-0 left-1/2 inline-flex max-w-24 -translate-x-1/2 items-center gap-1 text-[11px] font-medium text-foreground"230+ style={{ marginLeft: rootOffsetX }}231+ >232+ <span className="truncate">{selected.option.label}</span>233+ {options.length > 1 ? (234+ <span className="shrink-0 rounded-full bg-muted px-1 text-[9px] text-muted-foreground">235+ +{options.length - 1}236+ </span>237+ ) : null}238+ </span>239+ {options.length > 1240+ ? options.map(({ option, preview }, optionIndex) => {
juliusmarminge merged thisf0b57ca
juliusmarminge closed this
Sign in to join this conversation.



macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed