Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8945: feat(appearance): theme store backed by a GitHub registry (community themes 2/3) (#10304)
Jiayuan Zhang3ac0b31d4f90
diff --git a/.env.example b/.env.exampleindex 224ca2d2fc..c921b1b983 100644--- a/.env.example+++ b/.env.example@@ -613,6 +613,14 @@ GITHUB_APP_PRIVATE_KEY=MULTICA_VCS_INTEGRATION_ENABLED=MULTICA_VCS_SECRET_KEY=+# Community theme store (Settings → Appearance → Manage, beta). On by default:+# the server reads the registry at github.com/multica-ai/multica-themes and+# serves its themes to the app, cached. MULTICA_THEME_STORE=off hides the store+# and stops every registry request. MULTICA_THEME_REGISTRY_URL points the store+# at another registry's index.json (same format; fork that repository).+MULTICA_THEME_STORE=+MULTICA_THEME_REGISTRY_URL=+# Plugins (Settings → Plugins). A plugin's frontend is an artifact its author# uploads; Multica stores it and serves it into a sandboxed iframe, and an# installation is bound to one immutable version. Hook endpoints and MCP serversdiff --git a/apps/docs/content/docs/developers/meta.fr.json b/apps/docs/content/docs/developers/meta.fr.jsonindex 3da1e48016..3d4db13d91 100644--- a/apps/docs/content/docs/developers/meta.fr.json+++ b/apps/docs/content/docs/developers/meta.fr.json@@ -1,4 +1,4 @@{"title": "Développeurs",- "pages": ["contributing", "architecture", "conventions"]+ "pages": ["contributing", "architecture", "conventions", "themes"]}diff --git a/apps/docs/content/docs/developers/meta.ja.json b/apps/docs/content/docs/developers/meta.ja.jsonindex 5614db6d09..5782b901e3 100644--- a/apps/docs/content/docs/developers/meta.ja.json+++ b/apps/docs/content/docs/developers/meta.ja.json@@ -1,4 +1,4 @@{"title": "開発者",- "pages": ["contributing", "architecture", "conventions"]+ "pages": ["contributing", "architecture", "conventions", "themes"]}diff --git a/apps/docs/content/docs/developers/meta.json b/apps/docs/content/docs/developers/meta.jsonindex a3ecbd2741..092668d833 100644--- a/apps/docs/content/docs/developers/meta.json+++ b/apps/docs/content/docs/developers/meta.json@@ -1,4 +1,4 @@{"title": "Developers",- "pages": ["contributing", "architecture", "conventions"]+ "pages": ["contributing", "architecture", "conventions", "themes"]}diff --git a/apps/docs/content/docs/developers/meta.ko.json b/apps/docs/content/docs/developers/meta.ko.jsonindex d95df05b56..c7baee81c5 100644--- a/apps/docs/content/docs/developers/meta.ko.json+++ b/apps/docs/content/docs/developers/meta.ko.json@@ -1,4 +1,4 @@{"title": "개발자",- "pages": ["contributing", "architecture", "conventions"]+ "pages": ["contributing", "architecture", "conventions", "themes"]}diff --git a/apps/docs/content/docs/developers/meta.zh-Hant.json b/apps/docs/content/docs/developers/meta.zh-Hant.jsonindex d5d87c343e..55e219ac90 100644--- a/apps/docs/content/docs/developers/meta.zh-Hant.json+++ b/apps/docs/content/docs/developers/meta.zh-Hant.json@@ -1,4 +1,4 @@{"title": "參與開發",- "pages": ["contributing", "architecture", "conventions"]+ "pages": ["contributing", "architecture", "conventions", "themes"]}diff --git a/apps/docs/content/docs/developers/meta.zh.json b/apps/docs/content/docs/developers/meta.zh.jsonindex 3ef38e535e..98809d1570 100644--- a/apps/docs/content/docs/developers/meta.zh.json+++ b/apps/docs/content/docs/developers/meta.zh.json@@ -1,4 +1,4 @@{"title": "参与开发",- "pages": ["contributing", "architecture", "conventions"]+ "pages": ["contributing", "architecture", "conventions", "themes"]}diff --git a/apps/docs/content/docs/developers/themes.fr.mdx b/apps/docs/content/docs/developers/themes.fr.mdxnew file mode 100644index 0000000000..e617825933--- /dev/null+++ b/apps/docs/content/docs/developers/themes.fr.mdx@@ -0,0 +1,234 @@+---+title: Créer un thème+description: Le format des thèmes Multica — manifeste, variables CSS, options et ancres —, comment écrire et vérifier un thème, et comment le publier dans la boutique de thèmes.+---++import { Callout } from "fumadocs-ui/components/callout";+import { Step, Steps } from "fumadocs-ui/components/steps";++Un thème Multica est un dossier avec un `manifest.json` et un `theme.css`, plus les polices et images utilisées par le CSS. Le CSS définit des variables publiques pour les modes clair et sombre et peut restyler un ensemble d'ancres stables ; le manifeste nomme le thème et peut déclarer des options que l'on règle dans **Paramètres → Apparence**. Un thème n'exécute jamais de JavaScript.++<Callout type="warn">+ Le format des thèmes est une API bêta. Variables, ancres et manifeste peuvent changer jusqu'à ce qu'il soit déclaré stable. La liste complète et générée des variables et des ancres se trouve dans [`docs/theming.md`](https://github.com/multica-ai/multica/blob/main/docs/theming.md) ; cette page explique comment elles s'articulent.+</Callout>++## Démarrage rapide++<Steps>+<Step>++### Partir d'une copie++Dans **Paramètres → Apparence**, choisissez le thème le plus proche de ce que vous voulez, puis **Créer le vôtre → Importer un thème → Dupliquer « … » en nouveau thème**. La copie reçoit son propre id (`pop-copy`, `pop-copy-2`, …), les options de l'original et un `theme.css` avec une déclaration par ligne. Sans modification, elle est identique à l'original.++</Step>+<Step>++### La modifier++- **L'application de bureau** écrit la copie dans son dossier des thèmes et l'ouvre. Modifiez `theme.css` dans n'importe quel éditeur : chaque fenêtre ouverte applique une modification enregistrée en une seconde environ.+- **Le web** télécharge la copie en `.zip`. Décompressez-la, modifiez-la, puis importez de nouveau le dossier avec **Importer un thème → Dossier du thème**. Le même `id` remplace la copie installée et conserve les valeurs de ses options.++</Step>+<Step>++### La vérifier++Avant de la partager, lancez les vérifications depuis un clone du [dépôt Multica](https://github.com/multica-ai/multica) (voir [Vérifier et prévisualiser](#vérifier-et-prévisualiser)).++</Step>+</Steps>++## Le dossier++```text+paper/+├── manifest.json+├── theme.css+└── fonts/+ └── serif.woff2+```++Le dossier peut être à la racine d'un `.zip` ou en être le seul dossier. Les fichiers autres que les polices (`woff2`, `woff`, `ttf`, `otf`) et les images (`png`, `jpg`, `webp`, `gif`, `avif`, `svg`) sont ignorés. Un thème fait au plus 1 Mo.++### 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 }+ ]+}+```++| Champ | Règles |+|---|---|+| `apiVersion` | Doit valoir `1`. |+| `id` | 1 à 40 caractères parmi `a-z`, `0-9` et `-`. Les id intégrés (`default`, `pop`, `github`, `blueprint`, `notion`) sont réservés. Importer un thème dont l'id est déjà installé le remplace. |+| `name` | Obligatoire, 40 caractères au plus. |+| `author`, `version`, `description` | Facultatifs ; affichés à l'installation. La boutique exige `version`. |+| `options` | 24 au plus ; voir [Options](#options). |++### 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;+}++.theme-dark {+ --page-canvas: var(--paper-color);+}++:root[data-theme-option-hyphens] [data-mc="content"] p {+ hyphens: auto;+}+```++Définissez les variables sur `.theme-light` et `.theme-dark`, posées sur `<html>`. Le CSS du thème est chargé après les styles de l'app : à spécificité égale, le thème l'emporte. Gardez des sélecteurs aussi simples et évitez `!important`.++Les choix de la personne sur la page Apparence restent prioritaires : Augmenter le contraste remplace les couleurs atténuées et de bordure, et toute police autre que celle par défaut remplace les variables de police. La couleur appartient au thème seul ; pour laisser choisir une couleur, déclarez une option.++## Variables++Les variables sont organisées en couches :++- **Fondations** — couleurs, surfaces, ombres, `--radius`, échelle de texte et polices — sur lesquelles tout le reste repose. Changer `--surface` ou `--radius` déplace chaque composant qui les utilise.+- **Composants et produit** — menus, boutons, lignes de navigation, lignes de tâches, tableau, couleurs de statut — qui reprennent par défaut une fondation. En définir une ne change que ce composant : `--menu-radius: 0` rend les menus carrés et rien d'autre.+- **Contenu de l'éditeur** — titres, listes, tableaux, citations, liens, code et couleurs de syntaxe — qui style les descriptions de tâches, commentaires, discussions et documents.++L'app ne déclare jamais une variable de composant ; les composants la lisent avec leur valeur par défaut en repli. On peut donc la définir sur n'importe quel ancêtre, pas seulement sur `.theme-light` :++```css+.theme-light [data-mc="chat-window"] {+ --code-block-background: transparent;+}+```++La [référence des variables](https://github.com/multica-ai/multica/blob/main/docs/theming.md#variable-reference) liste chaque variable avec ses valeurs par défaut claire et sombre.++## Options++Les options s'affichent sous **Options du thème** sur la page Apparence tant que le thème est utilisé. `toggle` et `select` posent un attribut sur `<html>` ; les autres types définissent toujours la variable `--<id>` sur `<html>` — la valeur choisie ou celle par défaut —, que `theme.css` lit avec un simple `var(--<id>)`.++| Type | Champs | Résultat |+|---|---|---|+| `heading` | — | Ouvre un groupe ; sa `description` s'affiche dessous. |+| `toggle` | `default` : `true` ou `false` | `data-theme-option-<id>="on"` si activé, absent sinon. |+| `select` | `choices` : `[{ "value", "label", "swatch"? }]`, `default` | `data-theme-option-<id>="<value>"`. Avec un `swatch` sur chaque choix, les choix s'affichent en pastilles de couleur. |+| `color` | `default` : une couleur hexadécimale, ou `{ "light", "dark" }` | `--<id>` : une couleur hexadécimale par mode. |+| `number` | `default`, et en option `min`, `max`, `step`, `unit` | `--<id>` : le nombre suivi de `unit` (`px`, `rem`, `%`, …). |+| `slider` | comme `number`, avec `min` et `max` obligatoires | comme `number`. |+| `text` | `default` : une valeur CSS | `--<id>` : la valeur saisie, si elle est sûre. |+| `font` | `default` : une pile de polices | `--<id>` : une pile de polices. |+| `variable-select` | `choices` : `[{ "value", "label" }]` avec des valeurs CSS, `default` | `--<id>` : la valeur choisie. |++Les id d'option font 1 à 48 caractères parmi `a-z`, `0-9` et `-`, et commencent par une lettre. `label`, `description` et les libellés des choix sont une chaîne ou un objet indexé par langue (`en`, `zh-Hans`, `zh-Hant`, `ja`, `ko`, `es`, `fr`) ; l'anglais sert de repli.++```json+{ "id": "page-width", "type": "slider", "label": "Page width", "default": 46, "min": 30, "max": 60, "step": 2, "unit": "rem" }+```++```css+[data-mc="content"] { max-width: var(--page-width); }+```++## Sélecteurs++Ciblez les ancres, les slots et les attributs d'état — pas les noms de classes ni la structure du DOM, qui changent sans préavis. Ancres, slots et attributs d'état restent stables jusqu'au prochain `apiVersion`.++- **Les ancres** sont des attributs `data-mc` sur les parties principales de l'app : `app-rail`, `sidebar`, `nav-item`, `page`, `issue-row`, `board-card`, `content` (texte riche), `comment`, `chat-window`, `inbox-item`, etc. Beaucoup portent un état, comme `data-status` et `data-priority` sur une ligne de tâche.+- **Les slots** sont les attributs `data-slot` des composants d'interface : `button` (avec `data-variant` et `data-size`), `input`, `dialog-content`, `dropdown-menu-item`, entre autres.+- **L'état sur `<html>`** : `.theme-light` / `.theme-dark`, `.is-desktop` / `.is-web`, `.mod-macos` / `.mod-windows` / `.mod-linux`, `.is-focused`, `.is-sidebar-collapsed`, `[data-theme="<id>"]` et les `[data-theme-option-<id>]` du thème.++```css+.mod-macos.is-desktop:not(.is-focused) [data-mc="app-rail"] { opacity: 0.7; }+.theme-dark [data-mc="issue-row"][data-priority="urgent"] { box-shadow: inset 2px 0 var(--priority-urgent); }+```++La [référence des sélecteurs](https://github.com/multica-ai/multica/blob/main/docs/theming.md#selectors) liste chaque ancre, ses attributs et chaque slot.++## Ce que le CSS ne peut pas faire++Tout ce qui charge une ressource est refusé, car le CSS peut lire le contenu de la page avec des sélecteurs d'attributs et l'envoyer dans une requête :++- `url()` ne peut désigner qu'un fichier du dossier du thème (`url(fonts/serif.woff2)`) ou un fragment (`url(#filter)`). Il est réécrit en URL `data:` du fichier.+- `@import`, `image()`, `image-set()`, `cross-fade()`, `element()`, `src()` et `expression()` sont refusés, ainsi que `behavior` et `-moz-binding`.++Échappements, casse et commentaires ne contournent pas la vérification : elle lit le CSS comme un navigateur. Quand un thème échoue, rien n'est installé et chaque problème est listé avec sa ligne dans `theme.css`.++`pnpm theme:check` fait aussi échouer un thème qui :++- utilise une variable non publique, sauf si c'est un id d'option ou si le thème la lit lui-même avec `var()` ;+- définit des variables ailleurs que sur `.theme-light` et `.theme-dark` sans sélecteur descendant, ce qui empêche le sélecteur de thème de relire ses couleurs ;+- nomme une famille générique (`sans-serif`, `serif`, …) ou un mot-clé `ui-*` dans une pile de polices, ce qui écraserait la police CJK choisie ;+- n'atteint pas le contraste WCAG AA dans un des modes : `--foreground` et `--muted-foreground` demandent 4,5:1 sur chaque surface, `--brand` 4,5:1 sur les surfaces de lecture, le libellé du bouton principal 4,5:1 sur le bouton, et `--faint-foreground` 3:1.++## Vérifier et prévisualiser++Depuis un clone du [dépôt Multica](https://github.com/multica-ai/multica) :++```bash+pnpm theme:check path/to/paper # un dossier+pnpm theme:check paper.zip --json # un zip, en JSON pour la CI+pnpm theme:preview path/to/paper --out preview # preview/light.png et preview/dark.png+```++`theme:check` signale les erreurs de manifeste, le CSS bloqué, les variables non publiques, les familles de polices génériques et le contraste dans les deux modes, chacun avec sa ligne dans `theme.css`, et se termine avec le code 1 en cas d'erreur. Les avertissements, comme une couleur qu'il ne sait pas résoudre, ne le font pas échouer.++`theme:preview` produit les captures que montre la boutique : une liste de tâches à côté d'une tâche ouverte, construite avec les styles de l'app, avec le thème à ses options par défaut.++Si un thème masque ou casse une partie de l'interface pendant que vous travaillez dessus, ouvrez l'app avec `?theme=default`, ou maintenez **Maj** juste après le chargement ; voir [Quand un thème casse quelque chose](/themes#quand-un-thème-casse-quelque-chose).++## Publier dans la boutique++La boutique de thèmes liste les thèmes du registre [multica-ai/multica-themes](https://github.com/multica-ai/multica-themes). Son [guide de contribution](https://github.com/multica-ai/multica-themes/blob/main/CONTRIBUTING.md) donne les détails ; en bref :++<Steps>+<Step>++### Donner au thème son propre dépôt++Gardez le thème dans un dépôt GitHub public. [multica-ai/multica-theme-sample](https://github.com/multica-ai/multica-theme-sample) est un modèle avec un workflow de publication.++</Step>+<Step>++### Publier une release++Étiquetez la release avec la `version` du manifeste (`1.0.0` ou `v1.0.0`) et joignez-y le thème compressé sous le nom `theme.zip`.++</Step>+<Step>++### L'ajouter au registre++Ouvrez une pull request qui ajoute le thème à `themes.json` dans le registre. La pull request lance `theme:check` et `theme:preview` sur la release et commente le résultat ; un mainteneur la fusionne une fois qu'elle passe.++</Step>+</Steps>++Les nouvelles releases arrivent dans la boutique en une heure environ, après avoir passé les mêmes vérifications ; les personnes qui ont installé le thème voient alors une mise à jour. Une release qui échoue laisse la précédente en place. L'app n'installe que le `theme.zip` exact qui a passé les vérifications, et le lit avec le même analyseur et les mêmes vérifications CSS qu'un thème importé.++Chaque carte de la boutique indique combien de fois le thème a été téléchargé depuis ce serveur Multica. Chaque installation et chaque mise à jour comptent une fois, et les thèmes pas encore installés sont classés du plus téléchargé au moins téléchargé.++## Étapes suivantes++- [Thèmes et apparence](/themes) — installer, mettre à jour et supprimer des thèmes.+- [`docs/theming.md`](https://github.com/multica-ai/multica/blob/main/docs/theming.md) — la référence générée des variables et des sélecteurs.diff --git a/apps/docs/content/docs/developers/themes.ja.mdx b/apps/docs/content/docs/developers/themes.ja.mdxnew file mode 100644index 0000000000..955bc35764--- /dev/null+++ b/apps/docs/content/docs/developers/themes.ja.mdx@@ -0,0 +1,234 @@+---+title: テーマを作る+description: Multica のテーマ形式(マニフェスト、CSS 変数、オプション、アンカー)、テーマの書き方とチェック方法、テーマストアへの公開方法。+---++import { Callout } from "fumadocs-ui/components/callout";+import { Step, Steps } from "fumadocs-ui/components/steps";++Multica のテーマは、`manifest.json` と `theme.css`、それに CSS が使うフォントや画像を入れたフォルダです。CSS はライトとダークのモードごとに公開変数を設定し、安定したアンカーのスタイルを変更できます。マニフェストはテーマに名前を付け、**設定 → 外観** で調整できるオプションを宣言できます。テーマが JavaScript を実行することはありません。++<Callout type="warn">+ テーマの形式はベータ版の API です。安定版と宣言されるまで、変数、アンカー、マニフェストは変わる可能性があります。自動生成された変数とアンカーの完全な一覧は [`docs/theming.md`](https://github.com/multica-ai/multica/blob/main/docs/theming.md) にあります。このページではそれらの組み合わせ方を説明します。+</Callout>++## クイックスタート++<Steps>+<Step>++### コピーから始める++**設定 → 外観** で目的に近いテーマを選び、**自分で作る → テーマを読み込む → 「…」を複製して新しいテーマにする** を選びます。コピーには独自の id(`pop-copy`、`pop-copy-2` …)、元のテーマのオプション、1 行に 1 宣言の `theme.css` が付きます。変更しなければ元のテーマとまったく同じ見た目です。++</Step>+<Step>++### 編集する++- **デスクトップアプリ** はコピーをテーマフォルダに書き出して開きます。好きなエディタで `theme.css` を編集すると、保存した変更が開いているすべてのウィンドウに約 1 秒で反映されます。+- **Web** ではコピーが `.zip` としてダウンロードされます。展開して編集し、**テーマを読み込む → テーマフォルダ** で読み込み直します。同じ `id` ならインストール済みのコピーが置き換わり、オプションの値は保たれます。++</Step>+<Step>++### チェックする++共有する前に、[Multica リポジトリ](https://github.com/multica-ai/multica)のクローンでチェックを実行します([チェックとプレビュー](#チェックとプレビュー)を参照)。++</Step>+</Steps>++## フォルダ++```text+paper/+├── manifest.json+├── theme.css+└── fonts/+ └── serif.woff2+```++フォルダは `.zip` の最上位に置くか、`.zip` 内の唯一のフォルダにします。フォント(`woff2`、`woff`、`ttf`、`otf`)と画像(`png`、`jpg`、`webp`、`gif`、`avif`、`svg`)以外のファイルは無視されます。テーマ全体の上限は 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 }+ ]+}+```++| フィールド | ルール |+|---|---|+| `apiVersion` | `1` でなければなりません。 |+| `id` | `a-z`、`0-9`、`-` からなる 1〜40 文字。組み込みの id(`default`、`pop`、`github`、`blueprint`、`notion`)は予約済みです。インストール済みの id のテーマを読み込むと置き換わります。 |+| `name` | 必須、40 文字以内。 |+| `author`、`version`、`description` | 任意。インストール時に表示されます。テーマストアでは `version` が必須です。 |+| `options` | 24 個まで。[オプション](#オプション)を参照。 |++### 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;+}++.theme-dark {+ --page-canvas: var(--paper-color);+}++:root[data-theme-option-hyphens] [data-mc="content"] p {+ hyphens: auto;+}+```++変数は `<html>` に付く `.theme-light` と `.theme-dark` に設定します。テーマの CSS はアプリ自身のスタイルの後に読み込まれるので、詳細度が同じならテーマが優先されます。セレクタはこの程度に単純にし、`!important` は避けてください。++外観ページでの本人の選択はテーマより優先されます。コントラストを上げるはミュートされた色と枠線の色を置き換え、既定以外のフォントはフォント変数を置き換えます。色はテーマだけが決めます。色を選べるようにしたい場合はオプションを宣言します。++## 変数++変数はいくつかの層に分かれています。++- **基盤**:色、サーフェス、影、`--radius`、文字サイズの段階、フォント。ほかのすべてはこれを元に作られています。`--surface` や `--radius` を変えると、それを使うすべてのコンポーネントが変わります。+- **コンポーネントとプロダクト**:メニュー、ボタン、ナビゲーション行、タスク行、ボード、ステータスの色。既定ではいずれかの基盤変数を使います。1 つ設定するとそのコンポーネントだけが変わります。`--menu-radius: 0` はメニューだけを角丸なしにします。+- **エディタの内容**:見出し、リスト、表、引用、リンク、コード、シンタックスハイライトの色。タスクの説明、コメント、チャット、ドキュメントに適用されます。++アプリはコンポーネント変数を宣言しません。コンポーネントは既定値をフォールバックにして読み取ります。そのため `.theme-light` に限らず、任意の祖先要素に設定できます。++```css+.theme-light [data-mc="chat-window"] {+ --code-block-background: transparent;+}+```++[変数リファレンス](https://github.com/multica-ai/multica/blob/main/docs/theming.md#variable-reference)に、すべての変数とライト・ダークの既定値があります。++## オプション++オプションは、そのテーマを使っている間、外観ページの **テーマのオプション** に表示されます。`toggle` と `select` は `<html>` に属性を付けます。そのほかの型は常に `<html>` に変数 `--<id>`(選んだ値または既定値)を設定するので、`theme.css` ではそのまま `var(--<id>)` で読めます。++| 型 | フィールド | 結果 |+|---|---|---|+| `heading` | — | グループを始めます。`description` はその下に表示されます。 |+| `toggle` | `default`:`true` または `false` | オンのとき `data-theme-option-<id>="on"`、オフのときは属性なし。 |+| `select` | `choices`:`[{ "value", "label", "swatch"? }]`、`default` | `data-theme-option-<id>="<value>"`。すべての選択肢に `swatch` があると色の丸で表示されます。 |+| `color` | `default`:16 進カラー、または `{ "light", "dark" }` | `--<id>`:モードごとの 16 進カラー。 |+| `number` | `default`、任意で `min`、`max`、`step`、`unit` | `--<id>`:数値に `unit`(`px`、`rem`、`%` …)を付けた値。 |+| `slider` | `number` と同じ。`min` と `max` は必須 | `number` と同じ。 |+| `text` | `default`:CSS の値 | `--<id>`:入力された値(安全な値の場合)。 |+| `font` | `default`:フォントスタック | `--<id>`:フォントスタック。 |+| `variable-select` | `choices`:CSS の値を持つ `[{ "value", "label" }]`、`default` | `--<id>`:選んだ値。 |++オプションの id は `a-z`、`0-9`、`-` からなる 1〜48 文字で、英字で始まります。`label`、`description`、選択肢のラベルは文字列か、ロケールをキーにしたオブジェクト(`en`、`zh-Hans`、`zh-Hant`、`ja`、`ko`、`es`、`fr`)です。フォールバックは英語です。++```json+{ "id": "page-width", "type": "slider", "label": "Page width", "default": 46, "min": 30, "max": 60, "step": 2, "unit": "rem" }+```++```css+[data-mc="content"] { max-width: var(--page-width); }+```++## セレクタ++クラス名や DOM 構造ではなく、アンカー、スロット、状態フックを対象にしてください。前者は予告なく変わります。アンカー、スロット、フックは次の `apiVersion` まで維持されます。++- **アンカー** はアプリの主要な部分に付く `data-mc` 属性です:`app-rail`、`sidebar`、`nav-item`、`page`、`issue-row`、`board-card`、`content`(リッチテキスト)、`comment`、`chat-window`、`inbox-item` など。多くは状態も持ちます。たとえばタスク行の `data-status` と `data-priority` です。+- **スロット** は UI 部品の `data-slot` 属性です:`button`(`data-variant` と `data-size` も)、`input`、`dialog-content`、`dropdown-menu-item` など。+- **`<html>` の状態**:`.theme-light` / `.theme-dark`、`.is-desktop` / `.is-web`、`.mod-macos` / `.mod-windows` / `.mod-linux`、`.is-focused`、`.is-sidebar-collapsed`、`[data-theme="<id>"]`、テーマ自身の `[data-theme-option-<id>]`。++```css+.mod-macos.is-desktop:not(.is-focused) [data-mc="app-rail"] { opacity: 0.7; }+.theme-dark [data-mc="issue-row"][data-priority="urgent"] { box-shadow: inset 2px 0 var(--priority-urgent); }+```++[セレクタリファレンス](https://github.com/multica-ai/multica/blob/main/docs/theming.md#selectors)に、すべてのアンカーとその属性、すべてのスロットがあります。++## CSS でできないこと++リソースを読み込むものはすべて拒否されます。CSS は属性セレクタでページの内容を読み取り、リクエストで外部に送れてしまうからです。++- `url()` に指定できるのは、テーマフォルダ内のファイル(`url(fonts/serif.woff2)`)かフラグメント(`url(#filter)`)だけです。ファイルの `data:` URL に書き換えられます。+- `@import`、`image()`、`image-set()`、`cross-fade()`、`element()`、`src()`、`expression()` は拒否されます。`behavior` と `-moz-binding` も同様です。++エスケープ、大文字小文字、コメントではチェックを回避できません。チェックはブラウザと同じように CSS を読みます。テーマがチェックに失敗すると何もインストールされず、すべての問題が `theme.css` の行番号付きで表示されます。++`pnpm theme:check` は次のテーマも失敗にします。++- 公開されていない変数を使っている(オプションの id か、テーマ自身が `var()` で読む変数を除く)。+- `.theme-light` と `.theme-dark` 以外の場所で、子孫セレクタなしに変数を設定している。テーマピッカーがテーマの色を読み取れなくなります。+- フォントスタックに汎用ファミリー(`sans-serif`、`serif` …)や `ui-*` キーワードがある。本人が選んだ CJK フォントが効かなくなります。+- どちらかのモードで WCAG AA のコントラストを満たさない:`--foreground` と `--muted-foreground` はすべてのサーフェスで 4.5:1、`--brand` は読むためのサーフェスで 4.5:1、プライマリボタンのラベルはボタン上で 4.5:1、`--faint-foreground` は 3:1 が必要です。++## チェックとプレビュー++[Multica リポジトリ](https://github.com/multica-ai/multica)のクローンで実行します。++```bash+pnpm theme:check path/to/paper # フォルダ+pnpm theme:check paper.zip --json # zip、CI 向けに JSON で出力+pnpm theme:preview path/to/paper --out preview # preview/light.png と preview/dark.png+```++`theme:check` はマニフェストのエラー、ブロックされた CSS、公開されていない変数、汎用フォントファミリー、両モードのコントラストを `theme.css` の行番号付きで報告し、エラーがあれば終了コード 1 で終わります。解決できない色などの警告では失敗しません。++`theme:preview` はテーマストアに表示されるスクリーンショットを描画します。アプリ自身のスタイルで作ったタスク一覧と開いたタスクを、オプションを既定値にしたテーマで表示します。++作業中にテーマでインターフェースが隠れたり崩れたりしたら、`?theme=default` を付けてアプリを開くか、読み込み直後に **Shift** を押し続けます。[テーマで表示が崩れたとき](/themes#テーマで表示が崩れたとき)を参照してください。++## テーマストアに公開する++テーマストアには [multica-ai/multica-themes](https://github.com/multica-ai/multica-themes) レジストリのテーマが並びます。詳しくはその[コントリビューションガイド](https://github.com/multica-ai/multica-themes/blob/main/CONTRIBUTING.md)を参照してください。要点は次のとおりです。++<Steps>+<Step>++### テーマ専用のリポジトリを用意する++テーマを公開 GitHub リポジトリに置きます。[multica-ai/multica-theme-sample](https://github.com/multica-ai/multica-theme-sample) はリリース用のワークフロー付きのテンプレートです。++</Step>+<Step>++### リリースを公開する++マニフェストの `version`(`1.0.0` または `v1.0.0`)でタグを付け、zip にしたテーマを `theme.zip` として添付します。++</Step>+<Step>++### レジストリに追加する++レジストリの `themes.json` にテーマを追加する pull request を作ります。pull request はリリースに対して `theme:check` と `theme:preview` を実行して結果をコメントし、通過したらメンテナーがマージします。++</Step>+</Steps>++新しいリリースは同じチェックを通過してから約 1 時間でストアに反映され、テーマをインストールした人にはアップデートが表示されます。失敗したリリースは前のリリースを置き換えません。アプリはチェックを通過した `theme.zip` そのものだけをインストールし、読み込んだテーマと同じパーサーと CSS チェックで読み込みます。++ストアのカードには、その Multica サーバーからテーマがダウンロードされた回数が表示されます。インストールとアップデートはそれぞれ 1 回と数えられ、まだインストールされていないテーマはダウンロード数の多い順に並びます。++## 次のステップ++- [テーマと外観](/themes) — テーマのインストール、アップデート、削除。+- [`docs/theming.md`](https://github.com/multica-ai/multica/blob/main/docs/theming.md) — 自動生成された変数とセレクタのリファレンス。diff --git a/apps/docs/content/docs/developers/themes.ko.mdx b/apps/docs/content/docs/developers/themes.ko.mdxnew file mode 100644index 0000000000..fe5436c2d3--- /dev/null+++ b/apps/docs/content/docs/developers/themes.ko.mdx@@ -0,0 +1,234 @@+---+title: 테마 만들기+description: Multica 테마 형식(매니페스트, CSS 변수, 옵션, 앵커), 테마를 작성하고 검사하는 방법, 테마 스토어에 게시하는 방법.+---++import { Callout } from "fumadocs-ui/components/callout";+import { Step, Steps } from "fumadocs-ui/components/steps";++Multica 테마는 `manifest.json`과 `theme.css`, 그리고 CSS가 쓰는 글꼴과 이미지를 담은 폴더입니다. CSS는 라이트와 다크 모드의 공개 변수를 설정하고, 안정적인 앵커들의 스타일을 바꿀 수 있습니다. 매니페스트는 테마의 이름을 정하고, 사용자가 **설정 → 모양**에서 조정할 옵션을 선언할 수 있습니다. 테마는 JavaScript를 실행하지 않습니다.++<Callout type="warn">+ 테마 형식은 베타 API입니다. 안정 버전으로 선언되기 전까지 변수, 앵커, 매니페스트가 바뀔 수 있습니다. 자동 생성된 전체 변수와 앵커 목록은 [`docs/theming.md`](https://github.com/multica-ai/multica/blob/main/docs/theming.md)에 있으며, 이 페이지는 그것들이 어떻게 맞물리는지 설명합니다.+</Callout>++## 빠른 시작++<Steps>+<Step>++### 복사본에서 시작하기++**설정 → 모양**에서 원하는 모습에 가장 가까운 테마를 고른 뒤 **직접 만들기 → 테마 가져오기 → "…" 복제해서 새 테마 만들기**를 선택합니다. 복사본은 자체 id(`pop-copy`, `pop-copy-2`, …), 원본의 옵션, 한 줄에 선언 하나씩 쓴 `theme.css`를 갖습니다. 수정하지 않으면 원본과 똑같이 보입니다.++</Step>+<Step>++### 편집하기++- **데스크톱 앱**은 복사본을 테마 폴더에 쓰고 엽니다. 아무 편집기에서나 `theme.css`를 고치면, 저장한 변경이 열려 있는 모든 창에 약 1초 안에 반영됩니다.+- **웹**에서는 복사본이 `.zip`으로 다운로드됩니다. 압축을 풀고 편집한 뒤 **테마 가져오기 → 테마 폴더**로 다시 가져옵니다. `id`가 같으면 설치된 복사본을 대체하고 옵션 값은 유지됩니다.++</Step>+<Step>++### 검사하기++공유하기 전에 [Multica 저장소](https://github.com/multica-ai/multica)를 클론한 곳에서 검사를 실행합니다([검사와 미리보기](#검사와-미리보기) 참고).++</Step>+</Steps>++## 폴더++```text+paper/+├── manifest.json+├── theme.css+└── fonts/+ └── serif.woff2+```++폴더는 `.zip`의 최상위에 두거나 `.zip` 안의 유일한 폴더여야 합니다. 글꼴(`woff2`, `woff`, `ttf`, `otf`)과 이미지(`png`, `jpg`, `webp`, `gif`, `avif`, `svg`) 외의 파일은 무시됩니다. 테마 전체는 최대 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 }+ ]+}+```++| 필드 | 규칙 |+|---|---|+| `apiVersion` | 반드시 `1`이어야 합니다. |+| `id` | `a-z`, `0-9`, `-`로 된 1–40자. 기본 제공 id(`default`, `pop`, `github`, `blueprint`, `notion`)는 예약되어 있습니다. 이미 설치된 id의 테마를 가져오면 대체합니다. |+| `name` | 필수, 최대 40자. |+| `author`, `version`, `description` | 선택. 설치할 때 표시됩니다. 테마 스토어에는 `version`이 필요합니다. |+| `options` | 최대 24개. [옵션](#옵션)을 참고하세요. |++### 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;+}++.theme-dark {+ --page-canvas: var(--paper-color);+}++:root[data-theme-option-hyphens] [data-mc="content"] p {+ hyphens: auto;+}+```++변수는 `<html>`에 붙는 `.theme-light`와 `.theme-dark`에 설정합니다. 테마 CSS는 앱 자체 스타일 다음에 로드되므로, 명시도가 같으면 테마가 이깁니다. 선택자는 이 정도로 단순하게 유지하고 `!important`는 피하세요.++모양 페이지에서 사용자가 직접 고른 설정은 여전히 테마보다 우선합니다. 대비 높이기는 흐린 색과 테두리 색을 바꾸고, 기본값이 아닌 글꼴은 글꼴 변수를 바꿉니다. 색상은 오직 테마가 정합니다. 사용자가 색을 고르게 하려면 옵션을 선언하세요.++## 변수++변수는 몇 개의 층으로 나뉩니다.++- **기초**: 색상, 표면, 그림자, `--radius`, 글자 크기 단계, 글꼴. 나머지는 모두 이것을 바탕으로 만들어집니다. `--surface`나 `--radius`를 바꾸면 그것을 쓰는 모든 컴포넌트가 바뀝니다.+- **컴포넌트와 제품**: 메뉴, 버튼, 내비게이션 행, 태스크 행, 보드, 상태 색상. 기본값은 기초 변수 중 하나입니다. 하나를 설정하면 그 컴포넌트만 바뀝니다. `--menu-radius: 0`은 메뉴만 각지게 만듭니다.+- **편집기 콘텐츠**: 제목, 목록, 표, 인용, 링크, 코드, 구문 강조 색상. 태스크 설명, 댓글, 채팅, 문서에 적용됩니다.++앱은 컴포넌트 변수를 선언하지 않습니다. 컴포넌트는 기본값을 대체값으로 두고 읽습니다. 그래서 `.theme-light`뿐 아니라 어떤 조상 요소에든 설정할 수 있습니다.++```css+.theme-light [data-mc="chat-window"] {+ --code-block-background: transparent;+}+```++[변수 레퍼런스](https://github.com/multica-ai/multica/blob/main/docs/theming.md#variable-reference)에 모든 변수와 라이트·다크 기본값이 있습니다.++## 옵션++옵션은 그 테마를 쓰는 동안 모양 페이지의 **테마 옵션**에 표시됩니다. `toggle`과 `select`는 `<html>`에 속성을 붙이고, 나머지 타입은 항상 `<html>`에 변수 `--<id>`(고른 값 또는 기본값)를 설정합니다. 그래서 `theme.css`에서는 그냥 `var(--<id>)`로 읽으면 됩니다.++| 타입 | 필드 | 결과 |+|---|---|---|+| `heading` | — | 그룹을 시작합니다. `description`은 그 아래에 표시됩니다. |+| `toggle` | `default`: `true` 또는 `false` | 켜면 `data-theme-option-<id>="on"`, 끄면 속성 없음. |+| `select` | `choices`: `[{ "value", "label", "swatch"? }]`, `default` | `data-theme-option-<id>="<value>"`. 모든 선택지에 `swatch`가 있으면 색상 점으로 표시됩니다. |+| `color` | `default`: 16진수 색상 또는 `{ "light", "dark" }` | `--<id>`: 모드별 16진수 색상. |+| `number` | `default`, 선택적으로 `min`, `max`, `step`, `unit` | `--<id>`: 숫자 뒤에 `unit`(`px`, `rem`, `%`, …)을 붙인 값. |+| `slider` | `number`와 같으며 `min`, `max` 필수 | `number`와 같음. |+| `text` | `default`: CSS 값 | `--<id>`: 입력한 값(안전한 값일 때). |+| `font` | `default`: 글꼴 스택 | `--<id>`: 글꼴 스택. |+| `variable-select` | `choices`: CSS 값을 가진 `[{ "value", "label" }]`, `default` | `--<id>`: 고른 값. |++옵션 id는 `a-z`, `0-9`, `-`로 된 1–48자이며 영문자로 시작합니다. `label`, `description`, 선택지 라벨은 문자열이거나 로캘을 키로 하는 객체(`en`, `zh-Hans`, `zh-Hant`, `ja`, `ko`, `es`, `fr`)입니다. 대체 언어는 영어입니다.++```json+{ "id": "page-width", "type": "slider", "label": "Page width", "default": 46, "min": 30, "max": 60, "step": 2, "unit": "rem" }+```++```css+[data-mc="content"] { max-width: var(--page-width); }+```++## 선택자++클래스 이름이나 DOM 구조가 아니라 앵커, 슬롯, 상태 훅을 대상으로 하세요. 클래스 이름과 DOM 구조는 예고 없이 바뀝니다. 앵커, 슬롯, 훅은 다음 `apiVersion`까지 유지됩니다.++- **앵커**는 앱의 주요 부분에 붙은 `data-mc` 속성입니다: `app-rail`, `sidebar`, `nav-item`, `page`, `issue-row`, `board-card`, `content`(서식 있는 텍스트), `comment`, `chat-window`, `inbox-item` 등. 상당수는 상태도 가집니다. 예를 들어 태스크 행의 `data-status`와 `data-priority`입니다.+- **슬롯**은 UI 기본 컴포넌트의 `data-slot` 속성입니다: `button`(`data-variant`, `data-size`도 함께), `input`, `dialog-content`, `dropdown-menu-item` 등.+- **`<html>`의 상태**: `.theme-light` / `.theme-dark`, `.is-desktop` / `.is-web`, `.mod-macos` / `.mod-windows` / `.mod-linux`, `.is-focused`, `.is-sidebar-collapsed`, `[data-theme="<id>"]`, 그리고 테마 자체의 `[data-theme-option-<id>]`.++```css+.mod-macos.is-desktop:not(.is-focused) [data-mc="app-rail"] { opacity: 0.7; }+.theme-dark [data-mc="issue-row"][data-priority="urgent"] { box-shadow: inset 2px 0 var(--priority-urgent); }+```++[선택자 레퍼런스](https://github.com/multica-ai/multica/blob/main/docs/theming.md#selectors)에 모든 앵커와 그 속성, 모든 슬롯이 있습니다.++## CSS로 할 수 없는 것++리소스를 불러오는 것은 모두 거부됩니다. CSS는 속성 선택자로 페이지 내용을 읽어 요청으로 내보낼 수 있기 때문입니다.++- `url()`은 테마 폴더 안의 파일(`url(fonts/serif.woff2)`)이나 프래그먼트(`url(#filter)`)만 가리킬 수 있습니다. 파일의 `data:` URL로 바뀝니다.+- `@import`, `image()`, `image-set()`, `cross-fade()`, `element()`, `src()`, `expression()`은 거부되며, `behavior`와 `-moz-binding`도 마찬가지입니다.++이스케이프, 대소문자, 주석으로는 검사를 피할 수 없습니다. 검사는 브라우저와 같은 방식으로 CSS를 읽습니다. 테마가 검사에 실패하면 아무것도 설치되지 않고, 모든 문제가 `theme.css`의 줄 번호와 함께 표시됩니다.++`pnpm theme:check`는 다음과 같은 테마도 실패로 처리합니다.++- 공개되지 않은 변수를 쓰는 경우. 옵션 id이거나 테마가 직접 `var()`로 읽는 변수는 예외입니다.+- `.theme-light`와 `.theme-dark`가 아닌 곳에 하위 선택자 없이 변수를 설정한 경우. 테마 선택기가 테마의 색을 읽어 올 수 없게 됩니다.+- 글꼴 스택에 일반 글꼴 계열(`sans-serif`, `serif`, …)이나 `ui-*` 키워드를 쓴 경우. 사용자가 고른 CJK 글꼴이 적용되지 않게 됩니다.+- 어느 한 모드에서 WCAG AA 대비를 충족하지 못하는 경우: `--foreground`와 `--muted-foreground`는 모든 표면에서 4.5:1, `--brand`는 읽기 표면에서 4.5:1, 기본 버튼 라벨은 버튼 위에서 4.5:1, `--faint-foreground`는 3:1이 필요합니다.++## 검사와 미리보기++[Multica 저장소](https://github.com/multica-ai/multica)를 클론한 곳에서 실행합니다.++```bash+pnpm theme:check path/to/paper # 폴더+pnpm theme:check paper.zip --json # zip, CI용 JSON 출력+pnpm theme:preview path/to/paper --out preview # preview/light.png와 preview/dark.png+```++`theme:check`는 매니페스트 오류, 차단된 CSS, 공개되지 않은 변수, 일반 글꼴 계열, 두 모드의 대비를 `theme.css` 줄 번호와 함께 보고하고, 오류가 있으면 상태 코드 1로 종료합니다. 해석할 수 없는 색상 같은 경고로는 실패하지 않습니다.++`theme:preview`는 테마 스토어가 보여 주는 스크린샷을 렌더링합니다. 앱 자체 스타일로 만든 태스크 목록과 열린 태스크를, 옵션을 기본값으로 둔 테마로 보여 줍니다.++작업 중에 테마 때문에 인터페이스가 가려지거나 깨지면 `?theme=default`를 붙여 앱을 열거나, 로드 직후 **Shift**를 누르고 있으세요. [테마 때문에 화면이 깨졌을 때](/themes#테마-때문에-화면이-깨졌을-때)를 참고하세요.++## 테마 스토어에 게시하기++테마 스토어는 [multica-ai/multica-themes](https://github.com/multica-ai/multica-themes) 레지스트리의 테마를 보여 줍니다. 자세한 내용은 [기여 가이드](https://github.com/multica-ai/multica-themes/blob/main/CONTRIBUTING.md)에 있으며, 요약하면 다음과 같습니다.++<Steps>+<Step>++### 테마 전용 저장소 만들기++테마를 공개 GitHub 저장소에 둡니다. [multica-ai/multica-theme-sample](https://github.com/multica-ai/multica-theme-sample)은 릴리스 워크플로가 포함된 템플릿입니다.++</Step>+<Step>++### 릴리스 게시하기++매니페스트의 `version`(`1.0.0` 또는 `v1.0.0`)으로 태그를 달고, 압축한 테마를 `theme.zip`으로 첨부합니다.++</Step>+<Step>++### 레지스트리에 추가하기++레지스트리의 `themes.json`에 테마를 추가하는 pull request를 엽니다. pull request는 릴리스에 `theme:check`와 `theme:preview`를 실행해 결과를 댓글로 남기고, 통과하면 메인테이너가 병합합니다.++</Step>+</Steps>++새 릴리스는 같은 검사를 통과한 뒤 약 1시간 안에 스토어에 반영되고, 테마를 설치한 사람에게 업데이트가 표시됩니다. 실패한 릴리스는 이전 릴리스를 대체하지 않습니다. 앱은 검사를 통과한 바로 그 `theme.zip`만 설치하며, 가져온 테마와 같은 파서와 CSS 검사로 읽습니다.++스토어 카드에는 그 Multica 서버에서 테마가 다운로드된 횟수가 표시됩니다. 설치와 업데이트는 각각 한 번으로 세며, 아직 설치하지 않은 테마는 다운로드 수가 많은 순서로 나열됩니다.++## 다음 단계++- [테마와 모양](/themes) — 테마 설치, 업데이트, 제거.+- [`docs/theming.md`](https://github.com/multica-ai/multica/blob/main/docs/theming.md) — 자동 생성된 변수와 선택자 레퍼런스.diff --git a/apps/docs/content/docs/developers/themes.mdx b/apps/docs/content/docs/developers/themes.mdxnew file mode 100644index 0000000000..b9daa89b8a--- /dev/null+++ b/apps/docs/content/docs/developers/themes.mdx@@ -0,0 +1,234 @@+---+title: Make a theme+description: The Multica theme format — manifest, CSS variables, options, and anchors — how to write and check a theme, and how to publish it to the theme store.+---++import { Callout } from "fumadocs-ui/components/callout";+import { Step, Steps } from "fumadocs-ui/components/steps";++A Multica theme is a folder with a `manifest.json` and a `theme.css`, plus any fonts and images the CSS uses. The CSS sets public variables for light and dark mode and can restyle a set of stable anchors; the manifest names the theme and can declare options that people adjust in **Settings → Appearance**. Themes never run JavaScript.++<Callout type="warn">+ The theme format is a beta API. Variables, anchors, and the manifest may change until it is declared stable. The complete, generated list of variables and anchors is in [`docs/theming.md`](https://github.com/multica-ai/multica/blob/main/docs/theming.md); this page covers how they fit together.+</Callout>++## Quick start++<Steps>+<Step>++### Start from a copy++In **Settings → Appearance**, pick the theme closest to what you want, then choose **Make your own → Import theme → Duplicate "…" as a new theme**. The copy gets its own id (`pop-copy`, `pop-copy-2`, …), the original's options, and a `theme.css` with one declaration per line. Unchanged, it looks exactly like the original.++</Step>+<Step>++### Edit it++- **Desktop** writes the copy into its themes folder and opens it. Edit `theme.css` in any editor: every open window picks up a saved change within about a second.+- **Web** downloads the copy as a `.zip`. Unzip it, edit it, and import the folder again with **Import theme → Theme folder**. The same `id` replaces the installed copy and keeps its option values.++</Step>+<Step>++### Check it++Run the checks from a checkout of the [Multica repository](https://github.com/multica-ai/multica) before you share it (see [Check and preview](#check-and-preview)).++</Step>+</Steps>++## The folder++```text+paper/+├── manifest.json+├── theme.css+└── fonts/+ └── serif.woff2+```++The folder can be at the top of a `.zip` or be its only folder. Files other than fonts (`woff2`, `woff`, `ttf`, `otf`) and images (`png`, `jpg`, `webp`, `gif`, `avif`, `svg`) are ignored. A theme is 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 |+|---|---|+| `apiVersion` | Must be `1`. |+| `id` | 1–40 characters of `a-z`, `0-9`, and `-`. The 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. The theme store requires `version`. |+| `options` | Up to 24; see [Options](#options). |++### 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;+}++.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`, which are on `<html>`. The theme's CSS loads after the app's own styles, so at equal specificity the theme wins: keep selectors that simple and avoid `!important`.++A person's own Appearance choices still win over a theme: Increase contrast replaces the muted and border colors, and any font other than the default replaces the font variables. Color belongs to the theme alone; to let people choose one, declare an option.++## Variables++Variables come in layers:++- **Foundations** — colors, surfaces, shadows, `--radius`, the text scale, and fonts — are what everything else is built from. Changing `--surface` or `--radius` moves every component that uses it.+- **Components and product** — menus, buttons, navigation rows, issue rows, the board, status colors — default to a foundation. Set one to change only that component: `--menu-radius: 0` squares menus and nothing else.+- **Editor content** — headings, lists, tables, quotes, links, code, and syntax colors — styles issue descriptions, comments, chat, and documents.++The app never declares a component variable; components read it with their default as a fallback. So it can be set on any ancestor, not only on `.theme-light`:++```css+.theme-light [data-mc="chat-window"] {+ --code-block-background: transparent;+}+```++The [variable reference](https://github.com/multica-ai/multica/blob/main/docs/theming.md#variable-reference) lists every variable with its light and dark default.++## Options++Options are rendered under **Theme options** on the Appearance page while the theme is in use. `toggle` and `select` set an attribute on `<html>`; the other types always set the variable `--<id>` on `<html>` — the chosen value or the default — so `theme.css` can read it with a plain `var(--<id>)`.++| Type | Fields | Result |+|---|---|---|+| `heading` | — | Starts a group; its `description` is shown under it. |+| `toggle` | `default`: `true` or `false` | `data-theme-option-<id>="on"` when on, absent when off. |+| `select` | `choices`: `[{ "value", "label", "swatch"? }]`, `default` | `data-theme-option-<id>="<value>"`. With a `swatch` on every choice, the choices render as color dots. |+| `color` | `default`: a hex color, or `{ "light", "dark" }` | `--<id>`: a hex color per mode. |+| `number` | `default`, optional `min`, `max`, `step`, `unit` | `--<id>`: the number with `unit` appended (`px`, `rem`, `%`, …). |+| `slider` | as `number`, with `min` and `max` required | as `number`. |+| `text` | `default`: a CSS value | `--<id>`: what was typed, when it is a safe value. |+| `font` | `default`: a font stack | `--<id>`: a font stack. |+| `variable-select` | `choices`: `[{ "value", "label" }]` with CSS values, `default` | `--<id>`: the chosen value. |++Option ids are 1–48 characters of `a-z`, `0-9`, and `-`, starting with a letter. `label`, `description`, and choice labels are a string or an object keyed by locale (`en`, `zh-Hans`, `zh-Hant`, `ja`, `ko`, `es`, `fr`); English is the fallback.++```json+{ "id": "page-width", "type": "slider", "label": "Page width", "default": 46, "min": 30, "max": 60, "step": 2, "unit": "rem" }+```++```css+[data-mc="content"] { max-width: var(--page-width); }+```++## Selectors++Target anchors, slots, and state hooks — not class names or DOM structure, which change without notice. Anchors, slots, and hooks stay until the next `apiVersion`.++- **Anchors** are `data-mc` attributes on the main parts of the app: `app-rail`, `sidebar`, `nav-item`, `page`, `issue-row`, `board-card`, `content` (rich text), `comment`, `chat-window`, `inbox-item`, and more. Many carry state, such as `data-status` and `data-priority` on an issue row.+- **Slots** are the `data-slot` attributes of UI primitives: `button` (with `data-variant` and `data-size`), `input`, `dialog-content`, `dropdown-menu-item`, and others.+- **State on `<html>`**: `.theme-light` / `.theme-dark`, `.is-desktop` / `.is-web`, `.mod-macos` / `.mod-windows` / `.mod-linux`, `.is-focused`, `.is-sidebar-collapsed`, `[data-theme="<id>"]`, and the theme's own `[data-theme-option-<id>]`.++```css+.mod-macos.is-desktop:not(.is-focused) [data-mc="app-rail"] { opacity: 0.7; }+.theme-dark [data-mc="issue-row"][data-priority="urgent"] { box-shadow: inset 2px 0 var(--priority-urgent); }+```++The [selector reference](https://github.com/multica-ai/multica/blob/main/docs/theming.md#selectors) lists every anchor, its attributes, and every slot.++## What CSS may not do++Anything that loads a resource is rejected, because CSS can read page content through attribute selectors and send it out in a request:++- `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 don't get around the check; it reads the CSS the way a browser does. When a theme fails, nothing is installed and every problem is listed with its line in `theme.css`.++`pnpm theme:check` also fails a theme that:++- uses a variable that isn't public, unless it is an option id or the theme reads it itself with `var()`;+- sets variables anywhere other than `.theme-light` and `.theme-dark` without a descendant selector, so the theme picker can't read the theme's colors back;+- names a generic family (`sans-serif`, `serif`, …) or a `ui-*` keyword in a font stack, which would override the person's CJK font;+- misses WCAG AA contrast in either mode: `--foreground` and `--muted-foreground` need 4.5:1 on every surface, `--brand` 4.5:1 on reading surfaces, the primary button label 4.5:1 on the button, and `--faint-foreground` 3:1.++## Check and preview++From a checkout of the [Multica repository](https://github.com/multica-ai/multica):++```bash+pnpm theme:check path/to/paper # a folder+pnpm theme:check paper.zip --json # a zip, as JSON for CI+pnpm theme:preview path/to/paper --out preview # preview/light.png and preview/dark.png+```++`theme:check` reports manifest errors, blocked CSS, non-public variables, generic font families, and contrast in both modes, each with its line in `theme.css`, and exits with status 1 on an error. Warnings, such as a color it can't resolve, don't fail it.++`theme:preview` renders the screenshots the theme store shows: an issue list next to an open issue, built from the app's own styles, with the theme at its option defaults.++If a theme hides or breaks part of the interface while you work on it, open the app with `?theme=default`, or hold **Shift** right after it loads; see [When a theme breaks something](/themes#when-a-theme-breaks-something).++## Publish to the theme store++The theme store lists themes from the [multica-ai/multica-themes](https://github.com/multica-ai/multica-themes) registry. Its [contributing guide](https://github.com/multica-ai/multica-themes/blob/main/CONTRIBUTING.md) has the details; in short:++<Steps>+<Step>++### Give the theme its own repository++Keep the theme in a public GitHub repository. [multica-ai/multica-theme-sample](https://github.com/multica-ai/multica-theme-sample) is a template with a release workflow.++</Step>+<Step>++### Publish a release++Tag the release with the manifest's `version` (`1.0.0` or `v1.0.0`) and attach the zipped theme as `theme.zip`.++</Step>+<Step>++### Add it to the registry++Open a pull request that adds the theme to `themes.json` in the registry. The pull request runs `theme:check` and `theme:preview` on the release and comments with the result; a maintainer merges it once it passes.++</Step>+</Steps>++New releases reach the store within about an hour, after they pass the same checks; people who installed the theme then see an update. A release that fails keeps the previous one listed. The app only installs the exact `theme.zip` that passed, and reads it with the same parser and CSS checks as an imported theme.++Each store card shows how many times the theme has been downloaded from that Multica server. Every install and every update counts once, and themes people haven't installed yet are listed most downloaded first.++## Next steps++- [Themes and appearance](/themes) — installing, updating, and removing themes.+- [`docs/theming.md`](https://github.com/multica-ai/multica/blob/main/docs/theming.md) — the generated variable and selector reference.diff --git a/apps/docs/content/docs/developers/themes.zh-Hant.mdx b/apps/docs/content/docs/developers/themes.zh-Hant.mdxnew file mode 100644index 0000000000..bfa5c51e22--- /dev/null+++ b/apps/docs/content/docs/developers/themes.zh-Hant.mdx@@ -0,0 +1,234 @@+---+title: 製作主題+description: Multica 的主題格式(manifest、CSS 變數、選項和錨點),如何編寫和檢查主題,以及如何釋出到主題商店。+---++import { Callout } from "fumadocs-ui/components/callout";+import { Step, Steps } from "fumadocs-ui/components/steps";++Multica 主題是一個資料夾,包含 `manifest.json`、`theme.css`,以及 CSS 用到的字型和圖片。CSS 為淺色和深色模式設定公開變數,也可以重新設計一組穩定的錨點;manifest 給主題命名,還可以宣告選項,讓使用者在 **設定 → 外觀** 裡調整。主題永遠不會執行 JavaScript。++<Callout type="warn">+ 主題格式是 Beta API。在宣佈穩定之前,變數、錨點和 manifest 都可能變化。完整的、自動生成的變數和錨點列表在 [`docs/theming.md`](https://github.com/multica-ai/multica/blob/main/docs/theming.md);本頁講它們怎麼配合使用。+</Callout>++## 快速開始++<Steps>+<Step>++### 從副本開始++在 **設定 → 外觀** 選一個最接近你想要的主題,然後選擇 **製作自己的主題 → 匯入主題 → 複製"…"為新主題**。副本有自己的 id(`pop-copy`、`pop-copy-2` …),帶著原主題的選項,`theme.css` 每行一條宣告。不做修改時,它和原主題一模一樣。++</Step>+<Step>++### 編輯++- **桌面端** 把副本寫進主題資料夾並開啟它。用任何編輯器改 `theme.css`:儲存後,所有開啟的視窗約一秒內生效。+- **網頁端** 把副本下載為 `.zip`。解壓、修改,再用 **匯入主題 → 主題資料夾** 匯入。相同的 `id` 會替換已安裝的副本,並保留選項值。++</Step>+<Step>++### 檢查++分享之前,在 [Multica 倉庫](https://github.com/multica-ai/multica)的本地副本里執行檢查(見[檢查與預覽](#檢查與預覽))。++</Step>+</Steps>++## 資料夾++```text+paper/+├── manifest.json+├── theme.css+└── fonts/+ └── serif.woff2+```++資料夾可以放在 `.zip` 的最頂層,也可以是 `.zip` 裡唯一的資料夾。字型(`woff2`、`woff`、`ttf`、`otf`)和圖片(`png`、`jpg`、`webp`、`gif`、`avif`、`svg`)以外的檔案會被忽略。整個主題最大 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 }+ ]+}+```++| 欄位 | 規則 |+|---|---|+| `apiVersion` | 必須是 `1`。 |+| `id` | 1–40 個字元,只能是 `a-z`、`0-9` 和 `-`。內建 id(`default`、`pop`、`github`、`blueprint`、`notion`)保留不可用。匯入 id 已安裝的主題會替換它。 |+| `name` | 必填,最多 40 個字元。 |+| `author`、`version`、`description` | 可選,安裝時顯示。主題商店要求有 `version`。 |+| `options` | 最多 24 個,見[選項](#選項)。 |++### 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;+}++.theme-dark {+ --page-canvas: var(--paper-color);+}++:root[data-theme-option-hyphens] [data-mc="content"] p {+ hyphens: auto;+}+```++變數設定在 `.theme-light` 和 `.theme-dark` 上,它們都在 `<html>` 上。主題的 CSS 在應用自身樣式之後載入,所以優先順序相同時主題勝出:選擇器保持這麼簡單,不要用 `!important`。++使用者自己在外觀頁的選擇仍然優先於主題:提高對比會替換次要文字和邊框顏色,選了非預設的字型會替換字型變數。顏色完全由主題決定;想讓使用者自己選顏色,就宣告一個選項。++## 變數++變數分為幾層:++- **基礎**:顏色、表面、陰影、`--radius`、字號階梯和字型,其他一切都建立在它們之上。改 `--surface` 或 `--radius` 會影響所有用到它的元件。+- **元件與產品**:選單、按鈕、導航行、任務行、看板、狀態顏色,預設取自某個基礎變數。設定其中一個只改這個元件:`--menu-radius: 0` 只讓選單變成直角。+- **編輯器內容**:標題、列表、表格、引用、連結、程式碼和語法高亮顏色,作用於任務描述、評論、聊天和文件。++應用從不宣告元件變數;元件讀取它時自帶預設值作為回退。所以元件變數可以設定在任意祖先元素上,不限於 `.theme-light`:++```css+.theme-light [data-mc="chat-window"] {+ --code-block-background: transparent;+}+```++[變數參考](https://github.com/multica-ai/multica/blob/main/docs/theming.md#variable-reference)列出了每個變數及其淺色和深色預設值。++## 選項++使用這個主題時,選項顯示在外觀頁的 **主題選項** 下。`toggle` 和 `select` 在 `<html>` 上設定屬性;其他型別總會在 `<html>` 上設定變數 `--<id>`,值為使用者選的值或預設值,所以 `theme.css` 直接用 `var(--<id>)` 讀取即可。++| 型別 | 欄位 | 結果 |+|---|---|---|+| `heading` | — | 開始一個分組;`description` 顯示在標題下方。 |+| `toggle` | `default`:`true` 或 `false` | 開啟時為 `data-theme-option-<id>="on"`,關閉時沒有這個屬性。 |+| `select` | `choices`:`[{ "value", "label", "swatch"? }]`,`default` | `data-theme-option-<id>="<value>"`。每個選項都有 `swatch` 時,顯示為色點。 |+| `color` | `default`:十六進位制顏色,或 `{ "light", "dark" }` | `--<id>`:每個模式各一個十六進位制顏色。 |+| `number` | `default`,可選 `min`、`max`、`step`、`unit` | `--<id>`:數字加上 `unit`(`px`、`rem`、`%` …)。 |+| `slider` | 同 `number`,`min` 和 `max` 必填 | 同 `number`。 |+| `text` | `default`:一個 CSS 值 | `--<id>`:使用者輸入的值,前提是它安全。 |+| `font` | `default`:字型棧 | `--<id>`:字型棧。 |+| `variable-select` | `choices`:`[{ "value", "label" }]`,值為 CSS 值,`default` | `--<id>`:選中的值。 |++選項 id 為 1–48 個字元,只能是 `a-z`、`0-9` 和 `-`,以字母開頭。`label`、`description` 和選項標籤可以是字串,也可以是以語言為鍵的物件(`en`、`zh-Hans`、`zh-Hant`、`ja`、`ko`、`es`、`fr`),英文為回退。++```json+{ "id": "page-width", "type": "slider", "label": "Page width", "default": 46, "min": 30, "max": 60, "step": 2, "unit": "rem" }+```++```css+[data-mc="content"] { max-width: var(--page-width); }+```++## 選擇器++選擇錨點、slot 和狀態鉤子,不要選類名或 DOM 結構,後者隨時會變。錨點、slot 和鉤子會保持到下一個 `apiVersion`。++- **錨點** 是應用主要部分上的 `data-mc` 屬性:`app-rail`、`sidebar`、`nav-item`、`page`、`issue-row`、`board-card`、`content`(富文字)、`comment`、`chat-window`、`inbox-item` 等。很多錨點帶有狀態,比如任務行上的 `data-status` 和 `data-priority`。+- **Slot** 是 UI 基礎元件的 `data-slot` 屬性:`button`(還有 `data-variant` 和 `data-size`)、`input`、`dialog-content`、`dropdown-menu-item` 等。+- **`<html>` 上的狀態**:`.theme-light` / `.theme-dark`、`.is-desktop` / `.is-web`、`.mod-macos` / `.mod-windows` / `.mod-linux`、`.is-focused`、`.is-sidebar-collapsed`、`[data-theme="<id>"]`,以及主題自己的 `[data-theme-option-<id>]`。++```css+.mod-macos.is-desktop:not(.is-focused) [data-mc="app-rail"] { opacity: 0.7; }+.theme-dark [data-mc="issue-row"][data-priority="urgent"] { box-shadow: inset 2px 0 var(--priority-urgent); }+```++[選擇器參考](https://github.com/multica-ai/multica/blob/main/docs/theming.md#selectors)列出了每個錨點、它的屬性和每個 slot。++## CSS 不能做什麼++任何會載入資源的寫法都會被拒絕,因為 CSS 可以透過屬性選擇器讀取頁面內容,再透過請求把它發出去:++- `url()` 只能指向主題資料夾裡的檔案(`url(fonts/serif.woff2)`)或片段(`url(#filter)`),並會被改寫成檔案的 `data:` URL。+- `@import`、`image()`、`image-set()`、`cross-fade()`、`element()`、`src()` 和 `expression()` 都會被拒絕,`behavior` 和 `-moz-binding` 也是。++轉義、大小寫和註釋都繞不過檢查,它按瀏覽器的方式讀取 CSS。主題沒通過檢查時,什麼都不會安裝,並列出每個問題及其在 `theme.css` 中的行號。++以下情況 `pnpm theme:check` 也會判定失敗:++- 使用了非公開變數,除非它是選項 id,或者主題自己用 `var()` 讀取它;+- 在 `.theme-light` 和 `.theme-dark` 以外的地方設定變數而沒有後代選擇器,主題選擇器就讀不出主題的顏色;+- 在字型棧裡寫了通用字型族(`sans-serif`、`serif` …)或 `ui-*` 關鍵字,這會蓋掉使用者選的中文字型;+- 任一模式下沒達到 WCAG AA 對比度:`--foreground` 和 `--muted-foreground` 在每個表面上需要 4.5:1,`--brand` 在閱讀表面上需要 4.5:1,主按鈕文字在按鈕上需要 4.5:1,`--faint-foreground` 需要 3:1。++## 檢查與預覽++在 [Multica 倉庫](https://github.com/multica-ai/multica)的本地副本里執行:++```bash+pnpm theme:check path/to/paper # 資料夾+pnpm theme:check paper.zip --json # zip,輸出 JSON 供 CI 使用+pnpm theme:preview path/to/paper --out preview # preview/light.png 和 preview/dark.png+```++`theme:check` 報告 manifest 錯誤、被攔截的 CSS、非公開變數、通用字型族和兩種模式下的對比度,每條都帶 `theme.css` 中的行號;有錯誤時以狀態碼 1 退出。警告(比如無法解析的顏色)不會導致失敗。++`theme:preview` 渲染主題商店展示的截圖:任務列表旁邊開啟一個任務,用應用自己的樣式搭建,主題選項取預設值。++開發過程中如果主題隱藏或弄亂了介面,在地址後加 `?theme=default` 開啟應用,或者載入後立刻按住 **Shift**;見[主題出問題時](/themes#主題出問題時)。++## 釋出到主題商店++主題商店列出 [multica-ai/multica-themes](https://github.com/multica-ai/multica-themes) 倉庫裡的主題。詳細說明見它的[貢獻指南](https://github.com/multica-ai/multica-themes/blob/main/CONTRIBUTING.md),簡單來說:++<Steps>+<Step>++### 給主題一個獨立倉庫++把主題放在一個公開的 GitHub 倉庫裡。[multica-ai/multica-theme-sample](https://github.com/multica-ai/multica-theme-sample) 是一個帶釋出工作流的模板。++</Step>+<Step>++### 釋出一個 release++用 manifest 裡的 `version` 打 tag(`1.0.0` 或 `v1.0.0`),並把打包好的主題作為 `theme.zip` 附加到 release 上。++</Step>+<Step>++### 加入倉庫++提一個 pull request,把主題加到倉庫的 `themes.json` 裡。pull request 會對這個 release 執行 `theme:check` 和 `theme:preview`,並在評論裡貼出結果;通過後由維護者合併。++</Step>+</Steps>++新 release 通過同樣的檢查後,大約一小時內上架;裝過這個主題的人會看到更新。沒通過檢查的 release 不會替換已上架的版本。應用只會安裝通過檢查的那個 `theme.zip`,並用與匯入主題相同的解析器和 CSS 檢查讀取它。++商店卡片會顯示主題從這個 Multica 伺服器被下載的次數。每次安裝和每次更新都算一次,沒裝的主題按下載次數從多到少排列。++## 接下來++- [主題與外觀](/themes) — 安裝、更新和移除主題。+- [`docs/theming.md`](https://github.com/multica-ai/multica/blob/main/docs/theming.md) — 自動生成的變數和選擇器參考。diff --git a/apps/docs/content/docs/developers/themes.zh.mdx b/apps/docs/content/docs/developers/themes.zh.mdxnew file mode 100644index 0000000000..5cf41dba5d--- /dev/null+++ b/apps/docs/content/docs/developers/themes.zh.mdx@@ -0,0 +1,234 @@+---+title: 制作主题+description: Multica 的主题格式(manifest、CSS 变量、选项和锚点),如何编写和检查主题,以及如何发布到主题商店。+---++import { Callout } from "fumadocs-ui/components/callout";+import { Step, Steps } from "fumadocs-ui/components/steps";++Multica 主题是一个文件夹,包含 `manifest.json`、`theme.css`,以及 CSS 用到的字体和图片。CSS 为浅色和深色模式设置公开变量,也可以重新设计一组稳定的锚点;manifest 给主题命名,还可以声明选项,让用户在 **设置 → 外观** 里调整。主题永远不会运行 JavaScript。++<Callout type="warn">+ 主题格式是 Beta API。在宣布稳定之前,变量、锚点和 manifest 都可能变化。完整的、自动生成的变量和锚点列表在 [`docs/theming.md`](https://github.com/multica-ai/multica/blob/main/docs/theming.md);本页讲它们怎么配合使用。+</Callout>++## 快速开始++<Steps>+<Step>++### 从副本开始++在 **设置 → 外观** 选一个最接近你想要的主题,然后选择 **制作自己的主题 → 导入主题 → 复制"…"为新主题**。副本有自己的 id(`pop-copy`、`pop-copy-2` …),带着原主题的选项,`theme.css` 每行一条声明。不做修改时,它和原主题一模一样。++</Step>+<Step>++### 编辑++- **桌面端** 把副本写进主题文件夹并打开它。用任何编辑器改 `theme.css`:保存后,所有打开的窗口约一秒内生效。+- **网页端** 把副本下载为 `.zip`。解压、修改,再用 **导入主题 → 主题文件夹** 导入。相同的 `id` 会替换已安装的副本,并保留选项值。++</Step>+<Step>++### 检查++分享之前,在 [Multica 仓库](https://github.com/multica-ai/multica)的本地副本里运行检查(见[检查与预览](#检查与预览))。++</Step>+</Steps>++## 文件夹++```text+paper/+├── manifest.json+├── theme.css+└── fonts/+ └── serif.woff2+```++文件夹可以放在 `.zip` 的最顶层,也可以是 `.zip` 里唯一的文件夹。字体(`woff2`、`woff`、`ttf`、`otf`)和图片(`png`、`jpg`、`webp`、`gif`、`avif`、`svg`)以外的文件会被忽略。整个主题最大 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 }+ ]+}+```++| 字段 | 规则 |+|---|---|+| `apiVersion` | 必须是 `1`。 |+| `id` | 1–40 个字符,只能是 `a-z`、`0-9` 和 `-`。内置 id(`default`、`pop`、`github`、`blueprint`、`notion`)保留不可用。导入 id 已安装的主题会替换它。 |+| `name` | 必填,最多 40 个字符。 |+| `author`、`version`、`description` | 可选,安装时显示。主题商店要求有 `version`。 |+| `options` | 最多 24 个,见[选项](#选项)。 |++### 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;+}++.theme-dark {+ --page-canvas: var(--paper-color);+}++:root[data-theme-option-hyphens] [data-mc="content"] p {+ hyphens: auto;+}+```++变量设置在 `.theme-light` 和 `.theme-dark` 上,它们都在 `<html>` 上。主题的 CSS 在应用自身样式之后加载,所以优先级相同时主题胜出:选择器保持这么简单,不要用 `!important`。++用户自己在外观页的选择仍然优先于主题:提高对比度会替换次要文字和边框颜色,选了非默认的字体会替换字体变量。颜色完全由主题决定;想让用户自己选颜色,就声明一个选项。++## 变量++变量分为几层:++- **基础**:颜色、表面、阴影、`--radius`、字号阶梯和字体,其他一切都建立在它们之上。改 `--surface` 或 `--radius` 会影响所有用到它的组件。+- **组件与产品**:菜单、按钮、导航行、任务行、看板、状态颜色,默认取自某个基础变量。设置其中一个只改这个组件:`--menu-radius: 0` 只让菜单变成直角。+- **编辑器内容**:标题、列表、表格、引用、链接、代码和语法高亮颜色,作用于任务描述、评论、聊天和文档。++应用从不声明组件变量;组件读取它时自带默认值作为回退。所以组件变量可以设置在任意祖先元素上,不限于 `.theme-light`:++```css+.theme-light [data-mc="chat-window"] {+ --code-block-background: transparent;+}+```++[变量参考](https://github.com/multica-ai/multica/blob/main/docs/theming.md#variable-reference)列出了每个变量及其浅色和深色默认值。++## 选项++使用这个主题时,选项显示在外观页的 **主题选项** 下。`toggle` 和 `select` 在 `<html>` 上设置属性;其他类型总会在 `<html>` 上设置变量 `--<id>`,值为用户选的值或默认值,所以 `theme.css` 直接用 `var(--<id>)` 读取即可。++| 类型 | 字段 | 结果 |+|---|---|---|+| `heading` | — | 开始一个分组;`description` 显示在标题下方。 |+| `toggle` | `default`:`true` 或 `false` | 打开时为 `data-theme-option-<id>="on"`,关闭时没有这个属性。 |+| `select` | `choices`:`[{ "value", "label", "swatch"? }]`,`default` | `data-theme-option-<id>="<value>"`。每个选项都有 `swatch` 时,显示为色点。 |+| `color` | `default`:十六进制颜色,或 `{ "light", "dark" }` | `--<id>`:每个模式各一个十六进制颜色。 |+| `number` | `default`,可选 `min`、`max`、`step`、`unit` | `--<id>`:数字加上 `unit`(`px`、`rem`、`%` …)。 |+| `slider` | 同 `number`,`min` 和 `max` 必填 | 同 `number`。 |+| `text` | `default`:一个 CSS 值 | `--<id>`:用户输入的值,前提是它安全。 |+| `font` | `default`:字体栈 | `--<id>`:字体栈。 |+| `variable-select` | `choices`:`[{ "value", "label" }]`,值为 CSS 值,`default` | `--<id>`:选中的值。 |++选项 id 为 1–48 个字符,只能是 `a-z`、`0-9` 和 `-`,以字母开头。`label`、`description` 和选项标签可以是字符串,也可以是以语言为键的对象(`en`、`zh-Hans`、`zh-Hant`、`ja`、`ko`、`es`、`fr`),英文为回退。++```json+{ "id": "page-width", "type": "slider", "label": "Page width", "default": 46, "min": 30, "max": 60, "step": 2, "unit": "rem" }+```++```css+[data-mc="content"] { max-width: var(--page-width); }+```++## 选择器++选择锚点、slot 和状态钩子,不要选类名或 DOM 结构,后者随时会变。锚点、slot 和钩子会保持到下一个 `apiVersion`。++- **锚点** 是应用主要部分上的 `data-mc` 属性:`app-rail`、`sidebar`、`nav-item`、`page`、`issue-row`、`board-card`、`content`(富文本)、`comment`、`chat-window`、`inbox-item` 等。很多锚点带有状态,比如任务行上的 `data-status` 和 `data-priority`。+- **Slot** 是 UI 基础组件的 `data-slot` 属性:`button`(还有 `data-variant` 和 `data-size`)、`input`、`dialog-content`、`dropdown-menu-item` 等。+- **`<html>` 上的状态**:`.theme-light` / `.theme-dark`、`.is-desktop` / `.is-web`、`.mod-macos` / `.mod-windows` / `.mod-linux`、`.is-focused`、`.is-sidebar-collapsed`、`[data-theme="<id>"]`,以及主题自己的 `[data-theme-option-<id>]`。++```css+.mod-macos.is-desktop:not(.is-focused) [data-mc="app-rail"] { opacity: 0.7; }+.theme-dark [data-mc="issue-row"][data-priority="urgent"] { box-shadow: inset 2px 0 var(--priority-urgent); }+```++[选择器参考](https://github.com/multica-ai/multica/blob/main/docs/theming.md#selectors)列出了每个锚点、它的属性和每个 slot。++## CSS 不能做什么++任何会加载资源的写法都会被拒绝,因为 CSS 可以通过属性选择器读取页面内容,再通过请求把它发出去:++- `url()` 只能指向主题文件夹里的文件(`url(fonts/serif.woff2)`)或片段(`url(#filter)`),并会被改写成文件的 `data:` URL。+- `@import`、`image()`、`image-set()`、`cross-fade()`、`element()`、`src()` 和 `expression()` 都会被拒绝,`behavior` 和 `-moz-binding` 也是。++转义、大小写和注释都绕不过检查,它按浏览器的方式读取 CSS。主题没通过检查时,什么都不会安装,并列出每个问题及其在 `theme.css` 中的行号。++以下情况 `pnpm theme:check` 也会判定失败:++- 使用了非公开变量,除非它是选项 id,或者主题自己用 `var()` 读取它;+- 在 `.theme-light` 和 `.theme-dark` 以外的地方设置变量而没有后代选择器,主题选择器就读不出主题的颜色;+- 在字体栈里写了通用字体族(`sans-serif`、`serif` …)或 `ui-*` 关键字,这会盖掉用户选的中文字体;+- 任一模式下没达到 WCAG AA 对比度:`--foreground` 和 `--muted-foreground` 在每个表面上需要 4.5:1,`--brand` 在阅读表面上需要 4.5:1,主按钮文字在按钮上需要 4.5:1,`--faint-foreground` 需要 3:1。++## 检查与预览++在 [Multica 仓库](https://github.com/multica-ai/multica)的本地副本里运行:++```bash+pnpm theme:check path/to/paper # 文件夹+pnpm theme:check paper.zip --json # zip,输出 JSON 供 CI 使用+pnpm theme:preview path/to/paper --out preview # preview/light.png 和 preview/dark.png+```++`theme:check` 报告 manifest 错误、被拦截的 CSS、非公开变量、通用字体族和两种模式下的对比度,每条都带 `theme.css` 中的行号;有错误时以状态码 1 退出。警告(比如无法解析的颜色)不会导致失败。++`theme:preview` 渲染主题商店展示的截图:任务列表旁边打开一个任务,用应用自己的样式搭建,主题选项取默认值。++开发过程中如果主题隐藏或弄乱了界面,在地址后加 `?theme=default` 打开应用,或者加载后立刻按住 **Shift**;见[主题出问题时](/themes#主题出问题时)。++## 发布到主题商店++主题商店列出 [multica-ai/multica-themes](https://github.com/multica-ai/multica-themes) 仓库里的主题。详细说明见它的[贡献指南](https://github.com/multica-ai/multica-themes/blob/main/CONTRIBUTING.md),简单来说:++<Steps>+<Step>++### 给主题一个独立仓库++把主题放在一个公开的 GitHub 仓库里。[multica-ai/multica-theme-sample](https://github.com/multica-ai/multica-theme-sample) 是一个带发布工作流的模板。++</Step>+<Step>++### 发布一个 release++用 manifest 里的 `version` 打 tag(`1.0.0` 或 `v1.0.0`),并把打包好的主题作为 `theme.zip` 附加到 release 上。++</Step>+<Step>++### 加入仓库++提一个 pull request,把主题加到仓库的 `themes.json` 里。pull request 会对这个 release 运行 `theme:check` 和 `theme:preview`,并在评论里贴出结果;通过后由维护者合并。++</Step>+</Steps>++新 release 通过同样的检查后,大约一小时内上架;装过这个主题的人会看到更新。没通过检查的 release 不会替换已上架的版本。应用只会安装通过检查的那个 `theme.zip`,并用与导入主题相同的解析器和 CSS 检查读取它。++商店卡片会显示主题从这个 Multica 服务端被下载的次数。每次安装和每次更新都算一次,没装的主题按下载次数从多到少排列。++## 接下来++- [主题与外观](/themes) — 安装、更新和移除主题。+- [`docs/theming.md`](https://github.com/multica-ai/multica/blob/main/docs/theming.md) — 自动生成的变量和选择器参考。diff --git a/apps/docs/content/docs/environment-variables.fr.mdx b/apps/docs/content/docs/environment-variables.fr.mdxindex f780e56dec..5ada9e956a 100644--- a/apps/docs/content/docs/environment-variables.fr.mdx+++ b/apps/docs/content/docs/environment-variables.fr.mdx@@ -200,6 +200,8 @@ Les limites de débit d'authentification nécessitent `REDIS_URL` ; sans cette v| Plugins | `MULTICA_PLUGIN_SURFACE_ORIGIN` | Origine navigateur dédiée, sans cookies, routée vers ce backend ; doit différer des origines de l'application et de l'API, et préserver `Host` || Plugins | `MULTICA_PLUGIN_API_URL` | URL de base complète et versionnée de la Plugin Public API, comme `https://plugin-api.example.com/v1` ; se rabat sur `MULTICA_PUBLIC_URL` + `/v1` || Plugins | `MULTICA_PLUGIN_DIR` | Répertoire absolu facultatif utilisé pour publier des bundles de plugins locaux pendant le développement |+| Boutique de thèmes | `MULTICA_THEME_STORE` | Activée par défaut, elle lit le registre officiel [multica-themes](https://github.com/multica-ai/multica-themes) ; `off` désactive la boutique de thèmes communautaires et toute requête au registre |+| Boutique de thèmes | `MULTICA_THEME_REGISTRY_URL` | L'`index.json` d'un autre registre, par exemple un fork de l'officiel ; voir [Thèmes et apparence](/themes#auto-hébergement) |Sans `GITHUB_APP_ID` et la clé privée, les PR sont toujours liées, reflétées et changent normalement le statut de la tâche lors du merge, mais les cartes n'affichent ni statut CI ni possibilité de fusion, et l'entrée de dépôt « Choisir depuis GitHub » est désactivée.diff --git a/apps/docs/content/docs/environment-variables.ja.mdx b/apps/docs/content/docs/environment-variables.ja.mdxindex 7e071e3a39..0a4371c761 100644--- a/apps/docs/content/docs/environment-variables.ja.mdx+++ b/apps/docs/content/docs/environment-variables.ja.mdx@@ -200,6 +200,8 @@ allowlist の正確な判定順序は[ログインとサインアップ](/auth-s| Plugins | `MULTICA_PLUGIN_SURFACE_ORIGIN` | バックエンドへルーティングする Cookie なしの専用 origin。app/API origin と分離し、`Host` を保持すること || Plugins | `MULTICA_PLUGIN_API_URL` | バージョンを含む Plugin Public API の完全な Base URL(例: `https://plugin-api.example.com/v1`)。未設定時は `MULTICA_PUBLIC_URL` + `/v1` || Plugins | `MULTICA_PLUGIN_DIR` | 開発時にローカル plugin bundle を公開するための任意の絶対ディレクトリ |+| テーマストア | `MULTICA_THEME_STORE` | 既定で有効。公式の [multica-themes](https://github.com/multica-ai/multica-themes) レジストリを読みます。`off` でコミュニティのテーマストアを無効にし、レジストリへのリクエストを止めます |+| テーマストア | `MULTICA_THEME_REGISTRY_URL` | 公式レジストリの fork など、別のレジストリの `index.json`。[テーマと外観](/themes#セルフホスト)を参照 |`GITHUB_APP_ID` と秘密鍵を設定しなくても、PR の関連付け・ミラー・マージ時のステータス変更は通常どおり動きますが、カードに CI とマージ可否のステータスが表示されず、「GitHub から選択」のリポジトリ入口も無効になります。diff --git a/apps/docs/content/docs/environment-variables.ko.mdx b/apps/docs/content/docs/environment-variables.ko.mdxindex 972eab32cc..cf7ba7af41 100644--- a/apps/docs/content/docs/environment-variables.ko.mdx+++ b/apps/docs/content/docs/environment-variables.ko.mdx@@ -200,6 +200,8 @@ reverse proxy 뒤에 배포한다면 실제 proxy 네트워크를 입력해야| Plugins | `MULTICA_PLUGIN_SURFACE_ORIGIN` | 백엔드로 라우팅되는 쿠키 없는 전용 origin. app/API origin과 달라야 하며 `Host`를 보존해야 함 || Plugins | `MULTICA_PLUGIN_API_URL` | 버전을 포함한 Plugin Public API의 전체 Base URL(예: `https://plugin-api.example.com/v1`). 설정하지 않으면 `MULTICA_PUBLIC_URL` + `/v1` 사용 || Plugins | `MULTICA_PLUGIN_DIR` | 개발 중 로컬 plugin bundle을 게시하는 선택적 절대 디렉터리 |+| 테마 스토어 | `MULTICA_THEME_STORE` | 기본으로 켜져 있으며 공식 [multica-themes](https://github.com/multica-ai/multica-themes) 레지스트리를 읽습니다. `off`로 커뮤니티 테마 스토어를 끄고 레지스트리 요청을 모두 멈춥니다 |+| 테마 스토어 | `MULTICA_THEME_REGISTRY_URL` | 공식 레지스트리의 fork 등 다른 레지스트리의 `index.json`. [테마와 모양](/themes#셀프-호스팅)을 참고하세요 |`GITHUB_APP_ID`와 private key를 설정하지 않아도 PR 연결, 미러링, merge 시 상태 변경은 정상적으로 작동합니다. 다만 카드에 CI와 merge 가능 상태가 표시되지 않고 "GitHub에서 선택" 저장소 메뉴도 비활성화됩니다.diff --git a/apps/docs/content/docs/environment-variables.mdx b/apps/docs/content/docs/environment-variables.mdxindex 473c56e8a9..78831bdc6b 100644--- a/apps/docs/content/docs/environment-variables.mdx+++ b/apps/docs/content/docs/environment-variables.mdx@@ -200,6 +200,8 @@ The auth rate limits require `REDIS_URL`; without it, the startup log notes that| Plugins | `MULTICA_PLUGIN_SURFACE_ORIGIN` | Dedicated cookie-free browser origin routed to this backend; must differ from app/API origins and preserve `Host` || Plugins | `MULTICA_PLUGIN_API_URL` | Complete versioned Plugin Public API base URL, such as `https://plugin-api.example.com/v1`; falls back to `MULTICA_PUBLIC_URL` + `/v1` || Plugins | `MULTICA_PLUGIN_DIR` | Optional absolute directory used to publish local plugin bundles during development |+| Theme store | `MULTICA_THEME_STORE` | On by default, reading the official [multica-themes](https://github.com/multica-ai/multica-themes) registry; `off` turns the community theme store off and stops every registry request |+| Theme store | `MULTICA_THEME_REGISTRY_URL` | Another registry's `index.json`, such as a fork of the official one; see [Themes and appearance](/themes#self-hosting) |Without `GITHUB_APP_ID` and the private key, PRs still link, mirror, and move issues on merge normally, but cards show no CI or mergeability status, and the "pick from GitHub" repository entry is disabled.diff --git a/apps/docs/content/docs/environment-variables.zh-Hant.mdx b/apps/docs/content/docs/environment-variables.zh-Hant.mdxindex e3376a169e..14a1085d0b 100644--- a/apps/docs/content/docs/environment-variables.zh-Hant.mdx+++ b/apps/docs/content/docs/environment-variables.zh-Hant.mdx@@ -196,6 +196,8 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com| 外掛 | `MULTICA_PLUGIN_SURFACE_ORIGIN` | 路由到後端的獨立無 Cookie 瀏覽器 origin;必須不同於 app/API origin,並保留 `Host` || 外掛 | `MULTICA_PLUGIN_API_URL` | 帶版本的外掛 Public API 完整 Base URL,例如 `https://plugin-api.example.com/v1`;未設定時使用 `MULTICA_PUBLIC_URL` + `/v1` || 外掛 | `MULTICA_PLUGIN_DIR` | 開發時用於釋出本地外掛包的可選絕對目錄 |+| 主題商店 | `MULTICA_THEME_STORE` | 預設開啟,讀取官方 [multica-themes](https://github.com/multica-ai/multica-themes) 倉庫;設為 `off` 關閉社群主題商店,伺服器不再請求倉庫 |+| 主題商店 | `MULTICA_THEME_REGISTRY_URL` | 改用其他倉庫的 `index.json`,例如官方倉庫的 fork;見 [主題與外觀](/themes#自託管) |不配置 `GITHUB_APP_ID` 和私鑰時,PR 仍會正常關聯、映象,並在合併後改狀態,但卡片上不顯示 CI 與可合併狀態,"從 GitHub 選擇"倉庫入口也會禁用。diff --git a/apps/docs/content/docs/environment-variables.zh.mdx b/apps/docs/content/docs/environment-variables.zh.mdxindex f7e7aecf7d..ef6b53a803 100644--- a/apps/docs/content/docs/environment-variables.zh.mdx+++ b/apps/docs/content/docs/environment-variables.zh.mdx@@ -200,6 +200,8 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com| 插件 | `MULTICA_PLUGIN_SURFACE_ORIGIN` | 路由到后端的独立无 Cookie 浏览器 origin;必须不同于 app/API origin,并保留 `Host` || 插件 | `MULTICA_PLUGIN_API_URL` | 带版本的插件 Public API 完整 Base URL,例如 `https://plugin-api.example.com/v1`;未设置时使用 `MULTICA_PUBLIC_URL` + `/v1` || 插件 | `MULTICA_PLUGIN_DIR` | 开发时用于发布本地插件包的可选绝对目录 |+| 主题商店 | `MULTICA_THEME_STORE` | 默认开启,读取官方 [multica-themes](https://github.com/multica-ai/multica-themes) 仓库;设为 `off` 关闭社区主题商店,服务端不再请求仓库 |+| 主题商店 | `MULTICA_THEME_REGISTRY_URL` | 改用其他仓库的 `index.json`,比如官方仓库的 fork;见 [主题与外观](/themes#自托管) |不配置 `GITHUB_APP_ID` 和私钥时,PR 仍会正常关联、镜像,并在合并后改状态,但卡片上不显示 CI 与可合并状态,"从 GitHub 选择"仓库入口也会禁用。diff --git a/apps/docs/content/docs/meta.fr.json b/apps/docs/content/docs/meta.fr.jsonindex 49c9aefd56..662ec5be52 100644--- a/apps/docs/content/docs/meta.fr.json+++ b/apps/docs/content/docs/meta.fr.json@@ -31,6 +31,7 @@"chat","inbox","shortcuts",+ "themes","---Runtime et exécution---","tasks","daemon-runtimes",diff --git a/apps/docs/content/docs/meta.ja.json b/apps/docs/content/docs/meta.ja.jsonindex 5ebc6cc603..a28db4249e 100644--- a/apps/docs/content/docs/meta.ja.json+++ b/apps/docs/content/docs/meta.ja.json@@ -31,6 +31,7 @@"chat","inbox","shortcuts",+ "themes","---ランタイムと実行---","tasks","daemon-runtimes",diff --git a/apps/docs/content/docs/meta.json b/apps/docs/content/docs/meta.jsonindex 3d5d70f71c..b990ba5336 100644--- a/apps/docs/content/docs/meta.json+++ b/apps/docs/content/docs/meta.json@@ -31,6 +31,7 @@"chat","inbox","shortcuts",+ "themes","---Runtime & execution---","tasks","daemon-runtimes",diff --git a/apps/docs/content/docs/meta.ko.json b/apps/docs/content/docs/meta.ko.jsonindex 6940951a18..1042049d6c 100644--- a/apps/docs/content/docs/meta.ko.json+++ b/apps/docs/content/docs/meta.ko.json@@ -31,6 +31,7 @@"chat","inbox","shortcuts",+ "themes","---런타임과 실행---","tasks","daemon-runtimes",diff --git a/apps/docs/content/docs/meta.zh-Hant.json b/apps/docs/content/docs/meta.zh-Hant.jsonindex b74c9319cf..a1a5c30fa3 100644--- a/apps/docs/content/docs/meta.zh-Hant.json+++ b/apps/docs/content/docs/meta.zh-Hant.json@@ -31,6 +31,7 @@"chat","inbox","shortcuts",+ "themes","---執行時與執行---","tasks","daemon-runtimes",diff --git a/apps/docs/content/docs/meta.zh.json b/apps/docs/content/docs/meta.zh.jsonindex 04b4639a67..4eaa430d87 100644--- a/apps/docs/content/docs/meta.zh.json+++ b/apps/docs/content/docs/meta.zh.json@@ -31,6 +31,7 @@"chat","inbox","shortcuts",+ "themes","---运行时与执行---","tasks","daemon-runtimes",diff --git a/apps/docs/content/docs/shortcuts.fr.mdx b/apps/docs/content/docs/shortcuts.fr.mdxindex 9cc02ac412..dbe07aa6db 100644--- a/apps/docs/content/docs/shortcuts.fr.mdx+++ b/apps/docs/content/docs/shortcuts.fr.mdx@@ -104,7 +104,7 @@ Les préférences personnelles se trouvent dans **Paramètres → Préférences*| Groupe | Réglage | Enregistré ||---|---|---|| **Langue et région** | Langue : English, 中文, 한국어, 日本語, Français. La page se recharge après un changement.<br />Fuseau horaire : suit le navigateur par défaut ; sert aux dates et graphiques de tous vos espaces de travail. La liste couvre tous les fuseaux et se filtre par recherche. | Dans votre compte, synchronisé sur vos autres appareils |-| **Apparence** | Thème : Clair, Sombre ou Système. Vous pouvez aussi taper « thème » dans la recherche pour en changer. | Sur cet appareil |+| **Apparence** | A sa propre page, **Paramètres → Apparence** : mode (Clair, Sombre ou Système), thème, polices et mise en page. Vous pouvez aussi taper « thème » dans la recherche pour changer de mode. Voir [Thèmes et apparence](/themes). | Sur cet appareil || **Commentaires et discussion** | **Épingler la barre de commentaire en bas** : la zone de commentaire reste visible pendant la lecture d'une longue chronologie.<br />**En répondant à un agent en cours d'exécution** : choix par défaut entre « Ajouter à l'exécution en cours » et « Démarrer après cette exécution », modifiable pour chaque message avant l'envoi ; voir [Réorienter un agent en cours d'exécution](/mentioning-agents#réorienter-un-agent-en-cours-dexécution).<br />**Fenêtre de discussion flottante** : désactivée, le bouton de discussion n'apparaît plus en bas à droite. | Sur cet appareil || **Ouverture des tâches** | Un clic sur une carte ou une ligne ouvre la page complète ou l'aperçu latéral. Maj+clic ouvre l'autre. | Sur cet appareil || **Champs affichés à la création de tâches** | Les champs gardés dans la barre d'outils pour « Création avec un agent » et « Création manuelle ». Les champs masqués restent accessibles depuis le menu ⋯ et réapparaissent tant qu'ils contiennent une valeur. | Sur cet appareil, pour l'espace de travail actuel |diff --git a/apps/docs/content/docs/shortcuts.ja.mdx b/apps/docs/content/docs/shortcuts.ja.mdxindex 8c7d8a719c..a4fa7bb631 100644--- a/apps/docs/content/docs/shortcuts.ja.mdx+++ b/apps/docs/content/docs/shortcuts.ja.mdx@@ -10,7 +10,7 @@ import { Step, Steps } from "fumadocs-ui/components/steps";## 検索-`⌘K` を押すか、サイドバー上部の**検索...**をクリックすると検索ボックスが開きます。何も入力していないときは、**新規タスク**と最近開いたタスクが表示されます。キーワードを入力すると、結果がグループごとに表示されます。+`⌘K` を押すか、サイドバー上部の**検索...** をクリックすると検索ボックスが開きます。何も入力していないときは、**新規タスク**と最近開いたタスクが表示されます。キーワードを入力すると、結果がグループごとに表示されます。| グループ | 見つかるもの ||---|---|@@ -104,7 +104,7 @@ import { Step, Steps } from "fumadocs-ui/components/steps";| グループ | 設定 | 保存先 ||---|---|---|| **言語と地域** | 言語:English、中文、한국어、日本語、Français。変更するとページが再読み込みされます。<br />タイムゾーン:既定ではブラウザに従います。すべてのワークスペースの日付とグラフに使われ、全タイムゾーンから検索して選べます。 | アカウント(ほかのデバイスにも同期) |-| **外観** | テーマ:ライト、ダーク、システム。検索ボックスで「テーマ」と入力して切り替えることもできます。 | このデバイス |+| **外観** | 専用の **設定 → 外観** ページにあります:モード(ライト、ダーク、システム)、テーマ、フォント、レイアウト。検索ボックスで「テーマ」と入力してモードを切り替えることもできます。[テーマと外観](/themes)を参照。 | このデバイス || **コメントとチャット** | **コメント欄を下部に固定**:長いタイムラインを読んでいる間もコメント欄が見えたままになります。<br />**実行中のエージェントに返信するとき**:既定を「現在の実行に追加」と「この実行の後に開始」のどちらにするか。送信前にメッセージごとに変更できます。[実行中のエージェントに割り込む](/mentioning-agents#実行中のエージェントに割り込む)を参照。<br />**フローティングチャット**:オフにすると、右下のチャットボタンが表示されなくなります。 | このデバイス || **タスクを開く** | カードや行をクリックしたときに、ページ全体とサイドプレビューのどちらで開くか。Shift+クリックでもう一方で開きます。 | このデバイス || **タスク作成時に表示するフィールド** | 「エージェントで作成」と「手動作成」それぞれのツールバーに常に表示するフィールド。非表示のフィールドも ⋯ メニューから使え、値がある間は自動的に表示されます。 | このデバイスの現在のワークスペース |diff --git a/apps/docs/content/docs/shortcuts.ko.mdx b/apps/docs/content/docs/shortcuts.ko.mdxindex 101be9670e..ec771e871b 100644--- a/apps/docs/content/docs/shortcuts.ko.mdx+++ b/apps/docs/content/docs/shortcuts.ko.mdx@@ -10,7 +10,7 @@ import { Step, Steps } from "fumadocs-ui/components/steps";## 검색-`⌘K`를 누르거나 사이드바 위쪽의 **검색...**을 클릭하면 검색 창이 열립니다. 아무것도 입력하지 않으면 **새 태스크**와 최근에 연 태스크가 보입니다. 키워드를 입력하면 결과가 그룹별로 표시됩니다.+`⌘K`를 누르거나 사이드바 위쪽의 **검색...** 을 클릭하면 검색 창이 열립니다. 아무것도 입력하지 않으면 **새 태스크**와 최근에 연 태스크가 보입니다. 키워드를 입력하면 결과가 그룹별로 표시됩니다.| 그룹 | 찾을 수 있는 것 ||---|---|@@ -104,7 +104,7 @@ import { Step, Steps } from "fumadocs-ui/components/steps";| 그룹 | 설정 | 저장 위치 ||---|---|---|| **언어 및 지역** | 언어: English, 中文, 한국어, 日本語, Français. 바꾸면 페이지가 다시 로드됩니다.<br />시간대: 기본값은 브라우저를 따릅니다. 모든 워크스페이스의 날짜와 차트에 쓰이며, 전체 시간대에서 검색해 고를 수 있습니다. | 계정(다른 기기에도 동기화) |-| **모양** | 테마: 라이트, 다크, 시스템. 검색 창에 '테마'를 입력해 바꿀 수도 있습니다. | 이 기기 |+| **모양** | 별도의 **설정 → 모양** 페이지에 있습니다: 모드(라이트, 다크, 시스템), 테마, 글꼴, 레이아웃. 검색 창에 '테마'를 입력해 모드를 바꿀 수도 있습니다. [테마와 모양](/themes)을 참고하세요. | 이 기기 || **댓글 및 채팅** | **댓글 입력란을 하단에 고정**: 긴 타임라인을 읽는 동안에도 댓글 입력란이 보입니다.<br />**실행 중인 에이전트에 답장할 때**: 기본값을 '현재 실행에 추가'와 '이번 실행 후 시작' 중 무엇으로 할지 정합니다. 보내기 전에 메시지마다 바꿀 수 있습니다. [실행 중인 에이전트에게 끼어들기](/mentioning-agents#실행-중인-에이전트에게-끼어들기)를 참고하세요.<br />**플로팅 채팅 창**: 끄면 오른쪽 아래 채팅 버튼이 더 이상 표시되지 않습니다. | 이 기기 || **태스크 열기** | 카드나 행을 클릭했을 때 전체 페이지와 사이드 미리보기 중 어디로 열지 정합니다. Shift+클릭하면 다른 쪽으로 열립니다. | 이 기기 || **태스크 생성 시 표시할 필드** | '에이전트로 생성'과 '수동 생성' 각각의 툴바에 항상 표시할 필드. 숨긴 필드도 ⋯ 메뉴에서 쓸 수 있고, 값이 있는 동안에는 자동으로 표시됩니다. | 이 기기의 현재 워크스페이스 |diff --git a/apps/docs/content/docs/shortcuts.mdx b/apps/docs/content/docs/shortcuts.mdxindex cb89db34b9..3c1476c95d 100644--- a/apps/docs/content/docs/shortcuts.mdx+++ b/apps/docs/content/docs/shortcuts.mdx@@ -104,7 +104,7 @@ Personal preferences live under **Settings → Preferences** and apply immediate| Group | Setting | Stored in ||---|---|---|| **Language & region** | Language: English, 中文, 한국어, 日本語, Français. The page reloads after a change.<br />Time zone: follows the browser by default; used for dates and charts in all your workspaces. The list covers every time zone and is searchable. | Your account, synced to other devices |-| **Appearance** | Theme: Light, Dark, or System. You can also type "theme" in the search box to switch. | This device |+| **Appearance** | Has its own page, **Settings → Appearance**: mode (Light, Dark, or System), theme, fonts, and layout. You can also type "theme" in the search box to switch the mode. See [Themes and appearance](/themes). | This device || **Comments & chat** | **Pin comment bar to bottom**: keeps the comment box in view while you read a long timeline.<br />**When replying to a running agent**: whether a reply defaults to "Add to current run" or "Start after this run". You can still change it per message; see [Steer a running agent](/mentioning-agents#steer-a-running-agent).<br />**Floating chat window**: when off, the chat button no longer appears in the bottom-right corner. | This device || **Opening issues** | Whether clicking a card or row opens the full page or a side preview. Shift+Click opens the other one. | This device || **Fields shown when creating issues** | Which fields stay on the toolbar for "Create with agent" and "Manual create". Hidden fields remain in the ⋯ menu and reappear while they hold a value. | This device, for the current workspace |diff --git a/apps/docs/content/docs/shortcuts.zh-Hant.mdx b/apps/docs/content/docs/shortcuts.zh-Hant.mdxindex 5c0b04aace..109485812d 100644--- a/apps/docs/content/docs/shortcuts.zh-Hant.mdx+++ b/apps/docs/content/docs/shortcuts.zh-Hant.mdx@@ -104,7 +104,7 @@ import { Step, Steps } from "fumadocs-ui/components/steps";| 分組 | 設定 | 儲存在 ||---|---|---|| **語言與地區** | 語言:English、中文、한국어、日本語、Français。切換後頁面會重新載入。<br />時區:預設跟隨瀏覽器;用於所有工作區的日期和圖表,可以搜尋全部時區。 | 帳號,其他裝置同步 |-| **外觀** | 主題:淺色、深色、跟隨系統。也可以在搜尋框裡輸入"主題"切換。 | 當前裝置 |+| **外觀** | 在獨立的 **設定 → 外觀** 頁面:模式(淺色、深色、跟隨系統)、主題、字型和版面。也可以在搜尋框裡輸入"主題"切換模式。見 [主題與外觀](/themes)。 | 當前裝置 || **評論與聊天** | **固定底部評論欄**:開啟時,閱讀很長的時間線也能隨時看到評論框。<br />**回覆正在執行的 AI 代理時**:預設"插話到當前執行"還是"本輪結束後開始",傳送前每條訊息仍可單獨改,見[給正在執行的 AI 代理插話](/mentioning-agents#給正在執行的 AI 代理插話)。<br />**懸浮聊天窗**:關閉後,頁面右下角不再顯示聊天按鈕。 | 當前裝置 || **開啟任務** | 點選卡片或行時開啟詳情頁還是懸浮預覽。按住 Shift 點選會開啟另一種。 | 當前裝置 || **建立任務時顯示的欄位** | 分別為"AI 代理建立"和"手動建立"選擇工具欄上常駐的欄位。隱藏的欄位仍可從 ⋯ 選單使用,有值時自動顯示。 | 當前裝置上的當前工作區 |diff --git a/apps/docs/content/docs/shortcuts.zh.mdx b/apps/docs/content/docs/shortcuts.zh.mdxindex 803c8e76b7..188ed585d2 100644--- a/apps/docs/content/docs/shortcuts.zh.mdx+++ b/apps/docs/content/docs/shortcuts.zh.mdx@@ -104,7 +104,7 @@ import { Step, Steps } from "fumadocs-ui/components/steps";| 分组 | 设置 | 保存在 ||---|---|---|| **语言与地区** | 语言:English、中文、한국어、日本語、Français。切换后页面会重新加载。<br />时区:默认跟随浏览器;用于所有工作区的日期和图表,可以搜索全部时区。 | 账号,其他设备同步 |-| **外观** | 主题:浅色、深色、跟随系统。也可以在搜索框里输入"主题"切换。 | 当前设备 |+| **外观** | 在单独的 **设置 → 外观** 页面:模式(浅色、深色、跟随系统)、主题、字体和布局。也可以在搜索框里输入"主题"切换模式。见 [主题与外观](/themes)。 | 当前设备 || **评论与聊天** | **固定底部评论栏**:开启时,阅读很长的时间线也能随时看到评论框。<br />**回复正在运行的智能体时**:默认"插话到当前运行"还是"本轮结束后开始",发送前每条消息仍可单独改,见[给正在运行的智能体插话](/mentioning-agents#给正在运行的智能体插话)。<br />**悬浮聊天窗**:关闭后,页面右下角不再显示聊天按钮。 | 当前设备 || **打开任务** | 点击卡片或行时打开详情页还是悬浮预览。按住 Shift 点击会打开另一种。 | 当前设备 || **创建任务时显示的字段** | 分别为"智能体创建"和"手动创建"选择工具栏上常驻的字段。隐藏的字段仍可从 ⋯ 菜单使用,有值时自动显示。 | 当前设备上的当前工作区 |diff --git a/apps/docs/content/docs/themes.fr.mdx b/apps/docs/content/docs/themes.fr.mdxnew file mode 100644index 0000000000..72babd9d80--- /dev/null+++ b/apps/docs/content/docs/themes.fr.mdx@@ -0,0 +1,111 @@+---+title: Thèmes et apparence+description: Choisir le mode clair ou sombre et un thème, installer des thèmes de la communauté depuis la boutique, les tenir à jour, importer les vôtres et revenir au thème par défaut quand un thème casse quelque chose.+---++import { Callout } from "fumadocs-ui/components/callout";+import { Step, Steps } from "fumadocs-ui/components/steps";++**Paramètres → Apparence** règle l'aspect de Multica sur cet appareil : le mode, le thème, le texte et la mise en page. Chaque changement s'applique immédiatement.++<Callout type="info">+ Les thèmes et la boutique de thèmes sont en bêta. Un thème qui s'affiche bien aujourd'hui peut avoir besoin d'une mise à jour de son auteur après une version de Multica.+</Callout>++## Mode et thème++Le **Mode** est Clair, Sombre ou Système (suit votre système d'exploitation). Vous pouvez aussi taper « thème » dans la recherche (`⌘K`) pour en changer.++Le **Thème** définit les couleurs, bordures, ombres et coins de toute l'app. Multica inclut Default, Pop, GitHub, Blueprint et Notion ; choisissez-en un dans la liste. **Gérer**, juste à côté, sert à installer, mettre à jour et supprimer d'autres thèmes. Un thème prend en charge le mode clair, le mode sombre ou les deux, et suit le mode choisi.++Certains thèmes ont des options, comme une couleur d'accent ou une largeur de page. Elles apparaissent sous **Options du thème** tant que ce thème est utilisé ; **Réinitialiser les options** rétablit les valeurs par défaut du thème.++Le reste de la page ne dépend pas du thème :++| Groupe | Ce qu'il règle |+|---|---|+| **Texte de l'interface** | Police et taille des menus, boutons, listes, de la barre latérale et des titres. |+| **Texte du contenu** | Police, taille et interligne des descriptions de tâches, commentaires, discussions et documents, ainsi que la police du code. |+| **Mise en page et accessibilité** | Densité, Réduire les animations et Augmenter le contraste. |++Si vous choisissez une police autre que celle par défaut, ou activez Augmenter le contraste, votre choix l'emporte sur celui du thème. Les couleurs appartiennent au thème ; pour une couleur qu'il ne propose pas en option, choisissez un autre thème ou [créez le vôtre](/developers/themes).++## La boutique de thèmes++**Gérer** ouvre une fenêtre avec les thèmes que vous avez installés et ceux de la boutique de la communauté. Les thèmes intégrés n'y figurent pas : ils sont toujours dans la liste. Cherchez par nom ou par auteur, et activez **Afficher uniquement les thèmes installés** pour masquer le reste.++Chaque thème de la boutique a une carte avec une capture d'écran (basculez entre la capture claire et sombre dans le coin), son auteur, une description, son nombre de téléchargements et un lien vers son dépôt GitHub. Les thèmes que vous n'avez pas installés sont classés du plus téléchargé au moins téléchargé.++<Steps>+<Step>++### Installer++Cliquez sur **Installer** sur une carte. Le thème est téléchargé, vérifié, enregistré sur cet appareil et utilisé.++</Step>+<Step>++### Changer++Cliquez sur **Utiliser** sur un thème installé, ou choisissez n'importe quel thème dans la liste. Le thème actif est marqué **Utilisé**.++</Step>+<Step>++### Supprimer++Cliquez sur **Supprimer** sur un thème installé. S'il était utilisé, Multica revient à Default.++</Step>+</Steps>++Les thèmes de la boutique sont créés par la communauté et vérifiés automatiquement avant d'être listés : ils ne peuvent pas exécuter de code, charger quoi que ce soit depuis Internet ni utiliser de fichiers hors du thème. Un thème peut tout de même modifier le style de toutes les pages, y compris les boîtes de dialogue et les avertissements.++Le nombre de téléchargements compte chaque installation et chaque mise à jour, de toutes les personnes qui utilisent le même serveur Multica.++## Mises à jour++Dès que vous avez installé un thème de la boutique, la page Apparence affiche une ligne **Thèmes de la boutique**. Cliquez sur **Rechercher des mises à jour**, puis sur **Tout mettre à jour**, ou mettez à jour un seul thème depuis sa carte avec **Mettre à jour vers …**. Une mise à jour conserve les valeurs des options du thème et ne change pas le thème que vous utilisez.++Les thèmes ne sont jamais mis à jour sans votre demande.++## Importer un thème++Un thème reçu sous forme de fichier, ou que vous avez créé, s'installe depuis **Créer le vôtre → Importer un thème** :++- **Fichier de thème (.zip)** installe un thème compressé.+- **Dossier du thème** installe un thème décompressé.++Multica affiche le nom, l'auteur et la version du thème avant de l'installer. N'installez que des thèmes de personnes de confiance. Importer un thème qui a le même id qu'un thème installé le remplace.++Pour créer votre propre thème, voir [Créer un thème](/developers/themes).++## Quand un thème casse quelque chose++Un thème peut masquer ou casser une partie de l'interface. Pour revenir à Default :++- ouvrez Multica avec `?theme=default` à la fin de l'adresse, ou+- maintenez **Maj** enfoncée un instant juste après le chargement de la page. Dans l'application de bureau, rechargez avec `⌘R` (`Ctrl+R` sous Windows et Linux) puis maintenez **Maj**.++Le thème reste en pause jusqu'à la fermeture de la fenêtre. La page Apparence affiche un avis avec **Utiliser mon thème** pour le réactiver ; vous pouvez aussi y choisir un autre thème ou supprimer celui qui pose problème.++## Où c'est enregistré++Le mode, le thème, ses options et les thèmes installés sont enregistrés sur cet appareil et ne sont pas synchronisés avec votre compte. Chaque navigateur et chaque application de bureau a les siens. Ils sont identiques dans tous les espaces de travail sur cet appareil.++## Auto-hébergement++Un serveur auto-hébergé liste par défaut le registre officiel, [multica-ai/multica-themes](https://github.com/multica-ai/multica-themes). Le serveur récupère les thèmes et les captures sur GitHub et les met en cache ; l'app les télécharge depuis votre serveur. Les téléchargements sont comptés par serveur.++| Variable | Effet |+|---|---|+| `MULTICA_THEME_STORE` | `off` désactive la boutique. **Gérer** ne liste alors que les thèmes installés sur chaque appareil et n'apparaît qu'une fois un thème installé ; le serveur n'envoie aucune requête au registre. |+| `MULTICA_THEME_REGISTRY_URL` | Fait lire à la boutique l'`index.json` d'un autre registre, par exemple un fork de l'officiel. |++Voir [Variables d'environnement](/environment-variables) pour le reste de la configuration du serveur.++## Étapes suivantes++- [Créer un thème](/developers/themes) — le format des thèmes, les vérifications et la publication dans la boutique.+- [Recherche, raccourcis et préférences](/shortcuts) — les autres réglages personnels.diff --git a/apps/docs/content/docs/themes.ja.mdx b/apps/docs/content/docs/themes.ja.mdxnew file mode 100644index 0000000000..565e1c8ee6--- /dev/null+++ b/apps/docs/content/docs/themes.ja.mdx@@ -0,0 +1,111 @@+---+title: テーマと外観+description: ライト・ダークのモードとテーマを選び、テーマストアからコミュニティのテーマをインストールして最新に保ち、自作のテーマを読み込み、テーマで表示が崩れたときに既定のテーマへ戻す方法。+---++import { Callout } from "fumadocs-ui/components/callout";+import { Step, Steps } from "fumadocs-ui/components/steps";++**設定 → 外観** では、このデバイスでの Multica の見た目(モード、テーマ、文字、レイアウト)を設定します。変更はすぐに反映されます。++<Callout type="info">+ テーマとテーマストアはベータ版です。今は正しく表示されるテーマでも、Multica のリリース後に作者の更新が必要になることがあります。+</Callout>++## モードとテーマ++**モード** はライト、ダーク、システム(OS の設定に従う)から選びます。検索ボックス(`⌘K`)で「テーマ」と入力して切り替えることもできます。++**テーマ** はアプリ全体の色、枠線、影、角丸を決めます。Multica には Default、Pop、GitHub、Blueprint、Notion が含まれています。ドロップダウンから選びます。隣の **管理** では、ほかのテーマのインストール、アップデート、削除ができます。テーマはライト、ダーク、または両方に対応し、選んだモードに従います。++アクセントカラーやページ幅など、オプションを持つテーマもあります。そのテーマを使っている間は **テーマのオプション** に表示され、**オプションをリセット** でテーマの既定値に戻せます。++ページのほかの設定はテーマとは独立しています。++| グループ | 設定する内容 |+|---|---|+| **インターフェースの文字** | メニュー、ボタン、リスト、サイドバー、見出しのフォントとサイズ。 |+| **本文の文字** | タスクの説明、コメント、チャット、ドキュメントのフォント、サイズ、行の高さと、コードフォント。 |+| **レイアウトとアクセシビリティ** | 表示密度、視差効果を減らす、コントラストを上げる。 |++既定以外のフォントを選んだときや、コントラストを上げるをオンにしたときは、テーマよりあなたの選択が優先されます。色はテーマが決めます。オプションにない色にしたい場合は、別のテーマを選ぶか[自分で作って](/developers/themes)ください。++## テーマストア++**管理** を開くと、インストールしたテーマとコミュニティのテーマストアのテーマがひとつのウィンドウに並びます。組み込みのテーマはここには表示されず、常にドロップダウンにあります。名前や作者で検索でき、**インストール済みのみ表示** をオンにすると持っていないテーマを隠せます。++ストアのテーマはカードで表示されます。スクリーンショット(隅でライトとダークを切り替え)、作者、説明、ダウンロード数、GitHub リポジトリへのリンクがあります。まだインストールしていないテーマはダウンロード数の多い順に並びます。++<Steps>+<Step>++### インストール++カードの **インストール** をクリックします。テーマがダウンロード、チェックされ、このデバイスに保存されて使われます。++</Step>+<Step>++### 切り替え++インストール済みのテーマで **使う** をクリックするか、ドロップダウンから任意のテーマを選びます。使っているテーマには **使用中** と表示されます。++</Step>+<Step>++### 削除++インストール済みのテーマで **削除** をクリックします。使用中だった場合は Default に戻ります。++</Step>+</Steps>++ストアのテーマはコミュニティが作成したもので、掲載前に自動でチェックされます。コードを実行したり、インターネットから何かを読み込んだり、テーマ外のファイルを使ったりはできません。それでも、テーマはダイアログや警告を含むすべてのページのスタイルを変更できます。++ダウンロード数には、同じ Multica サーバーを使うすべての人のインストールとアップデートが 1 回ずつ数えられます。++## アップデート++ストアのテーマをインストールすると、外観ページに **ストアのテーマ** の行が表示されます。**アップデートを確認** で新しいリリースを探し、**すべてアップデート** をクリックします。カードの **… に更新** でテーマを 1 つずつ更新することもできます。アップデートしてもテーマのオプションの値は保たれ、使用中のテーマも変わりません。++テーマが勝手にアップデートされることはありません。++## テーマを読み込む++ファイルで受け取ったテーマや自作のテーマは、**自分で作る → テーマを読み込む** からインストールします。++- **テーマファイル(.zip)** は zip 形式のテーマをインストールします。+- **テーマフォルダ** は展開済みのテーマをインストールします。++インストール前に、テーマの名前、作者、バージョンが表示されます。信頼できる作者のテーマだけをインストールしてください。インストール済みのテーマと同じ id のテーマを読み込むと置き換わります。++テーマを自作するには[テーマを作る](/developers/themes)を参照してください。++## テーマで表示が崩れたとき++テーマによってインターフェースの一部が隠れたり崩れたりすることがあります。Default に戻すには、次のどちらかを行います。++- アドレスの末尾に `?theme=default` を付けて Multica を開く。+- ページの読み込み直後に **Shift** をしばらく押し続ける。デスクトップアプリでは `⌘R`(Windows と Linux では `Ctrl+R`)で再読み込みしてから **Shift** を押し続けます。++ウィンドウを閉じるまでテーマは一時停止します。外観ページに通知が表示され、**テーマを戻す** で再び有効にできます。そこで別のテーマを選んだり、問題のテーマを削除したりもできます。++## 保存場所++モード、テーマ、テーマのオプション、インストールしたテーマはこのデバイスに保存され、アカウントには同期されません。ブラウザごと、デスクトップアプリごとに別々です。同じデバイスのすべてのワークスペースで共通です。++## セルフホスト++セルフホストのサーバーは、既定で公式レジストリ [multica-ai/multica-themes](https://github.com/multica-ai/multica-themes) を表示します。サーバーが GitHub からテーマとスクリーンショットを取得してキャッシュし、アプリはそれをあなたのサーバーからダウンロードします。ダウンロード数はサーバーごとに数えられます。++| 変数 | 効果 |+|---|---|+| `MULTICA_THEME_STORE` | `off` でストアを無効にします。**管理** には各デバイスにインストールしたテーマだけが表示され、テーマをインストールするまでボタンは表示されません。サーバーはレジストリにリクエストしません。 |+| `MULTICA_THEME_REGISTRY_URL` | 公式レジストリの fork など、別のレジストリの `index.json` をストアに読ませます。 |++サーバーのほかの設定は[環境変数](/environment-variables)を参照してください。++## 次のステップ++- [テーマを作る](/developers/themes) — テーマの形式、チェック、ストアへの公開。+- [検索・ショートカット・環境設定](/shortcuts) — そのほかの個人設定。diff --git a/apps/docs/content/docs/themes.ko.mdx b/apps/docs/content/docs/themes.ko.mdxnew file mode 100644index 0000000000..a811c55fd9--- /dev/null+++ b/apps/docs/content/docs/themes.ko.mdx@@ -0,0 +1,111 @@+---+title: 테마와 모양+description: 라이트·다크 모드와 테마를 고르고, 테마 스토어에서 커뮤니티 테마를 설치해 최신으로 유지하고, 직접 만든 테마를 가져오고, 테마 때문에 화면이 깨졌을 때 기본 테마로 돌아가는 방법.+---++import { Callout } from "fumadocs-ui/components/callout";+import { Step, Steps } from "fumadocs-ui/components/steps";++**설정 → 모양**에서는 이 기기에서 Multica가 어떻게 보일지 정합니다. 모드, 테마, 글자, 레이아웃을 설정하며, 바꾸면 바로 적용됩니다.++<Callout type="info">+ 테마와 테마 스토어는 베타입니다. 지금 잘 보이는 테마도 Multica 릴리스 후에는 작성자의 업데이트가 필요할 수 있습니다.+</Callout>++## 모드와 테마++**모드**는 라이트, 다크, 시스템(운영체제 설정을 따름) 중에서 고릅니다. 검색 창(`⌘K`)에 '테마'를 입력해 바꿀 수도 있습니다.++**테마**는 앱 전체의 색상, 테두리, 그림자, 모서리를 정합니다. Multica에는 Default, Pop, GitHub, Blueprint, Notion이 들어 있습니다. 드롭다운에서 고르세요. 옆의 **관리**에서는 다른 테마를 설치, 업데이트, 제거합니다. 테마는 라이트, 다크 또는 둘 다를 지원하며, 고른 모드를 따릅니다.++강조 색상이나 페이지 너비 같은 옵션이 있는 테마도 있습니다. 그 테마를 사용하는 동안 **테마 옵션**에 표시되고, **옵션 초기화**로 테마의 기본값으로 되돌릴 수 있습니다.++페이지의 나머지 설정은 테마와 상관없습니다.++| 그룹 | 설정하는 것 |+|---|---|+| **인터페이스 글자** | 메뉴, 버튼, 목록, 사이드바, 제목의 글꼴과 크기. |+| **본문 글자** | 태스크 설명, 댓글, 채팅, 문서의 글꼴, 크기, 줄 높이와 코드 글꼴. |+| **레이아웃 및 접근성** | 밀도, 동작 줄이기, 대비 높이기. |++기본값이 아닌 글꼴을 고르거나 대비 높이기를 켜면 테마보다 사용자의 선택이 우선합니다. 색상은 테마가 정합니다. 옵션에 없는 색상을 원하면 다른 테마를 고르거나 [직접 만드세요](/developers/themes).++## 테마 스토어++**관리**를 열면 설치한 테마와 커뮤니티 테마 스토어의 테마가 한 창에 표시됩니다. 기본 제공 테마는 여기에 나오지 않고 항상 드롭다운에 있습니다. 이름이나 작성자로 검색할 수 있고, **설치된 테마만 보기**를 켜면 설치하지 않은 테마를 숨깁니다.++스토어 테마는 카드로 표시됩니다. 스크린샷(모서리에서 라이트와 다크 전환), 작성자, 설명, 다운로드 수, GitHub 저장소 링크가 있습니다. 아직 설치하지 않은 테마는 다운로드 수가 많은 순서로 나열됩니다.++<Steps>+<Step>++### 설치++카드에서 **설치**를 클릭합니다. 테마를 다운로드하고 검사한 뒤 이 기기에 저장하고 바로 사용합니다.++</Step>+<Step>++### 전환++설치한 테마에서 **사용**을 클릭하거나, 드롭다운에서 아무 테마나 고릅니다. 사용 중인 테마에는 **사용 중**이 표시됩니다.++</Step>+<Step>++### 제거++설치한 테마에서 **제거**를 클릭합니다. 사용 중이던 테마라면 Default로 돌아갑니다.++</Step>+</Steps>++스토어 테마는 커뮤니티가 만들며, 목록에 오르기 전에 자동으로 검사됩니다. 코드를 실행하거나, 인터넷에서 무엇이든 불러오거나, 테마 밖의 파일을 쓸 수 없습니다. 그래도 테마는 대화 상자와 경고를 포함한 모든 페이지의 스타일을 바꿀 수 있습니다.++다운로드 수에는 같은 Multica 서버를 쓰는 모든 사람의 설치와 업데이트가 각각 한 번씩 포함됩니다.++## 업데이트++스토어 테마를 설치하면 모양 페이지에 **스토어 테마** 행이 나타납니다. **업데이트 확인**으로 새 릴리스를 찾은 뒤 **모두 업데이트**를 클릭하거나, 카드의 **…(으)로 업데이트**로 테마를 하나씩 업데이트합니다. 업데이트해도 테마의 옵션 값은 유지되고, 사용 중인 테마도 바뀌지 않습니다.++테마는 요청하지 않으면 업데이트되지 않습니다.++## 테마 가져오기++파일로 받은 테마나 직접 만든 테마는 **직접 만들기 → 테마 가져오기**에서 설치합니다.++- **테마 파일(.zip)**: 압축된 테마를 설치합니다.+- **테마 폴더**: 압축을 푼 테마를 설치합니다.++설치 전에 테마의 이름, 작성자, 버전이 표시됩니다. 신뢰하는 사람이 만든 테마만 설치하세요. 설치된 테마와 id가 같은 테마를 가져오면 기존 테마를 대체합니다.++테마를 직접 만들려면 [테마 만들기](/developers/themes)를 참고하세요.++## 테마 때문에 화면이 깨졌을 때++테마 때문에 인터페이스 일부가 가려지거나 깨질 수 있습니다. Default로 돌아가려면 다음 중 하나를 하세요.++- 주소 끝에 `?theme=default`를 붙여 Multica를 엽니다.+- 페이지가 로드된 직후 **Shift**를 잠시 누르고 있습니다. 데스크톱 앱에서는 `⌘R`(Windows와 Linux에서는 `Ctrl+R`)로 다시 로드한 뒤 **Shift**를 누르고 있습니다.++창을 닫을 때까지 테마가 일시 중지됩니다. 모양 페이지에 알림이 표시되고, **내 테마 사용**으로 다시 켤 수 있습니다. 거기서 다른 테마를 고르거나 문제가 된 테마를 제거할 수도 있습니다.++## 저장 위치++모드, 테마, 테마 옵션, 설치한 테마는 이 기기에 저장되며 계정에 동기화되지 않습니다. 브라우저마다, 데스크톱 앱마다 따로 저장됩니다. 같은 기기의 모든 워크스페이스에서 동일합니다.++## 셀프 호스팅++셀프 호스팅 서버는 기본적으로 공식 레지스트리 [multica-ai/multica-themes](https://github.com/multica-ai/multica-themes)를 표시합니다. 서버가 GitHub에서 테마와 스크린샷을 가져와 캐시하고, 앱은 여러분의 서버에서 다운로드합니다. 다운로드 수는 서버별로 셉니다.++| 변수 | 효과 |+|---|---|+| `MULTICA_THEME_STORE` | `off`로 스토어를 끕니다. 그러면 **관리**에는 각 기기에 설치한 테마만 표시되고, 테마를 설치해야 버튼이 나타납니다. 서버는 레지스트리에 요청하지 않습니다. |+| `MULTICA_THEME_REGISTRY_URL` | 공식 레지스트리의 fork 등 다른 레지스트리의 `index.json`을 스토어가 읽게 합니다. |++서버의 다른 설정은 [환경 변수](/environment-variables)를 참고하세요.++## 다음 단계++- [테마 만들기](/developers/themes) — 테마 형식, 검사, 스토어에 게시하기.+- [검색, 단축키, 환경설정](/shortcuts) — 그 밖의 개인 설정.diff --git a/apps/docs/content/docs/themes.mdx b/apps/docs/content/docs/themes.mdxnew file mode 100644index 0000000000..a67c1a95f4--- /dev/null+++ b/apps/docs/content/docs/themes.mdx@@ -0,0 +1,111 @@+---+title: Themes and appearance+description: Pick light or dark mode and a theme, install community themes from the theme store, keep them up to date, import your own, and get back to the default when a theme breaks something.+---++import { Callout } from "fumadocs-ui/components/callout";+import { Step, Steps } from "fumadocs-ui/components/steps";++**Settings → Appearance** controls how Multica looks on this device: the mode, the theme, text and layout. Every change applies at once.++<Callout type="info">+ Themes and the theme store are in beta. A theme that looks right today may need an update from its author after a Multica release.+</Callout>++## Mode and theme++**Mode** is Light, Dark, or System (follows your operating system). You can also type "theme" in the search box (`⌘K`) to switch it.++**Theme** sets the colors, borders, shadows, and corners across the app. Multica comes with Default, Pop, GitHub, Blueprint, and Notion; pick one from the dropdown. **Manage**, next to it, is where you install, update, and remove other themes. A theme supports light mode, dark mode, or both, and follows the mode you picked.++Some themes come with options, such as an accent color or a page width. They show up under **Theme options** while that theme is in use; **Reset options** puts them back to the theme's defaults.++The rest of the page is independent of the theme:++| Group | What it sets |+|---|---|+| **Interface text** | Font and size for menus, buttons, lists, the sidebar, and headings. |+| **Content text** | Font, size, and line height for issue descriptions, comments, chat, and documents, plus the code font. |+| **Layout and accessibility** | Row density in lists, Reduce motion, and Increase contrast. |++When you pick a font other than the default, or turn on Increase contrast, your choice wins over the theme's. A theme sets the colors; to change a color it doesn't offer as an option, pick another theme or [make your own](/developers/themes).++## The theme store++**Manage** opens one window with the themes you installed and the community theme store. The built-in themes aren't listed there; they are always in the dropdown. Search by name or author, and turn on **Show installed only** to hide what you don't have.++Each store theme has a card with a screenshot (switch between its light and dark screenshot in the corner), its author, a description, how many times it has been downloaded, and a link to its GitHub repository. Themes you haven't installed are listed most downloaded first.++<Steps>+<Step>++### Install++Click **Install** on a card. The theme is downloaded, checked, saved on this device, and put in use.++</Step>+<Step>++### Switch++Click **Use** on an installed theme, or pick any theme from the dropdown. The theme in use is marked **In use**.++</Step>+<Step>++### Remove++Click **Remove** on an installed theme. If it was in use, Multica goes back to Default.++</Step>+</Steps>++Store themes are written by the community and checked automatically before they are listed: they cannot run code, load anything from the internet, or use files outside the theme. A theme can still restyle every page, including dialogs and warnings.++The download count includes every install and every update, from everyone who uses the same Multica server.++## Updates++Once you have installed a store theme, the Appearance page shows a **Store themes** row. Click **Check for updates** to look for new releases, then **Update all**, or update one theme from its card with **Update to …**. An update keeps the theme's option values and leaves your current theme as it is.++Themes are never updated without you asking.++## Import a theme++A theme you got as a file, or one you made, is installed from **Make your own → Import theme**:++- **Theme file (.zip)** installs a zipped theme.+- **Theme folder** installs an unzipped one.++Multica shows the theme's name, author, and version before installing it. Only install themes from people you trust. Importing a theme with the same id as an installed one replaces it.++To start a theme of your own, see [Make a theme](/developers/themes).++## When a theme breaks something++A theme can hide or break part of the interface. To get back to Default, either:++- open Multica with `?theme=default` at the end of the address, or+- hold **Shift** for a moment right after the page loads. In the desktop app, reload with `⌘R` (`Ctrl+R` on Windows and Linux) and then hold **Shift**.++The theme is paused until you close the window. The Appearance page shows a notice with **Use my theme** to turn it back on; from there you can also pick another theme or remove the broken one.++## Where it is stored++Mode, theme, theme options, and installed themes are saved on this device and are not synced to your account. Each browser and each desktop app has its own. They are the same in every workspace on that device.++## Self-hosting++A self-hosted server lists the official registry, [multica-ai/multica-themes](https://github.com/multica-ai/multica-themes), by default. The server fetches themes and screenshots from GitHub and caches them, so the app downloads them from your server. Download counts are kept per server.++| Variable | Effect |+|---|---|+| `MULTICA_THEME_STORE` | `off` turns the store off. **Manage** then lists only the themes installed on each device, and appears once one is installed; the server makes no registry requests. |+| `MULTICA_THEME_REGISTRY_URL` | Points the store at another registry's `index.json`, for example a fork of the official one. |++See [Environment variables](/environment-variables) for the rest of the server configuration.++## Next steps++- [Make a theme](/developers/themes) — the theme format, checks, and publishing to the store.+- [Search, shortcuts, and preferences](/shortcuts) — the other personal settings.diff --git a/apps/docs/content/docs/themes.zh-Hant.mdx b/apps/docs/content/docs/themes.zh-Hant.mdxnew file mode 100644index 0000000000..f9452fa862--- /dev/null+++ b/apps/docs/content/docs/themes.zh-Hant.mdx@@ -0,0 +1,111 @@+---+title: 主題與外觀+description: 選擇淺色或深色模式和主題,從主題商店安裝社群主題並保持更新,匯入自己的主題,以及在主題出問題時回到預設主題。+---++import { Callout } from "fumadocs-ui/components/callout";+import { Step, Steps } from "fumadocs-ui/components/steps";++**設定 → 外觀** 決定 Multica 在當前裝置上的樣子:模式、主題、文字和版面。所有改動立即生效。++<Callout type="info">+ 主題和主題商店目前是 Beta。Multica 發版後,一個原本正常的主題可能需要作者更新。+</Callout>++## 模式與主題++**模式** 可選淺色、深色或跟隨系統。也可以在搜尋框(`⌘K`)裡輸入"主題"切換。++**主題** 決定全域的顏色、邊框、陰影和圓角。Multica 自帶 Default、Pop、GitHub、Blueprint 和 Notion;在下拉框裡直接選。旁邊的 **管理** 用來安裝、更新和移除其他主題。一個主題可能支援淺色、深色或兩者都支援,並跟隨你選的模式。++有些主題帶選項,比如強調色或頁面寬度。使用這個主題時,選項會出現在 **主題選項** 裡;**恢復主題預設** 把選項恢復成主題的預設值。++頁面上的其他設定與主題無關:++| 分組 | 設定什麼 |+|---|---|+| **介面文字** | 選單、按鈕、列表、側邊欄和標題的字型與字號。 |+| **內容文字** | 任務描述、評論、聊天和文件的字型、字號和行高,以及程式碼字型。 |+| **版面與輔助功能** | 資訊密度、減少動態效果、提高對比。 |++選了非預設的字型,或者開啟了提高對比時,以你的選擇為準,而不是主題的。顏色由主題決定;想要主題沒有提供選項的顏色,換一個主題,或者[自己做一個](/developers/themes)。++## 主題商店++**管理** 開啟一個視窗,列出你安裝的主題和社群主題商店。內建主題不在這裡,它們始終在下拉框裡。可以按名稱或作者搜尋,開啟 **只看已安裝** 隱藏沒裝的主題。++商店裡每個主題是一張卡片:截圖(在角落切換淺色和深色截圖)、作者、描述、下載次數,以及它的 GitHub 倉庫連結。沒裝的主題按下載次數從多到少排列。++<Steps>+<Step>++### 安裝++點卡片上的 **安裝**。主題會被下載、檢查、儲存到當前裝置,並立即使用。++</Step>+<Step>++### 切換++在已安裝的主題上點 **使用**,或者在下拉框裡選任意主題。正在用的主題標著 **使用中**。++</Step>+<Step>++### 移除++在已安裝的主題上點 **移除**。如果它正在使用,Multica 會回到 Default。++</Step>+</Steps>++商店主題由社群製作,上架前會經過自動檢查:不能執行程式碼,不能從網路載入任何東西,也不能使用主題以外的檔案。但主題仍然可以改變每個頁面的樣式,包括彈窗和警告。++下載次數包含每一次安裝和每一次更新,統計的是使用同一個 Multica 伺服器的所有人。++## 更新++裝過商店主題後,外觀頁會出現 **商店主題** 一行。點 **檢查更新** 查詢新版本,然後點 **全部更新**;也可以在卡片上用 **更新至 …** 單獨更新一個主題。更新會保留主題的選項值,也不會改變你當前在用的主題。++主題不會在你不知情的情況下自動更新。++## 匯入主題++別人發給你的主題檔案,或者你自己做的主題,從 **製作自己的主題 → 匯入主題** 安裝:++- **主題檔案(.zip)** 安裝壓縮包形式的主題。+- **主題資料夾** 安裝解壓後的主題。++安裝前,Multica 會顯示主題的名稱、作者和版本。只安裝你信任的人做的主題。匯入一個與已安裝主題 id 相同的主題,會替換它。++想從頭做一個主題,見[製作主題](/developers/themes)。++## 主題出問題時++主題可能隱藏或弄亂介面的一部分。回到 Default 有兩種方法:++- 在地址末尾加上 `?theme=default` 開啟 Multica;+- 頁面載入完後立刻按住 **Shift** 一會兒。桌面端先用 `⌘R`(Windows 和 Linux 上是 `Ctrl+R`)重新載入,再按住 **Shift**。++關閉視窗前,主題會一直暫停。外觀頁會顯示一條提示,點 **恢復我的主題** 重新啟用;你也可以在那裡換一個主題,或者移除出問題的主題。++## 儲存在哪裡++模式、主題、主題選項和已安裝的主題都儲存在當前裝置上,不會同步到賬號。每個瀏覽器、每個桌面端各有一份,同一裝置上的所有工作區共用。++## 自託管++自託管的伺服器預設讀取官方倉庫 [multica-ai/multica-themes](https://github.com/multica-ai/multica-themes)。伺服器從 GitHub 拉取主題和截圖並快取,應用從你的伺服器下載。下載次數按伺服器分別統計。++| 變數 | 作用 |+|---|---|+| `MULTICA_THEME_STORE` | 設為 `off` 關閉主題商店。之後 **管理** 只列出各裝置上已安裝的主題,裝了主題後才會出現;伺服器也不再請求倉庫。 |+| `MULTICA_THEME_REGISTRY_URL` | 讓主題商店改讀另一個倉庫的 `index.json`,比如官方倉庫的 fork。 |++伺服器的其他設定見[環境變數](/environment-variables)。++## 接下來++- [製作主題](/developers/themes) — 主題格式、檢查,以及釋出到主題商店。+- [搜尋、快捷鍵與偏好設定](/shortcuts) — 其他個人設定。diff --git a/apps/docs/content/docs/themes.zh.mdx b/apps/docs/content/docs/themes.zh.mdxnew file mode 100644index 0000000000..1573544dbb--- /dev/null+++ b/apps/docs/content/docs/themes.zh.mdx@@ -0,0 +1,111 @@+---+title: 主题与外观+description: 选择浅色或深色模式和主题,从主题商店安装社区主题并保持更新,导入自己的主题,以及在主题出问题时回到默认主题。+---++import { Callout } from "fumadocs-ui/components/callout";+import { Step, Steps } from "fumadocs-ui/components/steps";++**设置 → 外观** 决定 Multica 在当前设备上的样子:模式、主题、文字和布局。所有改动立即生效。++<Callout type="info">+ 主题和主题商店目前是 Beta。Multica 发版后,一个原本正常的主题可能需要作者更新。+</Callout>++## 模式与主题++**模式** 可选浅色、深色或跟随系统。也可以在搜索框(`⌘K`)里输入"主题"切换。++**主题** 决定全局的颜色、边框、阴影和圆角。Multica 自带 Default、Pop、GitHub、Blueprint 和 Notion;在下拉框里直接选。旁边的 **管理** 用来安装、更新和移除其他主题。一个主题可能支持浅色、深色或两者都支持,并跟随你选的模式。++有些主题带选项,比如强调色或页面宽度。使用这个主题时,选项会出现在 **主题选项** 里;**恢复主题默认** 把选项恢复成主题的默认值。++页面上的其他设置与主题无关:++| 分组 | 设置什么 |+|---|---|+| **界面文字** | 菜单、按钮、列表、侧边栏和标题的字体与字号。 |+| **内容文字** | 任务描述、评论、聊天和文档的字体、字号和行高,以及代码字体。 |+| **布局与辅助功能** | 信息密度、减少动态效果、提高对比度。 |++选了非默认的字体,或者打开了提高对比度时,以你的选择为准,而不是主题的。颜色由主题决定;想要主题没有提供选项的颜色,换一个主题,或者[自己做一个](/developers/themes)。++## 主题商店++**管理** 打开一个窗口,列出你安装的主题和社区主题商店。内置主题不在这里,它们始终在下拉框里。可以按名称或作者搜索,打开 **只看已安装** 隐藏没装的主题。++商店里每个主题是一张卡片:截图(在角落切换浅色和深色截图)、作者、描述、下载次数,以及它的 GitHub 仓库链接。没装的主题按下载次数从多到少排列。++<Steps>+<Step>++### 安装++点卡片上的 **安装**。主题会被下载、检查、保存到当前设备,并立即使用。++</Step>+<Step>++### 切换++在已安装的主题上点 **使用**,或者在下拉框里选任意主题。正在用的主题标着 **使用中**。++</Step>+<Step>++### 移除++在已安装的主题上点 **移除**。如果它正在使用,Multica 会回到 Default。++</Step>+</Steps>++商店主题由社区制作,上架前会经过自动检查:不能运行代码,不能从网络加载任何东西,也不能使用主题以外的文件。但主题仍然可以改变每个页面的样式,包括弹窗和警告。++下载次数包含每一次安装和每一次更新,统计的是使用同一个 Multica 服务端的所有人。++## 更新++装过商店主题后,外观页会出现 **商店主题** 一行。点 **检查更新** 查找新版本,然后点 **全部更新**;也可以在卡片上用 **更新到 …** 单独更新一个主题。更新会保留主题的选项值,也不会改变你当前在用的主题。++主题不会在你不知情的情况下自动更新。++## 导入主题++别人发给你的主题文件,或者你自己做的主题,从 **制作自己的主题 → 导入主题** 安装:++- **主题文件(.zip)** 安装压缩包形式的主题。+- **主题文件夹** 安装解压后的主题。++安装前,Multica 会显示主题的名称、作者和版本。只安装你信任的人做的主题。导入一个与已安装主题 id 相同的主题,会替换它。++想从头做一个主题,见[制作主题](/developers/themes)。++## 主题出问题时++主题可能隐藏或弄乱界面的一部分。回到 Default 有两种方法:++- 在地址末尾加上 `?theme=default` 打开 Multica;+- 页面加载完后立刻按住 **Shift** 一会儿。桌面端先用 `⌘R`(Windows 和 Linux 上是 `Ctrl+R`)重新加载,再按住 **Shift**。++关闭窗口前,主题会一直暂停。外观页会显示一条提示,点 **恢复我的主题** 重新启用;你也可以在那里换一个主题,或者移除出问题的主题。++## 保存在哪里++模式、主题、主题选项和已安装的主题都保存在当前设备上,不会同步到账号。每个浏览器、每个桌面端各有一份,同一设备上的所有工作区共用。++## 自托管++自托管的服务端默认读取官方仓库 [multica-ai/multica-themes](https://github.com/multica-ai/multica-themes)。服务端从 GitHub 拉取主题和截图并缓存,应用从你的服务端下载。下载次数按服务端分别统计。++| 变量 | 作用 |+|---|---|+| `MULTICA_THEME_STORE` | 设为 `off` 关闭主题商店。之后 **管理** 只列出各设备上已安装的主题,装了主题后才会出现;服务端也不再请求仓库。 |+| `MULTICA_THEME_REGISTRY_URL` | 让主题商店改读另一个仓库的 `index.json`,比如官方仓库的 fork。 |++服务端的其他配置见[环境变量](/environment-variables)。++## 接下来++- [制作主题](/developers/themes) — 主题格式、检查,以及发布到主题商店。+- [搜索、快捷键与偏好设置](/shortcuts) — 其他个人设置。diff --git a/deploy/helm/multica/templates/configmap.yaml b/deploy/helm/multica/templates/configmap.yamlindex b6cf25d077..6988b381e9 100644--- a/deploy/helm/multica/templates/configmap.yaml+++ b/deploy/helm/multica/templates/configmap.yaml@@ -24,6 +24,8 @@ data:WORKSPACE_CREATION_ALLOWED_EMAILS: {{ .Values.backend.config.workspaceCreationAllowedEmails | quote }}DO_NOT_TRACK: {{ .Values.backend.config.doNotTrack | quote }}MULTICA_VCS_INTEGRATION_ENABLED: {{ .Values.backend.config.vcsIntegrationEnabled | quote }}+ MULTICA_THEME_STORE: {{ .Values.backend.config.themeStore.mode | quote }}+ MULTICA_THEME_REGISTRY_URL: {{ .Values.backend.config.themeStore.registryUrl | quote }}MULTICA_CLOUD_URL: {{ .Values.backend.config.cloud.url | quote }}GOOGLE_CLIENT_ID: {{ .Values.backend.config.googleClientId | quote }}GOOGLE_REDIRECT_URI: {{ .Values.backend.config.googleRedirectUri | quote }}diff --git a/deploy/helm/multica/values.yaml b/deploy/helm/multica/values.yamlindex ec80c031a3..2683bf005c 100644--- a/deploy/helm/multica/values.yaml+++ b/deploy/helm/multica/values.yaml@@ -160,6 +160,12 @@ backend:# MULTICA_VCS_SECRET_KEY through existingSecret before connections work.# Set false to hide and reject the integration for this deployment.vcsIntegrationEnabled: true+ # Community theme store (Settings → Appearance → Browse, beta). "off"+ # hides it and stops every registry request; registryUrl points it at+ # another registry's index.json. Empty keeps the official registry.+ themeStore:+ mode: ""+ registryUrl: ""# Managed multica-cloud connection. Empty keeps self-hosting independent.# Fleet, Billing, entitlement policy and strict seat capacity share it.cloud:diff --git a/docker-compose.selfhost.yml b/docker-compose.selfhost.ymlindex 8d8985449c..b70a97d870 100644--- a/docker-compose.selfhost.yml+++ b/docker-compose.selfhost.yml@@ -195,6 +195,11 @@ services:MULTICA_VCS_INTEGRATION_ENABLED: ${MULTICA_VCS_INTEGRATION_ENABLED:-true}# VCS integration at-rest encryption key for token-based providersMULTICA_VCS_SECRET_KEY: ${MULTICA_VCS_SECRET_KEY:-}+ # Community theme store (Settings → Appearance → Browse). On by default;+ # "off" hides it and stops every registry request. The registry URL+ # points it at another registry's index.json.+ MULTICA_THEME_STORE: ${MULTICA_THEME_STORE:-}+ MULTICA_THEME_REGISTRY_URL: ${MULTICA_THEME_REGISTRY_URL:-}# WeCom smart-bot integration. MULTICA_WECOM_SECRET_KEY is the# opt-in: unset = integration disabled. It encrypts each installation's# smart-bot secret at rest. The server needs it to unseal a bot'sdiff --git a/docs/theming.md b/docs/theming.mdindex 7e4299e788..a632a33274 100644--- a/docs/theming.md+++ b/docs/theming.md@@ -10,10 +10,13 @@ Appearance → Theme options**. Themes never run JavaScript.> 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.+**Settings → Appearance → Manage** lists the themes installed on the device+and the community theme store; the built-in themes are in the theme picker. Install a theme from the+store there, or with **Import theme**, from a `.zip` of the folder or from the+folder itself. Themes are saved on the device, like every other Appearance+setting; **Remove** on a theme's card deletes it, and goes back to Default+when it was in use. **Check for updates** looks for new releases of the+themes installed from the store.The built-in themes compile to exactly this format and live in`packages/core/appearance/built-in-themes.ts`: Pop shows options and CSS,@@ -265,16 +268,15 @@ back on.## Writing a themeStart 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+choose **Duplicate “…” as a new theme** from the **Import theme** menu. Thecopy gets its own id (`pop-copy`, `pop-copy-2`, …), a manifest with thetheme's options, and a `theme.css` with one declaration per line. Importingthe 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+Desktop keeps a `themes` folder in its user data folder. The **Open themes+folder** button next to **Import theme** shows it. Every folder (or `.zip`) in it isinstalled when the app starts and listed under **Themes folder** in thepicker. Save a file in it and every open window picks the change up withinabout a second, so edit `theme.css` in any editor and watch the app.@@ -306,6 +308,48 @@ families in font stacks and WCAG contrast in both modes, each with its linein `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.+To see the theme the way the theme store shows it:++```sh+pnpm theme:preview path/to/paper --out preview # preview/light.png and preview/dark.png+```++It renders a fixture page (an issue list next to an open issue) built from+the app's own styles and anchors, with the theme applied at its option+defaults.++## Publishing to the theme store++The theme store (beta) lists themes from+[multica-ai/multica-themes](https://github.com/multica-ai/multica-themes).+Its [contributing guide](https://github.com/multica-ai/multica-themes/blob/main/CONTRIBUTING.md)+has the details; in short:++1. Keep the theme in its own GitHub repository.+ [multica-ai/multica-theme-sample](https://github.com/multica-ai/multica-theme-sample)+ is a starting point with a release workflow.+2. Publish a release tagged with the manifest's `version` (`1.0.0` or+ `v1.0.0`) and attach the zipped theme as `theme.zip`.+3. Add the theme to `themes.json` in the registry with a pull request. The+ pull request runs `theme:check` and `theme:preview` on the release and+ comments with the result; a maintainer merges once it passes.++New releases reach the store within about an hour, after they pass the same+checks; people who installed the theme then see **Update**. A release that+fails keeps the previous one listed. The app only installs the exact+`theme.zip` the checks passed, and reads it with the same parser and CSS+sanitizer as an imported theme.++Each store card shows how many times the theme was downloaded from the+Multica server it lists on: every install and every update counts once.+Themes not yet installed are listed most downloaded first. A self-hosted+server counts its own downloads.++A self-hosted server reads the official registry by default.+`MULTICA_THEME_STORE=off` turns the store off: **Manage** lists only the+themes on the device, and the server makes no registry requests. `MULTICA_THEME_REGISTRY_URL` points it at+another registry's `index.json`.+## Variable referenceGenerated from `packages/core/appearance/theme-variables.ts`. Where lightdiff --git a/knip.jsonc b/knip.jsoncindex e7d44333d3..e9703652bb 100644--- a/knip.jsonc+++ b/knip.jsonc@@ -20,7 +20,10 @@"workspaces": {".": {"entry": ["scripts/*.mjs", "scripts/brand/*.mjs"],- "project": ["scripts/*.mjs", "scripts/brand/*.mjs"]+ "project": ["scripts/*.mjs", "scripts/brand/*.mjs"],+ // scripts/theme-preview.mjs drives Tailwind through the PostCSS API; the+ // root has no Tailwind stylesheets for the plugin to read.+ "tailwind": false},"apps/web": {diff --git a/package.json b/package.jsonindex 83cb35b714..784552795b 100644--- a/package.json+++ b/package.json@@ -29,6 +29,7 @@"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",+ "theme:preview": "node scripts/theme-preview.mjs","clean": "turbo clean && rm -rf node_modules","ui:add": "cd packages/ui && npx shadcn@latest add","generate:brand": "node scripts/brand/generate.mjs",@@ -63,10 +64,12 @@},"devDependencies": {"@playwright/test": "^1.58.2",+ "@tailwindcss/postcss": "catalog:","@types/node": "catalog:","@types/pg": "^8.20.0","knip": "^6.32.2","pg": "^8.20.0",+ "postcss": "catalog:","turbo": "^2.5.4","typescript": "catalog:"}diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 7a581a95d4..11b9a6c097 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -344,6 +344,10 @@ import {EMPTY_WEBHOOK_DELIVERY,AppConfigSchema,type AppConfigResponse,+ StoreThemeListSchema,+ EMPTY_STORE_THEME_LIST,+ type StoreTheme,+ type StoreThemeMode,type RefreshSessionResponse,RefreshSessionResponseSchema,EMPTY_REFRESH_SESSION_RESPONSE,@@ -3231,6 +3235,30 @@ export class ApiClient {});}+ // Theme store+ async listStoreThemes(): Promise<StoreTheme[]> {+ const raw = await this.fetch<unknown>("/api/theme-store/themes");+ return parseWithFallback(raw, StoreThemeListSchema, EMPTY_STORE_THEME_LIST, {+ endpoint: "GET /api/theme-store/themes",+ }).themes as StoreTheme[];+ }++ /** The theme's checked theme.zip, for the same reader as an imported theme. */+ async getStoreThemePackage(id: string): Promise<Uint8Array> {+ const res = await this.fetchRaw(`/api/theme-store/themes/${encodeURIComponent(id)}/package`);+ return new Uint8Array(await res.arrayBuffer());+ }++ // Fetched as bytes rather than linked: Desktop authenticates with a bearer+ // token that an <img> request would not carry.+ async getStoreThemeScreenshot(id: string, mode: StoreThemeMode, signal?: AbortSignal): Promise<Blob> {+ const res = await this.fetchRaw(+ `/api/theme-store/themes/${encodeURIComponent(id)}/screenshots/${mode}`,+ { signal },+ );+ return res.blob();+ }+// Workspacesasync listWorkspaces(): Promise<Workspace[]> {const raw = await this.fetch<unknown>("/api/workspaces");diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex b95d37f607..c65447c883 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -1043,6 +1043,10 @@ export interface AppConfigResponse {* DELETE /api/comments/{id}/keep-replies. Older servers deleted the replies* too, so absent must be treated as false (#8296). */comment_delete_keep_replies_supported?: boolean;+ /** Whether this server serves the community theme store under+ * /api/theme-store. Off when the operator turned it off, and absent on older+ * servers, so the app shows no Browse entry and makes no store requests. */+ theme_store_enabled?: boolean;server_version?: string;}@@ -1331,6 +1335,7 @@ export const AppConfigSchema = z.object({agent_conversation_starters_supported: BooleanWithDefaultSchema(false),issue_create_properties_supported: BooleanWithDefaultSchema(false),comment_delete_keep_replies_supported: BooleanWithDefaultSchema(false),+ theme_store_enabled: BooleanWithDefaultSchema(false),server_version: OptionalStringSchema,}).loose();@@ -1354,9 +1359,62 @@ export const EMPTY_APP_CONFIG: AppConfigResponse = {issue_create_properties_supported: false,// Fail closed: old servers delete a comment's replies with it.comment_delete_keep_replies_supported: false,+ theme_store_enabled: false,feature_flags: {},};+export type StoreThemeMode = "light" | "dark";++/** A theme of the community registry, as /api/theme-store lists it. */+export interface StoreTheme {+ id: string;+ name: string;+ author: string;+ /** The author's GitHub repository, `owner/name`. */+ repo: string;+ description?: string;+ modes: StoreThemeMode[];+ /** The release the registry checked; installs always get this one. */+ version: string;+ size: number;+ /** Modes the registry rendered a screenshot for. */+ screenshots: StoreThemeMode[];+ updated_at?: string;+ /** Installs and updates served by this server, all users together. */+ downloads: number;+}++const StoreThemeModesSchema = z.preprocess(+ (value) => (Array.isArray(value) ? value.filter((m) => m === "light" || m === "dark") : []),+ z.array(z.enum(["light", "dark"])),+);++const StoreThemeSchema = z+ .object({+ id: z.string(),+ name: z.string(),+ author: z.string(),+ repo: z.string(),+ description: OptionalStringSchema,+ modes: StoreThemeModesSchema,+ version: z.string(),+ size: z.number(),+ screenshots: StoreThemeModesSchema,+ updated_at: OptionalStringSchema,+ downloads: z.number().catch(0).default(0),+ })+ .loose();++/** One malformed entry drops that theme, not the whole list. */+export const StoreThemeListSchema = z.object({+ themes: z.preprocess(+ (value) => (Array.isArray(value) ? value.filter((item) => StoreThemeSchema.safeParse(item).success) : []),+ z.array(StoreThemeSchema),+ ),+});++export const EMPTY_STORE_THEME_LIST: { themes: StoreTheme[] } = { themes: [] };+// Preference keys may grow over time, so keep both the key and value spaces// forward-compatible while still rejecting non-string persisted data.export const NotificationPreferenceResponseSchema = z.object({diff --git a/packages/core/appearance/installed-themes.ts b/packages/core/appearance/installed-themes.tsindex 3e09ac0080..4284f6ead8 100644--- a/packages/core/appearance/installed-themes.ts+++ b/packages/core/appearance/installed-themes.ts@@ -14,6 +14,10 @@ import type { Theme } from "./themes";* 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.+ *+ * Themes installed from the theme store are installed the same way, and+ * `fromStore` remembers which release each one is, so the store can offer+ * an update.*/export const INSTALLED_THEMES_STORAGE_KEY = "multica_installed_themes";@@ -30,8 +34,12 @@ interface InstalledThemesState {themes: Theme[];/** Theme id to the themes-folder entry it came from. */folders: Readonly<Record<string, string>>;+ /** Theme id to the store release it was installed from. */+ fromStore: Readonly<Record<string, string>>;/** Adds the theme, or replaces the installed one with the same id. */install: (theme: Theme) => void;+ /** Installs a theme from the theme store, as release `version`. */+ installFromStore: (theme: Theme, version: string) => void;uninstall: (id: string) => void;/** Makes the folder themes match the themes folder's current contents. */syncFolder: (entries: readonly ThemeFolderEntry[]) => void;@@ -40,7 +48,7 @@ interface InstalledThemesState {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"> {+function revalidate(stored: unknown): Pick<InstalledThemesState, "themes" | "folders" | "fromStore"> {const record = isRecord(stored) ? stored : {};const list = Array.isArray(record.themes) ? record.themes : [];const themes: Theme[] = [];@@ -54,25 +62,51 @@ function revalidate(stored: unknown): Pick<InstalledThemesState, "themes" | "folif (typeof folder === "string" && themes.some((t) => t.id === id)) folders[id] = folder;}}- return { themes, folders };+ const fromStore: Record<string, string> = {};+ if (isRecord(record.fromStore)) {+ for (const [id, version] of Object.entries(record.fromStore)) {+ if (typeof version === "string" && !(id in folders) && themes.some((t) => t.id === id)) fromStore[id] = version;+ }+ }+ return { themes, folders, fromStore };}+const without = <T,>(record: Readonly<Record<string, T>>, id: string): Record<string, T> => {+ const { [id]: _removed, ...rest } = record;+ return rest;+};+export const useInstalledThemesStore = create<InstalledThemesState>()(persist((set) => ({themes: [],folders: {},+ fromStore: {},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 };+ return {+ themes: [...others, theme].slice(-MAX_INSTALLED_THEMES),+ folders: without(state.folders, theme.id),+ fromStore: without(state.fromStore, theme.id),+ };}),- uninstall: (id) =>+ installFromStore: (theme, version) =>set((state) => {- const { [id]: _removed, ...folders } = state.folders;- return { themes: state.themes.filter((t) => t.id !== id), folders };+ const others = state.themes.filter((t) => t.id !== theme.id);+ const themes = [...others, theme].slice(-MAX_INSTALLED_THEMES);+ return {+ themes,+ folders: without(state.folders, theme.id),+ fromStore: { ...state.fromStore, [theme.id]: version },+ };}),+ uninstall: (id) =>+ set((state) => ({+ themes: state.themes.filter((t) => t.id !== id),+ folders: without(state.folders, id),+ fromStore: without(state.fromStore, id),+ })),syncFolder: (entries) =>set((state) => {const fromFolder = new Map<string, Theme>();@@ -97,13 +131,16 @@ export const useInstalledThemesStore = create<InstalledThemesState>()(return {themes,folders: Object.fromEntries(Object.entries(folders).filter(([id]) => kept.has(id))),+ fromStore: Object.fromEntries(+ Object.entries(state.fromStore).filter(([id]) => kept.has(id) && !(id in folders)),+ ),};}),}),{name: INSTALLED_THEMES_STORAGE_KEY,storage: createJSONStorage(() => defaultStorage),- partialize: (state) => ({ themes: state.themes, folders: state.folders }),+ partialize: (state) => ({ themes: state.themes, folders: state.folders, fromStore: state.fromStore }),merge: (persisted, current) => ({ ...current, ...revalidate(persisted) }),},),diff --git a/packages/core/appearance/theme-store.test.ts b/packages/core/appearance/theme-store.test.tsnew file mode 100644index 0000000000..cecf30f78c--- /dev/null+++ b/packages/core/appearance/theme-store.test.ts@@ -0,0 +1,121 @@+// @vitest-environment jsdom+import { beforeEach, describe, expect, it, vi } from "vitest";+import { api } from "../api";+import { StoreThemeListSchema, type StoreTheme } from "../api/schemas";+import { INSTALLED_THEMES_STORAGE_KEY, useInstalledThemesStore } from "./installed-themes";+import { writeZip } from "./theme-archive";+import { parseTheme } from "./theme-package";+import { readStoreTheme, storeThemeState } from "./theme-store";++vi.mock("../api", () => ({ api: { getStoreThemePackage: vi.fn() } }));++const encoder = new TextEncoder();+const manifest = (id: string, version: string) => ({ apiVersion: 1, id, name: "Ink", author: "Someone", version });+const zip = (id: string, version: string, css = ".theme-light { --page-canvas: #f6efdf; }") =>+ writeZip([+ { path: `${id}/manifest.json`, data: encoder.encode(JSON.stringify(manifest(id, version))) },+ { path: `${id}/theme.css`, data: encoder.encode(css) },+ ]);+const entry = (overrides: Partial<StoreTheme> = {}): StoreTheme => ({+ id: "ink",+ name: "Ink",+ author: "Someone",+ repo: "someone/multica-theme-ink",+ modes: ["light", "dark"],+ version: "1.0.0",+ size: 100,+ screenshots: ["light", "dark"],+ downloads: 0,+ ...overrides,+});+const theme = (id: string, version = "1.0.0") => {+ const parsed = parseTheme({ manifest: manifest(id, version), css: "" });+ if (!parsed.ok) throw new Error("fixture");+ return parsed.theme;+};++describe("StoreThemeListSchema", () => {+ it("reads the download count, and counts none from a server that sends none", () => {+ const { downloads: _, ...withoutCount } = entry();+ const parsed = StoreThemeListSchema.parse({+ themes: [entry({ downloads: 12 }), { ...withoutCount, id: "sand" }],+ });+ expect(parsed.themes.map((t) => [t.id, t.downloads])).toEqual([+ ["ink", 12],+ ["sand", 0],+ ]);+ });+});++describe("readStoreTheme", () => {+ it("reads the release like an imported theme", async () => {+ vi.mocked(api.getStoreThemePackage).mockResolvedValue(zip("ink", "1.0.0"));+ const result = await readStoreTheme(entry());+ expect(result.ok && result.theme.id).toBe("ink");+ });++ it("runs the same CSS checks as an import", async () => {+ vi.mocked(api.getStoreThemePackage).mockResolvedValue(+ zip("ink", "1.0.0", "body { background: url(https://evil.test/x.png); }"),+ );+ const result = await readStoreTheme(entry());+ expect(result.ok).toBe(false);+ });++ it("refuses a package that is another theme or another release", async () => {+ vi.mocked(api.getStoreThemePackage).mockResolvedValue(zip("other", "1.0.0"));+ expect((await readStoreTheme(entry())).ok).toBe(false);+ vi.mocked(api.getStoreThemePackage).mockResolvedValue(zip("ink", "0.9.0"));+ expect((await readStoreTheme(entry())).ok).toBe(false);+ });+});++describe("store installs", () => {+ beforeEach(() => {+ localStorage.clear();+ useInstalledThemesStore.setState({ themes: [], folders: {}, fromStore: {} });+ });+ const state = () => {+ const { themes, fromStore } = useInstalledThemesStore.getState();+ return storeThemeState(entry(), { themes, fromStore });+ };++ it("offers an update when the store lists another release", () => {+ expect(state()).toBe("available");+ useInstalledThemesStore.getState().installFromStore(theme("ink", "0.9.0"), "0.9.0");+ expect(state()).toBe("update");+ useInstalledThemesStore.getState().installFromStore(theme("ink"), "1.0.0");+ expect(state()).toBe("installed");+ useInstalledThemesStore.getState().uninstall("ink");+ expect(state()).toBe("available");+ expect(useInstalledThemesStore.getState().fromStore).toEqual({});+ });++ it("does not take over a built-in, imported or themes-folder theme with the same id", () => {+ expect(storeThemeState(entry({ id: "default" }), { themes: [], fromStore: {} })).toBe("taken");+ useInstalledThemesStore.getState().install(theme("ink"));+ expect(state()).toBe("taken");+ useInstalledThemesStore.getState().installFromStore(theme("ink"), "1.0.0");+ useInstalledThemesStore.getState().syncFolder([{ folder: "ink", result: { ok: true, theme: theme("ink", "2.0.0") } }]);+ expect(state()).toBe("taken");+ expect(useInstalledThemesStore.getState().fromStore).toEqual({});+ });++ it("forgets the store release when the theme is imported over it", () => {+ useInstalledThemesStore.getState().installFromStore(theme("ink"), "1.0.0");+ useInstalledThemesStore.getState().install(theme("ink", "1.1.0"));+ expect(useInstalledThemesStore.getState().fromStore).toEqual({});+ });++ it("keeps the store release across reloads, for installed themes only", async () => {+ const parsed = parseTheme({ manifest: manifest("ink", "1.0.0"), css: ".theme-light { --page-canvas: #f6efdf; }" });+ if (!parsed.ok) throw new Error("fixture");+ const stored = parsed.theme;+ localStorage.setItem(+ INSTALLED_THEMES_STORAGE_KEY,+ JSON.stringify({ state: { themes: [stored], folders: {}, fromStore: { ink: "1.0.0", gone: "1.0.0", bad: 3 } }, version: 0 }),+ );+ await useInstalledThemesStore.persist.rehydrate();+ expect(useInstalledThemesStore.getState().fromStore).toEqual({ ink: "1.0.0" });+ });+});diff --git a/packages/core/appearance/theme-store.ts b/packages/core/appearance/theme-store.tsnew file mode 100644index 0000000000..3224f90bd8--- /dev/null+++ b/packages/core/appearance/theme-store.ts@@ -0,0 +1,88 @@+import { queryOptions } from "@tanstack/react-query";+import { api } from "../api";+import type { StoreTheme, StoreThemeMode } from "../api/schemas";+import { findBuiltInTheme } from "./built-in-themes";+import { readZip } from "./theme-archive";+import { THEME_PACKAGE_MAX_BYTES, themeFromFiles, type ThemePackageResult } from "./theme-package";+import type { Theme } from "./themes";++/**+ * The community theme store (beta). The registry lists themes; the server+ * serves each one's checked release, and it is read here with the same+ * parser and CSS sanitizer as a theme someone imports. A store install is+ * saved on this device like an import, with the release it came from.+ */++export type { StoreTheme, StoreThemeMode };++export const themeStoreKeys = {+ all: ["theme-store"] as const,+ themes: () => [...themeStoreKeys.all, "themes"] as const,+ screenshot: (id: string, version: string, mode: StoreThemeMode) =>+ [...themeStoreKeys.all, "screenshot", id, version, mode] as const,+};++export const storeThemesOptions = (enabled: boolean) =>+ queryOptions({+ queryKey: themeStoreKeys.themes(),+ queryFn: () => api.listStoreThemes(),+ enabled,+ staleTime: 5 * 60 * 1000,+ });++/** A version's screenshot never changes, so it is fetched once. */+export const storeThemeScreenshotOptions = (theme: StoreTheme, mode: StoreThemeMode) =>+ queryOptions({+ queryKey: themeStoreKeys.screenshot(theme.id, theme.version, mode),+ queryFn: ({ signal }) => api.getStoreThemeScreenshot(theme.id, mode, signal),+ enabled: theme.screenshots.includes(mode),+ staleTime: Infinity,+ gcTime: 30 * 60 * 1000,+ });++/**+ * Where a store theme stands on this device:+ * - `available`: not installed;+ * - `installed`: installed from the store at the listed version;+ * - `update`: installed from the store at another version;+ * - `taken`: its id belongs to a built-in, imported or themes-folder theme,+ * which a store install must not replace.+ */+export type StoreThemeState = "available" | "installed" | "update" | "taken";++export function storeThemeState(+ theme: StoreTheme,+ installed: { themes: readonly Theme[]; fromStore: Readonly<Record<string, string>> },+): StoreThemeState {+ if (findBuiltInTheme(theme.id)) return "taken";+ const version = installed.fromStore[theme.id];+ if (version !== undefined && installed.themes.some((t) => t.id === theme.id)) {+ return version === theme.version ? "installed" : "update";+ }+ return installed.themes.some((t) => t.id === theme.id) ? "taken" : "available";+}++/**+ * Downloads the theme's release and reads it as an imported theme is read.+ * The package must be the theme and release the registry lists.+ */+export async function readStoreTheme(theme: StoreTheme): Promise<ThemePackageResult> {+ const bytes = await api.getStoreThemePackage(theme.id);+ if (bytes.length > THEME_PACKAGE_MAX_BYTES) {+ return { ok: false, errors: [`A theme can be at most ${THEME_PACKAGE_MAX_BYTES / 1024} KB`] };+ }+ const archive = await readZip(bytes, THEME_PACKAGE_MAX_BYTES);+ if (!archive.ok) return { ok: false, errors: [archive.error] };+ const result = themeFromFiles(archive.files);+ if (!result.ok) return result;+ if (result.theme.id !== theme.id) {+ return { ok: false, errors: [`The release is the theme "${result.theme.id}", not "${theme.id}"`] };+ }+ if (result.theme.version !== theme.version) {+ return {+ ok: false,+ errors: [`The release is version ${result.theme.version ?? "(none)"}, not ${theme.version}`],+ };+ }+ return result;+}diff --git a/packages/core/config/index.ts b/packages/core/config/index.tsindex 3a1278a414..40e8644239 100644--- a/packages/core/config/index.ts+++ b/packages/core/config/index.ts@@ -47,6 +47,10 @@ interface ConfigState {// deleted the replies too, so absent must fail closed: the client then// promises nothing about replies and uses the legacy delete route.commentDeleteKeepRepliesSupported: boolean;+ // Whether the server serves the community theme store. Absent on older+ // servers and off when the operator turned it off: no Browse entry, no+ // store requests.+ themeStoreEnabled: boolean;setCdnConfig: (config: { cdnDomain: string; cdnSigned?: boolean }) => void;setAttachmentPublicUrl: (url?: string) => void;setAuthConfig: (config: {@@ -67,6 +71,7 @@ interface ConfigState {setAgentConversationStartersSupported: (supported?: boolean) => void;setIssueCreatePropertiesSupported: (supported?: boolean) => void;setCommentDeleteKeepRepliesSupported: (supported?: boolean) => void;+ setThemeStoreEnabled: (enabled?: boolean) => void;}export const configStore = createStore<ConfigState>((set) => ({@@ -87,6 +92,7 @@ export const configStore = createStore<ConfigState>((set) => ({agentConversationStartersSupported: false,issueCreatePropertiesSupported: false,commentDeleteKeepRepliesSupported: false,+ themeStoreEnabled: false,setCdnConfig: ({ cdnDomain, cdnSigned = false }) => set({ cdnDomain, cdnSigned }),setAttachmentPublicUrl: (url = "") => set({ attachmentPublicUrl: url }),setAuthConfig: ({@@ -116,6 +122,7 @@ export const configStore = createStore<ConfigState>((set) => ({set({ issueCreatePropertiesSupported: supported === true }),setCommentDeleteKeepRepliesSupported: (supported = false) =>set({ commentDeleteKeepRepliesSupported: supported === true }),+ setThemeStoreEnabled: (enabled = false) => set({ themeStoreEnabled: enabled === true }),}));export function useConfigStore(): ConfigState;diff --git a/packages/core/package.json b/packages/core/package.jsonindex 3e68004c4d..df00e8c477 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -18,6 +18,7 @@"./attachments/image-sequence": "./attachments/image-sequence.ts","./api": "./api/index.ts","./appearance": "./appearance/index.ts",+ "./appearance/theme-store": "./appearance/theme-store.ts","./api/client": "./api/client.ts","./api/schema": "./api/schema.ts","./api/schemas": "./api/schemas.ts",diff --git a/packages/core/platform/auth-initializer.tsx b/packages/core/platform/auth-initializer.tsxindex 004c3ba8ec..bbbb883f31 100644--- a/packages/core/platform/auth-initializer.tsx+++ b/packages/core/platform/auth-initializer.tsx@@ -117,6 +117,7 @@ export function AuthInitializer({.setCommentDeleteKeepRepliesSupported(cfg.comment_delete_keep_replies_supported === true,);+ configStore.getState().setThemeStoreEnabled(cfg.theme_store_enabled === true);if (cfg.posthog_key) {initAnalytics({key: cfg.posthog_key,diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.jsonindex c6ff728bbb..f5f1e54db6 100644--- a/packages/views/locales/en/settings.json+++ b/packages/views/locales/en/settings.json@@ -193,7 +193,7 @@},"theme": {"title": "Theme",- "description": "Colors, borders, shadows and corners across the app. Import a theme file to add more.",+ "description": "Colors, borders, shadows and corners across the app.","default": "Default","pop": "Pop","built_in": "Built in",@@ -224,12 +224,56 @@"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."},+ "store": {+ "manage": "Manage",+ "title": "Themes",+ "description": "The themes you installed, and themes made by the community.",+ "description_local": "The themes you installed.",+ "search": "Search themes",+ "installed_only": "Show installed only",+ "showing_one": "Showing {{count}} theme",+ "showing_other": "Showing {{count}} themes",+ "installed": "Installed",+ "loading": "Loading themes",+ "error": "Couldn't load the theme store. Try again in a moment.",+ "retry": "Try again",+ "none_installed": "No themes are installed yet.",+ "no_results": "No themes match “{{query}}”.",+ "by": "by {{author}}",+ "downloads_one": "{{downloads}} download",+ "downloads_other": "{{downloads}} downloads",+ "source": "{{repo}} on GitHub",+ "no_preview": "No preview",+ "screenshot_alt": "{{name}} in {{mode}} mode",+ "install": "Install",+ "installing": "Installing…",+ "use": "Use",+ "in_use": "In use",+ "update": "Update to {{version}}",+ "remove": "Remove",+ "taken": "A theme with this id is installed",+ "installed_toast": "Installed “{{name}}”.",+ "updated": "Updated “{{name}}” to {{version}}.",+ "install_failed": "Couldn't install “{{name}}”",+ "warning": "Themes can restyle every page, including dialogs and warnings. Store themes are checked automatically, but they are made by the community."+ },+ "updates": {+ "title": "Store themes",+ "description_one": "You have {{count}} theme from the store.",+ "description_other": "You have {{count}} themes from the store.",+ "check": "Check for updates",+ "checking": "Checking…",+ "up_to_date": "Your store themes are up to date.",+ "update_all": "Update all ({{count}})"+ },+ "own": {+ "title": "Make your own",+ "description": "Import a theme as a .zip or folder, or start from a copy of the current one."+ },"tools": {- "label": "More theme actions","duplicate": "Duplicate “{{name}}” as a new theme","open_folder": "Open themes folder","guide": "How to make a theme",diff --git a/packages/views/locales/es/settings.json b/packages/views/locales/es/settings.jsonindex f4fc1c1ed2..09f564cb90 100644--- a/packages/views/locales/es/settings.json+++ b/packages/views/locales/es/settings.json@@ -193,7 +193,7 @@},"theme": {"title": "Tema",- "description": "Colores, bordes, sombras y esquinas de toda la app. Importa un archivo de tema para añadir más.",+ "description": "Colores, bordes, sombras y esquinas de toda la app.","default": "Predeterminado","pop": "Pop","built_in": "Integrados",@@ -224,12 +224,56 @@"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."},+ "store": {+ "manage": "Gestionar",+ "title": "Temas",+ "description": "Los temas que has instalado y temas creados por la comunidad.",+ "description_local": "Los temas que has instalado.",+ "search": "Buscar temas",+ "installed_only": "Mostrar solo instalados",+ "showing_one": "Mostrando {{count}} tema",+ "showing_other": "Mostrando {{count}} temas",+ "installed": "Instalado",+ "loading": "Cargando temas",+ "error": "No se pudo cargar la tienda de temas. Inténtalo de nuevo en un momento.",+ "retry": "Reintentar",+ "none_installed": "Aún no hay temas instalados.",+ "no_results": "Ningún tema coincide con «{{query}}».",+ "by": "de {{author}}",+ "downloads_one": "{{downloads}} descarga",+ "downloads_other": "{{downloads}} descargas",+ "source": "{{repo}} en GitHub",+ "no_preview": "Sin vista previa",+ "screenshot_alt": "{{name}} en modo {{mode}}",+ "install": "Instalar",+ "installing": "Instalando…",+ "use": "Usar",+ "in_use": "En uso",+ "update": "Actualizar a {{version}}",+ "remove": "Quitar",+ "taken": "Ya hay un tema instalado con este id",+ "installed_toast": "Se instaló «{{name}}».",+ "updated": "«{{name}}» se actualizó a {{version}}.",+ "install_failed": "No se pudo instalar «{{name}}»",+ "warning": "Un tema puede cambiar el estilo de todas las páginas, incluidos los diálogos y las advertencias. Los temas de la tienda se revisan automáticamente, pero los crea la comunidad."+ },+ "updates": {+ "title": "Temas de la tienda",+ "description_one": "Tienes {{count}} tema de la tienda.",+ "description_other": "Tienes {{count}} temas de la tienda.",+ "check": "Buscar actualizaciones",+ "checking": "Buscando…",+ "up_to_date": "Tus temas de la tienda están actualizados.",+ "update_all": "Actualizar todo ({{count}})"+ },+ "own": {+ "title": "Crea el tuyo",+ "description": "Importa un tema como .zip o carpeta, o empieza con una copia del actual."+ },"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",diff --git a/packages/views/locales/fr/settings.json b/packages/views/locales/fr/settings.jsonindex a239843bef..6c230605df 100644--- a/packages/views/locales/fr/settings.json+++ b/packages/views/locales/fr/settings.json@@ -193,7 +193,7 @@},"theme": {"title": "Thème",- "description": "Couleurs, bordures, ombres et coins de toute l’app. Importez un fichier de thème pour en ajouter.",+ "description": "Couleurs, bordures, ombres et coins de toute l’app.","default": "Par défaut","pop": "Pop","built_in": "Intégrés",@@ -224,12 +224,56 @@"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."},+ "store": {+ "manage": "Gérer",+ "title": "Thèmes",+ "description": "Les thèmes que vous avez installés et ceux créés par la communauté.",+ "description_local": "Les thèmes que vous avez installés.",+ "search": "Rechercher des thèmes",+ "installed_only": "Afficher uniquement les thèmes installés",+ "showing_one": "{{count}} thème affiché",+ "showing_other": "{{count}} thèmes affichés",+ "installed": "Installé",+ "loading": "Chargement des thèmes",+ "error": "Impossible de charger la boutique de thèmes. Réessayez dans un instant.",+ "retry": "Réessayer",+ "none_installed": "Aucun thème n’est encore installé.",+ "no_results": "Aucun thème ne correspond à « {{query}} ».",+ "by": "par {{author}}",+ "downloads_one": "{{downloads}} téléchargement",+ "downloads_other": "{{downloads}} téléchargements",+ "source": "{{repo}} sur GitHub",+ "no_preview": "Pas d’aperçu",+ "screenshot_alt": "{{name}} en mode {{mode}}",+ "install": "Installer",+ "installing": "Installation…",+ "use": "Utiliser",+ "in_use": "Utilisé",+ "update": "Mettre à jour vers {{version}}",+ "remove": "Supprimer",+ "taken": "Un thème avec cet identifiant est déjà installé",+ "installed_toast": "« {{name}} » est installé.",+ "updated": "« {{name}} » est passé à {{version}}.",+ "install_failed": "Impossible d’installer « {{name}} »",+ "warning": "Un thème peut modifier le style de toutes les pages, y compris les boîtes de dialogue et les avertissements. Les thèmes de la boutique sont vérifiés automatiquement, mais ils sont créés par la communauté."+ },+ "updates": {+ "title": "Thèmes de la boutique",+ "description_one": "Vous avez {{count}} thème de la boutique.",+ "description_other": "Vous avez {{count}} thèmes de la boutique.",+ "check": "Rechercher des mises à jour",+ "checking": "Recherche…",+ "up_to_date": "Vos thèmes de la boutique sont à jour.",+ "update_all": "Tout mettre à jour ({{count}})"+ },+ "own": {+ "title": "Créer le vôtre",+ "description": "Importez un thème au format .zip ou depuis un dossier, ou partez d’une copie du thème actuel."+ },"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",diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.jsonindex 7d8961111c..e78b5a4cd7 100644--- a/packages/views/locales/ja/settings.json+++ b/packages/views/locales/ja/settings.json@@ -192,7 +192,7 @@},"theme": {"title": "テーマ",- "description": "アプリ全体の色、枠線、影、角丸。テーマファイルを読み込んで追加できます。",+ "description": "アプリ全体の色、枠線、影、角丸。","default": "デフォルト","pop": "ポップ","built_in": "組み込み",@@ -221,12 +221,53 @@"close": "閉じる","has_options_other": "オプション {{count}} 個","has_assets_other": "フォント・画像 {{count}} 個",- "menu_label": "カスタムテーマ","beta": "ベータ","beta_note": "カスタムテーマはベータ版です。テーマが使う変数やマニフェストは変わることがあり、テーマの更新が必要になる場合があります。"},+ "store": {+ "manage": "管理",+ "title": "テーマ",+ "description": "インストールしたテーマと、コミュニティが作ったテーマです。",+ "description_local": "インストールしたテーマです。",+ "search": "テーマを検索",+ "installed_only": "インストール済みのみ表示",+ "showing_other": "{{count}} 個のテーマを表示中",+ "installed": "インストール済み",+ "loading": "テーマを読み込み中",+ "error": "テーマストアを読み込めませんでした。しばらくしてからもう一度お試しください。",+ "retry": "再試行",+ "none_installed": "インストール済みのテーマはまだありません。",+ "no_results": "「{{query}}」に一致するテーマはありません。",+ "by": "作者:{{author}}",+ "downloads_other": "{{downloads}} 回ダウンロード",+ "source": "GitHub で {{repo}} を見る",+ "no_preview": "プレビューなし",+ "screenshot_alt": "{{name}}({{mode}}モード)",+ "install": "インストール",+ "installing": "インストール中…",+ "use": "使う",+ "in_use": "使用中",+ "update": "{{version}} に更新",+ "remove": "削除",+ "taken": "同じ ID のテーマがインストール済みです",+ "installed_toast": "「{{name}}」をインストールしました。",+ "updated": "「{{name}}」を {{version}} に更新しました。",+ "install_failed": "「{{name}}」をインストールできませんでした",+ "warning": "テーマはダイアログや警告を含むすべてのページのスタイルを変更できます。ストアのテーマは自動でチェックされますが、コミュニティが作成したものです。"+ },+ "updates": {+ "title": "ストアのテーマ",+ "description_other": "ストアのテーマを {{count}} 個インストールしています。",+ "check": "アップデートを確認",+ "checking": "確認中…",+ "up_to_date": "ストアのテーマはすべて最新です。",+ "update_all": "すべてアップデート ({{count}})"+ },+ "own": {+ "title": "自分で作る",+ "description": ".zip またはフォルダからテーマを読み込むか、現在のテーマのコピーから始めます。"+ },"tools": {- "label": "その他のテーマ操作","duplicate": "「{{name}}」を複製して新しいテーマにする","open_folder": "テーマフォルダを開く","guide": "テーマの作り方",diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.jsonindex 55bba3e4d4..4c5bc4154b 100644--- a/packages/views/locales/ko/settings.json+++ b/packages/views/locales/ko/settings.json@@ -192,7 +192,7 @@},"theme": {"title": "테마",- "description": "앱 전체의 색상, 테두리, 그림자, 모서리. 테마 파일을 가져와 더 추가할 수 있어요.",+ "description": "앱 전체의 색상, 테두리, 그림자, 모서리.","default": "기본","pop": "팝","built_in": "기본 제공",@@ -221,12 +221,53 @@"close": "닫기","has_options_other": "옵션 {{count}}개","has_assets_other": "글꼴·이미지 {{count}}개",- "menu_label": "사용자 테마","beta": "베타","beta_note": "사용자 테마는 베타예요. 테마가 쓰는 변수와 매니페스트가 바뀔 수 있어 테마를 업데이트해야 할 수도 있어요."},+ "store": {+ "manage": "관리",+ "title": "테마",+ "description": "설치한 테마와 커뮤니티가 만든 테마입니다.",+ "description_local": "설치한 테마입니다.",+ "search": "테마 검색",+ "installed_only": "설치된 테마만 보기",+ "showing_other": "테마 {{count}}개 표시 중",+ "installed": "설치됨",+ "loading": "테마를 불러오는 중",+ "error": "테마 스토어를 불러오지 못했습니다. 잠시 후 다시 시도하세요.",+ "retry": "다시 시도",+ "none_installed": "아직 설치된 테마가 없습니다.",+ "no_results": "“{{query}}”와 일치하는 테마가 없습니다.",+ "by": "작성자: {{author}}",+ "downloads_other": "다운로드 {{downloads}}회",+ "source": "GitHub에서 {{repo}} 보기",+ "no_preview": "미리보기 없음",+ "screenshot_alt": "{{mode}} 모드의 {{name}}",+ "install": "설치",+ "installing": "설치 중…",+ "use": "사용",+ "in_use": "사용 중",+ "update": "{{version}}(으)로 업데이트",+ "remove": "제거",+ "taken": "같은 ID의 테마가 설치되어 있습니다",+ "installed_toast": "“{{name}}”을(를) 설치했습니다.",+ "updated": "“{{name}}”을(를) {{version}}(으)로 업데이트했습니다.",+ "install_failed": "“{{name}}”을(를) 설치하지 못했습니다",+ "warning": "테마는 대화 상자와 경고를 포함한 모든 페이지의 스타일을 바꿀 수 있습니다. 스토어 테마는 자동으로 검사되지만 커뮤니티가 만든 것입니다."+ },+ "updates": {+ "title": "스토어 테마",+ "description_other": "스토어에서 설치한 테마가 {{count}}개 있습니다.",+ "check": "업데이트 확인",+ "checking": "확인 중…",+ "up_to_date": "스토어 테마가 모두 최신 상태입니다.",+ "update_all": "모두 업데이트 ({{count}})"+ },+ "own": {+ "title": "직접 만들기",+ "description": ".zip 파일이나 폴더로 테마를 가져오거나, 현재 테마의 사본으로 시작하세요."+ },"tools": {- "label": "테마 작업 더 보기","duplicate": "“{{name}}” 복제해서 새 테마 만들기","open_folder": "테마 폴더 열기","guide": "테마 만드는 방법",diff --git a/packages/views/locales/ru/settings.json b/packages/views/locales/ru/settings.jsonindex b29016056c..dd2204ff64 100644--- a/packages/views/locales/ru/settings.json+++ b/packages/views/locales/ru/settings.json@@ -194,7 +194,7 @@},"theme": {"title": "Тема",- "description": "Цвета, границы, тени и скругления во всём приложении. Чтобы добавить другие темы, импортируйте файл темы.",+ "description": "Цвета, границы, тени и скругления во всём приложении.","default": "По умолчанию","pop": "Pop","built_in": "Встроенные",@@ -229,12 +229,62 @@"has_assets_few": "{{count}} шрифта или изображения","has_assets_many": "{{count}} шрифтов или изображений","has_assets_other": "{{count}} шрифта или изображения",- "menu_label": "Свои темы","beta": "Бета","beta_note": "Свои темы в бета-версии. Переменные и манифест, которые использует тема, могут измениться, и тему придётся обновить."},+ "store": {+ "manage": "Управление",+ "title": "Темы",+ "description": "Установленные вами темы и темы от сообщества.",+ "description_local": "Установленные вами темы.",+ "search": "Поиск тем",+ "installed_only": "Только установленные",+ "showing_one": "Показана {{count}} тема",+ "showing_few": "Показано {{count}} темы",+ "showing_many": "Показано {{count}} тем",+ "showing_other": "Показано {{count}} темы",+ "installed": "Установлена",+ "loading": "Загрузка тем",+ "error": "Не удалось загрузить магазин тем. Повторите попытку чуть позже.",+ "retry": "Повторить",+ "none_installed": "Пока нет установленных тем.",+ "no_results": "Нет тем по запросу «{{query}}».",+ "by": "автор: {{author}}",+ "downloads_one": "{{downloads}} загрузка",+ "downloads_few": "{{downloads}} загрузки",+ "downloads_many": "{{downloads}} загрузок",+ "downloads_other": "{{downloads}} загрузки",+ "source": "{{repo}} на GitHub",+ "no_preview": "Нет превью",+ "screenshot_alt": "{{name}}, режим «{{mode}}»",+ "install": "Установить",+ "installing": "Установка…",+ "use": "Применить",+ "in_use": "Используется",+ "update": "Обновить до {{version}}",+ "remove": "Удалить",+ "taken": "Тема с таким id уже установлена",+ "installed_toast": "Тема «{{name}}» установлена.",+ "updated": "Тема «{{name}}» обновлена до {{version}}.",+ "install_failed": "Не удалось установить «{{name}}»",+ "warning": "Тема может менять оформление любой страницы, включая диалоги и предупреждения. Темы из магазина проверяются автоматически, но их создаёт сообщество."+ },+ "updates": {+ "title": "Темы из магазина",+ "description_one": "У вас {{count}} тема из магазина.",+ "description_few": "У вас {{count}} темы из магазина.",+ "description_many": "У вас {{count}} тем из магазина.",+ "description_other": "У вас {{count}} темы из магазина.",+ "check": "Проверить обновления",+ "checking": "Проверка…",+ "up_to_date": "Темы из магазина обновлены.",+ "update_all": "Обновить все ({{count}})"+ },+ "own": {+ "title": "Создайте свою",+ "description": "Импортируйте тему из .zip или папки либо начните с копии текущей."+ },"tools": {- "label": "Другие действия с темой","duplicate": "Дублировать «{{name}}» как новую тему","open_folder": "Открыть папку тем","guide": "Как сделать тему",diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.jsonindex f0f0cea571..519f785ebd 100644--- a/packages/views/locales/zh-Hans/settings.json+++ b/packages/views/locales/zh-Hans/settings.json@@ -192,7 +192,7 @@},"theme": {"title": "主题",- "description": "全局的颜色、边框、阴影和圆角。可以导入主题文件添加更多主题。",+ "description": "全局的颜色、边框、阴影和圆角。","default": "默认","pop": "波普","built_in": "内置",@@ -221,12 +221,53 @@"close": "关闭","has_options_other": "{{count}} 个选项","has_assets_other": "{{count}} 个字体和图片",- "menu_label": "自定义主题","beta": "Beta","beta_note": "自定义主题处于 Beta 阶段。主题用到的变量和清单可能会变,主题可能需要更新。"},+ "store": {+ "manage": "管理",+ "title": "主题",+ "description": "你安装的主题,以及社区制作的主题。",+ "description_local": "你安装的主题。",+ "search": "搜索主题",+ "installed_only": "只看已安装",+ "showing_other": "共 {{count}} 个主题",+ "installed": "已安装",+ "loading": "正在加载主题",+ "error": "无法加载主题商店,请稍后重试。",+ "retry": "重试",+ "none_installed": "还没有安装任何主题。",+ "no_results": "没有与“{{query}}”匹配的主题。",+ "by": "作者:{{author}}",+ "downloads_other": "{{downloads}} 次下载",+ "source": "在 GitHub 上查看 {{repo}}",+ "no_preview": "暂无预览",+ "screenshot_alt": "{{name}}({{mode}}模式)",+ "install": "安装",+ "installing": "正在安装…",+ "use": "使用",+ "in_use": "使用中",+ "update": "更新到 {{version}}",+ "remove": "移除",+ "taken": "已安装同 ID 的主题",+ "installed_toast": "已安装“{{name}}”。",+ "updated": "已将“{{name}}”更新到 {{version}}。",+ "install_failed": "无法安装“{{name}}”",+ "warning": "主题可以改变每个页面的样式,包括对话框和警告。商店主题会经过自动检查,但均由社区制作。"+ },+ "updates": {+ "title": "商店主题",+ "description_other": "你从商店安装了 {{count}} 个主题。",+ "check": "检查更新",+ "checking": "正在检查…",+ "up_to_date": "商店主题都是最新版本。",+ "update_all": "全部更新({{count}})"+ },+ "own": {+ "title": "制作自己的主题",+ "description": "从 .zip 或文件夹导入主题,或从当前主题的副本开始。"+ },"tools": {- "label": "更多主题操作","duplicate": "复制「{{name}}」为新主题","open_folder": "打开主题文件夹","guide": "如何制作主题",diff --git a/packages/views/locales/zh-Hant/settings.json b/packages/views/locales/zh-Hant/settings.jsonindex c894ea67e5..ccfc098387 100644--- a/packages/views/locales/zh-Hant/settings.json+++ b/packages/views/locales/zh-Hant/settings.json@@ -192,7 +192,7 @@},"theme": {"title": "主題",- "description": "全域的顏色、邊框、陰影和圓角。可以匯入主題檔案加入更多主題。",+ "description": "全域的顏色、邊框、陰影和圓角。","default": "預設","pop": "普普","built_in": "內建",@@ -221,12 +221,53 @@"close": "關閉","has_options_other": "{{count}} 個選項","has_assets_other": "{{count}} 個字型和圖片",- "menu_label": "自訂主題","beta": "Beta","beta_note": "自訂主題處於 Beta 階段。主題用到的變數和清單可能會變,主題可能需要更新。"},+ "store": {+ "manage": "管理",+ "title": "主題",+ "description": "你安裝的主題,以及社群製作的主題。",+ "description_local": "你安裝的主題。",+ "search": "搜尋主題",+ "installed_only": "只看已安裝",+ "showing_other": "共 {{count}} 個主題",+ "installed": "已安裝",+ "loading": "正在載入主題",+ "error": "無法載入主題商店,請稍後再試。",+ "retry": "重試",+ "none_installed": "還沒有安裝任何主題。",+ "no_results": "沒有符合「{{query}}」的主題。",+ "by": "作者:{{author}}",+ "downloads_other": "{{downloads}} 次下載",+ "source": "在 GitHub 上查看 {{repo}}",+ "no_preview": "暫無預覽",+ "screenshot_alt": "{{name}}({{mode}}模式)",+ "install": "安裝",+ "installing": "正在安裝…",+ "use": "使用",+ "in_use": "使用中",+ "update": "更新至 {{version}}",+ "remove": "移除",+ "taken": "已安裝相同 ID 的主題",+ "installed_toast": "已安裝「{{name}}」。",+ "updated": "已將「{{name}}」更新至 {{version}}。",+ "install_failed": "無法安裝「{{name}}」",+ "warning": "主題可以改變每個頁面的樣式,包括對話框與警告。商店主題會經過自動檢查,但皆由社群製作。"+ },+ "updates": {+ "title": "商店主題",+ "description_other": "你從商店安裝了 {{count}} 個主題。",+ "check": "檢查更新",+ "checking": "正在檢查…",+ "up_to_date": "商店主題都是最新版本。",+ "update_all": "全部更新({{count}})"+ },+ "own": {+ "title": "製作自己的主題",+ "description": "從 .zip 或資料夾匯入主題,或從目前主題的副本開始。"+ },"tools": {- "label": "更多主題操作","duplicate": "複製「{{name}}」為新主題","open_folder": "開啟主題資料夾","guide": "如何製作主題",diff --git a/packages/views/settings/components/appearance-tab.test.tsx b/packages/views/settings/components/appearance-tab.test.tsxindex a49bcc6c08..075ed53996 100644--- a/packages/views/settings/components/appearance-tab.test.tsx+++ b/packages/views/settings/components/appearance-tab.test.tsx@@ -1,15 +1,19 @@import type { ReactNode } from "react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { cleanup, render, screen, within } from "@testing-library/react";+import { act, cleanup, render, screen, waitFor, within } from "@testing-library/react";import userEvent from "@testing-library/user-event";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { I18nProvider } from "@multica/core/i18n/react";+import { configStore } from "@multica/core/config";import {DEFAULT_APPEARANCE,+ parseTheme,readZip,themeFromFiles,useAppearanceStore,useInstalledThemesStore,useThemeFolderStatus,+ writeZip,} from "@multica/core/appearance";import enCommon from "../../locales/en/common.json";import enSettings from "../../locales/en/settings.json";@@ -22,16 +26,26 @@ const themeState = vi.hoisted(() => ({vi.mock("@multica/ui/components/common/theme-provider", () => ({useTheme: () => themeState,}));+const api = vi.hoisted(() => ({+ listStoreThemes: vi.fn(),+ getStoreThemePackage: vi.fn(),+ getStoreThemeScreenshot: vi.fn(),+}));+vi.mock("@multica/core/api", () => ({ api }));import { AppearanceTab } from "./appearance-tab";const TEST_RESOURCES = { en: { common: enCommon, settings: enSettings } };+let queryClient: QueryClient;+function Wrapper({ children }: { children: ReactNode }) {return (- <I18nProvider locale="en" resources={TEST_RESOURCES}>- {children}- </I18nProvider>+ <QueryClientProvider client={queryClient}>+ <I18nProvider locale="en" resources={TEST_RESOURCES}>+ {children}+ </I18nProvider>+ </QueryClientProvider>);}@@ -67,8 +81,11 @@ describe("AppearanceTab", () => {themeState.setTheme.mockClear();localStorage.clear();useAppearanceStore.setState(DEFAULT_APPEARANCE);- useInstalledThemesStore.setState({ themes: [], folders: {} });+ useInstalledThemesStore.setState({ themes: [], folders: {}, fromStore: {} });useThemeFolderStatus.setState({ path: null, problems: [] });+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ configStore.getState().setThemeStoreEnabled(false);+ vi.clearAllMocks();});afterEach(() => {cleanup();@@ -174,6 +191,7 @@ describe("AppearanceTab", () => {const user = userEvent.setup();render(<AppearanceTab />, { wrapper: Wrapper });+ expect(screen.queryByText("Store themes")).toBeNull();await user.click(screen.getByRole("button", { name: "Import theme" }));expect(await screen.findByRole("menuitem", { name: "Theme file (.zip)" })).toBeInTheDocument();await user.keyboard("{Escape}");@@ -196,9 +214,71 @@ describe("AppearanceTab", () => {expect(await screen.findByText("Installed")).toBeInTheDocument();await user.keyboard("{Escape}");- await user.click(screen.getByRole("button", { name: "Remove Paper" }));+ await user.click(screen.getByRole("button", { name: "Manage" }));+ const themes = await screen.findByRole("dialog");+ expect(within(themes).getAllByRole("heading", { level: 3 }).map((h) => h.textContent)).toEqual(["Paper"]);+ expect(within(themes).getByText("Showing 1 theme")).toBeInTheDocument();+ expect(themes.querySelector('[data-theme-preview="paper"]')).not.toBeNull();+ expect(within(themes).queryByRole("switch", { name: "Show installed only" })).toBeNull();+ await user.click(within(themes).getByRole("button", { name: "Remove Paper" }));expect(useInstalledThemesStore.getState().themes).toEqual([]);expect(state().theme).toBe("default");+ expect(within(themes).getByText("No themes are installed yet.")).toBeInTheDocument();+ expect(api.listStoreThemes).not.toHaveBeenCalled();+ });++ it("keeps built-in themes in the picker only, and offers Manage once there is something to manage", async () => {+ const user = userEvent.setup();+ render(<AppearanceTab />, { wrapper: Wrapper });+ expect(screen.queryByRole("button", { name: "Manage" })).toBeNull();++ act(() => configStore.getState().setThemeStoreEnabled(true));+ api.listStoreThemes.mockResolvedValue([]);+ await user.click(screen.getByRole("button", { name: "Manage" }));+ const themes = await screen.findByRole("dialog");+ expect(await within(themes).findByText("No themes are installed yet.")).toBeInTheDocument();+ expect(within(themes).queryByRole("heading", { name: "Blueprint" })).toBeNull();+ });++ it("checks the store for updates when asked, and updates every theme that has one", async () => {+ const encoder = new TextEncoder();+ const manifest = (version: string) => ({ ...PAPER, version });+ const old = parseTheme({ manifest: manifest("0.9.0"), css: PAPER_CSS });+ if (!old.ok) throw new Error("fixture");+ useInstalledThemesStore.getState().installFromStore(old.theme, "0.9.0");+ configStore.getState().setThemeStoreEnabled(true);+ const listed = (version: string) => ({+ id: "paper",+ name: "Paper",+ author: "Someone",+ repo: "someone/multica-theme-paper",+ description: "",+ modes: ["light"],+ version,+ size: 100,+ screenshots: [],+ downloads: 0,+ });+ api.listStoreThemes.mockResolvedValueOnce([listed("0.9.0")]).mockResolvedValue([listed("1.0.0")]);+ api.getStoreThemePackage.mockResolvedValue(+ writeZip([+ { path: "manifest.json", data: encoder.encode(JSON.stringify(manifest("1.0.0"))) },+ { path: "theme.css", data: encoder.encode(PAPER_CSS) },+ ]),+ );+ const user = userEvent.setup();+ render(<AppearanceTab />, { wrapper: Wrapper });++ expect(screen.getByText("You have 1 theme from the store.")).toBeInTheDocument();+ expect(api.listStoreThemes).not.toHaveBeenCalled();+ await user.click(screen.getByRole("button", { name: "Check for updates" }));+ await waitFor(() => expect(api.listStoreThemes).toHaveBeenCalledTimes(1));+ expect(await screen.findByRole("button", { name: "Check for updates" })).toBeEnabled();++ await user.click(screen.getByRole("button", { name: "Check for updates" }));+ await user.click(await screen.findByRole("button", { name: "Update all (1)" }));+ await waitFor(() => expect(useInstalledThemesStore.getState().fromStore).toEqual({ paper: "1.0.0" }));+ expect(await screen.findByRole("button", { name: "Check for updates" })).toBeInTheDocument();});it("duplicates the active theme as a .zip to edit and import, on web", async () => {@@ -209,8 +289,8 @@ describe("AppearanceTab", () => {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();+ expect(screen.queryByRole("button", { name: "Open themes folder" })).toBeNull();+ await user.click(screen.getByRole("button", { name: "Import theme" }));await user.click(await screen.findByRole("menuitem", { name: "Duplicate “GitHub” as a new theme" }));expect(click).toHaveBeenCalledTimes(1);@@ -242,7 +322,7 @@ describe("AppearanceTab", () => {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(screen.getByRole("button", { name: "Import theme" }));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([@@ -267,7 +347,6 @@ describe("AppearanceTab", () => {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();@@ -275,9 +354,13 @@ describe("AppearanceTab", () => {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" }));+ await user.click(screen.getByRole("button", { name: "Open themes folder" }));expect(desktop.openThemeFolder).toHaveBeenCalledWith();++ await user.click(screen.getByRole("button", { name: "Manage" }));+ const themes = await screen.findByRole("dialog");+ expect(within(themes).getByRole("heading", { name: "Paper" })).toBeInTheDocument();+ expect(within(themes).queryByRole("button", { name: "Remove Paper" })).toBeNull();});});diff --git a/packages/views/settings/components/appearance-tab.tsx b/packages/views/settings/components/appearance-tab.tsxindex 80300edd71..68a0c833f7 100644--- a/packages/views/settings/components/appearance-tab.tsx+++ b/packages/views/settings/components/appearance-tab.tsx@@ -2,19 +2,20 @@import { useEffect, useMemo, useRef, useState } from "react";import { useShallow } from "zustand/react/shallow";+import { useQuery } from "@tanstack/react-query";import { toast } from "sonner";import {BookOpen,+ ChevronDown,Copy,- Ellipsis,+ FileArchive,+ FolderInput,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";@@ -32,9 +33,7 @@ import {import {DropdownMenu,DropdownMenuContent,- DropdownMenuGroup,DropdownMenuItem,- DropdownMenuLabel,DropdownMenuSeparator,DropdownMenuTrigger,} from "@multica/ui/components/ui/dropdown-menu";@@ -96,10 +95,15 @@ import {type ThemedColor,type UiFont,} from "@multica/core/appearance";+import { storeThemeState, storeThemesOptions } from "@multica/core/appearance/theme-store";+import { useConfigStore } from "@multica/core/config";import { useLocale, useT } from "../../i18n";import { SegmentedToggle } from "../../common/segmented-toggle";+import { docsLocalePrefix } from "../../common/docs-locale";import { openExternal } from "../../platform/open-external";import { themeFolderAPI } from "../../platform/theme-folder";+import { ThemesButton, useStoreThemeInstall } from "./themes-dialog";+import { ThemeSwatch, useAppliedMode, useThemeLabel, type PreviewMode } from "./theme-swatch";import {SettingsCard,SettingsRow,@@ -107,7 +111,6 @@ import {SettingsTab,} from "./settings-layout";-type PreviewMode = "light" | "dark";type ModeChoice = PreviewMode | "system";const UI_FONT_NAME: Record<UiFont, string> = {@@ -177,21 +180,6 @@ export function AppearanceTab() {);}-function useAppliedMode(): PreviewMode {- const { resolvedTheme } = useTheme();- return resolvedTheme === "dark" ? "dark" : "light";-}--function useThemeLabel() {- const { t } = useT("settings");- return (theme: Theme) =>- theme.id === "default"- ? t(($) => $.appearance.theme.default)- : theme.id === "pop"- ? t(($) => $.appearance.theme.pop)- : theme.name;-}-function ColorSection() {const { t } = useT("settings");const { theme: mode, setTheme: setMode } = useTheme();@@ -200,7 +188,6 @@ function ColorSection() {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();@@ -210,7 +197,6 @@ function ColorSection() {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),@@ -247,21 +233,6 @@ function ColorSection() {</SettingsRow><SettingsRow label={themeLabel} description={t(($) => $.appearance.theme.description)} anchor="theme"><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}<Selectitems={items}value={selected ? theme : "default"}@@ -304,10 +275,11 @@ function ColorSection() {) : null}</SelectContent></Select>- <ImportThemeButton />- <ThemeToolsMenu theme={activeTheme({ theme }, safeMode.active)} />+ <ThemesButton /></div></SettingsRow>+ <StoreThemesRow />+ <OwnThemeRow theme={activeTheme({ theme }, safeMode.active)} />{folderProblems.length > 0 ? (<div role="status" className="space-y-1.5 px-4 py-3 text-caption"><div className="flex items-center gap-2">@@ -339,12 +311,19 @@ function ColorSection() {);}+interface ThemeImport {+ chooseZip: () => void;+ chooseFolder: () => void;+ /** The file pickers and the confirm and error dialogs; render it once. */+ element: React.ReactNode;+}+/*** 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() {+function useThemeImport(): ThemeImport {const { t } = useT("settings");const zipRef = useRef<HTMLInputElement>(null);const folderRef = useRef<HTMLInputElement>(null);@@ -398,28 +377,8 @@ function ImportThemeButton() {const assetCount = pending ? Object.keys(pending.assets ?? {}).length : 0;const optionCount = pending?.options?.filter((option) => option.type !== "heading").length ?? 0;- return (+ const element = (<>- <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)}>@@ -486,9 +445,12 @@ function ImportThemeButton() {</AlertDialog></>);+ return { chooseZip: () => zipRef.current?.click(), chooseFolder: () => folderRef.current?.click(), element };}-const THEME_GUIDE_URL = "https://github.com/multica-ai/multica/blob/main/docs/theming.md";+function themeGuideUrl(language: string): string {+ return `https://multica.ai/docs${docsLocalePrefix(language)}/developers/themes`;+}function downloadFile(data: Uint8Array<ArrayBuffer>, name: string, type: string) {const url = URL.createObjectURL(new Blob([data], { type }));@@ -500,14 +462,74 @@ function downloadFile(data: Uint8Array<ArrayBuffer>, name: string, type: string)}/**- * 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.+ * Themes installed from the store, and their updates. The store is only+ * asked when this is clicked or the Manage window has been opened, and not+ * at all when the server does not serve it.*/-function ThemeToolsMenu({ theme }: { theme: Theme }) {+function StoreThemesRow() {const { t } = useT("settings");+ const enabled = useConfigStore((s) => s.themeStoreEnabled);+ const themes = useInstalledThemesStore((s) => s.themes);+ const fromStore = useInstalledThemesStore((s) => s.fromStore);+ const listing = useQuery(storeThemesOptions(false));+ const install = useStoreThemeInstall();+ const [updating, setUpdating] = useState(false);+ const count = themes.filter((theme) => theme.id in fromStore).length;+ if (!enabled || count === 0) return null;+ const updates = (listing.data ?? []).filter((theme) => storeThemeState(theme, { themes, fromStore }) === "update");++ const check = async () => {+ const result = await listing.refetch();+ if (result.isError || !result.data) {+ toast.error(t(($) => $.appearance.store.error));+ return;+ }+ const current = useInstalledThemesStore.getState();+ if (!result.data.some((theme) => storeThemeState(theme, current) === "update")) {+ toast.success(t(($) => $.appearance.updates.up_to_date));+ }+ };+ const updateAll = async () => {+ setUpdating(true);+ try {+ for (const theme of updates) await install(theme);+ } finally {+ setUpdating(false);+ }+ };++ return (+ <SettingsRow+ label={t(($) => $.appearance.updates.title)}+ description={t(($) => $.appearance.updates.description, { count })}+ anchor="theme-updates"+ >+ {updates.length > 0 ? (+ <Button size="sm" disabled={updating} onClick={() => void updateAll()}>+ {updating+ ? t(($) => $.appearance.store.installing)+ : t(($) => $.appearance.updates.update_all, { count: updates.length })}+ </Button>+ ) : (+ <Button variant="outline" size="sm" disabled={listing.isFetching} onClick={() => void check()}>+ {listing.isFetching ? t(($) => $.appearance.updates.checking) : t(($) => $.appearance.updates.check)}+ </Button>+ )}+ </SettingsRow>+ );+}++/**+ * Making a theme: import one, or duplicate the active theme as a starting+ * point. 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 OwnThemeRow({ theme }: { theme: Theme }) {+ const { t } = useT("settings");+ const locale = useLocale();const themeLabelFor = useThemeLabel();+ const importer = useThemeImport();const install = useInstalledThemesStore((s) => s.install);const set = useAppearanceStore((s) => s.set);const folder = themeFolderAPI();@@ -543,32 +565,63 @@ function ThemeToolsMenu({ theme }: { theme: Theme }) {};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>+ <SettingsRow+ label={+ <span className="flex items-center gap-2">+ {t(($) => $.appearance.own.title)}+ <Badge variant="secondary">{t(($) => $.appearance.import.beta)}</Badge>+ </span>+ }+ description={t(($) => $.appearance.own.description)}+ anchor="theme-import"+ >+ <div className="flex items-center gap-2">+ <Button+ variant="ghost"+ size="icon-sm"+ className="text-muted-foreground"+ onClick={() => openExternal(themeGuideUrl(locale))}+ aria-label={t(($) => $.appearance.tools.guide)}+ title={t(($) => $.appearance.tools.guide)}+ >+ <BookOpen />+ </Button>{folder ? (- <DropdownMenuItem onClick={() => void folder.openThemeFolder()}>+ <Button+ variant="ghost"+ size="icon-sm"+ className="text-muted-foreground"+ onClick={() => void folder.openThemeFolder()}+ aria-label={t(($) => $.appearance.tools.open_folder)}+ title={t(($) => $.appearance.tools.open_folder)}+ ><FolderOpen />- {t(($) => $.appearance.tools.open_folder)}- </DropdownMenuItem>+ </Button>) : null}- <DropdownMenuSeparator />- <DropdownMenuItem onClick={() => openExternal(THEME_GUIDE_URL)}>- <BookOpen />- {t(($) => $.appearance.tools.guide)}- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>+ <DropdownMenu>+ <DropdownMenuTrigger render={<Button variant="outline" size="sm" />}>+ {t(($) => $.appearance.import.button)}+ <ChevronDown data-icon="inline-end" className="text-muted-foreground" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="min-w-56">+ <DropdownMenuItem onClick={importer.chooseZip}>+ <FileArchive />+ {t(($) => $.appearance.import.from_zip)}+ </DropdownMenuItem>+ <DropdownMenuItem onClick={importer.chooseFolder}>+ <FolderInput />+ {t(($) => $.appearance.import.from_folder)}+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem onClick={() => void duplicate()}>+ <Copy />+ {t(($) => $.appearance.tools.duplicate, { name: themeLabelFor(theme) })}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ {importer.element}+ </div>+ </SettingsRow>);}@@ -1256,77 +1309,3 @@ function LayoutSection() {</SettingsSection>);}--type SwatchTokens = Record<"app-shell" | "page-canvas" | "surface-border" | "foreground" | "brand", string>;--/**- * The tokens a theme swatch needs, as tokens.css sets them for the default- * theme. A theme only overrides some of them, so swatches start from these.- */-const THEME_SWATCH_BASE: Record<PreviewMode, SwatchTokens> = {- light: {- "app-shell": "oklch(0.964 0.001 286)",- "page-canvas": "oklch(0.988 0 0)",- "surface-border": "oklch(0.92 0.004 286)",- foreground: "oklch(0.141 0.005 286)",- brand: "oklch(0.561 0.194 256.4)",- },- dark: {- "app-shell": "oklch(0.155 0.005 286)",- "page-canvas": "oklch(0.18 0.005 286)",- "surface-border": "oklch(0.3 0.006 286)",- foreground: "oklch(0.985 0 0)",- brand: "oklch(0.65 0.16 255)",- },-};--const swatchCache = new WeakMap<Theme, ReturnType<typeof themeModeVariables>>();--/**- * Resolves `var()` references a swatch can know without the theme applied:- * the theme's own variables for the mode and its colour options' defaults.- */-function resolveSwatchValue(value: string, theme: Theme, variables: Record<string, string>, mode: PreviewMode, depth = 0): string {- return value.replace(/var\(--([a-z0-9-]+)\)/g, (reference, name: string) => {- const option = theme.options?.find((o) => o.id === name);- if (option?.type === "color") return option.default[mode];- const own = variables[name];- return own && depth < 4 ? resolveSwatchValue(own, theme, variables, mode, depth + 1) : reference;- });-}--function swatchTokens(theme: Theme, mode: PreviewMode): SwatchTokens {- let variables = swatchCache.get(theme);- if (!variables) {- variables = themeModeVariables(theme.css);- swatchCache.set(theme, variables);- }- const tokens = { ...THEME_SWATCH_BASE[mode] };- for (const name of Object.keys(tokens) as (keyof SwatchTokens)[]) {- const own = variables[mode][name];- if (own) tokens[name] = resolveSwatchValue(own, theme, variables[mode], mode);- }- return tokens;-}--/** A theme in miniature: its frame, page, ink and brand colour. */-function ThemeSwatch({ theme, mode }: { theme: Theme; mode: PreviewMode }) {- const tokens = swatchTokens(theme, mode);- return (- <span- aria-hidden="true"- data-theme-swatch={theme.id}- data-swatch-mode={mode}- className="flex h-4 w-6 shrink-0 items-end overflow-hidden rounded-xs p-[2px] ring-1 ring-foreground/10"- style={{ background: tokens["app-shell"] }}- >- <span- className="flex size-full flex-col justify-center gap-[2px] rounded-[calc(var(--radius-xs)/2)] px-[2px]"- style={{ background: tokens["page-canvas"], boxShadow: `inset 0 0 0 0.5px ${tokens["surface-border"]}` }}- >- <span className="h-[2px] w-3/5 rounded-full" style={{ background: tokens.foreground }} />- <span className="h-[2px] w-2/5 rounded-full" style={{ background: tokens.brand }} />- </span>- </span>- );-}diff --git a/packages/views/settings/components/theme-swatch.tsx b/packages/views/settings/components/theme-swatch.tsxnew file mode 100644index 0000000000..2e8d8960e8--- /dev/null+++ b/packages/views/settings/components/theme-swatch.tsx@@ -0,0 +1,164 @@+"use client";++import { themeModeVariables, type Theme } from "@multica/core/appearance";+import { useTheme } from "@multica/ui/components/common/theme-provider";+import { useT } from "../../i18n";++export type PreviewMode = "light" | "dark";++/** The mode the app is drawn in right now. */+export function useAppliedMode(): PreviewMode {+ const { resolvedTheme } = useTheme();+ return resolvedTheme === "dark" ? "dark" : "light";+}++/** A theme's name; the built-in ones that have a translated name use it. */+export function useThemeLabel() {+ const { t } = useT("settings");+ return (theme: Theme) =>+ theme.id === "default"+ ? t(($) => $.appearance.theme.default)+ : theme.id === "pop"+ ? t(($) => $.appearance.theme.pop)+ : theme.name;+}++type SwatchToken =+ | "app-shell"+ | "page-canvas"+ | "surface"+ | "surface-border"+ | "surface-selected"+ | "foreground"+ | "muted-foreground"+ | "brand"+ | "warning"+ | "success"+ | "info";+type SwatchTokens = Record<SwatchToken, string>;++/**+ * The tokens a theme swatch needs, as tokens.css sets them for the default+ * theme. A theme only overrides some of them, so swatches start from these.+ */+const THEME_SWATCH_BASE: Record<PreviewMode, SwatchTokens> = {+ light: {+ "app-shell": "oklch(0.964 0.001 286)",+ "page-canvas": "oklch(0.988 0 0)",+ surface: "oklch(1 0 0)",+ "surface-border": "oklch(0.92 0.004 286)",+ "surface-selected": "oklch(0.95 0.002 286)",+ foreground: "oklch(0.141 0.005 286)",+ "muted-foreground": "oklch(0.505 0.016 286)",+ brand: "oklch(0.561 0.194 256.4)",+ warning: "oklch(0.75 0.16 85)",+ success: "oklch(0.55 0.16 145)",+ info: "oklch(0.55 0.18 250)",+ },+ dark: {+ "app-shell": "oklch(0.155 0.005 286)",+ "page-canvas": "oklch(0.18 0.005 286)",+ surface: "oklch(0.21 0.006 286)",+ "surface-border": "oklch(0.3 0.006 286)",+ "surface-selected": "oklch(0.3 0.006 286)",+ foreground: "oklch(0.985 0 0)",+ "muted-foreground": "oklch(0.705 0.015 286)",+ brand: "oklch(0.65 0.16 255)",+ warning: "oklch(0.7 0.16 85)",+ success: "oklch(0.65 0.15 145)",+ info: "oklch(0.65 0.18 250)",+ },+};++const swatchCache = new WeakMap<Theme, ReturnType<typeof themeModeVariables>>();++/**+ * Resolves `var()` references a swatch can know without the theme applied:+ * the theme's own variables for the mode and its colour options' defaults.+ */+function resolveSwatchValue(value: string, theme: Theme, variables: Record<string, string>, mode: PreviewMode, depth = 0): string {+ return value.replace(/var\(--([a-z0-9-]+)\)/g, (reference, name: string) => {+ const option = theme.options?.find((o) => o.id === name);+ if (option?.type === "color") return option.default[mode];+ const own = variables[name];+ return own && depth < 4 ? resolveSwatchValue(own, theme, variables, mode, depth + 1) : reference;+ });+}++function swatchTokens(theme: Theme, mode: PreviewMode): SwatchTokens {+ let variables = swatchCache.get(theme);+ if (!variables) {+ variables = themeModeVariables(theme.css);+ swatchCache.set(theme, variables);+ }+ const tokens = { ...THEME_SWATCH_BASE[mode] };+ for (const name of Object.keys(tokens) as (keyof SwatchTokens)[]) {+ const own = variables[mode][name];+ if (own) tokens[name] = resolveSwatchValue(own, theme, variables[mode], mode);+ }+ return tokens;+}++/** A theme in miniature: its frame, page, ink and brand colour. */+export function ThemeSwatch({ theme, mode }: { theme: Theme; mode: PreviewMode }) {+ const tokens = swatchTokens(theme, mode);+ return (+ <span+ aria-hidden="true"+ data-theme-swatch={theme.id}+ data-swatch-mode={mode}+ className="flex h-4 w-6 shrink-0 items-end overflow-hidden rounded-xs p-[2px] ring-1 ring-foreground/10"+ style={{ background: tokens["app-shell"] }}+ >+ <span+ className="flex size-full flex-col justify-center gap-[2px] rounded-[calc(var(--radius-xs)/2)] px-[2px]"+ style={{ background: tokens["page-canvas"], boxShadow: `inset 0 0 0 0.5px ${tokens["surface-border"]}` }}+ >+ <span className="h-[2px] w-3/5 rounded-full" style={{ background: tokens.foreground }} />+ <span className="h-[2px] w-2/5 rounded-full" style={{ background: tokens.brand }} />+ </span>+ </span>+ );+}++/**+ * A theme drawn as a small app window from its own tokens: sidebar, page,+ * a list and the brand button. It is the preview of a theme that has no+ * screenshot: the built-in ones, and the ones imported or in the themes folder.+ */+export function ThemePreview({ theme, mode, className }: { theme: Theme; mode: PreviewMode; className?: string }) {+ const c = swatchTokens(theme, mode);+ const rows = [+ { y: 43, dot: c.warning, width: 44 },+ { y: 55, dot: c.info, width: 32 },+ { y: 67, dot: c.success, width: 38 },+ ];+ return (+ <svg+ viewBox="0 0 160 100"+ preserveAspectRatio="xMidYMin slice"+ aria-hidden="true"+ data-theme-preview={theme.id}+ className={className}+ >+ <rect width="160" height="100" fill={c["app-shell"]} />+ <rect x="8" y="9" width="8" height="8" rx="2" fill={c.foreground} />+ <rect x="5" y="23" width="30" height="8" rx="2" fill={c["surface-selected"]} />+ <rect x="8" y="25" width="20" height="4" rx="2" fill={c.foreground} opacity="0.75" />+ {[18, 23, 14].map((width, i) => (+ <rect key={i} x="8" y={37 + i * 10} width={width} height="4" rx="2" fill={c["muted-foreground"]} opacity="0.55" />+ ))}+ <rect x="40.5" y="8.5" width="140" height="110" rx="7" fill={c["page-canvas"]} stroke={c["surface-border"]} />+ <rect x="50" y="18" width="46" height="5" rx="2.5" fill={c.foreground} />+ <rect x="128" y="16" width="22" height="9" rx="4" fill={c.brand} />+ <rect x="50.5" y="35.5" width="100" height="44" rx="4" fill={c.surface} stroke={c["surface-border"]} />+ {rows.map((row) => (+ <g key={row.y}>+ <circle cx="58" cy={row.y + 2} r="2.5" fill={row.dot} />+ <rect x="65" y={row.y} width={row.width} height="4" rx="2" fill={c.foreground} opacity="0.78" />+ <rect x="130" y={row.y} width="12" height="4" rx="2" fill={c["muted-foreground"]} opacity="0.5" />+ </g>+ ))}+ </svg>+ );+}diff --git a/packages/views/settings/components/themes-dialog.test.tsx b/packages/views/settings/components/themes-dialog.test.tsxnew file mode 100644index 0000000000..b05bd9bdd8--- /dev/null+++ b/packages/views/settings/components/themes-dialog.test.tsx@@ -0,0 +1,174 @@+import type { ReactNode } from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { cleanup, render, screen, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { I18nProvider } from "@multica/core/i18n/react";+import { configStore } from "@multica/core/config";+import {+ DEFAULT_APPEARANCE,+ parseTheme,+ useAppearanceStore,+ useInstalledThemesStore,+ writeZip,+} from "@multica/core/appearance";+import type { StoreTheme } from "@multica/core/api/schemas";+import enCommon from "../../locales/en/common.json";+import enSettings from "../../locales/en/settings.json";++const api = vi.hoisted(() => ({+ listStoreThemes: vi.fn(),+ getStoreThemePackage: vi.fn(),+ getStoreThemeScreenshot: vi.fn(),+}));+vi.mock("@multica/core/api", () => ({ api }));+vi.mock("@multica/ui/components/common/theme-provider", () => ({+ useTheme: () => ({ theme: "light", resolvedTheme: "light", setTheme: vi.fn() }),+}));++import { ThemesButton } from "./themes-dialog";++const TEST_RESOURCES = { en: { common: enCommon, settings: enSettings } };++function renderButton() {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ function Wrapper({ children }: { children: ReactNode }) {+ return (+ <QueryClientProvider client={client}>+ <I18nProvider locale="en" resources={TEST_RESOURCES}>+ {children}+ </I18nProvider>+ </QueryClientProvider>+ );+ }+ return render(<ThemesButton />, { wrapper: Wrapper });+}++const encoder = new TextEncoder();+const manifest = (id: string, name: string, version: string) => ({ apiVersion: 1, id, name, author: "Someone", version });+const css = ".theme-light { --page-canvas: #f6efdf; }";+const release = (id: string, name: string, version: string) =>+ writeZip([+ { path: "manifest.json", data: encoder.encode(JSON.stringify(manifest(id, name, version))) },+ { path: "theme.css", data: encoder.encode(css) },+ ]);+const listed = (id: string, name: string, version = "1.0.0", downloads = 0): StoreTheme => ({+ id,+ name,+ author: "Someone",+ repo: `someone/multica-theme-${id}`,+ description: `${name} theme`,+ modes: ["light", "dark"],+ version,+ size: 100,+ screenshots: ["light", "dark"],+ downloads,+});++describe("ThemesButton", () => {+ beforeEach(() => {+ localStorage.clear();+ useAppearanceStore.setState(DEFAULT_APPEARANCE);+ useInstalledThemesStore.setState({ themes: [], folders: {}, fromStore: {} });+ configStore.getState().setThemeStoreEnabled(true);+ api.listStoreThemes.mockResolvedValue([listed("ink", "Ink"), listed("sand", "Sand")]);+ api.getStoreThemeScreenshot.mockResolvedValue(new Blob(["png"], { type: "image/png" }));+ api.getStoreThemePackage.mockImplementation(async (id: string) =>+ release(id, id === "ink" ? "Ink" : "Sand", "1.0.0"),+ );+ });+ afterEach(() => {+ cleanup();+ vi.clearAllMocks();+ });++ it("lists only the installed themes and makes no requests when the server has no store", async () => {+ configStore.getState().setThemeStoreEnabled(false);+ const user = userEvent.setup();+ const { rerender } = renderButton();+ expect(screen.queryByRole("button", { name: "Manage" })).toBeNull();++ const parsed = parseTheme({ manifest: manifest("paper", "Paper", "1.0.0"), css });+ if (!parsed.ok) throw new Error("fixture");+ useInstalledThemesStore.getState().install(parsed.theme);+ rerender(<ThemesButton />);+ await user.click(screen.getByRole("button", { name: "Manage" }));+ expect(screen.getByText("The themes you installed.")).toBeTruthy();+ expect(screen.getAllByRole("heading", { level: 3 }).map((h) => h.textContent)).toEqual(["Paper"]);+ expect(api.listStoreThemes).not.toHaveBeenCalled();+ });++ it("lists and searches the store, installs a theme and removes it", async () => {+ const user = userEvent.setup();+ renderButton();+ await user.click(screen.getByRole("button", { name: "Manage" }));+ expect(await screen.findByRole("heading", { name: "Ink" })).toBeTruthy();+ expect(screen.getByText("Beta")).toBeTruthy();+ expect(screen.getByText("Showing 2 themes")).toBeTruthy();+ expect(screen.queryByRole("heading", { name: "Default" })).toBeNull();++ await user.type(screen.getByRole("textbox", { name: "Search themes" }), "san");+ expect(screen.queryByRole("heading", { name: "Ink" })).toBeNull();+ expect(screen.getByRole("heading", { name: "Sand" })).toBeTruthy();+ await user.clear(screen.getByRole("textbox", { name: "Search themes" }));++ const [installInk] = screen.getAllByRole("button", { name: "Install" });+ await user.click(installInk!);+ await waitFor(() => expect(useInstalledThemesStore.getState().fromStore).toEqual({ ink: "1.0.0" }));+ expect(useAppearanceStore.getState().theme).toBe("ink");+ expect(await screen.findByRole("button", { name: "In use" })).toBeTruthy();+ // The card stays where it was while the window is open.+ expect(screen.getAllByRole("heading", { level: 3 }).map((h) => h.textContent)).toEqual(["Ink", "Sand"]);+ await user.click(screen.getByRole("switch", { name: "Show installed only" }));+ expect(screen.getAllByRole("heading", { level: 3 }).map((h) => h.textContent)).toEqual(["Ink"]);++ await user.click(screen.getByRole("button", { name: "Remove Ink" }));+ expect(useInstalledThemesStore.getState().themes).toEqual([]);+ expect(useAppearanceStore.getState().theme).toBe("default");+ });++ it("shows how often each store theme was downloaded, most downloaded first, and recounts after an install", async () => {+ api.listStoreThemes.mockResolvedValue([listed("ink", "Ink", "1.0.0", 1), listed("sand", "Sand", "1.0.0", 1250)]);+ const user = userEvent.setup();+ renderButton();+ await user.click(screen.getByRole("button", { name: "Manage" }));+ expect(await screen.findByText("by Someone · 1.3K downloads")).toBeTruthy();+ expect(screen.getByText("by Someone · 1 download")).toBeTruthy();+ expect(screen.getAllByRole("heading", { level: 3 }).map((h) => h.textContent)).toEqual(["Sand", "Ink"]);++ api.listStoreThemes.mockResolvedValue([listed("ink", "Ink", "1.0.0", 2), listed("sand", "Sand", "1.0.0", 1250)]);+ const [installSand] = screen.getAllByRole("button", { name: "Install" });+ await user.click(installSand!);+ expect(await screen.findByText("by Someone · 2 downloads")).toBeTruthy();+ expect(api.listStoreThemes).toHaveBeenCalledTimes(2);+ });++ it("offers the listed release as an update", async () => {+ const parsed = parseTheme({ manifest: manifest("ink", "Ink", "0.9.0"), css });+ if (!parsed.ok) throw new Error("fixture");+ useInstalledThemesStore.getState().installFromStore(parsed.theme, "0.9.0");+ const user = userEvent.setup();+ renderButton();+ await user.click(screen.getByRole("button", { name: "Manage" }));+ await user.click(await screen.findByRole("button", { name: "Update to 1.0.0" }));+ await waitFor(() => expect(useInstalledThemesStore.getState().fromStore).toEqual({ ink: "1.0.0" }));+ expect(useInstalledThemesStore.getState().themes[0]?.version).toBe("1.0.0");+ });++ it("installs nothing when the release fails the checks", async () => {+ api.getStoreThemePackage.mockResolvedValue(+ writeZip([+ { path: "manifest.json", data: encoder.encode(JSON.stringify(manifest("ink", "Ink", "1.0.0"))) },+ { path: "theme.css", data: encoder.encode("body { background: url(https://evil.test/x.png); }") },+ ]),+ );+ const user = userEvent.setup();+ renderButton();+ await user.click(screen.getByRole("button", { name: "Manage" }));+ await screen.findByRole("heading", { name: "Ink" });+ await user.click(screen.getAllByRole("button", { name: "Install" })[0]!);+ await waitFor(() => expect(api.getStoreThemePackage).toHaveBeenCalled());+ await waitFor(() => expect(screen.getAllByRole("button", { name: "Install" })).toHaveLength(2));+ expect(useInstalledThemesStore.getState().themes).toEqual([]);+ });+});diff --git a/packages/views/settings/components/themes-dialog.tsx b/packages/views/settings/components/themes-dialog.tsxnew file mode 100644index 0000000000..863aabf4c7--- /dev/null+++ b/packages/views/settings/components/themes-dialog.tsx@@ -0,0 +1,501 @@+"use client";++import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";+import { useQuery, useQueryClient } from "@tanstack/react-query";+import { toast } from "sonner";+import { ExternalLink, Search } from "@multica/ui/icons";+import { Badge } from "@multica/ui/components/ui/badge";+import { Button } from "@multica/ui/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+} from "@multica/ui/components/ui/dialog";+import { Input } from "@multica/ui/components/ui/input";+import { Skeleton } from "@multica/ui/components/ui/skeleton";+import { Switch } from "@multica/ui/components/ui/switch";+import { useConfigStore } from "@multica/core/config";+import { useAppearanceStore, useInstalledThemesStore, type Theme } from "@multica/core/appearance";+import {+ readStoreTheme,+ storeThemeScreenshotOptions,+ storeThemeState,+ storeThemesOptions,+ themeStoreKeys,+ type StoreTheme,+ type StoreThemeMode,+} from "@multica/core/appearance/theme-store";+import { useLocale, useT } from "../../i18n";+import { SegmentedToggle } from "../../common/segmented-toggle";+import { openExternal } from "../../platform/open-external";+import { ThemePreview, useAppliedMode, useThemeLabel } from "./theme-swatch";++/**+ * Settings → Appearance → Manage: the themes installed on this device and,+ * when the server serves the community theme store (beta), the store's+ * themes. Built-in themes are only in the theme picker. A deployment that+ * turned the store off makes no store requests, and with nothing installed+ * there is nothing to manage.+ */+export function ThemesButton() {+ const { t } = useT("settings");+ const [open, setOpen] = useState(false);+ const storeEnabled = useConfigStore((s) => s.themeStoreEnabled);+ const hasInstalled = useInstalledThemesStore((s) => s.themes.length > 0);+ if (!storeEnabled && !hasInstalled && !open) return null;+ return (+ <>+ <Button variant="outline" size="sm" onClick={() => setOpen(true)}>+ {t(($) => $.appearance.store.manage)}+ </Button>+ <Dialog open={open} onOpenChange={setOpen}>+ <DialogContent className="flex max-h-[min(44rem,calc(100dvh-2rem))] flex-col gap-0 overflow-hidden p-0 sm:max-w-3xl">+ {open ? <Themes /> : null}+ </DialogContent>+ </Dialog>+ </>+ );+}++/**+ * Installs the listed release of a store theme, or updates to it. A new+ * install is applied at once; an update leaves the theme in use as it is.+ */+export function useStoreThemeInstall() {+ const { t } = useT("settings");+ const queryClient = useQueryClient();+ return useCallback(+ async (theme: StoreTheme) => {+ const themes = useInstalledThemesStore.getState();+ const update = storeThemeState(theme, themes) === "update";+ try {+ const result = await readStoreTheme(theme);+ void queryClient.invalidateQueries({ queryKey: themeStoreKeys.themes() });+ if (!result.ok) {+ toast.error(t(($) => $.appearance.store.install_failed, { name: theme.name }), {+ description: result.errors.join("\n"),+ });+ return;+ }+ const previous = themes.themes.find((installed) => installed.id === theme.id);+ const previousVersion = themes.fromStore[theme.id];+ try {+ themes.installFromStore(result.theme, theme.version);+ } catch {+ if (previous && previousVersion !== undefined) themes.installFromStore(previous, previousVersion);+ else if (previous) themes.install(previous);+ else themes.uninstall(theme.id);+ toast.error(t(($) => $.appearance.import.storage_full));+ return;+ }+ if (update) {+ toast.success(t(($) => $.appearance.store.updated, { name: theme.name, version: theme.version }));+ } else {+ useAppearanceStore.getState().set({ theme: theme.id });+ toast.success(t(($) => $.appearance.store.installed_toast, { name: theme.name }));+ }+ } catch (error) {+ toast.error(t(($) => $.appearance.store.install_failed, { name: theme.name }), {+ description: error instanceof Error ? error.message : undefined,+ });+ }+ },+ [t, queryClient],+ );+}++type Entry =+ | { kind: "local"; key: string; name: string; author: string; installed: boolean; theme: Theme }+ | { kind: "store"; key: string; name: string; author: string; installed: boolean; theme: StoreTheme };++function Themes() {+ const { t } = useT("settings");+ const storeEnabled = useConfigStore((s) => s.themeStoreEnabled);+ const listing = useQuery(storeThemesOptions(storeEnabled));+ const installed = useInstalledThemesStore((s) => s.themes);+ const fromStore = useInstalledThemesStore((s) => s.fromStore);+ const themeLabelFor = useThemeLabel();+ const [query, setQuery] = useState("");+ const [installedOnly, setInstalledOnly] = useState(false);+ const needle = query.trim().toLowerCase();++ // Installed themes, then what the store offers. A theme installed from the+ // store is shown as the store lists it.+ const listed = new Map((listing.data ?? []).map((theme) => [theme.id, theme]));+ const local = (theme: Theme): Entry => {+ const store = theme.id in fromStore ? listed.get(theme.id) : undefined;+ if (store) listed.delete(theme.id);+ return store+ ? { kind: "store", key: store.id, name: store.name, author: store.author, installed: true, theme: store }+ : { kind: "local", key: theme.id, name: themeLabelFor(theme), author: theme.author ?? "", installed: true, theme };+ };+ const entries = installed.map(local);+ for (const theme of [...listed.values()].sort((a, b) => b.downloads - a.downloads)) {+ // A listed theme whose id is taken on this device is shown next to the one that has it.+ const taken = entries.some((entry) => entry.key === theme.id);+ entries.push({+ kind: "store",+ key: taken ? `store:${theme.id}` : theme.id,+ name: theme.name,+ author: theme.author,+ installed: false,+ theme,+ });+ }+ // A card keeps its place while the window is open, so installing or+ // removing a theme does not move it from under the pointer.+ const order = useRef(new Map<string, number>()).current;+ for (const entry of entries) if (!order.has(entry.key)) order.set(entry.key, order.size);+ entries.sort((a, b) => order.get(a.key)! - order.get(b.key)!);++ const shown = entries.filter(+ (entry) =>+ (!installedOnly || entry.installed) &&+ (!needle || entry.name.toLowerCase().includes(needle) || entry.author.toLowerCase().includes(needle)),+ );+ const loadingStore = storeEnabled && listing.isPending && !installedOnly;++ return (+ <>+ <DialogHeader className="gap-1.5 border-b border-surface-border px-5 pt-5 pb-4">+ <DialogTitle className="flex items-center gap-2">+ {t(($) => $.appearance.store.title)}+ <Badge variant="secondary">{t(($) => $.appearance.import.beta)}</Badge>+ </DialogTitle>+ <DialogDescription className="text-caption">+ {storeEnabled ? t(($) => $.appearance.store.description) : t(($) => $.appearance.store.description_local)}+ </DialogDescription>+ <div className="mt-2 flex items-center gap-3">+ <div className="relative min-w-0 flex-1">+ <Search+ aria-hidden="true"+ className="pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2 text-muted-foreground"+ />+ <Input+ value={query}+ onChange={(event) => setQuery(event.target.value)}+ placeholder={t(($) => $.appearance.store.search)}+ aria-label={t(($) => $.appearance.store.search)}+ className="pl-8"+ />+ </div>+ {storeEnabled ? (+ <label className="flex shrink-0 items-center gap-2 text-label">+ <Switch+ checked={installedOnly}+ onCheckedChange={setInstalledOnly}+ aria-label={t(($) => $.appearance.store.installed_only)}+ />+ <span aria-hidden="true">{t(($) => $.appearance.store.installed_only)}</span>+ </label>+ ) : null}+ </div>+ </DialogHeader>+ <div className="min-h-0 flex-1 overflow-y-auto px-5 py-4">+ {shown.length === 0 && !loadingStore ? (+ <p className="py-12 text-center text-caption text-muted-foreground">+ {needle+ ? t(($) => $.appearance.store.no_results, { query: query.trim() })+ : t(($) => $.appearance.store.none_installed)}+ </p>+ ) : (+ <>+ <p className="mb-2.5 text-caption text-muted-foreground">+ {t(($) => $.appearance.store.showing, { count: shown.length })}+ </p>+ <ul className="grid gap-3 sm:grid-cols-3">+ {shown.map((entry) => (+ <li key={entry.key}>+ {entry.kind === "store" ? (+ <StoreThemeCard theme={entry.theme} />+ ) : (+ <LocalThemeCard theme={entry.theme} name={entry.name} />+ )}+ </li>+ ))}+ {loadingStore+ ? [0, 1, 2].map((i) => (+ <li key={`loading:${i}`} aria-label={i === 0 ? t(($) => $.appearance.store.loading) : undefined}>+ <Skeleton className="aspect-[16/14] rounded-lg" />+ </li>+ ))+ : null}+ </ul>+ </>+ )}+ {storeEnabled && listing.isError && !installedOnly ? (+ <div role="alert" className="flex flex-col items-center gap-3 py-8 text-center text-caption text-muted-foreground">+ {t(($) => $.appearance.store.error)}+ <Button variant="outline" size="sm" onClick={() => void listing.refetch()}>+ {t(($) => $.appearance.store.retry)}+ </Button>+ </div>+ ) : null}+ </div>+ {storeEnabled ? (+ <p className="border-t border-surface-border px-5 py-3 text-caption text-muted-foreground">+ {t(($) => $.appearance.store.warning)}+ </p>+ ) : null}+ </>+ );+}++/** The card every theme is shown as: a preview, what it is, and its actions. */+function ThemeCard({+ preview,+ name,+ version,+ badge,+ trailing,+ subtitle,+ description,+ children,+}: {+ preview: ReactNode;+ name: string;+ version?: string;+ badge?: ReactNode;+ trailing?: ReactNode;+ subtitle: string;+ description?: string;+ children: ReactNode;+}) {+ return (+ <article className="flex h-full flex-col overflow-hidden rounded-lg border border-surface-border bg-surface">+ <div className="relative">{preview}</div>+ <div className="flex flex-1 flex-col gap-0.5 px-3 pt-2 pb-2.5">+ <div className="flex min-h-[var(--button-height-xs)] min-w-0 items-center gap-1.5">+ <h3 className="truncate text-label font-medium">{name}</h3>+ {badge}+ {version ? <span className="shrink-0 text-caption text-muted-foreground">{version}</span> : null}+ {trailing}+ </div>+ <p className="truncate text-caption text-muted-foreground">{subtitle}</p>+ {description ? <p className="line-clamp-2 text-caption text-muted-foreground">{description}</p> : null}+ <div className="mt-auto flex items-center justify-end gap-1.5 pt-2">{children}</div>+ </div>+ </article>+ );+}++function StateBadge({ inUse, installed }: { inUse: boolean; installed: boolean }) {+ const { t } = useT("settings");+ if (inUse) {+ return (+ <Badge variant="secondary" className="shrink-0 bg-brand/15 text-brand">+ {t(($) => $.appearance.store.in_use)}+ </Badge>+ );+ }+ if (!installed) return null;+ return (+ <Badge variant="secondary" className="shrink-0">+ {t(($) => $.appearance.theme.installed)}+ </Badge>+ );+}++function UseButton({ id, inUse }: { id: string; inUse: boolean }) {+ const { t } = useT("settings");+ const set = useAppearanceStore((s) => s.set);+ return (+ <Button variant="outline" size="xs" disabled={inUse} onClick={() => set({ theme: id })}>+ {inUse ? t(($) => $.appearance.store.in_use) : t(($) => $.appearance.store.use)}+ </Button>+ );+}++function useRemoveTheme(id: string) {+ const uninstall = useInstalledThemesStore((s) => s.uninstall);+ const set = useAppearanceStore((s) => s.set);+ return () => {+ if (useAppearanceStore.getState().theme === id) set({ theme: "default" });+ uninstall(id);+ };+}++/**+ * An installed theme the store does not list: imported, or in the themes+ * folder. It has no screenshot, so it is drawn+ * from its tokens. Only an imported theme can be removed here; a theme in+ * the themes folder is removed by deleting its folder.+ */+function LocalThemeCard({ theme, name }: { theme: Theme; name: string }) {+ const { t } = useT("settings");+ const mode = useAppliedMode();+ const inFolder = useInstalledThemesStore((s) => theme.id in s.folders);+ const inUse = useAppearanceStore((s) => s.theme === theme.id);+ const remove = useRemoveTheme(theme.id);+ return (+ <ThemeCard+ preview={+ <div className="aspect-[16/10] border-b border-surface-border bg-muted">+ <ThemePreview theme={theme} mode={mode} className="size-full" />+ </div>+ }+ name={name}+ version={theme.version}+ badge={<StateBadge inUse={inUse} installed />}+ subtitle={+ inFolder+ ? t(($) => $.appearance.theme.folder)+ : theme.author+ ? t(($) => $.appearance.store.by, { author: theme.author })+ : t(($) => $.appearance.theme.installed)+ }+ >+ {!inFolder ? (+ <Button+ variant="ghost"+ size="xs"+ onClick={remove}+ aria-label={t(($) => $.appearance.theme.remove, { name })}+ >+ {t(($) => $.appearance.store.remove)}+ </Button>+ ) : null}+ <UseButton id={theme.id} inUse={inUse} />+ </ThemeCard>+ );+}++function StoreThemeCard({ theme }: { theme: StoreTheme }) {+ const { t } = useT("settings");+ const locale = useLocale();+ const appMode = useAppliedMode();+ const supported = theme.screenshots.length > 0 ? theme.screenshots : theme.modes;+ const [mode, setMode] = useState<StoreThemeMode>(supported.includes(appMode) ? appMode : supported[0] ?? appMode);+ const installed = useInstalledThemesStore((s) => s.themes);+ const fromStore = useInstalledThemesStore((s) => s.fromStore);+ const active = useAppearanceStore((s) => s.theme);+ const install = useStoreThemeInstall();+ const remove = useRemoveTheme(theme.id);+ const [busy, setBusy] = useState(false);+ const state = storeThemeState(theme, { themes: installed, fromStore });+ const onDevice = state === "installed" || state === "update";+ const inUse = active === theme.id && onDevice;++ const get = async () => {+ setBusy(true);+ try {+ await install(theme);+ } finally {+ setBusy(false);+ }+ };++ return (+ <ThemeCard+ preview={+ <>+ <Screenshot theme={theme} mode={mode} />+ {supported.length > 1 ? (+ <div className="absolute right-1.5 bottom-1.5 rounded-md bg-surface-raised/90 shadow-sm backdrop-blur">+ <SegmentedToggle<StoreThemeMode>+ value={mode}+ onChange={setMode}+ buttonClassName="px-1.5 py-0 text-caption"+ options={supported.map(+ (m) => [m, m === "light" ? t(($) => $.appearance.mode.light) : t(($) => $.appearance.mode.dark)] as const,+ )}+ />+ </div>+ ) : null}+ </>+ }+ name={theme.name}+ version={theme.version}+ badge={<StateBadge inUse={inUse} installed={onDevice} />}+ trailing={+ <Button+ variant="ghost"+ size="icon-xs"+ className="-mr-1.5 ml-auto text-muted-foreground"+ onClick={() => openExternal(`https://github.com/${theme.repo}`)}+ title={theme.repo}+ aria-label={t(($) => $.appearance.store.source, { repo: theme.repo })}+ >+ <ExternalLink />+ </Button>+ }+ subtitle={[+ t(($) => $.appearance.store.by, { author: theme.author }),+ t(($) => $.appearance.store.downloads, {+ count: theme.downloads,+ downloads: new Intl.NumberFormat(locale, { notation: "compact" }).format(theme.downloads),+ }),+ ].join(" · ")}+ description={theme.description}+ >+ {onDevice ? (+ <Button+ variant="ghost"+ size="xs"+ disabled={busy}+ onClick={remove}+ aria-label={t(($) => $.appearance.theme.remove, { name: theme.name })}+ >+ {t(($) => $.appearance.store.remove)}+ </Button>+ ) : null}+ {state === "update" ? (+ <Button size="xs" disabled={busy} onClick={() => void get()}>+ {busy ? t(($) => $.appearance.store.installing) : t(($) => $.appearance.store.update, { version: theme.version })}+ </Button>+ ) : null}+ {state === "available" ? (+ <Button size="xs" disabled={busy} onClick={() => void get()}>+ {busy ? t(($) => $.appearance.store.installing) : t(($) => $.appearance.store.install)}+ </Button>+ ) : onDevice ? (+ <UseButton id={theme.id} inUse={inUse} />+ ) : (+ <span className="text-caption text-muted-foreground">{t(($) => $.appearance.store.taken)}</span>+ )}+ </ThemeCard>+ );+}++function Screenshot({ theme, mode }: { theme: StoreTheme; mode: StoreThemeMode }) {+ const { t } = useT("settings");+ const shot = useQuery(storeThemeScreenshotOptions(theme, mode));+ const url = useObjectUrl(shot.data);+ return (+ <div className="aspect-[16/10] border-b border-surface-border bg-muted">+ {url ? (+ <img+ src={url}+ alt={t(($) => $.appearance.store.screenshot_alt, {+ name: theme.name,+ mode: mode === "light" ? t(($) => $.appearance.mode.light) : t(($) => $.appearance.mode.dark),+ })}+ className="size-full object-cover object-top"+ draggable={false}+ />+ ) : shot.isLoading ? (+ <Skeleton className="size-full rounded-none" />+ ) : (+ <div className="flex size-full items-center justify-center text-caption text-muted-foreground">+ {t(($) => $.appearance.store.no_preview)}+ </div>+ )}+ </div>+ );+}++function useObjectUrl(blob: Blob | undefined): string | null {+ const [url, setUrl] = useState<string | null>(null);+ useEffect(() => {+ if (!blob || typeof URL.createObjectURL !== "function") {+ setUrl(null);+ return;+ }+ const next = URL.createObjectURL(blob);+ setUrl(next);+ return () => URL.revokeObjectURL(next);+ }, [blob]);+ return url;+}diff --git a/packages/views/settings/components/use-settings-search-index.ts b/packages/views/settings/components/use-settings-search-index.tsindex 366d0715c6..d69b71bf73 100644--- a/packages/views/settings/components/use-settings-search-index.ts+++ b/packages/views/settings/components/use-settings-search-index.ts@@ -59,6 +59,12 @@ export function useSettingsSearchIndex(title: t(($) => $.appearance.theme.title),description: t(($) => $.appearance.theme.description),},+ {+ tab: "appearance",+ anchor: "theme-import",+ title: t(($) => $.appearance.own.title),+ description: t(($) => $.appearance.own.description),+ },{tab: "appearance",anchor: "ui-text",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 28a6251965..8e06a54147 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -212,6 +212,9 @@ importers:'@playwright/test':specifier: ^1.58.2version: 1.58.2+ '@tailwindcss/postcss':+ specifier: 'catalog:'+ version: 4.2.2'@types/node':specifier: 'catalog:'version: 25.5.0@@ -224,6 +227,9 @@ importers:pg:specifier: ^8.20.0version: 8.20.0+ postcss:+ specifier: 8.5.26+ version: 8.5.26turbo:specifier: ^2.5.4version: 2.9.5diff --git a/scripts/theme-check.mjs b/scripts/theme-check.mjsindex 4c87992ae5..358ac737e8 100644--- a/scripts/theme-check.mjs+++ b/scripts/theme-check.mjs@@ -9,51 +9,12 @@* 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";+import { readFileSync } from "node:fs";+import { basename, join, resolve } from "node:path";+import { appearance, readTheme, repoRoot } from "./theme-files.mjs";-// 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 { checkThemeFiles } = await appearance("theme-check.ts");+const { basePaletteFromTokens } = await appearance("theme-contrast.ts");const args = process.argv.slice(2);const json = args.includes("--json");diff --git a/scripts/theme-files.mjs b/scripts/theme-files.mjsnew file mode 100644index 0000000000..445847da38--- /dev/null+++ b/scripts/theme-files.mjs@@ -0,0 +1,53 @@+/**+ * Shared by the theme scripts: loads the appearance sources from+ * packages/core with Node's type stripping, and reads a theme folder or .zip+ * into the files the app's parser takes.+ */++import { readFileSync, readdirSync, statSync } from "node:fs";+import { register } from "node:module";+import { 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);+ }+ }+ `),+);++export const repoRoot = resolve(import.meta.dirname, "..");++/** Imports a module of packages/core/appearance. */+export const appearance = (file) => import(pathToFileURL(join(repoRoot, "packages/core/appearance", file)).href);++const { readZip } = await appearance("theme-archive.ts");+const { THEME_PACKAGE_MAX_BYTES } = await appearance("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;+}++/** The files of a theme folder or .zip, or why they could not be read. */+export 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 };+}diff --git a/scripts/theme-preview.mjs b/scripts/theme-preview.mjsnew file mode 100644index 0000000000..c266838fc8--- /dev/null+++ b/scripts/theme-preview.mjs@@ -0,0 +1,116 @@+#!/usr/bin/env node+/**+ * Renders a theme in light and dark mode on a fixture page built from the+ * app's own styles (scripts/theme-preview/fixture.html), for the theme+ * store's screenshots and for authors checking their work. The theme goes+ * through the app's parser and CSS sanitizer first; a theme that does not+ * parse is not rendered. The page cannot reach the network.+ *+ * Run: pnpm theme:preview <theme folder or .zip> [--out <dir>] [--modes light,dark]+ * Writes <out>/light.png and <out>/dark.png (default out: ./theme-preview).+ */++import { mkdirSync, readFileSync, writeFileSync } from "node:fs";+import { createRequire } from "node:module";+import { join, resolve } from "node:path";+import { appearance, readTheme, repoRoot } from "./theme-files.mjs";++const { themeFromFiles, themeCss } = await appearance("theme-package.ts");+const { themeOptionAttributes, themeOptionVariables } = await appearance("themes.ts");++const WIDTH = 1280;+const HEIGHT = 800;++function parseArgs(argv) {+ const args = { out: "theme-preview", modes: ["light", "dark"], targets: [] };+ for (let i = 0; i < argv.length; i += 1) {+ if (argv[i] === "--out") args.out = argv[++i];+ else if (argv[i] === "--modes") args.modes = argv[++i].split(",").filter((m) => m === "light" || m === "dark");+ else args.targets.push(argv[i]);+ }+ return args;+}++async function compileCss() {+ const require = createRequire(join(repoRoot, "package.json"));+ const postcss = require("postcss");+ const tailwind = require("@tailwindcss/postcss");+ const from = join(repoRoot, "scripts/theme-preview/fixture.css");+ const input = `+ @import "tailwindcss" source(none);+ @import "../../packages/ui/styles/tokens.css";+ @import "../../packages/ui/styles/theme-variables.css";+ @import "../../packages/ui/styles/appearance.css";+ @import "../../packages/ui/styles/base.css";+ @custom-variant dark (&:is(.dark *));+ @source "./fixture.html";+ :root {+ --font-sans: var(--font-ui, Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif);+ --font-mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;+ }+ `;+ const result = await postcss([tailwind({ base: repoRoot })]).process(input, { from });+ return result.css;+}++const declare = (variables) =>+ Object.entries(variables)+ .map(([name, value]) => `${name}: ${value};`)+ .join(" ");++/** The page as the app would draw it with the theme applied at its option defaults. */+function page(theme, mode, appCss) {+ const variables = themeOptionVariables(theme, undefined);+ const attributes = { "data-theme": theme.id, ...themeOptionAttributes(theme, undefined) };+ const attrs = Object.entries(attributes)+ .filter(([, value]) => value !== null)+ .map(([name, value]) => ` ${name}="${String(value).replace(/"/g, """)}"`)+ .join("");+ const adjustments = Object.keys(variables.light).length+ ? `:root.theme-light { ${declare(variables.light)} } :root.theme-dark { ${declare(variables.dark)} }`+ : "";+ const fixture = readFileSync(join(repoRoot, "scripts/theme-preview/fixture.html"), "utf8");+ // Inline <style> content cannot close its element: the sanitizer leaves no+ // markup in theme CSS, and "</" is escaped here as well.+ const style = (css) => `<style>${css.replace(/<\//g, "<\\/")}</style>`;+ return `<!doctype html><html lang="en" class="${mode} theme-${mode} is-web is-focused"${attrs}><head><meta charset="utf-8">${style(appCss)}${style(themeCss(theme))}${style(adjustments)}</head><body>${fixture}</body></html>`;+}++const args = parseArgs(process.argv.slice(2));+if (args.targets.length !== 1 || args.modes.length === 0) {+ console.error("Usage: pnpm theme:preview <theme folder or .zip> [--out <dir>] [--modes light,dark]");+ process.exit(2);+}+const target = resolve(process.env.INIT_CWD ?? process.cwd(), args.targets[0]);+const read = await readTheme(target);+const result = read.error ? { ok: false, errors: [read.error] } : themeFromFiles(read.files);+if (!result.ok) {+ console.error(`✗ ${args.targets[0]} does not pass the checks:\n${result.errors.map((e) => ` ${e}`).join("\n")}`);+ process.exit(1);+}++const out = resolve(process.env.INIT_CWD ?? process.cwd(), args.out);+mkdirSync(out, { recursive: true });+const appCss = await compileCss();+const { chromium } = createRequire(join(repoRoot, "package.json"))("@playwright/test");+const browser = await chromium.launch();+try {+ const context = await browser.newContext({+ viewport: { width: WIDTH, height: HEIGHT },+ deviceScaleFactor: 1,+ javaScriptEnabled: false,+ });+ await context.route("**/*", (route) =>+ route.request().url().startsWith("data:") ? route.continue() : route.abort(),+ );+ for (const mode of args.modes) {+ const tab = await context.newPage();+ await tab.setContent(page(result.theme, mode, appCss), { waitUntil: "load" });+ const file = join(out, `${mode}.png`);+ writeFileSync(file, await tab.screenshot({ animations: "disabled" }));+ await tab.close();+ console.log(`✓ ${result.theme.name} ${mode}: ${file}`);+ }+} finally {+ await browser.close();+}diff --git a/scripts/theme-preview/fixture.html b/scripts/theme-preview/fixture.htmlnew file mode 100644index 0000000000..709910ce7e--- /dev/null+++ b/scripts/theme-preview/fixture.html@@ -0,0 +1,120 @@+<!--+ The page theme screenshots are rendered on: an issue list next to an open+ issue, built from the app's own styles and its public `data-mc` anchors+ (packages/core/appearance/anchors.ts), so a theme's variables and anchor+ rules apply as they do in the app. Class names here are only for the+ fixture; themes must not rely on them.+-->+<div class="flex h-screen gap-0 bg-app-shell font-sans text-body text-foreground antialiased">+ <nav data-mc="app-rail" class="flex w-12 shrink-0 flex-col items-center gap-2 py-3">+ <span class="mb-2 flex size-7 items-center justify-center rounded-lg bg-primary text-micro font-semibold text-primary-foreground">M</span>+ <span class="size-7 rounded-md bg-sidebar-accent"></span>+ <span class="size-7 rounded-md"></span>+ <span class="size-7 rounded-md"></span>+ </nav>+ <aside data-mc="sidebar" data-state="expanded" class="flex w-56 shrink-0 flex-col gap-0.5 bg-sidebar px-2 py-3 text-sidebar-foreground">+ <div class="mb-2 px-2 text-label font-medium">Acme</div>+ <a data-mc="nav-item" data-active="false" class="flex items-center gap-2 rounded-md px-2 py-1.5 text-label text-sidebar-foreground">Inbox<span class="ml-auto rounded-sm bg-brand px-1.5 text-micro text-brand-foreground">3</span></a>+ <a data-mc="nav-item" data-active="true" class="flex items-center gap-2 rounded-md bg-sidebar-accent px-2 py-1.5 text-label font-medium text-sidebar-accent-foreground">Issues</a>+ <a data-mc="nav-item" data-active="false" class="flex items-center gap-2 rounded-md px-2 py-1.5 text-label text-sidebar-foreground">Projects</a>+ <a data-mc="nav-item" data-active="false" class="flex items-center gap-2 rounded-md px-2 py-1.5 text-label text-sidebar-foreground">Agents</a>+ <a data-mc="nav-item" data-active="false" class="flex items-center gap-2 rounded-md px-2 py-1.5 text-label text-sidebar-foreground">Autopilots</a>+ <div class="mt-4 mb-1 px-2 text-micro font-medium text-muted-foreground uppercase">Teams</div>+ <a data-mc="nav-item" data-active="false" class="flex items-center gap-2 rounded-md px-2 py-1.5 text-label text-sidebar-foreground">Design</a>+ <a data-mc="nav-item" data-active="false" class="flex items-center gap-2 rounded-md px-2 py-1.5 text-label text-sidebar-foreground">Platform</a>+ </aside>+ <main data-mc="page" class="my-2 mr-2 flex min-w-0 flex-1 overflow-hidden rounded-xl bg-page-canvas ring-1 ring-surface-border">+ <section class="flex w-[56%] min-w-0 flex-col border-r border-border">+ <header class="flex items-center gap-3 border-b border-border px-4 py-2.5">+ <h1 class="text-title-sm font-medium">Issues</h1>+ <div data-slot="tabs-list" class="flex gap-0.5 rounded-lg bg-muted p-0.5">+ <span data-slot="tabs-trigger" data-active class="rounded-md bg-background px-2 py-0.5 text-caption font-medium shadow-sm">All</span>+ <span data-slot="tabs-trigger" class="rounded-md px-2 py-0.5 text-caption text-muted-foreground">Active</span>+ <span data-slot="tabs-trigger" class="rounded-md px-2 py-0.5 text-caption text-muted-foreground">Backlog</span>+ </div>+ <button data-slot="button" data-variant="default" data-size="sm" class="ml-auto rounded-lg bg-primary px-2.5 py-1 text-caption font-medium text-primary-foreground">New issue</button>+ </header>+ <div class="flex-1 overflow-hidden">+ <div data-mc="issue-group-header" data-status="in_progress" class="flex items-center gap-2 bg-muted/60 px-4 py-1.5 text-label font-medium">+ <svg data-mc="status-icon" class="size-3.5 text-warning" viewBox="0 0 14 14" fill="none"><circle cx="7" cy="7" r="5.5" stroke="currentColor" stroke-width="1.5"/><path d="M7 1.5a5.5 5.5 0 0 1 0 11z" fill="currentColor"/></svg>+ In Progress <span class="text-muted-foreground">2</span>+ </div>+ <div data-mc="issue-row" data-status="in_progress" data-priority="high" data-assignee-type="agent" class="flex items-center gap-3 border-b border-border/60 bg-surface-selected px-4 py-2 text-surface-selected-foreground">+ <svg data-mc="priority-icon" class="size-3.5 text-priority-high" viewBox="0 0 14 14" fill="currentColor"><rect x="1" y="8" width="3" height="5" rx="1"/><rect x="5.5" y="5" width="3" height="8" rx="1"/><rect x="10" y="2" width="3" height="11" rx="1"/></svg>+ <span class="w-14 shrink-0 text-caption text-muted-foreground">ACM-142</span>+ <svg data-mc="status-icon" class="size-3.5 shrink-0 text-warning" viewBox="0 0 14 14" fill="none"><circle cx="7" cy="7" r="5.5" stroke="currentColor" stroke-width="1.5"/><path d="M7 1.5a5.5 5.5 0 0 1 0 11z" fill="currentColor"/></svg>+ <span class="truncate">Ship the onboarding checklist</span>+ <span data-mc="label-chip" data-color="#8b5cf6" class="ml-auto rounded-full border border-border px-2 text-caption">Design</span>+ </div>+ <div data-mc="issue-row" data-status="in_progress" data-priority="medium" data-assignee-type="member" class="flex items-center gap-3 border-b border-border/60 px-4 py-2">+ <svg data-mc="priority-icon" class="size-3.5 text-muted-foreground" viewBox="0 0 14 14" fill="currentColor"><rect x="1" y="8" width="3" height="5" rx="1"/><rect x="5.5" y="5" width="3" height="8" rx="1"/><rect x="10" y="2" width="3" height="11" rx="1" opacity=".3"/></svg>+ <span class="w-14 shrink-0 text-caption text-muted-foreground">ACM-139</span>+ <svg data-mc="status-icon" class="size-3.5 shrink-0 text-warning" viewBox="0 0 14 14" fill="none"><circle cx="7" cy="7" r="5.5" stroke="currentColor" stroke-width="1.5"/><path d="M7 1.5a5.5 5.5 0 0 1 0 11z" fill="currentColor"/></svg>+ <span class="truncate">Retry failed webhook deliveries</span>+ <span data-mc="label-chip" data-color="#0ea5e9" class="ml-auto rounded-full border border-border px-2 text-caption">Platform</span>+ </div>+ <div data-mc="issue-group-header" data-status="todo" class="flex items-center gap-2 bg-muted/60 px-4 py-1.5 text-label font-medium">+ <svg data-mc="status-icon" class="size-3.5 text-muted-foreground" viewBox="0 0 14 14" fill="none"><circle cx="7" cy="7" r="5.5" stroke="currentColor" stroke-width="1.5"/></svg>+ Todo <span class="text-muted-foreground">3</span>+ </div>+ <div data-mc="issue-row" data-status="todo" data-priority="low" data-assignee-type="none" class="flex items-center gap-3 border-b border-border/60 px-4 py-2">+ <svg data-mc="priority-icon" class="size-3.5 text-muted-foreground" viewBox="0 0 14 14" fill="currentColor"><rect x="1" y="8" width="3" height="5" rx="1"/><rect x="5.5" y="5" width="3" height="8" rx="1" opacity=".3"/><rect x="10" y="2" width="3" height="11" rx="1" opacity=".3"/></svg>+ <span class="w-14 shrink-0 text-caption text-muted-foreground">ACM-151</span>+ <svg data-mc="status-icon" class="size-3.5 shrink-0 text-muted-foreground" viewBox="0 0 14 14" fill="none"><circle cx="7" cy="7" r="5.5" stroke="currentColor" stroke-width="1.5"/></svg>+ <span class="truncate">Dark mode for exported PDFs</span>+ </div>+ <div data-mc="issue-row" data-status="todo" data-priority="high" data-assignee-type="squad" class="flex items-center gap-3 border-b border-border/60 px-4 py-2">+ <svg data-mc="priority-icon" class="size-3.5 text-priority-high" viewBox="0 0 14 14" fill="currentColor"><rect x="1" y="8" width="3" height="5" rx="1"/><rect x="5.5" y="5" width="3" height="8" rx="1"/><rect x="10" y="2" width="3" height="11" rx="1"/></svg>+ <span class="w-14 shrink-0 text-caption text-muted-foreground">ACM-148</span>+ <svg data-mc="status-icon" class="size-3.5 shrink-0 text-muted-foreground" viewBox="0 0 14 14" fill="none"><circle cx="7" cy="7" r="5.5" stroke="currentColor" stroke-width="1.5"/></svg>+ <span class="truncate">Audit log export for workspace admins</span>+ <span data-mc="label-chip" data-color="#ef4444" class="ml-auto rounded-full border border-border px-2 text-caption">Security</span>+ </div>+ <div data-mc="issue-row" data-status="todo" data-priority="medium" data-assignee-type="agent" class="flex items-center gap-3 border-b border-border/60 px-4 py-2">+ <svg data-mc="priority-icon" class="size-3.5 text-muted-foreground" viewBox="0 0 14 14" fill="currentColor"><rect x="1" y="8" width="3" height="5" rx="1"/><rect x="5.5" y="5" width="3" height="8" rx="1"/><rect x="10" y="2" width="3" height="11" rx="1" opacity=".3"/></svg>+ <span class="w-14 shrink-0 text-caption text-muted-foreground">ACM-147</span>+ <svg data-mc="status-icon" class="size-3.5 shrink-0 text-muted-foreground" viewBox="0 0 14 14" fill="none"><circle cx="7" cy="7" r="5.5" stroke="currentColor" stroke-width="1.5"/></svg>+ <span class="truncate">Summarise weekly agent activity</span>+ </div>+ <div data-mc="issue-group-header" data-status="done" class="flex items-center gap-2 bg-muted/60 px-4 py-1.5 text-label font-medium">+ <svg data-mc="status-icon" class="size-3.5 text-success" viewBox="0 0 14 14"><circle cx="7" cy="7" r="6" fill="currentColor"/><path d="m4.5 7 1.8 1.8L9.7 5.4" stroke="white" stroke-width="1.5" fill="none"/></svg>+ Done <span class="text-muted-foreground">1</span>+ </div>+ <div data-mc="issue-row" data-status="done" data-priority="low" data-assignee-type="member" class="flex items-center gap-3 border-b border-border/60 px-4 py-2 text-muted-foreground">+ <svg data-mc="priority-icon" class="size-3.5" viewBox="0 0 14 14" fill="currentColor"><rect x="1" y="8" width="3" height="5" rx="1"/><rect x="5.5" y="5" width="3" height="8" rx="1" opacity=".3"/><rect x="10" y="2" width="3" height="11" rx="1" opacity=".3"/></svg>+ <span class="w-14 shrink-0 text-caption">ACM-120</span>+ <svg data-mc="status-icon" class="size-3.5 shrink-0 text-success" viewBox="0 0 14 14"><circle cx="7" cy="7" r="6" fill="currentColor"/><path d="m4.5 7 1.8 1.8L9.7 5.4" stroke="white" stroke-width="1.5" fill="none"/></svg>+ <span class="truncate">Invite links that expire</span>+ </div>+ </div>+ </section>+ <section class="flex min-w-0 flex-1 flex-col gap-4 overflow-hidden px-6 py-5">+ <div class="text-caption text-muted-foreground">ACM-142</div>+ <h2 class="-mt-3 text-title-lg font-semibold">Ship the onboarding checklist</h2>+ <div data-mc="content" class="space-y-2.5 text-body leading-relaxed">+ <p>New workspaces should see a short checklist on the dashboard: connect a repository, create an agent and assign it a first issue.</p>+ <ul class="list-disc space-y-1 pl-5">+ <li>Hide it once every step is done.</li>+ <li>Keep the copy in <code class="rounded-sm bg-muted px-1 py-0.5 font-mono text-caption">checklist.json</code>.</li>+ </ul>+ <blockquote class="border-l-2 border-border pl-3 text-muted-foreground">Measure how many teams finish it in a week.</blockquote>+ </div>+ <div data-mc="comment" data-author-type="agent" data-slot="card" class="rounded-xl border border-surface-border bg-surface p-3 text-surface-foreground">+ <div class="mb-1.5 flex items-center gap-2 text-label">+ <span class="size-5 rounded-full bg-info"></span><span class="font-medium">Lambda</span><span class="text-caption text-muted-foreground">2h ago</span>+ </div>+ <div data-mc="content" data-density="compact" class="text-body">Opened a draft PR with the checklist and its empty state.</div>+ <div data-mc="comment-reply" data-author-type="member" class="mt-2.5 border-t border-border pt-2.5 text-body">+ <span class="font-medium">Ada</span> <span class="text-muted-foreground">Looks good, ship it.</span>+ </div>+ </div>+ <div data-mc="comment-composer" class="mt-auto rounded-xl border border-input bg-background p-3">+ <div data-slot="textarea" class="h-10 text-body text-muted-foreground">Leave a comment…</div>+ <div class="flex justify-end gap-2">+ <button data-slot="button" data-variant="outline" data-size="sm" class="rounded-lg border border-border bg-background px-2.5 py-1 text-caption">Attach</button>+ <button data-slot="button" data-variant="default" data-size="sm" class="rounded-lg bg-primary px-2.5 py-1 text-caption font-medium text-primary-foreground">Comment</button>+ </div>+ </div>+ </section>+ </main>+</div>diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 8835a58a71..a6bb6cd449 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -45,6 +45,7 @@ import ("github.com/multica-ai/multica/server/internal/seatcapacity""github.com/multica-ai/multica/server/internal/service""github.com/multica-ai/multica/server/internal/storage"+ "github.com/multica-ai/multica/server/internal/themestore""github.com/multica-ai/multica/server/internal/util""github.com/multica-ai/multica/server/internal/util/secretbox"composiosdk "github.com/multica-ai/multica/server/pkg/composio"@@ -462,6 +463,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bush.InvitationRateLimiters = handler.NewMemoryInvitationRateLimiters(invitationRateLimits)h.Metrics = opts.BusinessMetricsh.FeatureFlags = opts.FeatureFlags+ h.ThemeStore = themeStoreFromEnv()h.TaskService.FeatureFlags = opts.FeatureFlagsh.TaskService.Metrics = opts.BusinessMetricsh.IssueService.Metrics = opts.BusinessMetrics@@ -1745,6 +1747,9 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus// against it. Sits in the user-scoped group for that reason: there is// no workspace in the path to gate on.// --- User-scoped routes (no workspace context required) ---+ r.Get("/api/theme-store/themes", h.ListStoreThemes)+ r.Get("/api/theme-store/themes/{themeId}/package", h.GetStoreThemePackage)+ r.Get("/api/theme-store/themes/{themeId}/screenshots/{mode}", h.GetStoreThemeScreenshot)r.Get("/api/me", h.GetMe)r.Patch("/api/me", h.UpdateMe)r.Patch("/api/me/onboarding", h.PatchOnboarding)@@ -2843,6 +2848,26 @@ func optionalUUID(s string) pgtype.UUID {return util.MustParseUUID(s)}+// themeStoreFromEnv builds the community theme store. MULTICA_THEME_STORE=off+// (or false / 0) turns it off; MULTICA_THEME_REGISTRY_URL points it at+// another registry's index.json. A URL that does not parse turns the store+// off rather than failing the boot.+func themeStoreFromEnv() *themestore.Store {+ switch strings.ToLower(strings.TrimSpace(os.Getenv("MULTICA_THEME_STORE"))) {+ case "off", "false", "0", "disabled":+ slog.Info("theme store: turned off by MULTICA_THEME_STORE")+ return nil+ }+ store, err := themestore.New(themestore.Config{+ IndexURL: strings.TrimSpace(os.Getenv("MULTICA_THEME_REGISTRY_URL")),+ })+ if err != nil {+ slog.Error("theme store: turned off", "error", err)+ return nil+ }+ return store+}+func splitAndTrim(s string) []string {if s == "" {return nildiff --git a/server/internal/handler/config.go b/server/internal/handler/config.goindex 3352454621..186fa54cfb 100644--- a/server/internal/handler/config.go+++ b/server/internal/handler/config.go@@ -53,6 +53,12 @@ type AppConfig struct {// defaults absent to false (hidden).VCSIntegrationAvailable bool `json:"vcs_integration_available,omitempty"`+ // ThemeStoreEnabled tells the app it can browse and install community+ // themes through /api/theme-store. Self-hosted operators turn it off with+ // MULTICA_THEME_STORE=off. Omitted when off, and older servers omit it+ // too, so the app shows no Browse entry and makes no store requests.+ ThemeStoreEnabled bool `json:"theme_store_enabled,omitempty"`+// PostHog public config for the frontend. The key is the same Project// API Key the backend uses; returning it here (instead of baking it// into the frontend bundle via NEXT_PUBLIC_*) means self-hosted@@ -136,6 +142,7 @@ func (h *Handler) GetConfig(w http.ResponseWriter, r *http.Request) {config.DaemonServerURL, config.DaemonAppURL = daemonSetupURLsFromEnv()config.DaemonSetupTarget = "self_host"config.VCSIntegrationAvailable = h.cfg.VCSIntegrationEnabled+ config.ThemeStoreEnabled = h.ThemeStore != nilconfig.FeatureFlags = featureflags.EvaluateFrontendPublicFlags(r.Context(), h.FeatureFlags)// Only surface the build version on self-hosted deployments. The managed// cloud is continuously deployed and its users can't choose the build, sodiff --git a/server/internal/handler/config_test.go b/server/internal/handler/config_test.goindex 45db605846..7fadd1e9a7 100644--- a/server/internal/handler/config_test.go+++ b/server/internal/handler/config_test.go@@ -9,6 +9,7 @@ import ("github.com/multica-ai/multica/server/internal/auth""github.com/multica-ai/multica/server/internal/storage""github.com/multica-ai/multica/server/internal/testutil"+ "github.com/multica-ai/multica/server/internal/themestore")func TestGetConfigReportsCdnSignedMode(t *testing.T) {@@ -662,3 +663,32 @@ func TestGetConfigDeclaresCommentDeleteKeepsReplies(t *testing.T) {t.Fatalf("comment_delete_keep_replies_supported = %v, want true", raw["comment_delete_keep_replies_supported"])}}++func TestGetConfigReportsTheThemeStore(t *testing.T) {+ orig := testHandler.ThemeStore+ t.Cleanup(func() { testHandler.ThemeStore = orig })++ fetch := func() map[string]json.RawMessage {+ t.Helper()+ w := httptest.NewRecorder()+ testHandler.GetConfig(w, httptest.NewRequest(http.MethodGet, "/api/config", nil))+ var cfg map[string]json.RawMessage+ if err := json.Unmarshal(w.Body.Bytes(), &cfg); err != nil {+ t.Fatalf("decode config: %v", err)+ }+ return cfg+ }++ testHandler.ThemeStore = nil+ if _, ok := fetch()["theme_store_enabled"]; ok {+ t.Fatal("theme_store_enabled must be omitted when the store is off")+ }+ store, err := themestore.New(themestore.Config{})+ if err != nil {+ t.Fatal(err)+ }+ testHandler.ThemeStore = store+ if raw := fetch()["theme_store_enabled"]; string(raw) != "true" {+ t.Fatalf("theme_store_enabled: want true, got %s", raw)+ }+}diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.goindex d054a185dc..aa585f025d 100644--- a/server/internal/handler/handler.go+++ b/server/internal/handler/handler.go@@ -41,6 +41,7 @@ import ("github.com/multica-ai/multica/server/internal/seatcapacity""github.com/multica-ai/multica/server/internal/service""github.com/multica-ai/multica/server/internal/storage"+ "github.com/multica-ai/multica/server/internal/themestore""github.com/multica-ai/multica/server/internal/util""github.com/multica-ai/multica/server/internal/util/secretbox"db "github.com/multica-ai/multica/server/pkg/db/generated"@@ -245,6 +246,9 @@ type Handler struct {LocalSkillListStore LocalSkillListStoreLocalSkillImportStore LocalSkillImportStoreFeatureFlags *featureflag.Service+ // ThemeStore serves the community theme registry. Nil when the operator+ // turned the store off: its routes return 404 and /api/config omits it.+ ThemeStore *themestore.Store// IssueStatusCatalog reads the workspace status catalog. Defaults to// Queries; a test can substitute a counting wrapper to assert HOW MANY// catalog reads a request performs, which is the only property thatdiff --git a/server/internal/handler/theme_store.go b/server/internal/handler/theme_store.gonew file mode 100644index 0000000000..2d697fac2a--- /dev/null+++ b/server/internal/handler/theme_store.go@@ -0,0 +1,147 @@+package handler++import (+ "errors"+ "log/slog"+ "net/http"+ "strconv"++ "github.com/go-chi/chi/v5"+ "github.com/multica-ai/multica/server/internal/themestore"+)++// ThemeStoreTheme is a registry theme as the app sees it. Download URLs and+// screenshot paths stay on the server: the app fetches both through the+// routes below, so the web CSP stays closed and GitHub is never called from+// the browser.+type ThemeStoreTheme struct {+ ID string `json:"id"`+ Name string `json:"name"`+ Author string `json:"author"`+ Repo string `json:"repo"`+ Description string `json:"description,omitempty"`+ Modes []string `json:"modes"`+ Version string `json:"version"`+ Size int64 `json:"size"`+ Screenshots []string `json:"screenshots"`+ UpdatedAt string `json:"updated_at,omitempty"`+ // Downloads counts installs and updates served by this server.+ Downloads int64 `json:"downloads"`+}++func (h *Handler) themeStore(w http.ResponseWriter) *themestore.Store {+ if h.ThemeStore == nil {+ writeError(w, http.StatusNotFound, "the theme store is turned off on this server")+ }+ return h.ThemeStore+}++func writeThemeStoreError(w http.ResponseWriter, r *http.Request, err error) {+ if errors.Is(err, themestore.ErrNotFound) {+ writeError(w, http.StatusNotFound, "theme not found")+ return+ }+ slog.WarnContext(r.Context(), "theme store: registry request failed", "error", err)+ writeError(w, http.StatusBadGateway, "the theme registry could not be reached")+}++// ListStoreThemes returns the themes of the community registry.+func (h *Handler) ListStoreThemes(w http.ResponseWriter, r *http.Request) {+ store := h.themeStore(w)+ if store == nil {+ return+ }+ themes, err := store.Themes(r.Context())+ if err != nil {+ writeThemeStoreError(w, r, err)+ return+ }+ downloads := h.themeStoreDownloads(r)+ out := make([]ThemeStoreTheme, 0, len(themes))+ for _, t := range themes {+ shots := []string{}+ for _, mode := range themestore.Modes {+ if _, ok := t.Screenshots[mode]; ok {+ shots = append(shots, mode)+ }+ }+ out = append(out, ThemeStoreTheme{+ ID: t.ID,+ Name: t.Name,+ Author: t.Author,+ Repo: t.Repo,+ Description: t.Description,+ Modes: t.Modes,+ Version: t.Version,+ Size: t.Package.Size,+ Screenshots: shots,+ UpdatedAt: t.UpdatedAt,+ Downloads: downloads[t.ID],+ })+ }+ writeJSON(w, http.StatusOK, map[string]any{"themes": out})+}++// GetStoreThemePackage returns the theme's checked theme.zip. The app reads+// it with the same parser and CSS sanitizer as an imported theme.+func (h *Handler) GetStoreThemePackage(w http.ResponseWriter, r *http.Request) {+ store := h.themeStore(w)+ if store == nil {+ return+ }+ theme, data, err := store.Package(r.Context(), chi.URLParam(r, "themeId"))+ if err != nil {+ writeThemeStoreError(w, r, err)+ return+ }+ w.Header().Set("Content-Type", "application/zip")+ w.Header().Set("Content-Length", strconv.Itoa(len(data)))+ w.Header().Set("X-Theme-Version", theme.Version)+ w.Header().Set("Cache-Control", "private, no-cache")+ w.Header().Set("X-Content-Type-Options", "nosniff")+ if _, err := w.Write(data); err != nil {+ return+ }+ if h.Queries != nil {+ if err := h.Queries.AddThemeStoreDownload(r.Context(), theme.ID); err != nil {+ slog.WarnContext(r.Context(), "theme store: count download", "theme", theme.ID, "error", err)+ }+ }+}++// themeStoreDownloads is the download count of every theme served so far. A+// failed read leaves the counts out rather than failing the list.+func (h *Handler) themeStoreDownloads(r *http.Request) map[string]int64 {+ counts := map[string]int64{}+ if h.Queries == nil {+ return counts+ }+ rows, err := h.Queries.ListThemeStoreDownloads(r.Context())+ if err != nil {+ slog.WarnContext(r.Context(), "theme store: read download counts", "error", err)+ return counts+ }+ for _, row := range rows {+ counts[row.ThemeID] = row.Downloads+ }+ return counts+}++// GetStoreThemeScreenshot returns the screenshot the registry CI rendered+// for a theme in light or dark mode.+func (h *Handler) GetStoreThemeScreenshot(w http.ResponseWriter, r *http.Request) {+ store := h.themeStore(w)+ if store == nil {+ return+ }+ data, contentType, err := store.Screenshot(r.Context(), chi.URLParam(r, "themeId"), chi.URLParam(r, "mode"))+ if err != nil {+ writeThemeStoreError(w, r, err)+ return+ }+ w.Header().Set("Content-Type", contentType)+ w.Header().Set("Content-Length", strconv.Itoa(len(data)))+ w.Header().Set("Cache-Control", "private, max-age=600")+ w.Header().Set("X-Content-Type-Options", "nosniff")+ _, _ = w.Write(data)+}diff --git a/server/internal/handler/theme_store_test.go b/server/internal/handler/theme_store_test.gonew file mode 100644index 0000000000..ce64e00366--- /dev/null+++ b/server/internal/handler/theme_store_test.go@@ -0,0 +1,159 @@+package handler++import (+ "context"+ "crypto/sha256"+ "encoding/hex"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync/atomic"+ "testing"++ "github.com/go-chi/chi/v5"+ "github.com/multica-ai/multica/server/internal/themestore"+)++type themeStoreTransport func(*http.Request) (*http.Response, error)++func (f themeStoreTransport) RoundTrip(req *http.Request) (*http.Response, error) { return f(req) }++func themeStoreRouter(h *Handler) http.Handler {+ r := chi.NewRouter()+ r.Get("/api/theme-store/themes", h.ListStoreThemes)+ r.Get("/api/theme-store/themes/{themeId}/package", h.GetStoreThemePackage)+ r.Get("/api/theme-store/themes/{themeId}/screenshots/{mode}", h.GetStoreThemeScreenshot)+ return r+}++func TestThemeStoreRoutesAreOffWithoutAStore(t *testing.T) {+ router := themeStoreRouter(&Handler{})+ for _, path := range []string{+ "/api/theme-store/themes",+ "/api/theme-store/themes/sample/package",+ "/api/theme-store/themes/sample/screenshots/light",+ } {+ w := httptest.NewRecorder()+ router.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil))+ if w.Code != http.StatusNotFound {+ t.Errorf("%s: want 404 with the store off, got %d", path, w.Code)+ }+ }+}++func TestThemeStoreRoutes(t *testing.T) {+ zip := []byte("PK theme")+ sum := sha256.Sum256(zip)+ var upstream atomic.Int32+ var server *httptest.Server+ server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ upstream.Add(1)+ switch r.URL.Path {+ case "/index.json":+ _ = json.NewEncoder(w).Encode(map[string]any{"themes": []any{map[string]any{+ "id": "sample", "name": "Sample", "author": "Multica", "repo": "multica-ai/multica-theme-sample",+ "modes": []string{"light", "dark"}, "version": "1.0.0", "tag": "v1.0.0",+ "package": map[string]any{"url": "https://registry.test/theme.zip", "sha256": hex.EncodeToString(sum[:]), "size": len(zip)},+ "screenshots": map[string]string{"light": "shots/light.png"},+ }}})+ case "/theme.zip":+ _, _ = w.Write(zip)+ case "/shots/light.png":+ _, _ = w.Write([]byte("png"))+ default:+ http.NotFound(w, r)+ }+ }))+ defer server.Close()+ client := &http.Client{Transport: themeStoreTransport(func(req *http.Request) (*http.Response, error) {+ if req.URL.Host == "registry.test" {+ req = req.Clone(req.Context())+ req.URL.Scheme, req.URL.Host = "http", strings.TrimPrefix(server.URL, "http://")+ }+ return http.DefaultTransport.RoundTrip(req)+ })}+ store, err := themestore.New(themestore.Config{IndexURL: server.URL + "/index.json", HTTPClient: client})+ if err != nil {+ t.Fatal(err)+ }+ clearDownloads := func() {+ if _, err := testPool.Exec(context.Background(), `DELETE FROM theme_store_download WHERE theme_id IN ('sample', 'unlisted')`); err != nil {+ t.Fatalf("clear theme_store_download: %v", err)+ }+ }+ clearDownloads()+ t.Cleanup(clearDownloads)+ router := themeStoreRouter(&Handler{ThemeStore: store, Queries: testHandler.Queries})+ get := func(path string) *httptest.ResponseRecorder {+ w := httptest.NewRecorder()+ router.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil))+ return w+ }++ w := get("/api/theme-store/themes")+ if w.Code != http.StatusOK {+ t.Fatalf("list: %d %s", w.Code, w.Body.String())+ }+ var list struct {+ Themes []ThemeStoreTheme `json:"themes"`+ }+ if err := json.Unmarshal(w.Body.Bytes(), &list); err != nil {+ t.Fatal(err)+ }+ if len(list.Themes) != 1 || list.Themes[0].Version != "1.0.0" || strings.Join(list.Themes[0].Screenshots, ",") != "light" || list.Themes[0].Downloads != 0 {+ t.Fatalf("list = %+v", list.Themes)+ }+ if strings.Contains(w.Body.String(), "registry.test") || strings.Contains(w.Body.String(), "shots/") {+ t.Fatalf("download URLs and screenshot paths must stay on the server: %s", w.Body.String())+ }++ w = get("/api/theme-store/themes/sample/package")+ if w.Code != http.StatusOK || w.Body.String() != string(zip) || w.Header().Get("X-Theme-Version") != "1.0.0" {+ t.Fatalf("package: %d %q %v", w.Code, w.Body.String(), w.Header())+ }+ // An install and an update are both a download.+ if w := get("/api/theme-store/themes/sample/package"); w.Code != http.StatusOK {+ t.Fatalf("second package: %d", w.Code)+ }+ w = get("/api/theme-store/themes/sample/screenshots/light")+ if w.Code != http.StatusOK || w.Header().Get("Content-Type") != "image/png" {+ t.Fatalf("screenshot: %d %v", w.Code, w.Header())+ }+ if w := get("/api/theme-store/themes/sample/screenshots/dark"); w.Code != http.StatusNotFound {+ t.Fatalf("missing screenshot: want 404, got %d", w.Code)+ }+ if w := get("/api/theme-store/themes/unlisted/package"); w.Code != http.StatusNotFound {+ t.Fatalf("unlisted theme: want 404, got %d", w.Code)+ }+ var downloads int64+ if err := testPool.QueryRow(context.Background(), `SELECT downloads FROM theme_store_download WHERE theme_id = 'sample'`).Scan(&downloads); err != nil || downloads != 2 {+ t.Fatalf("downloads = %d (%v), want 2", downloads, err)+ }+ if err := json.Unmarshal(get("/api/theme-store/themes").Body.Bytes(), &list); err != nil || list.Themes[0].Downloads != 2 {+ t.Fatalf("listed downloads = %+v (%v), want 2", list.Themes, err)+ }+ var unlisted int+ if err := testPool.QueryRow(context.Background(), `SELECT count(*) FROM theme_store_download WHERE theme_id = 'unlisted'`).Scan(&unlisted); err != nil || unlisted != 0 {+ t.Fatalf("a failed download was counted: %d (%v)", unlisted, err)+ }+ if n := upstream.Load(); n != 3 {+ t.Fatalf("upstream requests = %d, want 3 (index, zip, screenshot)", n)+ }+}++func TestThemeStoreRegistryDownIsABadGateway(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ http.Error(w, "down", http.StatusInternalServerError)+ }))+ defer server.Close()+ store, err := themestore.New(themestore.Config{IndexURL: server.URL + "/index.json"})+ if err != nil {+ t.Fatal(err)+ }+ w := httptest.NewRecorder()+ themeStoreRouter(&Handler{ThemeStore: store}).ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/theme-store/themes", nil))+ if w.Code != http.StatusBadGateway {+ t.Fatalf("want 502, got %d", w.Code)+ }+}diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.goindex e6439f1247..eeda262989 100644--- a/server/internal/handler/workspace_delete_manifest_test.go+++ b/server/internal/handler/workspace_delete_manifest_test.go@@ -133,6 +133,7 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{"squad": workspaceDelete,"squad_member": workspaceDelete,"sys_cron_executions": workspaceDeleteKeep,+ "theme_store_download": workspaceDeleteKeep, // per registry theme, not workspace-owned"task_message": workspaceDelete,"task_supplement": workspaceDelete,"task_supplement_capability": workspaceDelete,diff --git a/server/internal/themestore/store.go b/server/internal/themestore/store.gonew file mode 100644index 0000000000..96e175737e--- /dev/null+++ b/server/internal/themestore/store.go@@ -0,0 +1,416 @@+// Package themestore reads the community theme registry and serves its+// themes to the app.+//+// The registry publishes an index.json that its CI writes: every theme with+// the one release that passed the checks, the SHA-256 of that release's+// theme.zip, and screenshots rendered by the same CI. The store only reads+// that file, the zips it names and the screenshots next to it, so it never+// calls the GitHub API and the app only installs files the checks passed.+//+// Everything is cached in memory. The index is refreshed after IndexTTL and+// the previous copy is served while the registry cannot be reached. Packages+// and screenshots are keyed by theme version, so a cached copy never goes+// stale; a size-bounded LRU keeps memory flat.+package themestore++import (+ "container/list"+ "context"+ "crypto/sha256"+ "encoding/hex"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "net/http"+ "net/url"+ "path"+ "regexp"+ "strings"+ "sync"+ "time"+ "unicode/utf16"++ "golang.org/x/sync/singleflight"+)++// DefaultIndexURL is the official registry, github.com/multica-ai/multica-themes.+// Its index is generated onto the `index` branch.+const DefaultIndexURL = "https://raw.githubusercontent.com/multica-ai/multica-themes/index/index.json"++const (+ // MaxPackageBytes matches THEME_PACKAGE_MAX_BYTES in packages/core/appearance.+ MaxPackageBytes = 1 << 20+ maxIndexBytes = 2 << 20+ maxScreenshotBytes = 2 << 20+ maxThemes = 500+ defaultIndexTTL = 10 * time.Minute+ // After a failed refresh the stale index is served for this long before+ // the registry is asked again.+ retryAfterFailure = time.Minute+ defaultCacheBytes = 48 << 20+)++var (+ ErrNotFound = errors.New("theme not found")+ ErrUpstream = errors.New("theme registry unavailable")++ themeID = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,39}$`)+ repoName = regexp.MustCompile(`^[A-Za-z0-9-]{1,39}/[A-Za-z0-9._-]{1,100}$`)+ versionText = regexp.MustCompile(`^[0-9A-Za-z.+-]{1,20}$`)+ sha256Hex = regexp.MustCompile(`^[0-9a-f]{64}$`)+ relativeFile = regexp.MustCompile(`^[A-Za-z0-9._-]+(/[A-Za-z0-9._-]+)*\.(png|jpg|jpeg|webp)$`)+)++// Modes a theme can support and have screenshots for.+var Modes = []string{"light", "dark"}++// Theme is one entry of the registry index.+type Theme struct {+ ID string `json:"id"`+ Name string `json:"name"`+ Author string `json:"author"`+ Repo string `json:"repo"`+ Description string `json:"description,omitempty"`+ Modes []string `json:"modes"`+ Version string `json:"version"`+ Tag string `json:"tag"`+ Package Package `json:"package"`+ Screenshots map[string]string `json:"screenshots,omitempty"`+ UpdatedAt string `json:"updated_at,omitempty"`+}++// Package is the release asset the registry checked.+type Package struct {+ URL string `json:"url"`+ SHA256 string `json:"sha256"`+ Size int64 `json:"size"`+}++type index struct {+ Themes []json.RawMessage `json:"themes"`+}++// Config configures a Store. Zero values select the defaults.+type Config struct {+ IndexURL string+ HTTPClient *http.Client+ IndexTTL time.Duration+ // CacheBytes bounds the packages and screenshots kept in memory.+ CacheBytes int64+ Now func() time.Time+}++// Store serves the registry with caching. It is safe for concurrent use.+type Store struct {+ indexURL *url.URL+ client *http.Client+ ttl time.Duration+ now func() time.Time+ group singleflight.Group++ mu sync.Mutex+ themes []Theme+ fetchedAt time.Time+ failedAt time.Time++ files *lru+}++// New returns a Store for the registry at cfg.IndexURL.+func New(cfg Config) (*Store, error) {+ raw := cfg.IndexURL+ if raw == "" {+ raw = DefaultIndexURL+ }+ u, err := url.Parse(raw)+ if err != nil || u.Host == "" || (u.Scheme != "https" && u.Scheme != "http") {+ return nil, fmt.Errorf("theme registry URL %q must be an absolute http(s) URL", raw)+ }+ client := cfg.HTTPClient+ if client == nil {+ client = &http.Client{Timeout: 20 * time.Second}+ }+ ttl := cfg.IndexTTL+ if ttl <= 0 {+ ttl = defaultIndexTTL+ }+ cacheBytes := cfg.CacheBytes+ if cacheBytes <= 0 {+ cacheBytes = defaultCacheBytes+ }+ now := cfg.Now+ if now == nil {+ now = time.Now+ }+ return &Store{indexURL: u, client: client, ttl: ttl, now: now, files: newLRU(cacheBytes)}, nil+}++// Themes lists the registry's themes.+func (s *Store) Themes(ctx context.Context) ([]Theme, error) {+ s.mu.Lock()+ themes, fetchedAt, failedAt := s.themes, s.fetchedAt, s.failedAt+ s.mu.Unlock()+ now := s.now()+ if themes != nil && now.Sub(fetchedAt) < s.ttl {+ return themes, nil+ }+ if themes != nil && now.Sub(failedAt) < retryAfterFailure {+ return themes, nil+ }+ v, err, _ := s.group.Do("index", func() (any, error) {+ fresh, err := s.fetchIndex(context.WithoutCancel(ctx))+ s.mu.Lock()+ defer s.mu.Unlock()+ if err != nil {+ s.failedAt = s.now()+ return nil, err+ }+ s.themes, s.fetchedAt = fresh, s.now()+ return fresh, nil+ })+ if err != nil {+ if themes != nil {+ return themes, nil+ }+ return nil, err+ }+ return v.([]Theme), nil+}++// Theme finds one theme of the registry by id.+func (s *Store) Theme(ctx context.Context, id string) (Theme, error) {+ themes, err := s.Themes(ctx)+ if err != nil {+ return Theme{}, err+ }+ for _, theme := range themes {+ if theme.ID == id {+ return theme, nil+ }+ }+ return Theme{}, ErrNotFound+}++// Package returns the theme's checked release: theme.zip, verified against+// the size and SHA-256 in the index.+func (s *Store) Package(ctx context.Context, id string) (Theme, []byte, error) {+ theme, err := s.Theme(ctx, id)+ if err != nil {+ return Theme{}, nil, err+ }+ key := "package\x00" + theme.ID + "\x00" + theme.Package.SHA256+ data, err := s.cached(ctx, key, func(ctx context.Context) ([]byte, error) {+ u, err := url.Parse(theme.Package.URL)+ if err != nil {+ return nil, err+ }+ data, err := s.get(ctx, u, MaxPackageBytes)+ if err != nil {+ return nil, err+ }+ sum := sha256.Sum256(data)+ if int64(len(data)) != theme.Package.Size || hex.EncodeToString(sum[:]) != theme.Package.SHA256 {+ return nil, fmt.Errorf("%w: %s does not match the checked release", ErrUpstream, theme.Package.URL)+ }+ return data, nil+ })+ return theme, data, err+}++// Screenshot returns the screenshot of the theme in a mode, and its content type.+func (s *Store) Screenshot(ctx context.Context, id, mode string) ([]byte, string, error) {+ theme, err := s.Theme(ctx, id)+ if err != nil {+ return nil, "", err+ }+ file, ok := theme.Screenshots[mode]+ if !ok {+ return nil, "", ErrNotFound+ }+ u := s.indexURL.ResolveReference(&url.URL{Path: file})+ key := "screenshot\x00" + theme.ID + "\x00" + theme.Version + "\x00" + u.String()+ data, err := s.cached(ctx, key, func(ctx context.Context) ([]byte, error) {+ return s.get(ctx, u, maxScreenshotBytes)+ })+ if err != nil {+ return nil, "", err+ }+ return data, imageType(file), nil+}++func (s *Store) cached(ctx context.Context, key string, load func(context.Context) ([]byte, error)) ([]byte, error) {+ if data, ok := s.files.get(key); ok {+ return data, nil+ }+ v, err, _ := s.group.Do(key, func() (any, error) {+ data, err := load(context.WithoutCancel(ctx))+ if err != nil {+ return nil, err+ }+ s.files.put(key, data)+ return data, nil+ })+ if err != nil {+ return nil, err+ }+ return v.([]byte), nil+}++func (s *Store) fetchIndex(ctx context.Context) ([]Theme, error) {+ body, err := s.get(ctx, s.indexURL, maxIndexBytes)+ if err != nil {+ return nil, err+ }+ var idx index+ if err := json.Unmarshal(body, &idx); err != nil {+ return nil, fmt.Errorf("%w: index.json: %v", ErrUpstream, err)+ }+ themes := make([]Theme, 0, len(idx.Themes))+ seen := map[string]bool{}+ for _, raw := range idx.Themes {+ if len(themes) == maxThemes {+ break+ }+ var theme Theme+ if json.Unmarshal(raw, &theme) != nil {+ continue+ }+ if clean, ok := validTheme(theme); ok && !seen[clean.ID] {+ seen[clean.ID] = true+ themes = append(themes, clean)+ }+ }+ return themes, nil+}++// validTheme keeps an entry only when every field the app relies on is+// well-formed. The index comes from the registry's own CI, but it is still+// read as untrusted input.+func validTheme(t Theme) (Theme, bool) {+ t.Name = strings.TrimSpace(t.Name)+ t.Author = strings.TrimSpace(t.Author)+ t.Description = strings.TrimSpace(t.Description)+ if !themeID.MatchString(t.ID) || !repoName.MatchString(t.Repo) ||+ t.Name == "" || textLength(t.Name) > 60 || t.Author == "" || textLength(t.Author) > 60 || textLength(t.Description) > 300 ||+ !versionText.MatchString(t.Version) || !versionText.MatchString(t.Tag) ||+ !sha256Hex.MatchString(t.Package.SHA256) || t.Package.Size <= 0 || t.Package.Size > MaxPackageBytes {+ return Theme{}, false+ }+ if u, err := url.Parse(t.Package.URL); err != nil || u.Scheme != "https" || u.Host == "" {+ return Theme{}, false+ }+ modes := []string{}+ for _, mode := range Modes {+ for _, m := range t.Modes {+ if m == mode {+ modes = append(modes, mode)+ break+ }+ }+ }+ if len(modes) == 0 {+ return Theme{}, false+ }+ t.Modes = modes+ shots := map[string]string{}+ for _, mode := range Modes {+ file := t.Screenshots[mode]+ if relativeFile.MatchString(file) && path.Clean(file) == file && !strings.HasPrefix(file, "..") {+ shots[mode] = file+ }+ }+ t.Screenshots = shots+ return t, true+}++// textLength counts UTF-16 code units, as the registry's checks do with+// JavaScript's String length, so a limit means the same on both sides.+func textLength(s string) int {+ return len(utf16.Encode([]rune(s)))+}++func (s *Store) get(ctx context.Context, u *url.URL, limit int64) ([]byte, error) {+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)+ if err != nil {+ return nil, err+ }+ req.Header.Set("User-Agent", "multica-theme-store")+ res, err := s.client.Do(req)+ if err != nil {+ return nil, fmt.Errorf("%w: %v", ErrUpstream, err)+ }+ defer res.Body.Close()+ if res.StatusCode != http.StatusOK {+ return nil, fmt.Errorf("%w: GET %s: %s", ErrUpstream, u.Redacted(), res.Status)+ }+ data, err := io.ReadAll(io.LimitReader(res.Body, limit+1))+ if err != nil {+ return nil, fmt.Errorf("%w: %v", ErrUpstream, err)+ }+ if int64(len(data)) > limit {+ return nil, fmt.Errorf("%w: %s is larger than %d bytes", ErrUpstream, u.Redacted(), limit)+ }+ return data, nil+}++func imageType(file string) string {+ switch strings.ToLower(path.Ext(file)) {+ case ".png":+ return "image/png"+ case ".webp":+ return "image/webp"+ default:+ return "image/jpeg"+ }+}++// lru keeps the most recently used entries up to a total size.+type lru struct {+ mu sync.Mutex+ max int64+ size int64+ order *list.List+ items map[string]*list.Element+}++type lruEntry struct {+ key string+ data []byte+}++func newLRU(max int64) *lru {+ return &lru{max: max, order: list.New(), items: map[string]*list.Element{}}+}++func (c *lru) get(key string) ([]byte, bool) {+ c.mu.Lock()+ defer c.mu.Unlock()+ el, ok := c.items[key]+ if !ok {+ return nil, false+ }+ c.order.MoveToFront(el)+ return el.Value.(*lruEntry).data, true+}++func (c *lru) put(key string, data []byte) {+ c.mu.Lock()+ defer c.mu.Unlock()+ if int64(len(data)) > c.max {+ return+ }+ if el, ok := c.items[key]; ok {+ c.size -= int64(len(el.Value.(*lruEntry).data))+ c.order.Remove(el)+ }+ c.items[key] = c.order.PushFront(&lruEntry{key: key, data: data})+ c.size += int64(len(data))+ for c.size > c.max {+ last := c.order.Back()+ entry := last.Value.(*lruEntry)+ c.order.Remove(last)+ delete(c.items, entry.key)+ c.size -= int64(len(entry.data))+ }+}diff --git a/server/internal/themestore/store_test.go b/server/internal/themestore/store_test.gonew file mode 100644index 0000000000..4c3d71124b--- /dev/null+++ b/server/internal/themestore/store_test.go@@ -0,0 +1,287 @@+package themestore++import (+ "context"+ "crypto/sha256"+ "encoding/hex"+ "encoding/json"+ "errors"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync/atomic"+ "testing"+ "time"+)++type registry struct {+ server *httptest.Server+ zip []byte+ png []byte+ index func(base string) any+ requests map[string]*atomic.Int32+ fail atomic.Bool+}++func newRegistry(t *testing.T) *registry {+ t.Helper()+ r := ®istry{+ zip: []byte("PK fake theme zip"),+ png: []byte("\x89PNG fake"),+ requests: map[string]*atomic.Int32{},+ }+ for _, p := range []string{"/index.json", "/release/theme.zip", "/screenshots/sample/light.png"} {+ r.requests[p] = &atomic.Int32{}+ }+ r.index = func(base string) any {+ return map[string]any{"schema": 1, "themes": []any{r.entry(base)}}+ }+ r.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {+ if counter, ok := r.requests[req.URL.Path]; ok {+ counter.Add(1)+ }+ if r.fail.Load() {+ http.Error(w, "down", http.StatusBadGateway)+ return+ }+ switch req.URL.Path {+ case "/index.json":+ _ = json.NewEncoder(w).Encode(r.index(r.server.URL))+ case "/release/theme.zip":+ _, _ = w.Write(r.zip)+ case "/screenshots/sample/light.png":+ _, _ = w.Write(r.png)+ default:+ http.NotFound(w, req)+ }+ }))+ t.Cleanup(r.server.Close)+ return r+}++func (r *registry) entry(base string) map[string]any {+ sum := sha256.Sum256(r.zip)+ return map[string]any{+ "id": "sample",+ "name": "Sample",+ "author": "Multica",+ "repo": "multica-ai/multica-theme-sample",+ "description": "A sample theme.",+ "modes": []string{"light", "dark"},+ "version": "1.0.0",+ "tag": "v1.0.0",+ "package": map[string]any{+ // httptest serves plain http; the store requires https, so the+ // test client below rewrites https://registry.test to the server.+ "url": "https://registry.test/release/theme.zip",+ "sha256": hex.EncodeToString(sum[:]),+ "size": len(r.zip),+ },+ "screenshots": map[string]string{"light": "screenshots/sample/light.png", "dark": "../secret.png"},+ }+}++// rewrite sends https://registry.test requests to the httptest server.+type rewrite struct{ target string }++func (rt rewrite) RoundTrip(req *http.Request) (*http.Response, error) {+ if req.URL.Host == "registry.test" {+ req = req.Clone(req.Context())+ req.URL.Scheme = "http"+ req.URL.Host = rt.target[len("http://"):]+ }+ return http.DefaultTransport.RoundTrip(req)+}++func newStore(t *testing.T, r *registry, now *time.Time) *Store {+ t.Helper()+ store, err := New(Config{+ IndexURL: r.server.URL + "/index.json",+ HTTPClient: &http.Client{Transport: rewrite{target: r.server.URL}},+ Now: func() time.Time { return *now },+ })+ if err != nil {+ t.Fatal(err)+ }+ return store+}++func TestThemesCachesTheIndexAndServesStaleCopyWhenTheRegistryIsDown(t *testing.T) {+ r := newRegistry(t)+ now := time.Unix(0, 0)+ store := newStore(t, r, &now)+ ctx := context.Background()++ themes, err := store.Themes(ctx)+ if err != nil || len(themes) != 1 || themes[0].ID != "sample" {+ t.Fatalf("Themes = %+v, %v", themes, err)+ }+ if got := themes[0].Screenshots; len(got) != 1 || got["light"] == "" {+ t.Fatalf("screenshot paths outside the registry must be dropped, got %v", got)+ }+ if _, err := store.Themes(ctx); err != nil {+ t.Fatal(err)+ }+ if n := r.requests["/index.json"].Load(); n != 1 {+ t.Fatalf("index fetched %d times within the TTL, want 1", n)+ }++ now = now.Add(defaultIndexTTL + time.Second)+ r.fail.Store(true)+ themes, err = store.Themes(ctx)+ if err != nil || len(themes) != 1 {+ t.Fatalf("stale index must be served while the registry is down: %+v, %v", themes, err)+ }+ if _, err := store.Themes(ctx); err != nil {+ t.Fatal(err)+ }+ if n := r.requests["/index.json"].Load(); n != 2 {+ t.Fatalf("index fetched %d times, want 2: one refresh, then back off", n)+ }+}++func TestThemesFailsWithoutACachedIndex(t *testing.T) {+ r := newRegistry(t)+ r.fail.Store(true)+ now := time.Unix(0, 0)+ if _, err := newStore(t, r, &now).Themes(context.Background()); !errors.Is(err, ErrUpstream) {+ t.Fatalf("want ErrUpstream, got %v", err)+ }+}++func TestPackageIsVerifiedAndCached(t *testing.T) {+ r := newRegistry(t)+ now := time.Unix(0, 0)+ store := newStore(t, r, &now)+ ctx := context.Background()++ theme, data, err := store.Package(ctx, "sample")+ if err != nil || string(data) != string(r.zip) || theme.Version != "1.0.0" {+ t.Fatalf("Package = %q, %v", data, err)+ }+ if _, _, err := store.Package(ctx, "sample"); err != nil {+ t.Fatal(err)+ }+ if n := r.requests["/release/theme.zip"].Load(); n != 1 {+ t.Fatalf("package fetched %d times, want 1", n)+ }+ if _, _, err := store.Package(ctx, "missing"); !errors.Is(err, ErrNotFound) {+ t.Fatalf("unlisted id: want ErrNotFound, got %v", err)+ }+}++func TestPackageRejectsAReleaseThatChangedAfterTheCheck(t *testing.T) {+ r := newRegistry(t)+ index := r.index+ r.index = func(base string) any {+ v := index(base).(map[string]any)+ r.zip = []byte("PK replaced after the registry checked it")+ return v+ }+ now := time.Unix(0, 0)+ if _, _, err := newStore(t, r, &now).Package(context.Background(), "sample"); !errors.Is(err, ErrUpstream) {+ t.Fatalf("want ErrUpstream for a mismatched sha256, got %v", err)+ }+}++func TestScreenshot(t *testing.T) {+ r := newRegistry(t)+ now := time.Unix(0, 0)+ store := newStore(t, r, &now)+ data, kind, err := store.Screenshot(context.Background(), "sample", "light")+ if err != nil || string(data) != string(r.png) || kind != "image/png" {+ t.Fatalf("Screenshot = %q %q %v", data, kind, err)+ }+ if _, _, err := store.Screenshot(context.Background(), "sample", "dark"); !errors.Is(err, ErrNotFound) {+ t.Fatalf("dropped screenshot: want ErrNotFound, got %v", err)+ }+}++func TestValidThemeRejectsMalformedEntries(t *testing.T) {+ r := newRegistry(t)+ base := func() Theme {+ raw, _ := json.Marshal(r.entry("https://registry.test"))+ var theme Theme+ _ = json.Unmarshal(raw, &theme)+ return theme+ }+ if _, ok := validTheme(base()); !ok {+ t.Fatal("the sample entry must be valid")+ }+ cases := map[string]func(*Theme){+ "id": func(t *Theme) { t.ID = "Bad ID" },+ "repo": func(t *Theme) { t.Repo = "not a repo" },+ "http package": func(t *Theme) { t.Package.URL = "http://example.com/theme.zip" },+ "sha256": func(t *Theme) { t.Package.SHA256 = "abc" },+ "size": func(t *Theme) { t.Package.Size = MaxPackageBytes + 1 },+ "modes": func(t *Theme) { t.Modes = []string{"sepia"} },+ "name": func(t *Theme) { t.Name = " " },+ }+ for name, mutate := range cases {+ theme := base()+ mutate(&theme)+ if _, ok := validTheme(theme); ok {+ t.Errorf("%s: malformed entry accepted", name)+ }+ }+}++func TestValidThemeCountsCharactersNotBytes(t *testing.T) {+ r := newRegistry(t)+ raw, _ := json.Marshal(r.entry("https://registry.test"))+ var theme Theme+ _ = json.Unmarshal(raw, &theme)++ theme.Name = strings.Repeat("亚麻", 30)+ theme.Author = strings.Repeat("作者", 30)+ theme.Description = strings.Repeat("温暖纸色与柔和的文字。", 27)+ if _, ok := validTheme(theme); !ok {+ t.Fatal("a 60-character Chinese name and author and a 297-character description must be valid")+ }++ theme.Description = strings.Repeat("温暖纸色与柔和的文字。", 28)+ if _, ok := validTheme(theme); ok {+ t.Fatal("a 308-character description must be rejected")+ }++ theme.Description = ""+ theme.Name = strings.Repeat("🎨", 31)+ if _, ok := validTheme(theme); ok {+ t.Fatal("31 emoji are 62 UTF-16 code units, over the registry's 60")+ }+}++func TestThemesKeepsChineseEntries(t *testing.T) {+ r := newRegistry(t)+ index := r.index+ r.index = func(base string) any {+ v := index(base).(map[string]any)+ entry := v["themes"].([]any)[0].(map[string]any)+ entry["name"] = "亚麻"+ entry["description"] = strings.Repeat("温暖纸色与柔和的文字。", 10)+ return v+ }+ now := time.Unix(0, 0)+ themes, err := newStore(t, r, &now).Themes(context.Background())+ if err != nil || len(themes) != 1 || themes[0].Name != "亚麻" {+ t.Fatalf("Themes = %+v, %v", themes, err)+ }+}++func TestLRUEvictsLeastRecentlyUsed(t *testing.T) {+ c := newLRU(10)+ c.put("a", make([]byte, 4))+ c.put("b", make([]byte, 4))+ c.get("a")+ c.put("c", make([]byte, 4))+ if _, ok := c.get("b"); ok {+ t.Fatal("b should have been evicted")+ }+ if _, ok := c.get("a"); !ok {+ t.Fatal("a was used recently and must stay")+ }+ c.put("huge", make([]byte, 11))+ if _, ok := c.get("huge"); ok {+ t.Fatal("an entry larger than the cache must not be stored")+ }+}diff --git a/server/migrations/646_theme_store_download.down.sql b/server/migrations/646_theme_store_download.down.sqlnew file mode 100644index 0000000000..dfb00c2677--- /dev/null+++ b/server/migrations/646_theme_store_download.down.sql@@ -0,0 +1 @@+DROP TABLE IF EXISTS theme_store_download;diff --git a/server/migrations/646_theme_store_download.up.sql b/server/migrations/646_theme_store_download.up.sqlnew file mode 100644index 0000000000..6804985f84--- /dev/null+++ b/server/migrations/646_theme_store_download.up.sql@@ -0,0 +1,9 @@+-- How many times each community store theme has been downloaded from this+-- server: every install and every update counts once. Keyed by the registry's+-- theme id, so it is global, not workspace-owned. Rows are created on the+-- first download.+CREATE TABLE IF NOT EXISTS theme_store_download (+ theme_id TEXT PRIMARY KEY,+ downloads BIGINT NOT NULL DEFAULT 0,+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+);diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex 8932efe4e8..e72cd87324 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -1822,6 +1822,12 @@ type TaskUsageHourlyRollupState struct {LastError pgtype.Text `json:"last_error"`}+type ThemeStoreDownload struct {+ ThemeID string `json:"theme_id"`+ Downloads int64 `json:"downloads"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+}+type User struct {ID pgtype.UUID `json:"id"`Name string `json:"name"`diff --git a/server/pkg/db/generated/theme_store_download.sql.go b/server/pkg/db/generated/theme_store_download.sql.gonew file mode 100644index 0000000000..2e48e28823--- /dev/null+++ b/server/pkg/db/generated/theme_store_download.sql.go@@ -0,0 +1,51 @@+// Code generated by sqlc. DO NOT EDIT.+// versions:+// sqlc v1.31.1+// source: theme_store_download.sql++package db++import (+ "context"+)++const addThemeStoreDownload = `-- name: AddThemeStoreDownload :exec+INSERT INTO theme_store_download (theme_id, downloads)+VALUES ($1, 1)+ON CONFLICT (theme_id) DO UPDATE+SET downloads = theme_store_download.downloads + 1, updated_at = now()+`++func (q *Queries) AddThemeStoreDownload(ctx context.Context, themeID string) error {+ _, err := q.db.Exec(ctx, addThemeStoreDownload, themeID)+ return err+}++const listThemeStoreDownloads = `-- name: ListThemeStoreDownloads :many+SELECT theme_id, downloads FROM theme_store_download+`++type ListThemeStoreDownloadsRow struct {+ ThemeID string `json:"theme_id"`+ Downloads int64 `json:"downloads"`+}++func (q *Queries) ListThemeStoreDownloads(ctx context.Context) ([]ListThemeStoreDownloadsRow, error) {+ rows, err := q.db.Query(ctx, listThemeStoreDownloads)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListThemeStoreDownloadsRow{}+ for rows.Next() {+ var i ListThemeStoreDownloadsRow+ if err := rows.Scan(&i.ThemeID, &i.Downloads); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}diff --git a/server/pkg/db/queries/theme_store_download.sql b/server/pkg/db/queries/theme_store_download.sqlnew file mode 100644index 0000000000..e7189b77e9--- /dev/null+++ b/server/pkg/db/queries/theme_store_download.sql@@ -0,0 +1,8 @@+-- name: ListThemeStoreDownloads :many+SELECT theme_id, downloads FROM theme_store_download;++-- name: AddThemeStoreDownload :exec+INSERT INTO theme_store_download (theme_id, downloads)+VALUES ($1, 1)+ON CONFLICT (theme_id) DO UPDATE+SET downloads = theme_store_download.downloads + 1, updated_at = now();