Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ee0d31d5e6 | ||
|
|
dd8a0db88b | ||
|
|
62d130714d | ||
|
|
af4383e893 | ||
|
|
a33718663d | ||
|
|
59e1bd230c | ||
|
|
bd9e3f953d | ||
|
|
7bcd756fc5 | ||
|
|
4b78960aff | ||
|
|
784493f144 | ||
|
|
d11283bac6 | ||
|
|
8779f184bb | ||
|
|
4e5bafcff7 | ||
|
|
64490d4c65 | ||
|
|
d1d74f1397 |
No files matched your search
@@ -23,6 +23,7 @@
|
||||
"@formkit/auto-animate": "^0.9.0",
|
||||
"@legendapp/list": "3.3.3",
|
||||
"@lexical/react": "^0.41.0",
|
||||
"@noble/hashes": "catalog:",
|
||||
"@pierre/diffs": "catalog:",
|
||||
"@pierre/trees": "1.0.0-beta.4",
|
||||
"@t3tools/client-runtime": "workspace:*",
|
||||
@@ -33,6 +34,8 @@
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"effect": "catalog:",
|
||||
"jose": "catalog:",
|
||||
"jsonc-parser": "3.3.1",
|
||||
"jszip": "3.10.1",
|
||||
"lexical": "^0.41.0",
|
||||
"lucide-react": "^0.564.0",
|
||||
"react": "19.2.6",
|
||||
|
||||
@@ -663,8 +663,8 @@ export function ThemeEditorPanel({
|
||||
return;
|
||||
}
|
||||
mergedAppearance = editedModes[0] ?? null;
|
||||
savedTheme = updateCustomTheme(
|
||||
parseThemeFile({
|
||||
savedTheme = updateCustomTheme({
|
||||
...parseThemeFile({
|
||||
version: THEME_FILE_VERSION,
|
||||
id: mergeTarget.id,
|
||||
name: mergeTarget.label,
|
||||
@@ -677,7 +677,8 @@ export function ThemeEditorPanel({
|
||||
...(sidebarArtwork ? { sidebarArtwork: true } : {}),
|
||||
...(mergeTarget.managed === true && !isAdvanced ? { managed: true } : {}),
|
||||
}),
|
||||
);
|
||||
...(mergeTarget.collection ? { collection: mergeTarget.collection } : {}),
|
||||
});
|
||||
retiredTheme = editingTheme;
|
||||
try {
|
||||
removeCustomTheme(editingTheme.id);
|
||||
@@ -695,8 +696,8 @@ export function ThemeEditorPanel({
|
||||
} else if (editingTheme) {
|
||||
const baseAppearance = editingTheme.appearance;
|
||||
const variantAppearance = baseAppearance === "light" ? "dark" : "light";
|
||||
savedTheme = updateCustomTheme(
|
||||
parseThemeFile({
|
||||
savedTheme = updateCustomTheme({
|
||||
...parseThemeFile({
|
||||
version: THEME_FILE_VERSION,
|
||||
id: editingTheme.id,
|
||||
name,
|
||||
@@ -708,7 +709,8 @@ export function ThemeEditorPanel({
|
||||
...(sidebarArtwork ? { sidebarArtwork: true } : {}),
|
||||
...(isAdvanced ? {} : { managed: true }),
|
||||
}),
|
||||
);
|
||||
...(editingTheme.collection ? { collection: editingTheme.collection } : {}),
|
||||
});
|
||||
} else if (mergeTarget) {
|
||||
if (takenAppearances.includes(activeAppearance)) {
|
||||
setError(
|
||||
@@ -721,8 +723,8 @@ export function ThemeEditorPanel({
|
||||
// survives when every palette in the theme came from the guided
|
||||
// editor.
|
||||
mergedAppearance = activeAppearance;
|
||||
savedTheme = updateCustomTheme(
|
||||
parseThemeFile({
|
||||
savedTheme = updateCustomTheme({
|
||||
...parseThemeFile({
|
||||
version: THEME_FILE_VERSION,
|
||||
id: mergeTarget.id,
|
||||
name: mergeTarget.label,
|
||||
@@ -735,7 +737,8 @@ export function ThemeEditorPanel({
|
||||
...(sidebarArtwork ? { sidebarArtwork: true } : {}),
|
||||
...(mergeTarget.managed === true && !isAdvanced ? { managed: true } : {}),
|
||||
}),
|
||||
);
|
||||
...(mergeTarget.collection ? { collection: mergeTarget.collection } : {}),
|
||||
});
|
||||
} else {
|
||||
savedTheme = installCustomTheme(
|
||||
parseThemeFile({
|
||||
|
||||
@@ -28,6 +28,7 @@ import {
|
||||
DialogPopup,
|
||||
DialogTitle,
|
||||
} from "../ui/dialog";
|
||||
import { ThemeSearchSection } from "./ThemeSearchSection";
|
||||
|
||||
/**
|
||||
* A full theme export is a few KB, so anything past this is not a theme file.
|
||||
@@ -360,9 +361,16 @@ export function ThemeImportDialog({
|
||||
: null;
|
||||
for (const theme of conflicts) {
|
||||
try {
|
||||
const existingTheme =
|
||||
mode === "update"
|
||||
? getCustomThemes().find((candidate) => candidate.id === theme.id)
|
||||
: undefined;
|
||||
const themeToUpdate = existingTheme?.collection
|
||||
? { ...theme, collection: existingTheme.collection }
|
||||
: theme;
|
||||
resolved.push(
|
||||
mode === "update"
|
||||
? updateCustomTheme(theme)
|
||||
? updateCustomTheme(themeToUpdate)
|
||||
: installCustomTheme(versionedCopy(theme, preferredName)),
|
||||
);
|
||||
} catch (cause) {
|
||||
@@ -426,7 +434,23 @@ export function ThemeImportDialog({
|
||||
<DialogHeader>
|
||||
<DialogTitle>Add a theme</DialogTitle>
|
||||
</DialogHeader>
|
||||
<DialogPanel className="space-y-4">
|
||||
<DialogPanel className="space-y-5">
|
||||
<ThemeSearchSection
|
||||
onInstalled={(themes, context) => {
|
||||
onImportedMany(themes, context);
|
||||
onOpenChange(false);
|
||||
}}
|
||||
open={open}
|
||||
/>
|
||||
|
||||
<div className="flex items-center gap-3" aria-hidden>
|
||||
<div className="h-px flex-1 bg-border" />
|
||||
<span className="text-muted-foreground text-[11px] uppercase tracking-wider">
|
||||
or import a file
|
||||
</span>
|
||||
<div className="h-px flex-1 bg-border" />
|
||||
</div>
|
||||
|
||||
{(() => {
|
||||
const dropHandlers = {
|
||||
onDragEnter: (event: DragEvent<HTMLDivElement>) => {
|
||||
|
||||
@@ -0,0 +1,301 @@
|
||||
import {
|
||||
CheckCircle2Icon,
|
||||
PaletteIcon,
|
||||
PlusIcon,
|
||||
RefreshCwIcon,
|
||||
SearchIcon,
|
||||
ShieldCheckIcon,
|
||||
} from "lucide-react";
|
||||
import type { FormEvent } from "react";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import {
|
||||
importOpenVsxThemeExtension,
|
||||
searchOpenVsxThemes,
|
||||
type OpenVsxThemeExtension,
|
||||
} from "../../openVsxThemes";
|
||||
import {
|
||||
getCustomThemes,
|
||||
replaceCustomThemeCollection,
|
||||
type ThemeDefinition,
|
||||
} from "../../themePalette";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogClose,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogPopup,
|
||||
AlertDialogTitle,
|
||||
} from "../ui/alert-dialog";
|
||||
import { Button } from "../ui/button";
|
||||
import { Input } from "../ui/input";
|
||||
import { Spinner } from "../ui/spinner";
|
||||
|
||||
const DOWNLOAD_FORMAT = new Intl.NumberFormat(undefined, {
|
||||
notation: "compact",
|
||||
maximumFractionDigits: 1,
|
||||
});
|
||||
const SUGGESTED_SEARCHES = ["Dracula", "Catppuccin", "Nord", "Tokyo Night"];
|
||||
|
||||
export function ThemeSearchSection({
|
||||
open,
|
||||
onInstalled,
|
||||
}: {
|
||||
open: boolean;
|
||||
onInstalled: (themes: ReadonlyArray<ThemeDefinition>, context: { updated: boolean }) => void;
|
||||
}) {
|
||||
const [query, setQuery] = useState("");
|
||||
const [results, setResults] = useState<ReadonlyArray<OpenVsxThemeExtension> | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isSearching, setIsSearching] = useState(false);
|
||||
const [installingId, setInstallingId] = useState<string | null>(null);
|
||||
const [pendingUpdate, setPendingUpdate] = useState<OpenVsxThemeExtension | null>(null);
|
||||
const requestRef = useRef<AbortController | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
requestRef.current?.abort();
|
||||
requestRef.current = null;
|
||||
if (open) {
|
||||
setQuery("");
|
||||
setResults(null);
|
||||
setError(null);
|
||||
setIsSearching(false);
|
||||
setInstallingId(null);
|
||||
setPendingUpdate(null);
|
||||
}
|
||||
return () => {
|
||||
requestRef.current?.abort();
|
||||
requestRef.current = null;
|
||||
};
|
||||
}, [open]);
|
||||
|
||||
const runSearch = useCallback(async (searchText: string) => {
|
||||
const trimmed = searchText.trim();
|
||||
if (!trimmed) return;
|
||||
requestRef.current?.abort();
|
||||
const controller = new AbortController();
|
||||
requestRef.current = controller;
|
||||
setQuery(trimmed);
|
||||
setIsSearching(true);
|
||||
setError(null);
|
||||
setResults(null);
|
||||
try {
|
||||
const nextResults = await searchOpenVsxThemes(trimmed, controller.signal);
|
||||
if (!controller.signal.aborted) setResults(nextResults);
|
||||
} catch (cause) {
|
||||
if (!controller.signal.aborted) {
|
||||
setError(cause instanceof Error ? cause.message : "Open VSX search failed.");
|
||||
}
|
||||
} finally {
|
||||
if (requestRef.current === controller) {
|
||||
requestRef.current = null;
|
||||
setIsSearching(false);
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleSearch = useCallback(
|
||||
(event: FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
void runSearch(query);
|
||||
},
|
||||
[query, runSearch],
|
||||
);
|
||||
|
||||
const handleInstall = useCallback(
|
||||
async (extension: OpenVsxThemeExtension, allowUpdate: boolean) => {
|
||||
const updated = getCustomThemes().some(
|
||||
(theme) => theme.collection?.id === extension.collectionId,
|
||||
);
|
||||
if (updated && !allowUpdate) {
|
||||
setPendingUpdate(extension);
|
||||
return;
|
||||
}
|
||||
|
||||
requestRef.current?.abort();
|
||||
const controller = new AbortController();
|
||||
requestRef.current = controller;
|
||||
setInstallingId(extension.id);
|
||||
setError(null);
|
||||
try {
|
||||
const themes = await importOpenVsxThemeExtension(extension, controller.signal);
|
||||
if (controller.signal.aborted) return;
|
||||
const imported = replaceCustomThemeCollection(extension.collectionId, themes);
|
||||
onInstalled(imported, { updated });
|
||||
} catch (cause) {
|
||||
if (!controller.signal.aborted) {
|
||||
setError(cause instanceof Error ? cause.message : "That theme could not be added.");
|
||||
}
|
||||
} finally {
|
||||
if (requestRef.current === controller) {
|
||||
requestRef.current = null;
|
||||
setInstallingId(null);
|
||||
}
|
||||
}
|
||||
},
|
||||
[onInstalled],
|
||||
);
|
||||
|
||||
return (
|
||||
<section className="space-y-3" aria-labelledby="theme-search-heading">
|
||||
<div>
|
||||
<h3 className="text-sm font-medium" id="theme-search-heading">
|
||||
Search community themes
|
||||
</h3>
|
||||
<p className="mt-0.5 text-muted-foreground text-xs">
|
||||
Find open-source themes from Open VSX.
|
||||
</p>
|
||||
</div>
|
||||
<form className="relative flex gap-2" onSubmit={handleSearch}>
|
||||
<SearchIcon className="pointer-events-none absolute left-3 top-1/2 z-10 size-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
aria-label="Search Open VSX themes"
|
||||
className="rounded-xl [&_input]:pl-9"
|
||||
autoFocus
|
||||
onChange={(event) => setQuery(event.currentTarget.value)}
|
||||
placeholder="try dracula, nord, catppuccin..."
|
||||
size="lg"
|
||||
type="search"
|
||||
value={query}
|
||||
/>
|
||||
<Button
|
||||
disabled={!query.trim() || isSearching || installingId !== null}
|
||||
type="submit"
|
||||
variant="outline"
|
||||
>
|
||||
{isSearching ? <Spinner /> : <SearchIcon />}
|
||||
Search
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
<div className="sr-only" role="status">
|
||||
{isSearching
|
||||
? "Finding themes..."
|
||||
: results
|
||||
? `${results.length} supported ${results.length === 1 ? "theme" : "themes"} found.`
|
||||
: ""}
|
||||
</div>
|
||||
|
||||
{error ? (
|
||||
<div
|
||||
aria-live="polite"
|
||||
className="rounded-xl border border-destructive/30 bg-destructive/5 px-3 py-2 text-destructive text-sm"
|
||||
>
|
||||
{error}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{results === null && !isSearching ? (
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
<span className="mr-1 text-muted-foreground text-xs">Popular</span>
|
||||
{SUGGESTED_SEARCHES.map((suggestion) => (
|
||||
<Button
|
||||
key={suggestion}
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
onClick={() => void runSearch(suggestion)}
|
||||
>
|
||||
{suggestion}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{isSearching ? (
|
||||
<div className="flex min-h-20 items-center justify-center gap-2 text-muted-foreground text-sm">
|
||||
<Spinner /> Finding themes...
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{results ? (
|
||||
results.length === 0 ? (
|
||||
<div className="flex min-h-40 flex-col items-center justify-center rounded-2xl border border-dashed text-center">
|
||||
<p className="text-sm font-medium">No supported open-source themes found</p>
|
||||
<p className="mt-1 text-muted-foreground text-xs">Try a broader search.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
{results.map((extension) => {
|
||||
const isInstalling = installingId === extension.id;
|
||||
const isInstalled = getCustomThemes().some(
|
||||
(theme) => theme.collection?.id === extension.collectionId,
|
||||
);
|
||||
const action = isInstalled ? "Update" : "Add";
|
||||
const progressAction = isInstalled ? "Updating" : "Adding";
|
||||
return (
|
||||
<article
|
||||
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"
|
||||
key={extension.id}
|
||||
>
|
||||
<div className="flex min-w-0 gap-3">
|
||||
<div className="flex size-10 shrink-0 items-center justify-center rounded-lg bg-muted text-muted-foreground">
|
||||
<PaletteIcon className="size-4" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<h4 className="truncate text-sm font-medium">{extension.name}</h4>
|
||||
<p className="truncate text-muted-foreground text-xs">
|
||||
{extension.publisher} · {DOWNLOAD_FORMAT.format(extension.downloadCount)}{" "}
|
||||
downloads
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<p className="line-clamp-2 min-h-8 text-muted-foreground text-xs leading-4">
|
||||
{extension.description || "A community color theme for your editor."}
|
||||
</p>
|
||||
<div className="mt-auto flex items-center justify-between gap-2">
|
||||
<span className="inline-flex items-center gap-1 text-muted-foreground text-[11px]">
|
||||
<ShieldCheckIcon className="size-3" /> {extension.license}
|
||||
</span>
|
||||
<Button
|
||||
aria-label={`${isInstalling ? progressAction : action} ${extension.name}`}
|
||||
disabled={installingId !== null}
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={() => void handleInstall(extension, false)}
|
||||
>
|
||||
{isInstalling ? <Spinner /> : isInstalled ? <RefreshCwIcon /> : <PlusIcon />}
|
||||
{isInstalling ? `${progressAction}...` : action}
|
||||
</Button>
|
||||
</div>
|
||||
</article>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
) : null}
|
||||
|
||||
<div className="flex items-center gap-1.5 text-muted-foreground text-[11px]">
|
||||
<CheckCircle2Icon className="size-3" /> Licensed themes only, with package integrity checks
|
||||
</div>
|
||||
|
||||
<AlertDialog
|
||||
open={pendingUpdate !== null}
|
||||
onOpenChange={(nextOpen) => {
|
||||
if (!nextOpen) setPendingUpdate(null);
|
||||
}}
|
||||
>
|
||||
<AlertDialogPopup>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Update “{pendingUpdate?.name}”?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
This replaces its installed variants, including any local edits. Variants no longer in
|
||||
the extension will be removed.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
|
||||
<Button
|
||||
onClick={() => {
|
||||
const extension = pendingUpdate;
|
||||
setPendingUpdate(null);
|
||||
if (extension) void handleInstall(extension, true);
|
||||
}}
|
||||
>
|
||||
Update theme
|
||||
</Button>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogPopup>
|
||||
</AlertDialog>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
import {
|
||||
ChevronLeftIcon,
|
||||
ChevronRightIcon,
|
||||
CopyIcon,
|
||||
DownloadIcon,
|
||||
PenLineIcon,
|
||||
@@ -75,6 +77,7 @@ function ThemeLibraryCard({
|
||||
onDuplicate,
|
||||
onDownload,
|
||||
onRemove,
|
||||
variantNavigation,
|
||||
}: {
|
||||
theme: ThemeCardDefinition;
|
||||
isActive: boolean;
|
||||
@@ -85,6 +88,17 @@ function ThemeLibraryCard({
|
||||
onDuplicate?: () => void;
|
||||
onDownload?: () => void;
|
||||
onRemove?: () => void;
|
||||
variantNavigation?: {
|
||||
collectionLabel: string;
|
||||
index: number;
|
||||
count: number;
|
||||
activeAssignments: ReadonlyArray<{
|
||||
mode: ThemeAppearance;
|
||||
label: string;
|
||||
}>;
|
||||
onPrevious: () => void;
|
||||
onNext: () => void;
|
||||
};
|
||||
}) {
|
||||
// A one-appearance theme can only take its own side of the mix, so the card
|
||||
// tooltip promises exactly what clicking it does.
|
||||
@@ -111,11 +125,55 @@ function ThemeLibraryCard({
|
||||
onSelectMode={onUseMode}
|
||||
previews={theme.previews}
|
||||
/>
|
||||
{variantNavigation ? (
|
||||
<div
|
||||
className="flex items-center gap-1 border-t border-border/50 px-2 py-1"
|
||||
aria-label={variantNavigation.collectionLabel}
|
||||
>
|
||||
<Button
|
||||
aria-label={`Previous ${variantNavigation.collectionLabel} variant`}
|
||||
size="icon-xs"
|
||||
variant="ghost"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
variantNavigation.onPrevious();
|
||||
}}
|
||||
>
|
||||
<ChevronLeftIcon />
|
||||
</Button>
|
||||
<div
|
||||
className="min-w-0 flex-1 text-center text-xs text-muted-foreground"
|
||||
aria-live="polite"
|
||||
>
|
||||
<div className="truncate">
|
||||
{theme.label} · {variantNavigation.index + 1} of {variantNavigation.count}
|
||||
</div>
|
||||
{variantNavigation.activeAssignments.length > 0 ? (
|
||||
<div className="truncate text-[10px]">
|
||||
{variantNavigation.activeAssignments
|
||||
.map(({ mode, label }) => `${mode}: ${label}`)
|
||||
.join(" · ")}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
<Button
|
||||
aria-label={`Next ${variantNavigation.collectionLabel} variant`}
|
||||
size="icon-xs"
|
||||
variant="ghost"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
variantNavigation.onNext();
|
||||
}}
|
||||
>
|
||||
<ChevronRightIcon />
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
<div className="flex items-center gap-2 px-3 pb-3 pt-2">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<button
|
||||
aria-label={`Use ${theme.label} theme${isActive ? ", currently active" : ""}`}
|
||||
aria-label={`Use ${variantNavigation ? `${variantNavigation.collectionLabel}, ${theme.label} variant` : `${theme.label} theme`}${isActive ? ", currently active" : ""}`}
|
||||
aria-pressed={isActive}
|
||||
className="min-w-0 cursor-pointer truncate rounded-sm text-left text-sm font-medium text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-card"
|
||||
type="button"
|
||||
@@ -124,7 +182,7 @@ function ThemeLibraryCard({
|
||||
onUse();
|
||||
}}
|
||||
>
|
||||
{theme.label}
|
||||
{variantNavigation?.collectionLabel ?? theme.label}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -224,6 +282,73 @@ function ThemeLibraryCard({
|
||||
);
|
||||
}
|
||||
|
||||
function CustomThemeCollectionCard({
|
||||
themes,
|
||||
activeModesFor,
|
||||
onUse,
|
||||
onUseMode,
|
||||
onDuplicate,
|
||||
onEdit,
|
||||
onDownload,
|
||||
onRemove,
|
||||
}: {
|
||||
themes: ReadonlyArray<ThemeDefinition>;
|
||||
activeModesFor: (themeId: string) => ReadonlyArray<ThemeMode>;
|
||||
onUse: (theme: ThemeDefinition) => void;
|
||||
onUseMode: (theme: ThemeDefinition, mode: ThemeMode) => void;
|
||||
onDuplicate: (theme: ThemeDefinition) => void;
|
||||
onEdit: (theme: ThemeDefinition) => void;
|
||||
onDownload: (theme: ThemeDefinition) => void;
|
||||
onRemove: (theme: ThemeDefinition) => void;
|
||||
}) {
|
||||
const [variantIndex, setVariantIndex] = useState(() => {
|
||||
const activeIndex = themes.findIndex((theme) => activeModesFor(theme.id).length > 0);
|
||||
return activeIndex < 0 ? 0 : activeIndex;
|
||||
});
|
||||
const safeIndex = Math.min(variantIndex, themes.length - 1);
|
||||
const theme = themes[safeIndex];
|
||||
|
||||
useEffect(() => {
|
||||
if (variantIndex !== safeIndex) setVariantIndex(safeIndex);
|
||||
}, [safeIndex, variantIndex]);
|
||||
|
||||
if (!theme) return null;
|
||||
const collectionLabel = theme.collection?.label ?? theme.label;
|
||||
const activeAssignments = (["light", "dark"] as const).flatMap((mode) => {
|
||||
const assignedTheme = themes.find((candidate) => activeModesFor(candidate.id).includes(mode));
|
||||
return assignedTheme ? [{ mode, label: assignedTheme.label }] : [];
|
||||
});
|
||||
const move = (offset: number) => {
|
||||
setVariantIndex((current) => (current + offset + themes.length) % themes.length);
|
||||
};
|
||||
|
||||
return (
|
||||
<ThemeLibraryCard
|
||||
activeModes={activeModesFor(theme.id)}
|
||||
isActive={false}
|
||||
onDownload={() => onDownload(theme)}
|
||||
onDuplicate={() => onDuplicate(theme)}
|
||||
onEdit={() => onEdit(theme)}
|
||||
onRemove={() => onRemove(theme)}
|
||||
onUse={() => onUse(theme)}
|
||||
onUseMode={(mode) => onUseMode(theme, mode)}
|
||||
theme={getThemeCardDefinition(theme)}
|
||||
{...(themes.length > 1
|
||||
? {
|
||||
variantNavigation: {
|
||||
collectionLabel,
|
||||
index: safeIndex,
|
||||
count: themes.length,
|
||||
activeAssignments,
|
||||
onPrevious: () => move(-1),
|
||||
onNext: () => move(1),
|
||||
},
|
||||
}
|
||||
: {})}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ThemeLibrary({
|
||||
theme,
|
||||
setTheme,
|
||||
@@ -460,6 +585,18 @@ export function ThemeLibrary({
|
||||
</div>
|
||||
);
|
||||
|
||||
const customThemeCollections = [
|
||||
...customThemes
|
||||
.reduce((groups, customTheme) => {
|
||||
const groupId = customTheme.collection?.id ?? `theme:${customTheme.id}`;
|
||||
const group = groups.get(groupId);
|
||||
if (group) group.push(customTheme);
|
||||
else groups.set(groupId, [customTheme]);
|
||||
return groups;
|
||||
}, new Map<string, ThemeDefinition[]>())
|
||||
.entries(),
|
||||
];
|
||||
|
||||
const renderPairGrid = () => (
|
||||
// One shared provider so every tooltip in the grid hands off instantly to
|
||||
// the next hovered trigger instead of stacking on top of it. The card
|
||||
@@ -501,43 +638,39 @@ export function ThemeLibrary({
|
||||
/>
|
||||
);
|
||||
})}
|
||||
{customThemes.map((customTheme) => {
|
||||
const card = getThemeCardDefinition(customTheme);
|
||||
return (
|
||||
<ThemeLibraryCard
|
||||
activeModes={pickedModesFor(customTheme.id)}
|
||||
isActive={false}
|
||||
key={customTheme.id}
|
||||
onDuplicate={() =>
|
||||
openThemeEditor({
|
||||
editingThemeId: null,
|
||||
seedThemeId: customTheme.id,
|
||||
seedName: `${customTheme.label} copy`,
|
||||
initialAppearance,
|
||||
})
|
||||
}
|
||||
onEdit={() =>
|
||||
openThemeEditor({
|
||||
editingThemeId: customTheme.id,
|
||||
seedThemeId: null,
|
||||
seedName: null,
|
||||
initialAppearance,
|
||||
})
|
||||
}
|
||||
onDownload={() =>
|
||||
downloadThemeFile(`${customTheme.id}.json`, serializeThemeFile(customTheme))
|
||||
}
|
||||
onRemove={() => handleRemoveTheme(customTheme)}
|
||||
onUse={() => {
|
||||
const modes = getThemeModes(customTheme);
|
||||
if (modes.length === 1) assignHalf(modes[0]!, customTheme.id);
|
||||
else persistTheme(customTheme.id);
|
||||
}}
|
||||
onUseMode={handlePairPick(customTheme.id)}
|
||||
theme={card}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
{customThemeCollections.map(([collectionId, themes]) => (
|
||||
<CustomThemeCollectionCard
|
||||
activeModesFor={pickedModesFor}
|
||||
key={collectionId}
|
||||
onDownload={(customTheme) =>
|
||||
downloadThemeFile(`${customTheme.id}.json`, serializeThemeFile(customTheme))
|
||||
}
|
||||
onDuplicate={(customTheme) =>
|
||||
openThemeEditor({
|
||||
editingThemeId: null,
|
||||
seedThemeId: customTheme.id,
|
||||
seedName: `${customTheme.label} copy`,
|
||||
initialAppearance,
|
||||
})
|
||||
}
|
||||
onEdit={(customTheme) =>
|
||||
openThemeEditor({
|
||||
editingThemeId: customTheme.id,
|
||||
seedThemeId: null,
|
||||
seedName: null,
|
||||
initialAppearance,
|
||||
})
|
||||
}
|
||||
onRemove={handleRemoveTheme}
|
||||
onUse={(customTheme) => {
|
||||
const modes = getThemeModes(customTheme);
|
||||
if (modes.length === 1) assignHalf(modes[0]!, customTheme.id);
|
||||
else persistTheme(customTheme.id);
|
||||
}}
|
||||
onUseMode={(customTheme, mode) => handlePairPick(customTheme.id)(mode)}
|
||||
themes={themes}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
);
|
||||
@@ -553,9 +686,8 @@ export function ThemeLibrary({
|
||||
{renderModeTiles()}
|
||||
<div className="flex min-h-8 flex-wrap items-center justify-between gap-3 px-3 pt-2 sm:px-4">
|
||||
<h3 className="text-sm font-medium tracking-[-0.005em] text-foreground">Themes</h3>
|
||||
<div className="flex flex-wrap items-center justify-end gap-3">
|
||||
<div className="flex flex-wrap items-center justify-end gap-2">
|
||||
<Button
|
||||
className="h-7 rounded-md border border-border/70 bg-muted/30 px-2 text-xs font-medium text-foreground shadow-none hover:bg-accent/40"
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
onClick={() =>
|
||||
@@ -579,19 +711,9 @@ export function ThemeLibrary({
|
||||
{renderPairGrid()}
|
||||
<ThemeImportDialog
|
||||
onImportedMany={(importedThemes, { updated }) => {
|
||||
// An updated theme that is showing (as the base or either half)
|
||||
// needs its palette re-applied.
|
||||
if (
|
||||
updated &&
|
||||
importedThemes.some(
|
||||
(imported) =>
|
||||
getThemeDefinition(theme)?.id === imported.id ||
|
||||
themeHalves?.light === imported.id ||
|
||||
themeHalves?.dark === imported.id,
|
||||
)
|
||||
) {
|
||||
refreshTheme();
|
||||
}
|
||||
// Re-apply after collection updates. The update may remove the
|
||||
// selected variant, in which case the theme hook falls back safely.
|
||||
if (updated) refreshTheme();
|
||||
const verb = updated ? "updated" : "added";
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
|
||||
@@ -0,0 +1,396 @@
|
||||
import { sha256 } from "@noble/hashes/sha2";
|
||||
import JSZip from "jszip";
|
||||
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
importOpenVsxThemeExtension,
|
||||
searchOpenVsxThemes,
|
||||
type OpenVsxThemeExtension,
|
||||
} from "./openVsxThemes";
|
||||
import { getThemeColorsForMode } from "./themePalette";
|
||||
|
||||
const ASSET_ROOT = "https://open-vsx.org/api/demo/theme/1.0.0/file";
|
||||
|
||||
function extensionDetail(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
namespace: "demo",
|
||||
name: "theme",
|
||||
displayName: "Demo Theme",
|
||||
description: "A nice theme",
|
||||
version: "1.0.0",
|
||||
downloadCount: 123456,
|
||||
license: "MIT",
|
||||
files: {
|
||||
icon: `${ASSET_ROOT}/icon.png`,
|
||||
manifest: `${ASSET_ROOT}/package.json`,
|
||||
sha256: `${ASSET_ROOT}/demo.theme-1.0.0.sha256`,
|
||||
download: `${ASSET_ROOT}/demo.theme-1.0.0.vsix`,
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe("Open VSX themes", () => {
|
||||
it("searches theme extensions and keeps only supported open-source licenses", async () => {
|
||||
const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
|
||||
const url = String(input);
|
||||
if (url.includes("/-/search?")) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
extensions: [
|
||||
{ namespace: "demo", name: "theme" },
|
||||
{ namespace: "icons", name: "theme" },
|
||||
{ namespace: "oversized", name: "theme" },
|
||||
{ namespace: "closed", name: "theme" },
|
||||
{ namespace: "huge", name: "theme" },
|
||||
],
|
||||
}),
|
||||
{ status: 200 },
|
||||
);
|
||||
}
|
||||
if (url.endsWith("/icons/theme")) {
|
||||
return new Response(
|
||||
JSON.stringify(
|
||||
extensionDetail({
|
||||
namespace: "icons",
|
||||
files: {
|
||||
...extensionDetail().files,
|
||||
manifest: `${ASSET_ROOT.replace("demo/theme", "icons/theme")}/package.json`,
|
||||
},
|
||||
}),
|
||||
),
|
||||
{ status: 200 },
|
||||
);
|
||||
}
|
||||
if (url.endsWith("/oversized/theme")) {
|
||||
return new Response(
|
||||
JSON.stringify(
|
||||
extensionDetail({
|
||||
namespace: "oversized",
|
||||
files: {
|
||||
...extensionDetail().files,
|
||||
download: `${ASSET_ROOT.replace("demo/theme", "oversized/theme")}/oversized.vsix`,
|
||||
},
|
||||
}),
|
||||
),
|
||||
{ status: 200 },
|
||||
);
|
||||
}
|
||||
if (url.endsWith("/closed/theme")) {
|
||||
return new Response(
|
||||
JSON.stringify(extensionDetail({ namespace: "closed", license: "All Rights Reserved" })),
|
||||
{ status: 200 },
|
||||
);
|
||||
}
|
||||
if (url.endsWith("/huge/theme")) {
|
||||
return new Response(JSON.stringify({ padding: "x".repeat(256 * 1024) }), { status: 200 });
|
||||
}
|
||||
if (url.endsWith("/oversized/theme/1.0.0/file/oversized.vsix")) {
|
||||
return new Response(null, {
|
||||
headers: { "content-length": String(20 * 1024 * 1024 + 1) },
|
||||
status: 200,
|
||||
});
|
||||
}
|
||||
if (url.endsWith(".vsix")) {
|
||||
return new Response(null, { headers: { "content-length": "1024" }, status: 200 });
|
||||
}
|
||||
if (url.endsWith("/icons/theme/1.0.0/file/package.json")) {
|
||||
return new Response(JSON.stringify({ contributes: { iconThemes: [{}] } }), { status: 200 });
|
||||
}
|
||||
if (url.endsWith("/demo/theme/1.0.0/file/package.json")) {
|
||||
return new Response(
|
||||
JSON.stringify({ contributes: { themes: [{ path: "./theme.json" }] } }),
|
||||
{ status: 200 },
|
||||
);
|
||||
}
|
||||
return new Response(JSON.stringify(extensionDetail()), { status: 200 });
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
const results = await searchOpenVsxThemes(" dracula ");
|
||||
|
||||
expect(results).toEqual([
|
||||
expect.objectContaining({
|
||||
id: "demo.theme",
|
||||
name: "Demo Theme",
|
||||
publisher: "demo",
|
||||
downloadCount: 123456,
|
||||
license: "MIT",
|
||||
}),
|
||||
]);
|
||||
const searchUrl = new URL(String(fetchMock.mock.calls[0]![0]));
|
||||
expect(searchUrl.searchParams.get("query")).toBe("dracula");
|
||||
expect(searchUrl.searchParams.get("category")).toBe("Themes");
|
||||
expect(searchUrl.searchParams.get("size")).toBe("16");
|
||||
});
|
||||
|
||||
it("reports an unavailable search when every detail request fails", async () => {
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async (input: RequestInfo | URL) => {
|
||||
if (String(input).includes("/-/search?")) {
|
||||
return new Response(
|
||||
JSON.stringify({ extensions: [{ namespace: "demo", name: "theme" }] }),
|
||||
{ status: 200 },
|
||||
);
|
||||
}
|
||||
return new Response(null, { status: 429 });
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(searchOpenVsxThemes("dracula")).rejects.toThrow(
|
||||
"Open VSX theme details are unavailable",
|
||||
);
|
||||
});
|
||||
|
||||
it("reports an unavailable search when every detail response is malformed", async () => {
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async (input: RequestInfo | URL) => {
|
||||
if (String(input).includes("/-/search?")) {
|
||||
return new Response(
|
||||
JSON.stringify({ extensions: [{ namespace: "demo", name: "theme" }] }),
|
||||
{ status: 200 },
|
||||
);
|
||||
}
|
||||
return new Response("{}", { status: 200 });
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(searchOpenVsxThemes("dracula")).rejects.toThrow(
|
||||
"Open VSX theme details are unavailable",
|
||||
);
|
||||
});
|
||||
|
||||
it("times out a stalled search request", async () => {
|
||||
vi.useFakeTimers();
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(
|
||||
(_input: RequestInfo | URL, init?: RequestInit) =>
|
||||
new Promise<Response>((_resolve, reject) => {
|
||||
init?.signal?.addEventListener("abort", () => {
|
||||
reject(new DOMException("The operation was aborted.", "AbortError"));
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const search = expect(searchOpenVsxThemes("dracula")).rejects.toThrow(
|
||||
"Open VSX took too long to respond",
|
||||
);
|
||||
await vi.advanceTimersByTimeAsync(10_000);
|
||||
|
||||
await search;
|
||||
});
|
||||
|
||||
it("downloads a verified VSIX, reads JSONC includes, and pairs contributed variants", async () => {
|
||||
const zip = new JSZip();
|
||||
zip.file(
|
||||
"extension/themes/base.jsonc",
|
||||
`{
|
||||
// inherited workbench colors
|
||||
"colors": {
|
||||
"editor.foreground": "#eeeeee",
|
||||
"focusBorder": "#8b5cf6",
|
||||
},
|
||||
}`,
|
||||
);
|
||||
zip.file(
|
||||
"extension/themes/demo-dark.json",
|
||||
`{
|
||||
"include": "./base.jsonc",
|
||||
"colors": { "editor.background": "#111111" }
|
||||
}`,
|
||||
);
|
||||
zip.file(
|
||||
"extension/themes/demo-light.json",
|
||||
`{
|
||||
"colors": {
|
||||
"editor.background": "#fafafa",
|
||||
"editor.foreground": "#222222",
|
||||
"focusBorder": "#8b5cf6"
|
||||
}
|
||||
}`,
|
||||
);
|
||||
zip.file(
|
||||
"extension/themes/demo.json",
|
||||
`{
|
||||
"colors": {
|
||||
"editor.background": "#181818",
|
||||
"editor.foreground": "#eeeeee"
|
||||
}
|
||||
}`,
|
||||
);
|
||||
const packagedManifest = {
|
||||
publisher: "demo",
|
||||
name: "theme",
|
||||
version: "1.0.0",
|
||||
license: "MIT",
|
||||
contributes: {
|
||||
themes: [
|
||||
{ label: "Demo Dark", uiTheme: "vs-dark", path: "./themes/demo-dark.json" },
|
||||
{ label: "Demo Light", uiTheme: "vs", path: "./themes/demo-light.json" },
|
||||
{ label: "Demo", uiTheme: "vs-dark", path: "./themes/demo.json" },
|
||||
],
|
||||
},
|
||||
};
|
||||
let packageBytes = new ArrayBuffer(0);
|
||||
let checksum = "";
|
||||
const rebuildPackage = async () => {
|
||||
zip.file("extension/package.json", JSON.stringify(packagedManifest));
|
||||
packageBytes = await zip.generateAsync({
|
||||
type: "arraybuffer",
|
||||
comment: `PK\u0005\u0006${"x".repeat(26)}`,
|
||||
});
|
||||
checksum = [...sha256(new Uint8Array(packageBytes))]
|
||||
.map((byte) => byte.toString(16).padStart(2, "0"))
|
||||
.join("");
|
||||
};
|
||||
await rebuildPackage();
|
||||
// The public manifest is only a preflight hint. Imports must use the manifest
|
||||
// inside the checksummed VSIX rather than this inconsistent contribution.
|
||||
const manifest = {
|
||||
contributes: { themes: [{ label: "Wrong", path: "./themes/missing.json" }] },
|
||||
};
|
||||
const extension: OpenVsxThemeExtension = {
|
||||
collectionId: "open-vsx:demo.theme",
|
||||
id: "demo.theme",
|
||||
name: "Demo Theme",
|
||||
publisher: "demo",
|
||||
description: "",
|
||||
downloadCount: 1,
|
||||
license: "MIT",
|
||||
manifestUrl: `${ASSET_ROOT}/package.json`,
|
||||
sha256Url: `${ASSET_ROOT}/demo.theme-1.0.0.sha256`,
|
||||
version: "1.0.0",
|
||||
vsixUrl: `${ASSET_ROOT}/demo.theme-1.0.0.vsix`,
|
||||
};
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async (input: string | URL | Request) => {
|
||||
const url = String(input);
|
||||
if (url === extension.manifestUrl) {
|
||||
return new Response(JSON.stringify(manifest), { status: 200 });
|
||||
}
|
||||
if (url === extension.sha256Url) return new Response(`${checksum} demo.vsix`);
|
||||
return new Response(packageBytes, {
|
||||
status: 200,
|
||||
headers: { "Content-Length": String(packageBytes.byteLength) },
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
const themes = await importOpenVsxThemeExtension(extension);
|
||||
|
||||
expect(themes).toHaveLength(2);
|
||||
expect(new Set(themes.map((theme) => theme.id)).size).toBe(2);
|
||||
expect(themes.every((theme) => /^ovx-[a-z0-9-]+-[0-9a-f]{12}$/.test(theme.id))).toBe(true);
|
||||
expect(themes.every((theme) => theme.collection?.id === "open-vsx:demo.theme")).toBe(true);
|
||||
const paired = themes.find(
|
||||
(theme) =>
|
||||
getThemeColorsForMode(theme, "light") !== null &&
|
||||
getThemeColorsForMode(theme, "dark") !== null,
|
||||
)!;
|
||||
expect(paired.label).toBe("Demo");
|
||||
expect(paired.colors.canvas).toBe("#fafafa");
|
||||
expect(getThemeColorsForMode(paired, "dark")!.canvas).toBe("#111111");
|
||||
expect(getThemeColorsForMode(paired, "dark")!.text).toBe("#eeeeee");
|
||||
|
||||
packagedManifest.contributes.themes[0]!.label = "Renamed Dark";
|
||||
packagedManifest.contributes.themes[1]!.label = "Renamed Light";
|
||||
packagedManifest.contributes.themes[2]!.label = "Renamed Solo";
|
||||
await rebuildPackage();
|
||||
const renamedThemes = await importOpenVsxThemeExtension(extension);
|
||||
expect(renamedThemes.map((theme) => theme.id)).toEqual(themes.map((theme) => theme.id));
|
||||
|
||||
packagedManifest.license = "Proprietary";
|
||||
await rebuildPackage();
|
||||
await expect(importOpenVsxThemeExtension(extension)).rejects.toThrow(
|
||||
"does not match its advertised license",
|
||||
);
|
||||
|
||||
Reflect.deleteProperty(packagedManifest, "license");
|
||||
await rebuildPackage();
|
||||
await expect(importOpenVsxThemeExtension(extension)).rejects.toThrow(
|
||||
"does not match its advertised license",
|
||||
);
|
||||
});
|
||||
|
||||
it("stops import work when the request is cancelled", async () => {
|
||||
const packageBytes = new Uint8Array([1, 2, 3]);
|
||||
const checksum = [...sha256(packageBytes)]
|
||||
.map((byte) => byte.toString(16).padStart(2, "0"))
|
||||
.join("");
|
||||
const controller = new AbortController();
|
||||
const extension: OpenVsxThemeExtension = {
|
||||
collectionId: "open-vsx:demo.theme",
|
||||
id: "demo.theme",
|
||||
name: "Demo Theme",
|
||||
publisher: "demo",
|
||||
description: "",
|
||||
downloadCount: 1,
|
||||
license: "MIT",
|
||||
manifestUrl: `${ASSET_ROOT}/package.json`,
|
||||
sha256Url: `${ASSET_ROOT}/demo.theme-1.0.0.sha256`,
|
||||
version: "1.0.0",
|
||||
vsixUrl: `${ASSET_ROOT}/demo.theme-1.0.0.vsix`,
|
||||
};
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async (input: string | URL | Request) => {
|
||||
const url = String(input);
|
||||
if (url === extension.manifestUrl) {
|
||||
return new Response(
|
||||
JSON.stringify({ contributes: { themes: [{ path: "./theme.json" }] } }),
|
||||
);
|
||||
}
|
||||
if (url === extension.sha256Url) {
|
||||
controller.abort();
|
||||
return new Response(checksum);
|
||||
}
|
||||
return new Response(packageBytes);
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(importOpenVsxThemeExtension(extension, controller.signal)).rejects.toMatchObject({
|
||||
name: "AbortError",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects a package whose Open VSX checksum does not match", async () => {
|
||||
const extension: OpenVsxThemeExtension = {
|
||||
collectionId: "open-vsx:demo.theme",
|
||||
id: "demo.theme",
|
||||
name: "Demo Theme",
|
||||
publisher: "demo",
|
||||
description: "",
|
||||
downloadCount: 1,
|
||||
license: "MIT",
|
||||
manifestUrl: `${ASSET_ROOT}/package.json`,
|
||||
sha256Url: `${ASSET_ROOT}/demo.theme-1.0.0.sha256`,
|
||||
version: "1.0.0",
|
||||
vsixUrl: `${ASSET_ROOT}/demo.theme-1.0.0.vsix`,
|
||||
};
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async (input: string | URL | Request) => {
|
||||
const url = String(input);
|
||||
if (url === extension.manifestUrl) {
|
||||
return new Response(
|
||||
JSON.stringify({ contributes: { themes: [{ path: "./theme.json" }] } }),
|
||||
);
|
||||
}
|
||||
if (url === extension.sha256Url) return new Response("0".repeat(64));
|
||||
return new Response(new Uint8Array([1, 2, 3]));
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(importOpenVsxThemeExtension(extension)).rejects.toThrow("integrity check");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,723 @@
|
||||
import { sha256 } from "@noble/hashes/sha2";
|
||||
import JSZip from "jszip";
|
||||
import { parse, type ParseError } from "jsonc-parser";
|
||||
|
||||
import type { ThemeDefinition } from "./themePalette";
|
||||
import {
|
||||
isVsCodeThemeFile,
|
||||
pairVsCodeThemes,
|
||||
parseVsCodeThemeFile,
|
||||
resolveThemeLabelCollisions,
|
||||
} from "./vscodeThemeImport";
|
||||
|
||||
const OPEN_VSX_SEARCH_URL = "https://open-vsx.org/api/-/search";
|
||||
const MAX_VSIX_BYTES = 20 * 1024 * 1024;
|
||||
const MAX_SEARCH_BYTES = 512 * 1024;
|
||||
const MAX_DETAIL_BYTES = 256 * 1024;
|
||||
const MAX_MANIFEST_BYTES = 256 * 1024;
|
||||
const SEARCH_REQUEST_TIMEOUT_MS = 10_000;
|
||||
const MAX_THEME_BYTES = 256 * 1024;
|
||||
const MAX_ZIP_ENTRIES = 2_000;
|
||||
const MAX_UNCOMPRESSED_BYTES = 50 * 1024 * 1024;
|
||||
const MAX_COMPRESSION_RATIO = 200;
|
||||
const MAX_THEMES_PER_EXTENSION = 40;
|
||||
const MAX_INCLUDE_DEPTH = 8;
|
||||
const MAX_PACKAGE_PATH_LENGTH = 1_024;
|
||||
const MAX_COLOR_VALUE_LENGTH = 128;
|
||||
const MAX_RESOLVED_THEME_FILES = MAX_THEMES_PER_EXTENSION * MAX_INCLUDE_DEPTH;
|
||||
const SUPPORTED_LICENSES = new Set([
|
||||
"0BSD",
|
||||
"Apache-2.0",
|
||||
"BSD-2-Clause",
|
||||
"BSD-3-Clause",
|
||||
"CC0-1.0",
|
||||
"ISC",
|
||||
"MIT",
|
||||
"MPL-2.0",
|
||||
"Unlicense",
|
||||
]);
|
||||
const USED_WORKBENCH_COLORS = new Set([
|
||||
"activityBar.background",
|
||||
"activityBarBadge.background",
|
||||
"badge.background",
|
||||
"button.background",
|
||||
"button.foreground",
|
||||
"contrastBorder",
|
||||
"descriptionForeground",
|
||||
"disabledForeground",
|
||||
"dropdown.background",
|
||||
"dropdown.border",
|
||||
"editor.background",
|
||||
"editor.foreground",
|
||||
"editor.selectionBackground",
|
||||
"editorCursor.foreground",
|
||||
"editorError.foreground",
|
||||
"editorGroup.border",
|
||||
"editorPane.background",
|
||||
"editorWarning.foreground",
|
||||
"editorWidget.background",
|
||||
"errorForeground",
|
||||
"focusBorder",
|
||||
"foreground",
|
||||
"input.border",
|
||||
"input.placeholderForeground",
|
||||
"list.activeSelectionBackground",
|
||||
"list.hoverBackground",
|
||||
"list.inactiveSelectionBackground",
|
||||
"menu.background",
|
||||
"panel.background",
|
||||
"panel.border",
|
||||
"progressBar.background",
|
||||
"quickInput.background",
|
||||
"scrollbarSlider.background",
|
||||
"sideBar.background",
|
||||
"sideBar.border",
|
||||
"sideBar.foreground",
|
||||
"terminal.background",
|
||||
"terminal.foreground",
|
||||
"terminal.selectionBackground",
|
||||
"terminalCursor.foreground",
|
||||
"textCodeBlock.background",
|
||||
"textLink.foreground",
|
||||
]);
|
||||
|
||||
export type OpenVsxThemeExtension = {
|
||||
id: string;
|
||||
collectionId: string;
|
||||
name: string;
|
||||
publisher: string;
|
||||
description: string;
|
||||
downloadCount: number;
|
||||
manifestUrl: string;
|
||||
sha256Url: string;
|
||||
vsixUrl: string;
|
||||
version: string;
|
||||
license: string;
|
||||
};
|
||||
|
||||
type ThemeContribution = { label?: unknown; uiTheme?: unknown; path?: unknown };
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function shortHash(value: string): string {
|
||||
return [...sha256(new TextEncoder().encode(value))]
|
||||
.slice(0, 6)
|
||||
.map((byte) => byte.toString(16).padStart(2, "0"))
|
||||
.join("");
|
||||
}
|
||||
|
||||
function openVsxThemeId(extensionId: string, source: string): string {
|
||||
return `ovx-theme-${shortHash(`${extensionId}:${source}`)}`;
|
||||
}
|
||||
|
||||
function openVsxCollectionId(extensionId: string): string {
|
||||
const normalized = `open-vsx:${extensionId.toLowerCase()}`;
|
||||
return /^[a-z0-9][a-z0-9.:-]{0,127}$/.test(normalized)
|
||||
? normalized
|
||||
: `open-vsx:${shortHash(extensionId)}`;
|
||||
}
|
||||
|
||||
function trustedOpenVsxUrl(value: unknown): string | null {
|
||||
if (typeof value !== "string") return null;
|
||||
try {
|
||||
const url = new URL(value);
|
||||
return url.protocol === "https:" && url.hostname.toLowerCase() === "open-vsx.org"
|
||||
? url.toString()
|
||||
: null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function themeContributions(manifest: Record<string, unknown>): ThemeContribution[] {
|
||||
const contributes = isRecord(manifest.contributes) ? manifest.contributes : null;
|
||||
return Array.isArray(contributes?.themes)
|
||||
? (contributes.themes.filter(isRecord) as ThemeContribution[])
|
||||
: [];
|
||||
}
|
||||
|
||||
function extensionFromDetail(value: unknown): OpenVsxThemeExtension | null {
|
||||
if (!isRecord(value) || !isRecord(value.files)) {
|
||||
throw new Error("Open VSX returned malformed theme details.");
|
||||
}
|
||||
const namespace = typeof value.namespace === "string" ? value.namespace.trim() : "";
|
||||
const extensionName = typeof value.name === "string" ? value.name.trim() : "";
|
||||
const displayName =
|
||||
(typeof value.displayName === "string" ? value.displayName.trim() : "") || extensionName;
|
||||
const version = typeof value.version === "string" ? value.version.trim() : "";
|
||||
const license = typeof value.license === "string" ? value.license.trim() : "";
|
||||
const manifestUrl = trustedOpenVsxUrl(value.files.manifest);
|
||||
const sha256Url = trustedOpenVsxUrl(value.files.sha256);
|
||||
const vsixUrl = trustedOpenVsxUrl(value.files.download);
|
||||
if (!namespace || !extensionName || !version || !manifestUrl || !sha256Url || !vsixUrl) {
|
||||
throw new Error("Open VSX returned malformed theme details.");
|
||||
}
|
||||
if (!SUPPORTED_LICENSES.has(license)) return null;
|
||||
const id = `${namespace}.${extensionName}`;
|
||||
return {
|
||||
id,
|
||||
collectionId: openVsxCollectionId(id),
|
||||
name: displayName,
|
||||
publisher: namespace,
|
||||
description: typeof value.description === "string" ? value.description : "",
|
||||
downloadCount:
|
||||
typeof value.downloadCount === "number" && Number.isFinite(value.downloadCount)
|
||||
? value.downloadCount
|
||||
: 0,
|
||||
manifestUrl,
|
||||
sha256Url,
|
||||
vsixUrl,
|
||||
version,
|
||||
license,
|
||||
};
|
||||
}
|
||||
|
||||
async function withSearchTimeout<T>(
|
||||
operation: (signal: AbortSignal) => Promise<T>,
|
||||
parentSignal?: AbortSignal,
|
||||
): Promise<T> {
|
||||
const controller = new AbortController();
|
||||
const abort = () => controller.abort();
|
||||
if (parentSignal?.aborted) abort();
|
||||
else parentSignal?.addEventListener("abort", abort, { once: true });
|
||||
const timeout = setTimeout(abort, SEARCH_REQUEST_TIMEOUT_MS);
|
||||
try {
|
||||
return await operation(controller.signal);
|
||||
} catch (cause) {
|
||||
if (controller.signal.aborted && !parentSignal?.aborted) {
|
||||
throw new Error("Open VSX took too long to respond.", { cause });
|
||||
}
|
||||
throw cause;
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
parentSignal?.removeEventListener("abort", abort);
|
||||
}
|
||||
}
|
||||
|
||||
export async function searchOpenVsxThemes(
|
||||
query: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<OpenVsxThemeExtension[]> {
|
||||
const searchText = query.trim();
|
||||
if (!searchText) return [];
|
||||
const url = new URL(OPEN_VSX_SEARCH_URL);
|
||||
url.searchParams.set("query", searchText);
|
||||
url.searchParams.set("category", "Themes");
|
||||
// Ask for a few extras because results without a supported SPDX license
|
||||
// are intentionally omitted.
|
||||
url.searchParams.set("size", "16");
|
||||
const value = await withSearchTimeout(async (requestSignal) => {
|
||||
const response = await fetch(url, { signal: requestSignal });
|
||||
if (!response.ok) throw new Error("Open VSX search is unavailable right now.");
|
||||
const searchBytes = await readCappedResponse(
|
||||
response,
|
||||
MAX_SEARCH_BYTES,
|
||||
"Open VSX returned an unexpectedly large response.",
|
||||
);
|
||||
try {
|
||||
return JSON.parse(new TextDecoder().decode(searchBytes)) as unknown;
|
||||
} catch {
|
||||
throw new Error("Open VSX returned an unreadable response.");
|
||||
}
|
||||
}, signal);
|
||||
const candidates = isRecord(value) && Array.isArray(value.extensions) ? value.extensions : [];
|
||||
const identities = candidates.flatMap((candidate): Array<[string, string]> => {
|
||||
if (!isRecord(candidate)) return [];
|
||||
const namespace = typeof candidate.namespace === "string" ? candidate.namespace : "";
|
||||
const name = typeof candidate.name === "string" ? candidate.name : "";
|
||||
return namespace && name ? [[namespace, name]] : [];
|
||||
});
|
||||
const details = await Promise.allSettled(
|
||||
identities.slice(0, 16).map(([namespace, name]) =>
|
||||
withSearchTimeout(async (requestSignal) => {
|
||||
const detailUrl = `https://open-vsx.org/api/${encodeURIComponent(namespace)}/${encodeURIComponent(name)}`;
|
||||
const detailResponse = await fetch(detailUrl, { signal: requestSignal });
|
||||
if (!detailResponse.ok) throw new Error("Open VSX theme details are unavailable.");
|
||||
const detailBytes = await readCappedResponse(
|
||||
detailResponse,
|
||||
MAX_DETAIL_BYTES,
|
||||
"Open VSX returned an unexpectedly large detail response.",
|
||||
);
|
||||
try {
|
||||
const extension = extensionFromDetail(JSON.parse(new TextDecoder().decode(detailBytes)));
|
||||
if (!extension) return null;
|
||||
const [manifestResponse, packageResponse] = await Promise.all([
|
||||
fetch(extension.manifestUrl, { signal: requestSignal }),
|
||||
fetch(extension.vsixUrl, { method: "HEAD", signal: requestSignal }),
|
||||
]);
|
||||
if (!manifestResponse.ok) throw new Error("manifest unavailable");
|
||||
const packageLength = Number(packageResponse.headers.get("content-length"));
|
||||
if (
|
||||
packageResponse.ok &&
|
||||
Number.isFinite(packageLength) &&
|
||||
packageLength > MAX_VSIX_BYTES
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const manifestBytes = await readCappedResponse(
|
||||
manifestResponse,
|
||||
MAX_MANIFEST_BYTES,
|
||||
"Open VSX returned an unexpectedly large manifest.",
|
||||
);
|
||||
const manifest = parseJsoncObject(
|
||||
new TextDecoder().decode(manifestBytes),
|
||||
"Extension manifest",
|
||||
);
|
||||
return themeContributions(manifest).length > 0 ? extension : null;
|
||||
} catch {
|
||||
throw new Error("Open VSX returned unreadable theme details.");
|
||||
}
|
||||
}, signal),
|
||||
),
|
||||
);
|
||||
if (signal?.aborted) throw new DOMException("The operation was aborted.", "AbortError");
|
||||
const completedDetails = details.filter((result) => result.status === "fulfilled");
|
||||
if (identities.length > 0 && completedDetails.length === 0) {
|
||||
throw new Error("Open VSX theme details are unavailable right now.");
|
||||
}
|
||||
return completedDetails.flatMap((result) => (result.value ? [result.value] : [])).slice(0, 8);
|
||||
}
|
||||
|
||||
function parseJsoncObject(source: string, description: string): Record<string, unknown> {
|
||||
const errors: ParseError[] = [];
|
||||
const value: unknown = parse(source, errors, { allowTrailingComma: true });
|
||||
if (errors.length > 0 || !isRecord(value)) throw new Error(`${description} is not valid JSON.`);
|
||||
return value;
|
||||
}
|
||||
|
||||
function sanitizeThemeObject(value: Record<string, unknown>): Record<string, unknown> {
|
||||
const colors: Record<string, string> = {};
|
||||
if (isRecord(value.colors)) {
|
||||
for (const [key, color] of Object.entries(value.colors)) {
|
||||
if (
|
||||
USED_WORKBENCH_COLORS.has(key) &&
|
||||
typeof color === "string" &&
|
||||
color.length <= MAX_COLOR_VALUE_LENGTH
|
||||
) {
|
||||
colors[key] = color;
|
||||
}
|
||||
}
|
||||
}
|
||||
return {
|
||||
...(typeof value.include === "string" ? { include: value.include } : {}),
|
||||
colors,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizePackagePath(path: string, relativeTo = "extension/"): string {
|
||||
if (
|
||||
path.length > MAX_PACKAGE_PATH_LENGTH ||
|
||||
path.includes("\0") ||
|
||||
path.startsWith("/") ||
|
||||
/^[a-zA-Z]:/.test(path)
|
||||
) {
|
||||
throw new Error("Theme path is not a safe relative package path.");
|
||||
}
|
||||
const normalizedInput = path.replaceAll("\\", "/");
|
||||
const baseSegments = relativeTo.split("/").slice(0, -1);
|
||||
const segments = baseSegments;
|
||||
for (const segment of normalizedInput.split("/")) {
|
||||
if (!segment || segment === ".") continue;
|
||||
if (segment === "..") {
|
||||
if (segments.length <= 1) throw new Error("Theme path escapes the extension package.");
|
||||
segments.pop();
|
||||
continue;
|
||||
}
|
||||
segments.push(segment);
|
||||
}
|
||||
if (segments[0] !== "extension") segments.unshift("extension");
|
||||
return segments.join("/");
|
||||
}
|
||||
|
||||
function contributionType(uiTheme: unknown): string | null {
|
||||
if (uiTheme === "vs") return "light";
|
||||
if (uiTheme === "vs-dark") return "dark";
|
||||
if (uiTheme === "hc-black" || uiTheme === "hc-light") return uiTheme;
|
||||
return null;
|
||||
}
|
||||
|
||||
type ZipEntrySizes = {
|
||||
compressedSize?: unknown;
|
||||
uncompressedSize?: unknown;
|
||||
};
|
||||
|
||||
type InspectableZipObject = JSZip.JSZipObject & {
|
||||
_data?: ZipEntrySizes;
|
||||
unsafeOriginalName?: string;
|
||||
internalStream?: (type: "uint8array") => JSZip.JSZipStreamHelper<Uint8Array>;
|
||||
};
|
||||
|
||||
function inspectZipDirectory(bytes: Uint8Array): Uint8Array {
|
||||
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
||||
const minimumOffset = Math.max(0, bytes.byteLength - 65_557);
|
||||
let endOffset = bytes.byteLength - 22;
|
||||
while (
|
||||
endOffset >= minimumOffset &&
|
||||
(view.getUint32(endOffset, true) !== 0x06054b50 ||
|
||||
endOffset + 22 + view.getUint16(endOffset + 20, true) !== bytes.byteLength)
|
||||
) {
|
||||
endOffset -= 1;
|
||||
}
|
||||
if (endOffset < minimumOffset) throw new Error("That extension package has no ZIP directory.");
|
||||
|
||||
const directorySize = view.getUint32(endOffset + 12, true);
|
||||
const directoryOffset = view.getUint32(endOffset + 16, true);
|
||||
const directoryEnd = directoryOffset + directorySize;
|
||||
if (directoryEnd > endOffset || directoryEnd > bytes.byteLength) {
|
||||
throw new Error("That extension package has an invalid ZIP directory.");
|
||||
}
|
||||
|
||||
let entryCount = 0;
|
||||
let offset = directoryOffset;
|
||||
while (offset < directoryEnd) {
|
||||
if (offset + 46 > directoryEnd || view.getUint32(offset, true) !== 0x02014b50) {
|
||||
throw new Error("That extension package has an invalid ZIP directory.");
|
||||
}
|
||||
entryCount += 1;
|
||||
if (entryCount > MAX_ZIP_ENTRIES) {
|
||||
throw new Error("That extension package has too many files.");
|
||||
}
|
||||
const nameLength = view.getUint16(offset + 28, true);
|
||||
const extraLength = view.getUint16(offset + 30, true);
|
||||
const commentLength = view.getUint16(offset + 32, true);
|
||||
offset += 46 + nameLength + extraLength + commentLength;
|
||||
}
|
||||
if (offset !== directoryEnd)
|
||||
throw new Error("That extension package has an invalid ZIP directory.");
|
||||
|
||||
const commentLength = view.getUint16(endOffset + 20, true);
|
||||
if (commentLength === 0) return bytes;
|
||||
|
||||
// JSZip mistakes EOCD-like bytes inside an archive comment for the real EOCD.
|
||||
// The comment is not needed for theme import, so remove it before parsing.
|
||||
const withoutComment = bytes.slice(0, endOffset + 22);
|
||||
withoutComment[endOffset + 20] = 0;
|
||||
withoutComment[endOffset + 21] = 0;
|
||||
return withoutComment;
|
||||
}
|
||||
|
||||
function inspectZip(zip: JSZip): void {
|
||||
const entries = Object.values(zip.files) as InspectableZipObject[];
|
||||
if (entries.length > MAX_ZIP_ENTRIES)
|
||||
throw new Error("That extension package has too many files.");
|
||||
|
||||
let totalUncompressed = 0;
|
||||
for (const entry of entries) {
|
||||
if (entry.unsafeOriginalName) normalizePackagePath(entry.unsafeOriginalName);
|
||||
if (entry.dir) continue;
|
||||
const compressed = entry._data?.compressedSize;
|
||||
const uncompressed = entry._data?.uncompressedSize;
|
||||
if (typeof compressed !== "number" || typeof uncompressed !== "number") {
|
||||
throw new Error("That extension package has unreadable file metadata.");
|
||||
}
|
||||
totalUncompressed += uncompressed;
|
||||
if (totalUncompressed > MAX_UNCOMPRESSED_BYTES) {
|
||||
throw new Error("That extension package expands beyond the safe import limit.");
|
||||
}
|
||||
if (
|
||||
uncompressed > 0 &&
|
||||
(compressed === 0 || uncompressed / compressed > MAX_COMPRESSION_RATIO)
|
||||
) {
|
||||
throw new Error("That extension package has an unsafe compression ratio.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function readZipText(
|
||||
zip: JSZip,
|
||||
path: string,
|
||||
description: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<string> {
|
||||
signal?.throwIfAborted();
|
||||
const file = zip.file(path) as InspectableZipObject | null;
|
||||
if (!file) throw new Error(`${description} is missing from the extension package.`);
|
||||
if (typeof file._data?.uncompressedSize !== "number" || !file.internalStream) {
|
||||
throw new Error(`${description} has unreadable size metadata.`);
|
||||
}
|
||||
if (file._data.uncompressedSize > MAX_THEME_BYTES) {
|
||||
throw new Error(`${description} is too large.`);
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const chunks: Uint8Array[] = [];
|
||||
let byteLength = 0;
|
||||
let settled = false;
|
||||
const stream = file.internalStream!("uint8array");
|
||||
const cleanup = () => signal?.removeEventListener("abort", handleAbort);
|
||||
const handleAbort = () => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
stream.pause();
|
||||
cleanup();
|
||||
reject(signal?.reason);
|
||||
};
|
||||
signal?.addEventListener("abort", handleAbort, { once: true });
|
||||
stream
|
||||
.on("data", (chunk) => {
|
||||
if (settled) return;
|
||||
byteLength += chunk.byteLength;
|
||||
if (byteLength > MAX_THEME_BYTES) {
|
||||
settled = true;
|
||||
stream.pause();
|
||||
cleanup();
|
||||
reject(new Error(`${description} is too large.`));
|
||||
return;
|
||||
}
|
||||
chunks.push(chunk);
|
||||
})
|
||||
.on("error", (cause) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
cleanup();
|
||||
reject(cause);
|
||||
})
|
||||
.on("end", () => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
cleanup();
|
||||
const bytes = new Uint8Array(byteLength);
|
||||
let offset = 0;
|
||||
for (const chunk of chunks) {
|
||||
bytes.set(chunk, offset);
|
||||
offset += chunk.byteLength;
|
||||
}
|
||||
resolve(new TextDecoder().decode(bytes));
|
||||
})
|
||||
.resume();
|
||||
});
|
||||
}
|
||||
|
||||
async function loadThemeObject(
|
||||
zip: JSZip,
|
||||
path: string,
|
||||
cache: Map<string, Record<string, unknown>>,
|
||||
budget: { files: number },
|
||||
ancestors: ReadonlySet<string> = new Set(),
|
||||
signal?: AbortSignal,
|
||||
): Promise<Record<string, unknown>> {
|
||||
signal?.throwIfAborted();
|
||||
if (ancestors.size >= MAX_INCLUDE_DEPTH) throw new Error("Theme includes are nested too deeply.");
|
||||
if (ancestors.has(path)) throw new Error("Theme includes contain a cycle.");
|
||||
const cached = cache.get(path);
|
||||
if (cached) return cached;
|
||||
budget.files += 1;
|
||||
if (budget.files > MAX_RESOLVED_THEME_FILES) {
|
||||
throw new Error("That extension references too many theme files.");
|
||||
}
|
||||
|
||||
const value = sanitizeThemeObject(
|
||||
parseJsoncObject(await readZipText(zip, path, path, signal), path),
|
||||
);
|
||||
if (typeof value.include !== "string") {
|
||||
cache.set(path, value);
|
||||
return value;
|
||||
}
|
||||
|
||||
const includePath = normalizePackagePath(value.include, path);
|
||||
const nextAncestors = new Set(ancestors);
|
||||
nextAncestors.add(path);
|
||||
const base = await loadThemeObject(zip, includePath, cache, budget, nextAncestors, signal);
|
||||
const resolved = {
|
||||
...base,
|
||||
...value,
|
||||
colors: {
|
||||
...(isRecord(base.colors) ? base.colors : {}),
|
||||
...(isRecord(value.colors) ? value.colors : {}),
|
||||
},
|
||||
};
|
||||
cache.set(path, resolved);
|
||||
return resolved;
|
||||
}
|
||||
|
||||
async function readCappedResponse(
|
||||
response: Response,
|
||||
limit: number,
|
||||
tooLargeMessage: string,
|
||||
): Promise<Uint8Array> {
|
||||
const contentLength = response.headers.get("content-length");
|
||||
if (contentLength && Number(contentLength) > limit) throw new Error(tooLargeMessage);
|
||||
if (!response.body) {
|
||||
const bytes = new Uint8Array(await response.arrayBuffer());
|
||||
if (bytes.byteLength > limit) throw new Error(tooLargeMessage);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const chunks: Uint8Array[] = [];
|
||||
let byteLength = 0;
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
byteLength += value.byteLength;
|
||||
if (byteLength > limit) {
|
||||
await reader.cancel();
|
||||
throw new Error(tooLargeMessage);
|
||||
}
|
||||
chunks.push(value);
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
|
||||
const result = new Uint8Array(byteLength);
|
||||
let offset = 0;
|
||||
for (const chunk of chunks) {
|
||||
result.set(chunk, offset);
|
||||
offset += chunk.byteLength;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
async function fetchPackage(url: string, signal?: AbortSignal): Promise<Uint8Array> {
|
||||
const response = await fetch(url, signal ? { signal } : {});
|
||||
if (!response.ok) throw new Error("That Open VSX theme could not be downloaded.");
|
||||
return readCappedResponse(
|
||||
response,
|
||||
MAX_VSIX_BYTES,
|
||||
"That theme extension is too large to import safely.",
|
||||
);
|
||||
}
|
||||
|
||||
export async function importOpenVsxThemeExtension(
|
||||
extension: OpenVsxThemeExtension,
|
||||
signal?: AbortSignal,
|
||||
): Promise<ReadonlyArray<ThemeDefinition>> {
|
||||
const manifestResponse = await fetch(extension.manifestUrl, signal ? { signal } : {});
|
||||
if (!manifestResponse.ok) throw new Error("That Open VSX extension has no readable manifest.");
|
||||
const manifestBytes = await readCappedResponse(
|
||||
manifestResponse,
|
||||
MAX_MANIFEST_BYTES,
|
||||
"That Open VSX extension manifest is too large.",
|
||||
);
|
||||
const manifest = parseJsoncObject(new TextDecoder().decode(manifestBytes), "Extension manifest");
|
||||
const advertisedContributions = themeContributions(manifest);
|
||||
if (advertisedContributions.length === 0) {
|
||||
throw new Error("That extension does not contain color themes.");
|
||||
}
|
||||
if (advertisedContributions.length > MAX_THEMES_PER_EXTENSION) {
|
||||
throw new Error("That extension contains too many color themes to import safely.");
|
||||
}
|
||||
|
||||
const packageBytes = await fetchPackage(extension.vsixUrl, signal);
|
||||
signal?.throwIfAborted();
|
||||
const checksumResponse = await fetch(extension.sha256Url, signal ? { signal } : {});
|
||||
if (!checksumResponse.ok) throw new Error("That Open VSX theme has no readable checksum.");
|
||||
const expectedChecksum = new TextDecoder()
|
||||
.decode(
|
||||
await readCappedResponse(
|
||||
checksumResponse,
|
||||
256,
|
||||
"That Open VSX checksum response is invalid.",
|
||||
),
|
||||
)
|
||||
.trim()
|
||||
.split(/\s+/)[0];
|
||||
if (!expectedChecksum || !/^[a-f\d]{64}$/i.test(expectedChecksum)) {
|
||||
throw new Error("That Open VSX theme has an invalid checksum.");
|
||||
}
|
||||
signal?.throwIfAborted();
|
||||
const actualChecksum = [...sha256(packageBytes)]
|
||||
.map((byte) => byte.toString(16).padStart(2, "0"))
|
||||
.join("");
|
||||
if (actualChecksum.toLowerCase() !== expectedChecksum.toLowerCase()) {
|
||||
throw new Error("That Open VSX theme failed its integrity check.");
|
||||
}
|
||||
signal?.throwIfAborted();
|
||||
let zip: JSZip;
|
||||
try {
|
||||
const inspectedPackageBytes = inspectZipDirectory(packageBytes);
|
||||
zip = await JSZip.loadAsync(inspectedPackageBytes);
|
||||
signal?.throwIfAborted();
|
||||
inspectZip(zip);
|
||||
} catch (cause) {
|
||||
if (signal?.aborted) signal.throwIfAborted();
|
||||
if (cause instanceof Error && cause.message.startsWith("That extension package")) throw cause;
|
||||
throw new Error("That Open VSX extension package could not be opened.", { cause });
|
||||
}
|
||||
|
||||
const packagedManifest = parseJsoncObject(
|
||||
await readZipText(zip, "extension/package.json", "Extension manifest", signal),
|
||||
"Extension manifest",
|
||||
);
|
||||
if (
|
||||
typeof packagedManifest.publisher !== "string" ||
|
||||
packagedManifest.publisher.toLowerCase() !== extension.publisher.toLowerCase() ||
|
||||
typeof packagedManifest.name !== "string" ||
|
||||
`${packagedManifest.publisher}.${packagedManifest.name}`.toLowerCase() !==
|
||||
extension.id.toLowerCase() ||
|
||||
packagedManifest.version !== extension.version
|
||||
) {
|
||||
throw new Error("That extension package does not match the selected Open VSX theme.");
|
||||
}
|
||||
if (
|
||||
typeof packagedManifest.license !== "string" ||
|
||||
packagedManifest.license.trim().toLowerCase() !== extension.license.toLowerCase()
|
||||
) {
|
||||
throw new Error("That extension package does not match its advertised license.");
|
||||
}
|
||||
const contributions = themeContributions(packagedManifest);
|
||||
if (contributions.length === 0) throw new Error("That extension does not contain color themes.");
|
||||
if (contributions.length > MAX_THEMES_PER_EXTENSION) {
|
||||
throw new Error("That extension contains too many color themes to import safely.");
|
||||
}
|
||||
|
||||
const parsed: Array<{ theme: ThemeDefinition; sourceName: string; sourcePath: string }> = [];
|
||||
const failures: string[] = [];
|
||||
const themeCache = new Map<string, Record<string, unknown>>();
|
||||
const themeBudget = { files: 0 };
|
||||
for (const contribution of contributions) {
|
||||
signal?.throwIfAborted();
|
||||
if (typeof contribution.path !== "string") continue;
|
||||
try {
|
||||
const path = normalizePackagePath(contribution.path);
|
||||
const themeValue = await loadThemeObject(
|
||||
zip,
|
||||
path,
|
||||
themeCache,
|
||||
themeBudget,
|
||||
new Set(),
|
||||
signal,
|
||||
);
|
||||
const type = contributionType(contribution.uiTheme);
|
||||
const label =
|
||||
typeof contribution.label === "string" && contribution.label.trim()
|
||||
? contribution.label.trim()
|
||||
: extension.name;
|
||||
const decorated = {
|
||||
...themeValue,
|
||||
displayName: label,
|
||||
...(type ? { type } : {}),
|
||||
};
|
||||
if (!isVsCodeThemeFile(decorated)) throw new Error("not a VS Code color theme");
|
||||
parsed.push({
|
||||
theme: parseVsCodeThemeFile(decorated),
|
||||
sourceName: path.split("/").at(-1)!,
|
||||
sourcePath: path,
|
||||
});
|
||||
} catch (cause) {
|
||||
signal?.throwIfAborted();
|
||||
failures.push(cause instanceof Error ? cause.message : "theme could not be read");
|
||||
}
|
||||
}
|
||||
if (parsed.length === 0) {
|
||||
throw new Error(failures[0] ?? "That extension has no compatible color themes.");
|
||||
}
|
||||
const extensionId = extension.id.toLowerCase();
|
||||
const resolved = resolveThemeLabelCollisions(parsed).map((theme, index) => ({
|
||||
...theme,
|
||||
id: openVsxThemeId(extensionId, parsed[index]!.sourcePath),
|
||||
}));
|
||||
const paired = pairVsCodeThemes(resolved, {
|
||||
pairedId: (light, dark) => openVsxThemeId(extensionId, [light.id, dark.id].sort().join(":")),
|
||||
});
|
||||
const themes = resolveThemeLabelCollisions(paired.map((theme) => ({ theme })));
|
||||
const collection = {
|
||||
id: extension.collectionId,
|
||||
label: extension.name.slice(0, 48),
|
||||
};
|
||||
return themes.map((theme) => ({ ...theme, collection }));
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
canonicalThemePreference,
|
||||
parseThemeFile,
|
||||
parseThemeHalves,
|
||||
replaceCustomThemeCollection,
|
||||
resolveDesktopTheme,
|
||||
resolveThemeAppearance,
|
||||
serializeThemeFile,
|
||||
@@ -195,13 +196,25 @@ describe("theme files", () => {
|
||||
});
|
||||
|
||||
it("serializes a theme back into the importable file shape", () => {
|
||||
const serialized = serializeThemeFile(T3_CHAT_THEME);
|
||||
const theme = {
|
||||
...parseThemeFile({
|
||||
version: THEME_FILE_VERSION,
|
||||
id: "community-demo",
|
||||
name: "Community Demo",
|
||||
appearance: "dark",
|
||||
colors: { canvas: "#111111" },
|
||||
}),
|
||||
collection: { id: "open-vsx:demo.theme", label: "Demo Theme" },
|
||||
};
|
||||
const serialized = serializeThemeFile(theme);
|
||||
expect(JSON.parse(serialized)).toMatchObject({
|
||||
version: THEME_FILE_VERSION,
|
||||
id: T3_CHAT_THEME.id,
|
||||
name: T3_CHAT_THEME.label,
|
||||
appearance: "light",
|
||||
id: theme.id,
|
||||
name: theme.label,
|
||||
appearance: "dark",
|
||||
collection: theme.collection,
|
||||
});
|
||||
expect(parseThemeFile(JSON.parse(serialized)).collection).toEqual(theme.collection);
|
||||
});
|
||||
|
||||
it("keeps sidebar artwork opt-in through theme files", () => {
|
||||
@@ -417,6 +430,110 @@ describe("theme files", () => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("preserves valid imported-theme collections and drops malformed metadata", () => {
|
||||
vi.stubGlobal("window", {
|
||||
localStorage: {
|
||||
getItem: (key: string) =>
|
||||
key === CUSTOM_THEMES_STORAGE_KEY
|
||||
? JSON.stringify([
|
||||
{
|
||||
id: "github-dark",
|
||||
label: "GitHub Dark",
|
||||
appearance: "dark",
|
||||
colors: { canvas: "#0d1117" },
|
||||
collection: { id: "open-vsx:github.github-vscode-theme", label: "GitHub Theme" },
|
||||
},
|
||||
{
|
||||
id: "github-light",
|
||||
label: "GitHub Light",
|
||||
appearance: "light",
|
||||
colors: { canvas: "#ffffff" },
|
||||
collection: { id: "bad collection id", label: "GitHub Theme" },
|
||||
},
|
||||
])
|
||||
: null,
|
||||
},
|
||||
});
|
||||
|
||||
invalidateCustomThemes();
|
||||
expect(getCustomThemes()).toMatchObject([
|
||||
{ collection: { id: "open-vsx:github.github-vscode-theme", label: "GitHub Theme" } },
|
||||
{ id: "github-light" },
|
||||
]);
|
||||
expect(getCustomThemes()[1]).not.toHaveProperty("collection");
|
||||
|
||||
vi.unstubAllGlobals();
|
||||
invalidateCustomThemes();
|
||||
});
|
||||
|
||||
it("atomically replaces an imported collection and removes stale variants", () => {
|
||||
const collection = { id: "open-vsx:demo.theme", label: "Demo Theme" };
|
||||
const stored = new Map<string, string>([
|
||||
[
|
||||
CUSTOM_THEMES_STORAGE_KEY,
|
||||
JSON.stringify([
|
||||
{ id: "personal", label: "Personal", appearance: "dark", colors: { canvas: "#111111" } },
|
||||
{
|
||||
id: "old-light",
|
||||
label: "Old Light",
|
||||
appearance: "light",
|
||||
colors: { canvas: "#ffffff" },
|
||||
collection,
|
||||
},
|
||||
{
|
||||
id: "removed-dark",
|
||||
label: "Removed Dark",
|
||||
appearance: "dark",
|
||||
colors: { canvas: "#000000" },
|
||||
collection,
|
||||
},
|
||||
]),
|
||||
],
|
||||
]);
|
||||
const setItem = vi.fn((key: string, value: string) => stored.set(key, value));
|
||||
vi.stubGlobal("window", {
|
||||
localStorage: {
|
||||
getItem: (key: string) => stored.get(key) ?? null,
|
||||
setItem,
|
||||
},
|
||||
});
|
||||
|
||||
invalidateCustomThemes();
|
||||
const replacement = [
|
||||
{
|
||||
...parseThemeFile({
|
||||
version: THEME_FILE_VERSION,
|
||||
id: "old-light",
|
||||
name: "New Light",
|
||||
appearance: "light",
|
||||
colors: { canvas: "#fafafa" },
|
||||
}),
|
||||
collection,
|
||||
},
|
||||
{
|
||||
...parseThemeFile({
|
||||
version: THEME_FILE_VERSION,
|
||||
id: "new-dark",
|
||||
name: "New Dark",
|
||||
appearance: "dark",
|
||||
colors: { canvas: "#101010" },
|
||||
}),
|
||||
collection,
|
||||
},
|
||||
];
|
||||
|
||||
expect(replaceCustomThemeCollection(collection.id, replacement)).toEqual(replacement);
|
||||
expect(getCustomThemes().map((theme) => theme.id)).toEqual([
|
||||
"personal",
|
||||
"old-light",
|
||||
"new-dark",
|
||||
]);
|
||||
expect(setItem).toHaveBeenCalledTimes(1);
|
||||
|
||||
vi.unstubAllGlobals();
|
||||
invalidateCustomThemes();
|
||||
});
|
||||
|
||||
it("updates a personal theme without changing its id", () => {
|
||||
const stored = new Map<string, string>();
|
||||
vi.stubGlobal("window", {
|
||||
|
||||
@@ -90,12 +90,15 @@ export type ThemeColorOverrides = Readonly<Partial<Record<ThemeColorRole, string
|
||||
export type ThemeVariants = Readonly<Partial<Record<ThemeAppearance, ThemeColors>>>;
|
||||
export type ThemeVariantOverrides = Readonly<Partial<Record<ThemeAppearance, ThemeColorOverrides>>>;
|
||||
export type ThemePreferenceMode = ThemeAppearance | "system";
|
||||
export type ThemeCollection = Readonly<{ id: string; label: string }>;
|
||||
export type ThemeDefinition = Readonly<{
|
||||
id: string;
|
||||
label: string;
|
||||
appearance: ThemeAppearance;
|
||||
colors: ThemeColors;
|
||||
variants?: ThemeVariants;
|
||||
/** Groups related imported variants into one library card. */
|
||||
collection?: ThemeCollection;
|
||||
/** Allows fixed Dev/Nightly artwork to render over this theme's sidebar. */
|
||||
sidebarArtwork?: boolean;
|
||||
/** True when the palette was generated by the guided editor from its
|
||||
@@ -109,6 +112,7 @@ export type ThemeFile = Readonly<{
|
||||
appearance: ThemeAppearance;
|
||||
colors: ThemeColorOverrides;
|
||||
variants?: ThemeVariantOverrides;
|
||||
collection?: ThemeCollection;
|
||||
sidebarArtwork?: boolean;
|
||||
managed?: boolean;
|
||||
}>;
|
||||
@@ -172,6 +176,15 @@ function isThemeLabel(value: unknown): value is string {
|
||||
return typeof value === "string" && value.trim().length > 0 && value.trim().length <= 48;
|
||||
}
|
||||
|
||||
function parseThemeCollection(value: unknown): ThemeCollection | undefined {
|
||||
return isRecord(value) &&
|
||||
typeof value.id === "string" &&
|
||||
/^[a-z0-9][a-z0-9.:-]{0,127}$/i.test(value.id) &&
|
||||
isThemeLabel(value.label)
|
||||
? { id: value.id, label: value.label.trim() }
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function parseStoredThemeColors(value: unknown, appearance: ThemeAppearance): ThemeColors | null {
|
||||
if (!isRecord(value)) return null;
|
||||
|
||||
@@ -216,6 +229,7 @@ function parseStoredTheme(value: unknown): ThemeDefinition | null {
|
||||
if (!colors) return null;
|
||||
const variants = parseStoredThemeVariants(value.variants, value.appearance);
|
||||
if (value.variants !== undefined && variants === null) return null;
|
||||
const collection = parseThemeCollection(value.collection);
|
||||
|
||||
return {
|
||||
id: value.id,
|
||||
@@ -223,6 +237,7 @@ function parseStoredTheme(value: unknown): ThemeDefinition | null {
|
||||
appearance: value.appearance,
|
||||
colors,
|
||||
...(variants ? { variants } : {}),
|
||||
...(collection ? { collection } : {}),
|
||||
...(value.sidebarArtwork === true ? { sidebarArtwork: true } : {}),
|
||||
...(value.managed === true ? { managed: true } : {}),
|
||||
};
|
||||
@@ -1485,6 +1500,42 @@ export function updateCustomTheme(theme: ThemeDefinition): ThemeDefinition {
|
||||
return theme;
|
||||
}
|
||||
|
||||
export function replaceCustomThemeCollection(
|
||||
collectionId: string,
|
||||
themes: ReadonlyArray<ThemeDefinition>,
|
||||
): ReadonlyArray<ThemeDefinition> {
|
||||
if (themes.length === 0) throw new Error("A theme collection cannot be empty.");
|
||||
|
||||
const validated = themes.map((theme) => parseStoredTheme(theme));
|
||||
if (
|
||||
validated.some((theme) => theme === null || theme.collection?.id !== collectionId) ||
|
||||
new Set(validated.map((theme) => theme?.id)).size !== validated.length
|
||||
) {
|
||||
throw new Error("That theme collection is invalid.");
|
||||
}
|
||||
const replacement = validated as ThemeDefinition[];
|
||||
const current = getCustomThemes();
|
||||
const firstCollectionIndex = current.findIndex((theme) => theme.collection?.id === collectionId);
|
||||
const withoutCollection = current.filter((theme) => theme.collection?.id !== collectionId);
|
||||
const occupiedIds = new Set([
|
||||
...BUILT_IN_THEME_DEFINITIONS.map((theme) => theme.id),
|
||||
...withoutCollection.map((theme) => theme.id),
|
||||
]);
|
||||
const conflictingTheme = replacement.find(
|
||||
(theme) => RESERVED_THEME_IDS.has(theme.id) || occupiedIds.has(theme.id),
|
||||
);
|
||||
if (conflictingTheme) {
|
||||
throw new Error(`A theme named "${conflictingTheme.label}" is already installed.`);
|
||||
}
|
||||
|
||||
const insertionIndex =
|
||||
firstCollectionIndex === -1 ? withoutCollection.length : firstCollectionIndex;
|
||||
const nextThemes = [...withoutCollection];
|
||||
nextThemes.splice(insertionIndex, 0, ...replacement);
|
||||
saveCustomThemes(nextThemes);
|
||||
return replacement;
|
||||
}
|
||||
|
||||
export function removeCustomTheme(themeId: string): void {
|
||||
const nextThemes = getCustomThemes().filter((theme) => theme.id !== themeId);
|
||||
if (nextThemes.length === getCustomThemes().length) return;
|
||||
@@ -1536,6 +1587,10 @@ export function parseThemeFile(value: unknown): ThemeDefinition {
|
||||
}
|
||||
|
||||
const overrides = parseThemeColorOverrides(rawColors);
|
||||
const collection = parseThemeCollection(value.collection);
|
||||
if (value.collection !== undefined && !collection) {
|
||||
throw new Error("Theme collections need a valid id and label.");
|
||||
}
|
||||
|
||||
const fallback = getDefaultThemeColors(appearance);
|
||||
const variants: Partial<Record<ThemeAppearance, ThemeColors>> = {};
|
||||
@@ -1562,6 +1617,7 @@ export function parseThemeFile(value: unknown): ThemeDefinition {
|
||||
appearance,
|
||||
colors: { ...fallback, ...overrides },
|
||||
...(Object.keys(variants).length > 0 ? { variants } : {}),
|
||||
...(collection ? { collection } : {}),
|
||||
...(value.sidebarArtwork === true ? { sidebarArtwork: true } : {}),
|
||||
...(value.managed === true ? { managed: true } : {}),
|
||||
};
|
||||
@@ -1575,6 +1631,7 @@ export function serializeThemeFile(theme: ThemeDefinition): string {
|
||||
appearance: theme.appearance,
|
||||
colors: theme.colors,
|
||||
...(theme.variants ? { variants: theme.variants } : {}),
|
||||
...(theme.collection ? { collection: theme.collection } : {}),
|
||||
...(theme.sidebarArtwork ? { sidebarArtwork: true } : {}),
|
||||
...(theme.managed ? { managed: true } : {}),
|
||||
};
|
||||
|
||||
@@ -336,6 +336,9 @@ export function parseVsCodeThemeFile(value: unknown): ThemeDefinition {
|
||||
*/
|
||||
export function pairVsCodeThemes(
|
||||
themes: ReadonlyArray<ThemeDefinition>,
|
||||
options?: {
|
||||
pairedId?: (light: ThemeDefinition, dark: ThemeDefinition) => string;
|
||||
},
|
||||
): ReadonlyArray<ThemeDefinition> {
|
||||
const stripAppearance = (label: string) =>
|
||||
label
|
||||
@@ -371,6 +374,7 @@ export function pairVsCodeThemes(
|
||||
order: group.order,
|
||||
theme: parseThemeFile({
|
||||
version: THEME_FILE_VERSION,
|
||||
...(options?.pairedId ? { id: options.pairedId(group.light[0]!, group.dark[0]!) } : {}),
|
||||
name: key,
|
||||
appearance: "light",
|
||||
colors: group.light[0]!.colors,
|
||||
|
||||
Generated
+9
@@ -542,6 +542,9 @@ importers:
|
||||
'@lexical/react':
|
||||
specifier: ^0.41.0
|
||||
version: 0.41.0([email protected]([email protected]))([email protected])([email protected])
|
||||
'@noble/hashes':
|
||||
specifier: 'catalog:'
|
||||
version: 1.8.0
|
||||
'@pierre/diffs':
|
||||
specifier: 'catalog:'
|
||||
version: 1.3.0-beta.10(patch_hash=7ef7cb0cbabb17c15cdb137554068b36f15f6f5265e73fb51452aa3380db91aa)(@shikijs/[email protected])([email protected]([email protected]))([email protected])
|
||||
@@ -572,6 +575,12 @@ importers:
|
||||
jose:
|
||||
specifier: 'catalog:'
|
||||
version: 6.2.2
|
||||
jsonc-parser:
|
||||
specifier: 3.3.1
|
||||
version: 3.3.1
|
||||
jszip:
|
||||
specifier: 3.10.1
|
||||
version: 3.10.1
|
||||
lexical:
|
||||
specifier: ^0.41.0
|
||||
version: 0.41.0
|
||||
|
||||
Reference in new issue
Block a user