fix(web): make community theme updates explicit

This commit is contained in:
t3-code[bot] committed 2026-08-08 00:25:58 +00:00
1 parent dd8a0db88b
commit ee0d31d5e6
7 files changed
+188 -61

No files matched your search

@@ -436,8 +436,8 @@ export function ThemeImportDialog({
</DialogHeader>
<DialogPanel className="space-y-5">
<ThemeSearchSection
onInstalled={(themes) => {
onImportedMany(themes, { updated: false });
onInstalled={(themes, context) => {
onImportedMany(themes, context);
onOpenChange(false);
}}
open={open}
@@ -1,4 +1,11 @@
import { CheckCircle2Icon, PaletteIcon, PlusIcon, SearchIcon, ShieldCheckIcon } from "lucide-react";
import {
CheckCircle2Icon,
PaletteIcon,
PlusIcon,
RefreshCwIcon,
SearchIcon,
ShieldCheckIcon,
} from "lucide-react";
import type { FormEvent } from "react";
import { useCallback, useEffect, useRef, useState } from "react";
import {
@@ -8,11 +15,18 @@ import {
} from "../../openVsxThemes";
import {
getCustomThemes,
installCustomTheme,
removeCustomTheme,
updateCustomTheme,
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";
@@ -28,13 +42,14 @@ export function ThemeSearchSection({
onInstalled,
}: {
open: boolean;
onInstalled: (themes: ReadonlyArray<ThemeDefinition>) => void;
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(() => {
@@ -46,6 +61,7 @@ export function ThemeSearchSection({
setError(null);
setIsSearching(false);
setInstallingId(null);
setPendingUpdate(null);
}
return () => {
requestRef.current?.abort();
@@ -87,7 +103,15 @@ export function ThemeSearchSection({
);
const handleInstall = useCallback(
async (extension: OpenVsxThemeExtension) => {
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;
@@ -96,40 +120,8 @@ export function ThemeSearchSection({
try {
const themes = await importOpenVsxThemeExtension(extension, controller.signal);
if (controller.signal.aborted) return;
const existingById = new Map(getCustomThemes().map((theme) => [theme.id, theme]));
const installedIds: string[] = [];
const replaced: ThemeDefinition[] = [];
const imported: ThemeDefinition[] = [];
try {
for (const theme of themes) {
const existing = existingById.get(theme.id);
if (existing) {
replaced.push(existing);
imported.push(updateCustomTheme(theme));
} else {
const installed = installCustomTheme(theme);
installedIds.push(installed.id);
imported.push(installed);
}
}
} catch (cause) {
for (const themeId of installedIds) {
try {
removeCustomTheme(themeId);
} catch {
// Best effort rollback. The original storage failure is clearer.
}
}
for (const theme of replaced) {
try {
updateCustomTheme(theme);
} catch {
// Best effort rollback. The original storage failure is clearer.
}
}
throw cause;
}
onInstalled(imported);
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.");
@@ -225,6 +217,11 @@ export function ThemeSearchSection({
<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"
@@ -250,14 +247,14 @@ export function ThemeSearchSection({
<ShieldCheckIcon className="size-3" /> {extension.license}
</span>
<Button
aria-label={`${isInstalling ? "Adding" : "Add"} ${extension.name}`}
aria-label={`${isInstalling ? progressAction : action} ${extension.name}`}
disabled={installingId !== null}
size="xs"
variant="outline"
onClick={() => void handleInstall(extension)}
onClick={() => void handleInstall(extension, false)}
>
{isInstalling ? <Spinner /> : <PlusIcon />}
{isInstalling ? "Adding..." : "Add"}
{isInstalling ? <Spinner /> : isInstalled ? <RefreshCwIcon /> : <PlusIcon />}
{isInstalling ? `${progressAction}...` : action}
</Button>
</div>
</article>
@@ -270,6 +267,35 @@ export function ThemeSearchSection({
<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>
);
}
@@ -711,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({
+3
View File
@@ -259,6 +259,7 @@ describe("Open VSX themes", () => {
contributes: { themes: [{ label: "Wrong", path: "./themes/missing.json" }] },
};
const extension: OpenVsxThemeExtension = {
collectionId: "open-vsx:demo.theme",
id: "demo.theme",
name: "Demo Theme",
publisher: "demo",
@@ -328,6 +329,7 @@ describe("Open VSX themes", () => {
.join("");
const controller = new AbortController();
const extension: OpenVsxThemeExtension = {
collectionId: "open-vsx:demo.theme",
id: "demo.theme",
name: "Demo Theme",
publisher: "demo",
@@ -363,6 +365,7 @@ describe("Open VSX themes", () => {
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",
+5 -2
View File
@@ -83,6 +83,7 @@ const USED_WORKBENCH_COLORS = new Set([
export type OpenVsxThemeExtension = {
id: string;
collectionId: string;
name: string;
publisher: string;
description: string;
@@ -154,8 +155,10 @@ function extensionFromDetail(value: unknown): OpenVsxThemeExtension | null {
throw new Error("Open VSX returned malformed theme details.");
}
if (!SUPPORTED_LICENSES.has(license)) return null;
const id = `${namespace}.${extensionName}`;
return {
id: `${namespace}.${extensionName}`,
id,
collectionId: openVsxCollectionId(id),
name: displayName,
publisher: namespace,
description: typeof value.description === "string" ? value.description : "",
@@ -713,7 +716,7 @@ export async function importOpenVsxThemeExtension(
});
const themes = resolveThemeLabelCollisions(paired.map((theme) => ({ theme })));
const collection = {
id: openVsxCollectionId(extension.id),
id: extension.collectionId,
label: extension.name.slice(0, 48),
};
return themes.map((theme) => ({ ...theme, collection }));
+69
View File
@@ -15,6 +15,7 @@ import {
canonicalThemePreference,
parseThemeFile,
parseThemeHalves,
replaceCustomThemeCollection,
resolveDesktopTheme,
resolveThemeAppearance,
serializeThemeFile,
@@ -465,6 +466,74 @@ describe("theme files", () => {
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", {
+36
View File
@@ -1500,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;