Skip to content

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

Go

feat(theme): anchors, layout tokens, colour slots and one embed token contract (MUL-9231) (#10579)

Jiayuan Zhangee3b33f08c16
diff --git a/apps/desktop/src/renderer/src/components/desktop-layout.tsx b/apps/desktop/src/renderer/src/components/desktop-layout.tsx
index 18c0b0a58f..beb772923d 100644
--- a/apps/desktop/src/renderer/src/components/desktop-layout.tsx
+++ b/apps/desktop/src/renderer/src/components/desktop-layout.tsx
@@ -104,13 +104,14 @@ function MainTopBar({ railMounted }: { railMounted: boolean }) {
>
<TabBar />
</div>
- {/* pr-6 is the canvas's mr-2 plus the page header's PAGE_GUTTER (px-4),
- and gap-1 is the page header's action gap, so each icon here stands
- on the same column as a trailing icon of the page header below. */}
+ {/* The right padding is the canvas's mr-2 plus the page header's
+ PAGE_GUTTER, and gap-1 is the page header's action gap, so each icon
+ here stands on the same column as a trailing icon of the page header
+ below. */}
{railMounted && (
<div
data-slot="title-bar-actions"
- className="relative z-10 ml-auto flex shrink-0 items-center gap-1 pr-6"
+ className="relative z-10 ml-auto flex shrink-0 items-center gap-1 pr-[calc(var(--page-padding-x,var(--space-md,1rem))+0.5rem)]"
style={{ WebkitAppRegion: "no-drag" } as React.CSSProperties}
>
<NewIssueButton className={TITLE_BAR_ACTION_CLASS} tooltipSide="bottom" />
diff --git a/apps/desktop/src/renderer/src/components/tab-bar.tsx b/apps/desktop/src/renderer/src/components/tab-bar.tsx
index e465f1f246..a5caec6762 100644
--- a/apps/desktop/src/renderer/src/components/tab-bar.tsx
+++ b/apps/desktop/src/renderer/src/components/tab-bar.tsx
@@ -336,6 +336,9 @@ function SortableTabItem({
style={style}
data-tab-frame
data-tab-id={tab.id}
+ data-mc="tab"
+ data-active={isActive ? "true" : "false"}
+ data-pinned={tab.pinned ? "true" : "false"}
className={cn("h-full w-56 min-w-32", isActive && "z-10")}
>
<motion.div
diff --git a/docs/theming.md b/docs/theming.md
index a656633c55..611ceb3d41 100644
--- a/docs/theming.md
+++ b/docs/theming.md
@@ -94,9 +94,11 @@ Set variables on `.theme-light` and `.theme-dark` (both on `<html>`). The
CSS loads after the app's own styles while the theme is active, so at equal
specificity the theme wins; keep selectors that simple and avoid
`!important`. What the person picks on the Appearance page still wins over a
-theme: high contrast replaces the muted and border colours, and font choices
-other than the defaults replace the font variables. Colour is the theme's
-alone; to let people pick one, declare an option.
+theme: high contrast replaces the muted and border colours, font choices
+other than the defaults replace the font variables, and Compact or
+Comfortable density replaces the issue row and group header heights, board
+card padding and gap, and the space panel's row height and padding. Colour
+is the theme's alone; to let people pick one, declare an option.
## Variables
@@ -109,6 +111,11 @@ at the end, with its default. They come in layers:
- **Components and product** (menus, buttons, nav rows, issue rows, the
board, status colours) default to a foundation. Set one to change just
that component: `--menu-radius: 0` squares menus and nothing else.
+- **Layout and spacing** (a spacing scale `--space-xs` to `--space-xl`, the
+ page's side padding, the navigation panel's starting width, the widest the
+ reading column and object pages get) sets the room around everything.
+ Board card and page paddings read the scale, so changing `--space-sm`
+ moves each of them that has no variable of its own set.
- **Editor content** (headings, lists, tables, quotes, links, code and
syntax colours) styles issue descriptions, comments, chat and documents.
@@ -125,6 +132,33 @@ their default as a fallback. So it can be set on any ancestor, not only on
Values that could load a resource are rejected anywhere in `theme.css`, see
[What CSS may not do](#what-css-may-not-do).
+### Colour slots
+
+Labels, custom statuses and select options carry the colour someone picked,
+a `#rrggbb`. A theme recolours them through ten slots named after the
+colour picker's presets: `--palette-gray`, `-red`, `-orange`, `-yellow`,
+`-green`, `-teal`, `-blue`, `-indigo`, `-purple` and `-pink`. A preset lands
+on its own slot. Any other colour is placed in OKLab: one with little chroma
+on gray, the rest on the slot whose hue is nearest, so pale and dark shades
+stay with their hue. A slot the theme leaves unset keeps every colour in it
+as picked, so declare only the ones you want to change:
+
+```css
+.theme-dark {
+ --palette-red: oklch(0.7 0.14 25);
+ --palette-yellow: oklch(0.82 0.12 90);
+ --label-chip-color: oklch(0.2 0.02 260);
+}
+```
+
+Label text is dark or light by the colour as picked, so a slot shows both:
+a pale pick and a deep pick of red both land in `--palette-red`. Once slots
+change, set `--label-chip-color` too, per slot if needed:
+`[data-mc="label-chip"][data-palette="yellow"] { --label-chip-color: … }`.
+The label chip and a custom status's icon carry `data-color` (the hex) and
+`data-palette` (the slot). The built-in statuses keep their own variables,
+`--status-*`.
+
## Options
Options render on the Appearance page while the theme is active. Their
@@ -181,9 +215,9 @@ those change without notice. Anchors, slots and hooks stay until the next
| `[data-mc="issue-row"]` | One issue in a list; `data-status`, `data-priority` (`urgent`, `high`, `medium`, `low`, `none`), `data-assignee-type` (`member`, `agent`, `squad` or `none`), `data-parity` (`even` or `odd`, the row's index within its status group, so stripes survive virtual scrolling where `:nth-child` does not) and `data-selected` (`true` or `false`, ticked for bulk actions). |
| `[data-mc="board-column"]` | One column on a board. |
| `[data-mc="board-card"]` | One issue card on a board; `data-status`, `data-priority` and `data-assignee-type` as on `issue-row`. Cards have no `data-parity` or `data-selected`. |
-| `[data-mc="status-icon"]` | The status glyph (an `svg`). |
+| `[data-mc="status-icon"]` | The status glyph (an `svg`). A custom status adds `data-color`, its hex colour, and `data-palette`, its [colour slot](#colour-slots). |
| `[data-mc="priority-icon"]` | The priority glyph (an `svg`). |
-| `[data-mc="label-chip"]` | A label; `data-color` is its hex colour. The chip paints with `var(--label-color)` and `var(--label-foreground)`, so a rule can restyle it without `!important`. |
+| `[data-mc="label-chip"]` | A label; `data-color` is its hex colour and `data-palette` its [colour slot](#colour-slots). The chip paints with `var(--label-color)` and `var(--label-foreground)`, so a rule can restyle it without `!important`. `--label-color` is the slot's colour when the theme declares one, else the colour as picked; `--label-foreground` is `--label-chip-color` when set, else dark or light text by the picked colour. |
| `[data-mc="content"]` | Rich text: issue descriptions, comments, chat messages and documents, reading and editing. `data-density` is `document` or `compact` when reading. |
| `[data-mc="comment"]` | A top-level comment card; `data-author-type` is `member`, `agent` or `system`. |
| `[data-mc="comment-reply"]` | A reply inside a comment card; `data-author-type` as on `comment`. |
@@ -196,6 +230,18 @@ those change without notice. Anchors, slots and hooks stay until the next
| `[data-mc="unread-dot"]` | The unread marker on an inbox item. |
| `[data-mc="toaster"]` | The toast region. Each toast inside is an `li` with `data-type` `success`, `error`, `info`, `warning`, `loading` or `default`. A plain toast usually has no `data-type`, so match it with both `li:not([data-type])` and `li[data-type="default"]`. |
| `[data-mc="settings-page"]` | The settings page. |
+| `[data-mc="issue-detail"]` | An open issue, on its page or in the peek; `data-status`, `data-priority`, and `data-view` (`page` or `peek`). |
+| `[data-mc="issue-title"]` | The issue's title above its description, reading and editing. |
+| `[data-mc="issue-properties"]` | The properties sidebar next to an issue. |
+| `[data-mc="issue-activity"]` | The activity and comments under an issue. |
+| `[data-mc="object-page"]` | The page of one project, agent, squad, runtime, member, autopilot or skill; `data-type` is `project`, `agent`, `squad`, `runtime`, `member`, `autopilot` or `skill`. |
+| `[data-mc="command-palette"]` | The search and command palette. |
+| `[data-mc="palette-item"]` | A row in the palette; `data-type` is `command`, `page`, `workspace`, `issue`, `project`, `member`, `agent`, `squad`, `object` or `option` (a choice inside a palette page). The highlighted row has `data-selected`. |
+| `[data-mc="avatar"]` | An avatar; `data-type` is `member`, `agent`, `squad` or `system`. |
+| `[data-mc="empty-state"]` | A placeholder for something with nothing in it yet; `data-variant` is `page` (a centred state) or `section` (a quiet row in a page section). |
+| `[data-mc="editor-toolbar"]` | The formatting toolbar over selected text; `data-mode` is `format` or `link`. |
+| `[data-mc="editor-menu"]` | A menu floating over the editor while typing; `data-kind` is `slash` or `mention`. |
+| `[data-mc="tab"]` | Desktop only: one tab in `tab-bar`; `data-active` and `data-pinned` are `true` or `false`. |
Each label chip sets `--label-color` (its hex colour) and `--label-foreground`
(a text colour readable on it). Read them to draw a label another way, such
@@ -278,6 +324,36 @@ that breaks them:
somewhere else, such as inside `@media` or on `body`, it says so instead
of passing it.
+## Embedded content
+
+Plugin surfaces and HTML blocks (`` ```html `` fences in issues and chat)
+run in sandboxed frames, so a theme's CSS does not reach them. Instead both receive the same
+set of [embed tokens](#embed-token-reference) as custom properties on their
+`:root`: surfaces and text, accents, status, priority and label colours,
+chart series, code highlighting, the interface, content and code fonts, two
+text sizes, radii and `--color-scheme`. Each one is resolved where the embed
+sits, so the theme's values and its rules on an ancestor anchor apply, and
+it crosses as a plain value: a colour, a length in pixels, a font stack or a
+keyword. Nothing that could load a resource or read another variable gets
+through.
+
+They follow the theme and mode as they change: a plugin surface receives a
+new set (`multica.ui.onThemeChange` in the
+[SDK](../packages/plugin-sdk/README.md#theme)), and an HTML block that
+uses any of them rebuilds with the new values, reruns its scripts and takes
+the app's `color-scheme`. In an HTML block, `--background` is the
+block's own surface, so a document that paints it sits flush in its frame.
+
+```html
+<div style="background: var(--surface); color: var(--foreground);
+ border-radius: var(--radius-card); font: var(--text-body) var(--font-ui)">
+ <span style="color: var(--status-done)">Done</span>
+</div>
+```
+
+Fonts arrive as names: an embed shows the app's font only if the system has
+it, and otherwise the next family in the stack.
+
## Safe mode
A theme can hide or break parts of the interface. To get back, open the app
@@ -347,8 +423,12 @@ When a mode has frame rules, the rail takes the frame's colours and a failure
reads `Contrast, dark mode (frame): …`; without them it takes the page's
colours and reads `Contrast, light mode: …`, like the other page pairs.
-Contrast covers the page, the frame, and two places a theme reaches only
-indirectly:
+Contrast covers the page, the frame, labels and two places a theme reaches
+only indirectly. Labels are measured in each colour slot the theme
+declares: `--label-chip-color` on the slot, or, when it is not set, whichever
+of the dark and light text reads worse on it, since either can land there.
+A failure reads `Contrast, light mode (label): …`. The tooltip and display
+chips:
- **Tooltips** are always drawn with dark-mode text: the tooltip is a
`.dark` scope, so its `--foreground` is the app's dark value in both
@@ -495,6 +575,22 @@ and dark differ, both defaults are given.
| `--pr-merged` | `oklch(54.1% 0.281 293.009)` / `oklch(70.2% 0.183 293.541)` | Merged pull request icon and pill. The pill's text defaults one shade darker in light mode. |
| `--pr-closed` | `oklch(58.6% 0.253 17.585)` / `oklch(71.2% 0.194 13.428)` | Closed pull request icon. |
+### Label and custom status colours
+
+| Variable | Default (light / dark) | Use |
+| --- | --- | --- |
+| `--palette-gray` | the colour as picked | Labels, custom statuses and select options whose colour is the gray preset (`#6b7280`) or nearest to it. |
+| `--palette-red` | the colour as picked | Labels, custom statuses and select options whose colour is the red preset (`#ef4444`) or nearest to it. |
+| `--palette-orange` | the colour as picked | Labels, custom statuses and select options whose colour is the orange preset (`#f97316`) or nearest to it. |
+| `--palette-yellow` | the colour as picked | Labels, custom statuses and select options whose colour is the yellow preset (`#eab308`) or nearest to it. |
+| `--palette-green` | the colour as picked | Labels, custom statuses and select options whose colour is the green preset (`#22c55e`) or nearest to it. |
+| `--palette-teal` | the colour as picked | Labels, custom statuses and select options whose colour is the teal preset (`#14b8a6`) or nearest to it. |
+| `--palette-blue` | the colour as picked | Labels, custom statuses and select options whose colour is the blue preset (`#3b82f6`) or nearest to it. |
+| `--palette-indigo` | the colour as picked | Labels, custom statuses and select options whose colour is the indigo preset (`#6366f1`) or nearest to it. |
+| `--palette-purple` | the colour as picked | Labels, custom statuses and select options whose colour is the purple preset (`#a855f7`) or nearest to it. |
+| `--palette-pink` | the colour as picked | Labels, custom statuses and select options whose colour is the pink preset (`#ec4899`) or nearest to it. |
+| `--label-chip-color` | dark or light, whichever reads on the picked colour | Text on a label. Set it with the slots it has to read on; `[data-palette]` on the chip names its slot. |
+
### Shape and depth
| Variable | Default (light / dark) | Use |
@@ -591,6 +687,7 @@ and dark differ, both defaults are given.
| `--rail-item-active-background` | `var(--sidebar-accent)` | The current space. |
| `--rail-item-active-color` | `var(--sidebar-accent-foreground)` | Icon and label of the current space. |
| `--nav-item-height` | `2rem` | Minimum height of a row in the space panel. |
+| `--nav-item-padding-y` | `0.375rem` | Top and bottom padding of a row in the space panel; with the text, it sets the row's height when that is above the minimum. |
| `--nav-item-radius` | `var(--radius)` | Rows in the space panel. |
| `--nav-item-color` | `var(--muted-foreground)` | Row text. |
| `--nav-item-hover-background` | `var(--surface-hover)` | Row hover. |
@@ -598,6 +695,20 @@ and dark differ, both defaults are given.
| `--nav-item-active-background` | `var(--surface-selected)` | The current row. |
| `--nav-item-active-color` | `var(--surface-selected-foreground)` | Text of the current row. |
+### Layout and spacing
+
+| Variable | Default (light / dark) | Use |
+| --- | --- | --- |
+| `--space-xs` | `0.5rem` | Spacing step: the gap between board cards. |
+| `--space-sm` | `0.75rem` | Spacing step: board card padding, the issue page's side padding on phones. |
+| `--space-md` | `1rem` | Spacing step: the page's side padding. |
+| `--space-lg` | `1.5rem` | Spacing step: an object page's side padding, the issue page's top padding on phones. |
+| `--space-xl` | `2rem` | Spacing step: an object page's top padding, the issue page's padding. |
+| `--page-padding-x` | `var(--space-md, 1rem)` | Side padding of page headers, the toolbars under them and full-width lists. |
+| `--sidebar-panel-width` | `240px` | Starting width of the navigation panel, kept between 200px and 320px. Once the person drags its edge, their width wins. |
+| `--content-max-width` | `clamp(56rem, 70cqi, 70rem)` | Widest the reading column gets on an issue page and in chat. |
+| `--object-page-max-width` | `760px` | Widest the body of a project, agent, squad, runtime or other object page gets. |
+
### Issues
| Variable | Default (light / dark) | Use |
@@ -618,6 +729,9 @@ and dark differ, both defaults are given.
| `--board-card-hover-background` | `var(--surface-hover)` | Board card hover. |
| `--board-card-border-color` | `var(--surface-border)` | Board card border. |
| `--board-card-shadow` | `var(--surface-shadow)` | Board card shadow. |
+| `--board-card-padding-y` | `var(--space-sm, 0.75rem)` | Top and bottom padding of a board card. |
+| `--board-card-padding-x` | `0.625rem` | Side padding of a board card. |
+| `--board-card-gap` | `var(--space-xs, 0.5rem)` | Space between cards in a board column. |
### Editor content
@@ -739,3 +853,133 @@ and dark differ, both defaults are given.
| `--code-punctuation` | `var(--muted-foreground)` | HTML and XML brackets. |
<!-- theme-variables:end -->
+
+## Embed token reference
+
+Generated from `packages/core/appearance/embed-tokens.ts`. Every token is
+set when the host defines it; `--background`, colours and fonts follow the
+[variables](#variable-reference) of the same name.
+
+<!-- embed-tokens:start (generated by packages/views/common/embed-tokens.test.ts) -->
+
+### Surfaces and text
+
+| Token | Kind | Use |
+| --- | --- | --- |
+| `--background` | colour | What the embed sits on. In an HTML block, the block's own surface. |
+| `--foreground` | colour | Body text. |
+| `--muted-foreground` | colour | Secondary text. |
+| `--faint-foreground` | colour | Hints and placeholders; not for text that must be read. |
+| `--surface` | colour | A panel or card on the page. |
+| `--surface-raised` | colour | A surface above another: menus, popovers. |
+| `--surface-hover` | colour | A row or control under the pointer. |
+| `--surface-selected` | colour | A selected row or control. |
+| `--surface-border` | colour | The border of a surface. |
+| `--page-canvas` | colour | The page behind the content column. |
+| `--card` | colour | Card fill. |
+| `--card-foreground` | colour | Text on a card. |
+| `--popover` | colour | Popover fill. |
+| `--popover-foreground` | colour | Text in a popover. |
+| `--muted` | colour | A quiet fill: code, tags, tracks. |
+| `--border` | colour | Dividers and outlines. |
+| `--input` | colour | Input borders. |
+| `--ring` | colour | Focus rings. |
+| `--color-scheme` | keyword | `light` or `dark`, for `color-scheme: var(--color-scheme)`. |
+
+### Accent and intent
+
+| Token | Kind | Use |
+| --- | --- | --- |
+| `--primary` | colour | Primary buttons and strong accents. |
+| `--primary-foreground` | colour | Text on `--primary`. |
+| `--secondary` | colour | Secondary buttons. |
+| `--secondary-foreground` | colour | Text on `--secondary`. |
+| `--accent` | colour | Hover and highlight fill. |
+| `--accent-foreground` | colour | Text on `--accent`. |
+| `--brand` | colour | Links and the brand accent. |
+| `--destructive` | colour | Errors and destructive actions. |
+| `--success` | colour | Success. |
+| `--warning` | colour | Warnings. |
+| `--info` | colour | Information. |
+
+### Status and priority
+
+| Token | Kind | Use |
+| --- | --- | --- |
+| `--status-backlog` | colour | Backlog. |
+| `--status-todo` | colour | Todo. |
+| `--status-in-progress` | colour | In progress. |
+| `--status-in-review` | colour | In review. |
+| `--status-done` | colour | Done. |
+| `--status-blocked` | colour | Blocked. |
+| `--status-cancelled` | colour | Cancelled. |
+| `--priority-urgent` | colour | Urgent priority. |
+| `--priority-high` | colour | High priority. |
+| `--priority-medium` | colour | Medium priority. |
+| `--priority-low` | colour | Low priority. |
+| `--priority-none` | colour | No priority. |
+
+### Label colours
+
+| Token | Kind | Use |
+| --- | --- | --- |
+| `--palette-gray` | colour | Labels and custom statuses in the gray slot, as the theme paints them. |
+| `--palette-red` | colour | Labels and custom statuses in the red slot, as the theme paints them. |
+| `--palette-orange` | colour | Labels and custom statuses in the orange slot, as the theme paints them. |
+| `--palette-yellow` | colour | Labels and custom statuses in the yellow slot, as the theme paints them. |
+| `--palette-green` | colour | Labels and custom statuses in the green slot, as the theme paints them. |
+| `--palette-teal` | colour | Labels and custom statuses in the teal slot, as the theme paints them. |
+| `--palette-blue` | colour | Labels and custom statuses in the blue slot, as the theme paints them. |
+| `--palette-indigo` | colour | Labels and custom statuses in the indigo slot, as the theme paints them. |
+| `--palette-purple` | colour | Labels and custom statuses in the purple slot, as the theme paints them. |
+| `--palette-pink` | colour | Labels and custom statuses in the pink slot, as the theme paints them. |
+
+### Charts
+
+| Token | Kind | Use |
+| --- | --- | --- |
+| `--chart-1` | colour | Chart series 1. |
+| `--chart-2` | colour | Chart series 2. |
+| `--chart-3` | colour | Chart series 3. |
+| `--chart-4` | colour | Chart series 4. |
+| `--chart-5` | colour | Chart series 5. |
+
+### Code highlighting
+
+| Token | Kind | Use |
+| --- | --- | --- |
+| `--code-block-background` | colour | Code block fill. |
+| `--code-block-color` | colour | Code block text. |
+| `--code-keyword` | colour | Keywords and built-ins. |
+| `--code-string` | colour | Strings and added lines. |
+| `--code-number` | colour | Numbers and literals. |
+| `--code-comment` | colour | Comments. |
+| `--code-function` | colour | Function names. |
+| `--code-type` | colour | Types and class names. |
+| `--code-tag` | colour | Tag names. |
+| `--code-property` | colour | Properties and attributes. |
+| `--code-variable` | colour | Variables. |
+| `--code-punctuation` | colour | Punctuation and tag brackets. |
+| `--code-deletion` | colour | Deleted lines. |
+
+### Type
+
+| Token | Kind | Use |
+| --- | --- | --- |
+| `--font-ui` | font stack | Interface font stack. |
+| `--font-sans` | font stack | The same as `--font-ui`. |
+| `--font-content` | font stack | Font stack for rich text: descriptions, comments, documents. |
+| `--font-mono` | font stack | Code font stack. |
+| `--text-caption` | length (px) | Caption size, after the person's font size. |
+| `--text-body` | length (px) | Body size, after the person's font size. |
+
+### Shape
+
+| Token | Kind | Use |
+| --- | --- | --- |
+| `--radius` | length (px) | Base corner radius. |
+| `--radius-card` | length (px) | Cards and panels. |
+| `--radius-button` | length (px) | Buttons. |
+| `--radius-input` | length (px) | Inputs. |
+
+<!-- embed-tokens:end -->
diff --git a/packages/core/appearance/anchors.ts b/packages/core/appearance/anchors.ts
index c760284fd6..87baa2ff4e 100644
--- a/packages/core/appearance/anchors.ts
+++ b/packages/core/appearance/anchors.ts
@@ -23,10 +23,11 @@ export const THEME_ANCHORS = {
"board-column": "One column on a board.",
"board-card":
"One issue card on a board; `data-status`, `data-priority` and `data-assignee-type` as on `issue-row`.",
- "status-icon": "The status glyph (an svg).",
+ "status-icon":
+ "The status glyph (an svg). A custom status adds `data-color`, its hex colour, and `data-palette`, its colour slot.",
"priority-icon": "The priority glyph (an svg).",
"label-chip":
- "A label; `data-color` is its hex colour, also set as `--label-color` (and the text colour as `--label-foreground`).",
+ "A label; `data-color` is its hex colour and `data-palette` its colour slot. The chip paints with `--label-color` (the slot's colour when the theme declares one) and `--label-foreground`.",
content:
"Rich text: issue descriptions, comments, chat messages and documents, in both reading and editing; `data-density` is document or compact when reading.",
comment: "A top-level comment card in an issue timeline; `data-author-type` is member, agent or system.",
@@ -42,6 +43,21 @@ export const THEME_ANCHORS = {
toaster:
"The toast region. Each toast is an `li`; `data-type` is success, error, info, warning, loading or default, and a plain toast may have no `data-type` at all.",
"settings-page": "The settings page.",
+ "issue-detail":
+ "An open issue, on its page or in the peek; `data-status`, `data-priority`, and `data-view` (page or peek).",
+ "issue-title": "The issue's title above its description, reading and editing.",
+ "issue-properties": "The properties sidebar next to an issue.",
+ "issue-activity": "The activity and comments under an issue.",
+ "object-page":
+ "The page of one project, agent, squad, runtime, member, autopilot or skill; `data-type` names which.",
+ "command-palette": "The search and command palette.",
+ "palette-item":
+ "A row in the palette; `data-type` is command, page, workspace, issue, project, member, agent, squad, object or option (a choice inside a palette page). The highlighted row has `data-selected`.",
+ avatar: "An avatar; `data-type` is member, agent, squad or system.",
+ "empty-state": "A placeholder for something with nothing in it yet; `data-variant` is page or section.",
+ "editor-toolbar": "The formatting toolbar over selected text; `data-mode` is format or link.",
+ "editor-menu": "A menu floating over the editor while typing; `data-kind` is slash or mention.",
+ tab: "Desktop only: one tab in `tab-bar`; `data-active` and `data-pinned` are true or false.",
} as const;
export type ThemeAnchor = keyof typeof THEME_ANCHORS;
diff --git a/packages/core/appearance/embed-tokens.ts b/packages/core/appearance/embed-tokens.ts
new file mode 100644
index 0000000000..1dd8594725
--- /dev/null
+++ b/packages/core/appearance/embed-tokens.ts
@@ -0,0 +1,205 @@
+/**
+ * The theme tokens a sandboxed embed receives: plugin surfaces and ```html
+ * blocks get the same set, as custom properties on their `:root`. This list is
+ * the public contract for embed authors; docs/theming.md is generated from it.
+ *
+ * Every value crosses into the frame resolved in the host to a plain colour,
+ * length, font stack or keyword, never a `var()` or anything that could load a
+ * resource. Renaming or removing a token breaks embeds; add instead.
+ */
+
+import { PALETTE_PRESETS, PALETTE_SLOTS } from "./palette";
+import { THEME_VARIABLES } from "./theme-variables";
+
+export type EmbedTokenKind = "color" | "length" | "font" | "keyword";
+
+export type EmbedTokenGroup = "surfaces" | "intent" | "status" | "palette" | "chart" | "code" | "type" | "shape";
+
+export interface EmbedToken {
+ /** With the leading `--`. */
+ name: string;
+ kind: EmbedTokenKind;
+ group: EmbedTokenGroup;
+ description: string;
+ /** What the host resolves, in its own stylesheet: `var(<name>)` when absent. */
+ source?: string;
+ /** In dark mode, when the app's fallback differs. */
+ darkSource?: string;
+}
+
+export const EMBED_TOKEN_GROUPS: Record<EmbedTokenGroup, string> = {
+ surfaces: "Surfaces and text",
+ intent: "Accent and intent",
+ status: "Status and priority",
+ palette: "Label colours",
+ chart: "Charts",
+ code: "Code highlighting",
+ type: "Type",
+ shape: "Shape",
+};
+
+type Row = readonly [name: string, description: string];
+
+const rows = (group: EmbedTokenGroup, kind: EmbedTokenKind, entries: readonly Row[]): EmbedToken[] =>
+ entries.map(([name, description]) => ({ name: `--${name}`, kind, group, description }));
+
+/** A component variable, read with the fallback the app reads it with. */
+function themed(group: EmbedTokenGroup, kind: EmbedTokenKind, name: string, description: string): EmbedToken {
+ const variable = THEME_VARIABLES.find((v) => v.name === name);
+ if (!variable?.default) return { name: `--${name}`, kind, group, description };
+ return {
+ name: `--${name}`,
+ kind,
+ group,
+ description,
+ source: `var(--${name}, ${variable.default})`,
+ ...(variable.darkDefault ? { darkSource: `var(--${name}, ${variable.darkDefault})` } : {}),
+ };
+}
+
+const SURFACES = rows("surfaces", "color", [
+ ["background", "What the embed sits on. In an HTML block, the block's own surface."],
+ ["foreground", "Body text."],
+ ["muted-foreground", "Secondary text."],
+ ["faint-foreground", "Hints and placeholders; not for text that must be read."],
+ ["surface", "A panel or card on the page."],
+ ["surface-raised", "A surface above another: menus, popovers."],
+ ["surface-hover", "A row or control under the pointer."],
+ ["surface-selected", "A selected row or control."],
+ ["surface-border", "The border of a surface."],
+ ["page-canvas", "The page behind the content column."],
+ ["card", "Card fill."],
+ ["card-foreground", "Text on a card."],
+ ["popover", "Popover fill."],
+ ["popover-foreground", "Text in a popover."],
+ ["muted", "A quiet fill: code, tags, tracks."],
+ ["border", "Dividers and outlines."],
+ ["input", "Input borders."],
+ ["ring", "Focus rings."],
+]);
+
+const INTENT = rows("intent", "color", [
+ ["primary", "Primary buttons and strong accents."],
+ ["primary-foreground", "Text on `--primary`."],
+ ["secondary", "Secondary buttons."],
+ ["secondary-foreground", "Text on `--secondary`."],
+ ["accent", "Hover and highlight fill."],
+ ["accent-foreground", "Text on `--accent`."],
+ ["brand", "Links and the brand accent."],
+ ["destructive", "Errors and destructive actions."],
+ ["success", "Success."],
+ ["warning", "Warnings."],
+ ["info", "Information."],
+]);
+
+const STATUS_NAMES: Row[] = [
+ ["status-backlog", "Backlog."],
+ ["status-todo", "Todo."],
+ ["status-in-progress", "In progress."],
+ ["status-in-review", "In review."],
+ ["status-done", "Done."],
+ ["status-blocked", "Blocked."],
+ ["status-cancelled", "Cancelled."],
+ ["priority-urgent", "Urgent priority."],
+ ["priority-high", "High priority."],
+ ["priority-medium", "Medium priority."],
+ ["priority-low", "Low priority."],
+ ["priority-none", "No priority."],
+];
+
+const CODE_NAMES: Row[] = [
+ ["code-block-background", "Code block fill."],
+ ["code-block-color", "Code block text."],
+ ["code-keyword", "Keywords and built-ins."],
+ ["code-string", "Strings and added lines."],
+ ["code-number", "Numbers and literals."],
+ ["code-comment", "Comments."],
+ ["code-function", "Function names."],
+ ["code-type", "Types and class names."],
+ ["code-tag", "Tag names."],
+ ["code-property", "Properties and attributes."],
+ ["code-variable", "Variables."],
+ ["code-punctuation", "Punctuation and tag brackets."],
+ ["code-deletion", "Deleted lines."],
+];
+
+export const EMBED_TOKENS: readonly EmbedToken[] = [
+ ...SURFACES,
+ ...INTENT,
+ ...STATUS_NAMES.map(([name, description]) => themed("status", "color", name, description)),
+ ...PALETTE_SLOTS.map(
+ (slot): EmbedToken => ({
+ name: `--palette-${slot}`,
+ kind: "color",
+ group: "palette",
+ description: `Labels and custom statuses in the ${slot} slot, as the theme paints them.`,
+ source: `var(--palette-${slot}, ${PALETTE_PRESETS[slot]})`,
+ }),
+ ),
+ ...rows("chart", "color", [1, 2, 3, 4, 5].map((n): Row => [`chart-${n}`, `Chart series ${n}.`])),
+ ...CODE_NAMES.map(([name, description]) => themed("code", "color", name, description)),
+ { name: "--font-ui", kind: "font", group: "type", description: "Interface font stack.", source: "inherit" },
+ { name: "--font-sans", kind: "font", group: "type", description: "The same as `--font-ui`.", source: "inherit" },
+ { name: "--font-content", kind: "font", group: "type", description: "Font stack for rich text: descriptions, comments, documents." },
+ { name: "--font-mono", kind: "font", group: "type", description: "Code font stack." },
+ { name: "--text-caption", kind: "length", group: "type", description: "Caption size, after the person's font size." },
+ { name: "--text-body", kind: "length", group: "type", description: "Body size, after the person's font size." },
+ { name: "--radius", kind: "length", group: "shape", description: "Base corner radius." },
+ {
+ name: "--radius-card",
+ kind: "length",
+ group: "shape",
+ description: "Cards and panels.",
+ source: "var(--card-radius, calc(var(--radius) * 1.5))",
+ },
+ {
+ name: "--radius-button",
+ kind: "length",
+ group: "shape",
+ description: "Buttons.",
+ source: "var(--button-radius, var(--radius))",
+ },
+ {
+ name: "--radius-input",
+ kind: "length",
+ group: "shape",
+ description: "Inputs.",
+ source: "var(--input-radius, var(--radius))",
+ },
+ { name: "--color-scheme", kind: "keyword", group: "surfaces", description: "`light` or `dark`, for `color-scheme: var(--color-scheme)`." },
+];
+
+export const EMBED_TOKEN_NAMES: ReadonlySet<string> = new Set(EMBED_TOKENS.map((token) => token.name));
+
+/**
+ * Every custom property the tokens are resolved from: their own names and the
+ * variables their sources read, such as `--card-radius` behind `--radius-card`.
+ */
+export const EMBED_TOKEN_INPUTS: readonly string[] = [
+ ...new Set(
+ EMBED_TOKENS.flatMap((token) => [
+ token.name,
+ ...`${token.source ?? ""} ${token.darkSource ?? ""}`.match(/--[\w-]+/g) ?? [],
+ ]),
+ ),
+];
+
+/** Longest value passed on; a font stack is the longest legitimate one. */
+const MAX_VALUE_LENGTH = 512;
+
+// Rejects anything that could close the style rule or element, escape a
+// string, load a resource, or read another variable inside the frame.
+const UNSAFE_VALUE = /[<>{};\\]|url\s*\(|image(?:-set)?\s*\(|src\s*\(|var\s*\(|@|\/\*/i;
+
+/** Whether a resolved value is plain enough to hand to an embed. */
+export function isPlainEmbedValue(value: string): boolean {
+ return value.length > 0 && value.length <= MAX_VALUE_LENGTH && !UNSAFE_VALUE.test(value);
+}
+
+/** `:root` declarations for the tokens that are safe, in contract order. */
+export function embedTokenDeclarations(tokens: Readonly<Record<string, string>>): string {
+ return EMBED_TOKENS.flatMap((token) => {
+ const value = tokens[token.name]?.trim();
+ return value && isPlainEmbedValue(value) ? [`${token.name}:${value}`] : [];
+ }).join(";");
+}
diff --git a/packages/core/appearance/index.test.ts b/packages/core/appearance/index.test.ts
index f67ff68911..e2b7e98caf 100644
--- a/packages/core/appearance/index.test.ts
+++ b/packages/core/appearance/index.test.ts
@@ -129,6 +129,26 @@ describe("appearanceRootVariables", () => {
expect(vars["--font-scale"]).toBe(String(15 / 14));
expect(vars["--issue-row-height"]).toBe("32px");
});
+
+ it("spreads density over list rows, group headers, board cards and navigation rows", () => {
+ const names = [
+ "--issue-row-height",
+ "--issue-group-header-height",
+ "--board-card-padding-y",
+ "--board-card-gap",
+ "--nav-item-height",
+ "--nav-item-padding-y",
+ ];
+ const compact = appearanceRootVariables({ ...DEFAULT_APPEARANCE, density: "compact" });
+ const comfortable = appearanceRootVariables({ ...DEFAULT_APPEARANCE, density: "comfortable" });
+ const standard = appearanceRootVariables(DEFAULT_APPEARANCE);
+ for (const name of names) {
+ expect(standard[name]).toBeNull();
+ expect(parseFloat(compact[name]!)).toBeLessThan(parseFloat(comfortable[name]!));
+ }
+ expect(compact).toMatchObject({ "--nav-item-height": "1.75rem", "--board-card-gap": "0.375rem" });
+ expect(comfortable).toMatchObject({ "--nav-item-height": "2.25rem", "--board-card-padding-y": "1rem" });
+ });
});
describe("appearanceStylesheet", () => {
diff --git a/packages/core/appearance/index.ts b/packages/core/appearance/index.ts
index 583f9018a5..c10be775ae 100644
--- a/packages/core/appearance/index.ts
+++ b/packages/core/appearance/index.ts
@@ -21,6 +21,8 @@ export * from "./theme-package";
export * from "./installed-themes";
export * from "./anchors";
export * from "./theme-variables";
+export * from "./palette";
+export * from "./embed-tokens";
export * from "./local-fonts";
export * from "./theme-archive";
export * from "./theme-export";
@@ -209,11 +211,24 @@ const CODE_FONT_FAMILIES: Record<CodeFont, string | null> = {
jetbrains: "var(--font-code-jetbrains), var(--font-ui-mono), ui-monospace, monospace",
system: 'ui-monospace, "SF Mono", SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace',
};
-const ROW_HEIGHTS: Record<Density, string | null> = {
- compact: "32px",
- default: null,
- comfortable: "42px",
-};
+/** What each density sets; Default leaves the theme's or the stylesheet's values. */
+const DENSITY_VARIABLES = {
+ "--issue-row-height": ["32px", "42px"],
+ "--issue-group-header-height": ["2.25rem", "2.75rem"],
+ "--board-card-padding-y": ["0.5rem", "1rem"],
+ "--board-card-gap": ["0.375rem", "0.75rem"],
+ "--nav-item-height": ["1.75rem", "2.25rem"],
+ "--nav-item-padding-y": ["0.25rem", "0.5rem"],
+} as const satisfies Record<string, readonly [compact: string, comfortable: string]>;
+
+function densityVariables(density: Density): Record<string, string | null> {
+ return Object.fromEntries(
+ Object.entries(DENSITY_VARIABLES).map(([name, [compact, comfortable]]) => [
+ name,
+ density === "compact" ? compact : density === "comfortable" ? comfortable : null,
+ ]),
+ );
+}
const LEADINGS: Record<ContentLeading, [string, string] | null> = {
compact: ["1.5", "1.65"],
default: null,
@@ -242,7 +257,7 @@ export function appearanceRootVariables(
"--content-scale": prefs.contentSize === FOLLOW_UI ? null : String(prefs.contentSize / 14),
"--content-leading": leading?.[0] ?? null,
"--content-leading-cjk": leading?.[1] ?? null,
- "--issue-row-height": ROW_HEIGHTS[prefs.density],
+ ...densityVariables(prefs.density),
};
}
diff --git a/packages/core/appearance/palette.test.ts b/packages/core/appearance/palette.test.ts
new file mode 100644
index 0000000000..23d1e01989
--- /dev/null
+++ b/packages/core/appearance/palette.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it } from "vitest";
+import { PALETTE_PRESETS, PALETTE_SLOTS, labelTextColor, paletteColor, paletteSlot } from "./palette";
+import { THEME_VARIABLE_NAMES } from "./theme-variables";
+
+describe("palette", () => {
+ it("puts each preset on its own slot", () => {
+ for (const slot of PALETTE_SLOTS) {
+ expect(paletteSlot(PALETTE_PRESETS[slot])).toBe(slot);
+ expect(paletteSlot(PALETTE_PRESETS[slot].toUpperCase())).toBe(slot);
+ }
+ });
+
+ it("puts any other colour on the nearest slot", () => {
+ expect(paletteSlot("#b91c1c")).toBe("red");
+ expect(paletteSlot("#16a34a")).toBe("green");
+ expect(paletteSlot("#d1d5db")).toBe("gray");
+ expect(paletteSlot("#7c3aed")).toBe("purple");
+ expect(paletteSlot("fb923c")).toBe("orange");
+ expect(paletteSlot("#111827")).toBe("gray");
+ expect(paletteSlot("#ffffff")).toBe("gray");
+ expect(paletteSlot("#fecaca")).toBe("red");
+ expect(paletteSlot("#1e3a8a")).toBe("blue");
+ expect(paletteSlot("#92400e")).toBe("orange");
+ });
+
+ it("reads a slot's variable with the colour as picked as its fallback", () => {
+ expect(paletteColor("#ef4444")).toBe("var(--palette-red, #ef4444)");
+ expect(paletteColor("#b91c1c")).toBe("var(--palette-red, #b91c1c)");
+ });
+
+ it("passes anything that is not a hex through", () => {
+ expect(paletteSlot("red")).toBeNull();
+ expect(paletteColor("red")).toBe("red");
+ expect(paletteColor(null)).toBeUndefined();
+ expect(paletteColor(undefined)).toBeUndefined();
+ });
+
+ it("registers every slot as a theme variable", () => {
+ for (const slot of PALETTE_SLOTS) expect(THEME_VARIABLE_NAMES.has(`palette-${slot}`)).toBe(true);
+ expect(THEME_VARIABLE_NAMES.has("label-chip-color")).toBe(true);
+ });
+
+ it("picks dark text on light labels and light text on dark ones", () => {
+ expect(labelTextColor("#eab308")).toBe("#111827");
+ expect(labelTextColor("#3b82f6")).toBe("#f9fafb");
+ expect(labelTextColor("nope")).toBe("#111827");
+ });
+});
diff --git a/packages/core/appearance/palette.ts b/packages/core/appearance/palette.ts
new file mode 100644
index 0000000000..e7ef24e692
--- /dev/null
+++ b/packages/core/appearance/palette.ts
@@ -0,0 +1,118 @@
+/**
+ * The colour slots a theme can recolour labels, custom statuses and select
+ * options through. Every colour people pick is a `#rrggbb`; it renders as
+ * `var(--palette-<slot>, <its own hex>)`, so with no slot declared it looks
+ * exactly as picked. A preset lands on its own slot. Any other colour is
+ * placed in OKLab: one with little chroma on gray, the rest on the slot whose
+ * hue is nearest, so a pale or dark shade stays with its hue.
+ */
+
+export const PALETTE_SLOTS = [
+ "gray",
+ "red",
+ "orange",
+ "yellow",
+ "green",
+ "teal",
+ "blue",
+ "indigo",
+ "purple",
+ "pink",
+] as const;
+
+export type PaletteSlot = (typeof PALETTE_SLOTS)[number];
+
+/** The colour picker's presets, one per slot, in the picker's order. */
+export const PALETTE_PRESETS: Readonly<Record<PaletteSlot, string>> = {
+ gray: "#6b7280",
+ red: "#ef4444",
+ orange: "#f97316",
+ yellow: "#eab308",
+ green: "#22c55e",
+ teal: "#14b8a6",
+ blue: "#3b82f6",
+ indigo: "#6366f1",
+ purple: "#a855f7",
+ pink: "#ec4899",
+};
+
+const HEX = /^#?([0-9a-f]{6})$/i;
+
+type Lab = readonly [number, number, number];
+
+const linear = (c: number) => (c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4));
+
+function hexToOklab(hex: string): Lab | null {
+ const match = HEX.exec(hex.trim());
+ if (!match) return null;
+ const n = parseInt(match[1]!, 16);
+ const r = linear(((n >> 16) & 255) / 255);
+ const g = linear(((n >> 8) & 255) / 255);
+ const b = linear((n & 255) / 255);
+ const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);
+ const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);
+ const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);
+ return [
+ 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s,
+ 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s,
+ 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s,
+ ];
+}
+
+/** OKLab chroma below which a colour reads as gray; the gray preset's is 0.023. */
+const NEUTRAL_CHROMA = 0.04;
+
+const hueOf = ([, a, b]: Lab) => Math.atan2(b, a);
+
+const PRESET_HUES = PALETTE_SLOTS.filter((slot) => slot !== "gray").map(
+ (slot) => [slot, hueOf(hexToOklab(PALETTE_PRESETS[slot])!)] as const,
+);
+
+/** The slot a `#rrggbb` colour belongs to; null when it is not one. */
+export function paletteSlot(hex: string): PaletteSlot | null {
+ const lab = hexToOklab(hex);
+ if (!lab) return null;
+ if (Math.hypot(lab[1], lab[2]) < NEUTRAL_CHROMA) return "gray";
+ const hue = hueOf(lab);
+ let nearest: PaletteSlot = "gray";
+ let best = Infinity;
+ for (const [slot, presetHue] of PRESET_HUES) {
+ const turn = Math.abs(hue - presetHue);
+ const distance = Math.min(turn, 2 * Math.PI - turn);
+ if (distance < best) {
+ best = distance;
+ nearest = slot;
+ }
+ }
+ return nearest;
+}
+
+/** The label text colours the app picks between: dark, then light. */
+export const LABEL_TEXT_COLORS = ["#111827", "#f9fafb"] as const;
+
+/**
+ * Text that reads on a label of this colour when the theme sets no
+ * `--label-chip-color`: dark above a BT.601 perceived luminance of 0.55,
+ * light below, dark for anything that is not a hex.
+ */
+export function labelTextColor(hex: string): string {
+ const [dark, light] = LABEL_TEXT_COLORS;
+ const match = HEX.exec(hex.trim());
+ if (!match) return dark;
+ const n = parseInt(match[1]!, 16);
+ const luminance = (0.299 * ((n >> 16) & 255) + 0.587 * ((n >> 8) & 255) + 0.114 * (n & 255)) / 255;
+ return luminance > 0.55 ? dark : light;
+}
+
+/**
+ * The CSS colour to paint a picked colour with: its slot's variable, falling
+ * back to the colour itself. Anything that is not a `#rrggbb` comes back as
+ * is, so a caller's existing handling of it does not change.
+ */
+export function paletteColor(hex: string): string;
+export function paletteColor(hex: string | null | undefined): string | undefined;
+export function paletteColor(hex: string | null | undefined): string | undefined {
+ if (!hex) return hex ?? undefined;
+ const slot = paletteSlot(hex);
+ return slot ? `var(--palette-${slot}, ${hex})` : hex;
+}
diff --git a/packages/core/appearance/theme-check.test.ts b/packages/core/appearance/theme-check.test.ts
index 651e125034..43473e93c7 100644
--- a/packages/core/appearance/theme-check.test.ts
+++ b/packages/core/appearance/theme-check.test.ts
@@ -294,6 +294,31 @@ describe("theme check", () => {
]);
});
+ it("measures label text on the colour slots the theme declares", () => {
+ expect(errors(".theme-light { --palette-blue: #bfdbfe; }")).toEqual([
+ expect.stringMatching(
+ /^Contrast, light mode \(label\): --label-chip-color is below 4\.5:1 on --palette-blue \(1\.\d\d:1\)\. Without --label-chip-color/,
+ ),
+ ]);
+ expect(check(".theme-light { --palette-blue: #bfdbfe; --label-chip-color: #111827; }")).toMatchObject({ ok: true, issues: [] });
+ expect(errors(".theme-dark { --palette-yellow: #fde68a; --palette-red: #fecaca; --label-chip-color: #ffffff; }")).toEqual([
+ expect.stringMatching(/^Contrast, dark mode \(label\): --label-chip-color is below 4\.5:1 on --palette-red \(.*\) and --palette-yellow \([\d.]+:1\)\.$/),
+ ]);
+ expect(check(".theme-light { --radius: 0; }").contrast.some((c) => c.area === "label")).toBe(false);
+ });
+
+ it("measures the worse of the dark and light label text a slot can get", () => {
+ // A label picked as #fecaca falls in the red slot with dark text, which a
+ // dark red slot cannot carry, although the red preset itself takes light text.
+ const checked = check(".theme-light { --palette-red: #7f1d1d; }");
+ expect(checked.contrast.filter((c) => c.area === "label")).toEqual([
+ expect.objectContaining({ background: "--palette-red", ratio: 1.77, defaulted: true }),
+ ]);
+ expect(errors(".theme-light { --palette-red: #7f1d1d; }")).toEqual([
+ expect.stringMatching(/^Contrast, light mode \(label\): --label-chip-color is below 4\.5:1 on --palette-red \(1\.77:1\)\./),
+ ]);
+ });
+
it("measures pressed display chips in the popover they sit in", () => {
expect(errors(".theme-light { --input: #111111; }")).toEqual([
expect.stringMatching(
diff --git a/packages/core/appearance/theme-check.ts b/packages/core/appearance/theme-check.ts
index 4a1c218ea3..e1dd69ec99 100644
--- a/packages/core/appearance/theme-check.ts
+++ b/packages/core/appearance/theme-check.ts
@@ -2,6 +2,7 @@ import type { ArchiveFile } from "./theme-archive";
import { parseTheme, readThemeFiles, type ThemePackageInput } from "./theme-package";
import { THEME_VARIABLE_NAMES } from "./theme-variables";
import { contrastRatio, paintOver, resolveColor, type BasePalette, type Rgba } from "./theme-contrast";
+import { LABEL_TEXT_COLORS, PALETTE_SLOTS } from "./palette";
import {
THEME_OPTION_ATTR_PREFIX,
localizedText,
@@ -40,15 +41,18 @@ export interface ContrastCheck {
mode: "light" | "dark";
/**
* Where the pair is painted: the page, the frame (rail, toolbar, tabs),
- * a tooltip, or a pressed chip in a display popover.
+ * a tooltip, a pressed chip in a display popover, or a label in a colour
+ * slot the theme declares.
*/
- area: "page" | "frame" | "tooltip" | "display chip";
+ area: "page" | "frame" | "tooltip" | "display chip" | "label";
foreground: string;
background: string;
ratio: number;
required: number;
/** Set when one option was off its default for this measurement. */
variant?: ContrastVariant;
+ /** Set when the foreground is the app's default, not a variable the theme set. */
+ defaulted?: boolean;
}
export interface ThemeCheckReport {
@@ -102,13 +106,16 @@ type Slot = "tooltip-content" | "popover-content";
const SLOTS: readonly Slot[] = ["tooltip-content", "popover-content"];
/** How to fix a pair the theme reaches only through a default. */
-function contrastHint({ area, foreground, background }: ContrastCheck): string {
+function contrastHint({ area, foreground, background, defaulted }: ContrastCheck): string {
if (area === "tooltip" && foreground === "--foreground") {
return " Tooltip text is the app's dark-mode --foreground in both modes; set --tooltip-foreground to choose it.";
}
if (area === "display chip" && background === "--input") {
return " Pressed chips fill with --input, the input border colour; set --display-chip-pressed-background to colour them on their own.";
}
+ if (area === "label" && defaulted) {
+ return " Without --label-chip-color, label text is dark or light by the colour as picked, not the slot's, so either can land on any slot; set it to choose.";
+ }
return "";
}
@@ -483,7 +490,7 @@ function measureContrast(
backgrounds: readonly string[],
required: number,
/** Where the backgrounds are resolved, when not where the text is; and what a translucent one sits on. */
- { surface = p, under }: { surface?: Map<string, string>; under?: string } = {},
+ { surface = p, under, defaulted }: { surface?: Map<string, string>; under?: string; defaulted?: boolean } = {},
) => {
const fg = resolveColor(p, foreground);
if ("unresolved" in fg) {
@@ -514,6 +521,7 @@ function measureContrast(
ratio: Math.round(ratio * 100) / 100,
required,
...(variant ? { variant } : {}),
+ ...(defaulted ? { defaulted } : {}),
});
}
};
@@ -583,6 +591,26 @@ function measureContrast(
const chipText = popover.has("--display-chip-pressed-color") ? "--display-chip-pressed-color" : "--foreground";
const chipFill = popover.has("--display-chip-pressed-background") ? "--display-chip-pressed-background" : "--input";
measure("display chip", popover, chipText, [chipFill], TEXT, { under: "--surface-raised" });
+
+ // A label paints its slot's colour behind --label-chip-color. When that is
+ // unset the app picks dark or light text by the colour as picked, and every
+ // slot holds both light and dark picks, so either text can land on it: the
+ // worse of the two is what some label shows.
+ const declaredSlots = PALETTE_SLOTS.filter((slot) => palette.has(`--palette-${slot}`));
+ if (palette.has("--label-chip-color")) {
+ const slots = declaredSlots.map((slot) => `--palette-${slot}`);
+ measure("label", palette, "--label-chip-color", slots, TEXT, { under: "--background" });
+ } else {
+ for (const slot of declaredSlots) {
+ const start = results.length;
+ for (const text of LABEL_TEXT_COLORS) {
+ const label = new ReadTracker(read, [...palette, ["--label-chip-color", text]]);
+ measure("label", label, "--label-chip-color", [`--palette-${slot}`], TEXT, { under: "--background", defaulted: true });
+ }
+ const measured = results.splice(start);
+ if (measured.length) results.push(measured.reduce((worse, next) => (next.ratio < worse.ratio ? next : worse)));
+ }
+ }
}
for (const [name, where] of unmodelled) {
diff --git a/packages/core/appearance/theme-variables.ts b/packages/core/appearance/theme-variables.ts
index e61de9b14f..c2a4fe6517 100644
--- a/packages/core/appearance/theme-variables.ts
+++ b/packages/core/appearance/theme-variables.ts
@@ -14,13 +14,17 @@
* until the next THEME_API_VERSION.
*/
+import { PALETTE_PRESETS, PALETTE_SLOTS } from "./palette";
+
export type ThemeVariableSection =
| "colors"
| "status"
+ | "palette"
| "shape"
| "typography"
| "controls"
| "navigation"
+ | "layout"
| "issues"
| "editor"
| "code";
@@ -41,10 +45,12 @@ export interface ThemeVariable {
export const THEME_VARIABLE_SECTIONS: Record<ThemeVariableSection, string> = {
colors: "Colours and surfaces",
status: "Status and priority",
+ palette: "Label and custom status colours",
shape: "Shape and depth",
typography: "Typography",
controls: "Controls and overlays",
navigation: "Navigation and page",
+ layout: "Layout and spacing",
issues: "Issues",
editor: "Editor content",
code: "Code",
@@ -61,6 +67,8 @@ const DEFAULT_TEXT: Record<string, string> = {
"button-primary": "`--primary`",
"button-primary-foreground": "`--primary-foreground`",
"button-primary-border": "`--button-primary`",
+ ...Object.fromEntries(PALETTE_SLOTS.map((slot) => [`palette-${slot}`, "the colour as picked"])),
+ "label-chip-color": "dark or light, whichever reads on the picked colour",
};
function section(name: ThemeVariableSection, entries: readonly Entry[]): ThemeVariable[] {
@@ -132,6 +140,16 @@ const COLORS: Entry[] = [
["scrollbar-thumb-hover", "Scrollbar thumb on hover."],
];
+const PALETTE: Entry[] = [
+ ...PALETTE_SLOTS.map(
+ (slot): Entry => [
+ `palette-${slot}`,
+ `Labels, custom statuses and select options whose colour is the ${slot} preset (\`${PALETTE_PRESETS[slot]}\`) or nearest to it.`,
+ ],
+ ),
+ ["label-chip-color", "Text on a label. Set it with the slots it has to read on; `[data-palette]` on the chip names its slot."],
+];
+
const STATUS: Entry[] = [
["status-backlog", "Backlog status icon.", "var(--muted-foreground)"],
["status-todo", "Todo status icon.", "var(--muted-foreground)"],
@@ -237,6 +255,7 @@ const NAVIGATION: Entry[] = [
["rail-item-active-background", "The current space.", "var(--sidebar-accent)"],
["rail-item-active-color", "Icon and label of the current space.", "var(--sidebar-accent-foreground)"],
["nav-item-height", "Minimum height of a row in the space panel.", "2rem"],
+ ["nav-item-padding-y", "Top and bottom padding of a row in the space panel; with the text, it sets the row's height when that is above the minimum.", "0.375rem"],
["nav-item-radius", "Rows in the space panel.", "var(--radius)"],
["nav-item-color", "Row text.", "var(--muted-foreground)"],
["nav-item-hover-background", "Row hover.", "var(--surface-hover)"],
@@ -245,6 +264,18 @@ const NAVIGATION: Entry[] = [
["nav-item-active-color", "Text of the current row.", "var(--surface-selected-foreground)"],
];
+const LAYOUT: Entry[] = [
+ ["space-xs", "Spacing step: the gap between board cards.", "0.5rem"],
+ ["space-sm", "Spacing step: board card padding, the issue page's side padding on phones.", "0.75rem"],
+ ["space-md", "Spacing step: the page's side padding.", "1rem"],
+ ["space-lg", "Spacing step: an object page's side padding, the issue page's top padding on phones.", "1.5rem"],
+ ["space-xl", "Spacing step: an object page's top padding, the issue page's padding.", "2rem"],
+ ["page-padding-x", "Side padding of page headers, the toolbars under them and full-width lists.", "var(--space-md, 1rem)"],
+ ["sidebar-panel-width", "Starting width of the navigation panel, kept between 200px and 320px. Once the person drags its edge, their width wins.", "240px"],
+ ["content-max-width", "Widest the reading column gets on an issue page and in chat.", "clamp(56rem, 70cqi, 70rem)"],
+ ["object-page-max-width", "Widest the body of a project, agent, squad, runtime or other object page gets.", "760px"],
+];
+
const ISSUES: Entry[] = [
["issue-row-height", "Height of a row in the issue list."],
["issue-row-padding-x", "Side padding of an issue row.", "1rem"],
@@ -262,6 +293,9 @@ const ISSUES: Entry[] = [
["board-card-hover-background", "Board card hover.", "var(--surface-hover)"],
["board-card-border-color", "Board card border.", "var(--surface-border)"],
["board-card-shadow", "Board card shadow.", "var(--surface-shadow)"],
+ ["board-card-padding-y", "Top and bottom padding of a board card.", "var(--space-sm, 0.75rem)"],
+ ["board-card-padding-x", "Side padding of a board card.", "0.625rem"],
+ ["board-card-gap", "Space between cards in a board column.", "var(--space-xs, 0.5rem)"],
];
const HEADING_SIZES = [
@@ -360,10 +394,12 @@ const CODE: Entry[] = [
export const THEME_VARIABLES: readonly ThemeVariable[] = [
...section("colors", COLORS),
...section("status", STATUS),
+ ...section("palette", PALETTE),
...section("shape", SHAPE),
...section("typography", TYPOGRAPHY),
...section("controls", CONTROLS),
...section("navigation", NAVIGATION),
+ ...section("layout", LAYOUT),
...section("issues", ISSUES),
...section("editor", EDITOR),
...section("code", CODE),
diff --git a/packages/plugin-sdk/README.md b/packages/plugin-sdk/README.md
index a446981164..0277334493 100644
--- a/packages/plugin-sdk/README.md
+++ b/packages/plugin-sdk/README.md
@@ -67,12 +67,33 @@ cannot start agent runs as a side effect of posting text.
## Theme
-The host pushes design tokens over the private port and again on every theme switch, and
-the SDK writes them as custom properties on `:root`. Use `var(--foreground)`,
-`var(--background)`, `var(--border)`, `var(--radius)` and friends and your
-surface will look native without shipping a stylesheet.
+The host sends design tokens over the private port when the surface connects
+and again on every theme or mode switch, and the SDK writes them as custom
+properties on `:root`. Use `var(--foreground)`, `var(--surface)`,
+`var(--border)`, `var(--radius-card)`, `var(--status-done)`, `var(--chart-1)`,
+`var(--font-ui)` and friends and your surface will look native without
+shipping a stylesheet:
+
+```css
+:root { color-scheme: var(--color-scheme); }
+body {
+ background: var(--background);
+ color: var(--foreground);
+ font: var(--text-body) var(--font-ui);
+}
+```
-`multica.ui.onThemeChange(fn)` if you need to react in JS.
+They are the same tokens HTML blocks in issues and chat get, listed with their kinds in
+[Embed token reference](../../docs/theming.md#embed-token-reference): surfaces
+and text, accents, status, priority and label colours, chart series, code
+highlighting, fonts, text sizes, radii and `--color-scheme`. Every value is
+resolved by the host to a plain colour, pixel length, font stack or keyword,
+so it is safe to use anywhere a value is expected. A token the host does not
+define is not sent; give it a fallback (`var(--chart-1, steelblue)`) if your
+surface needs one.
+
+`multica.ui.onThemeChange(fn)` if you need to react in JS, for example to
+redraw a canvas chart with the new colours.
## Sizing
diff --git a/packages/plugin-sdk/index.ts b/packages/plugin-sdk/index.ts
index dfb8a8e093..f63863b1f1 100644
--- a/packages/plugin-sdk/index.ts
+++ b/packages/plugin-sdk/index.ts
@@ -131,10 +131,15 @@ class Bridge {
};
private applyTheme(theme: ThemeTokens) {
+ const previous = this.theme;
this.theme = theme;
if (typeof document !== "undefined") {
+ const root = document.documentElement.style;
+ for (const name of Object.keys(previous)) {
+ if (!(name in theme)) root.removeProperty(name);
+ }
for (const [name, value] of Object.entries(theme)) {
- document.documentElement.style.setProperty(name, value);
+ root.setProperty(name, value);
}
}
for (const listener of this.themeListeners) listener(theme);
diff --git a/packages/ui/components/common/actor-avatar.tsx b/packages/ui/components/common/actor-avatar.tsx
index d779ddcdba..d2601284bd 100644
--- a/packages/ui/components/common/actor-avatar.tsx
+++ b/packages/ui/components/common/actor-avatar.tsx
@@ -51,6 +51,8 @@ function ActorAvatar({
return (
<div
data-slot="avatar"
+ data-mc="avatar"
+ data-type={isSystem ? "system" : isAgent ? "agent" : isSquad ? "squad" : "member"}
className={cn(
"inline-flex shrink-0 items-center justify-center font-medium overflow-hidden",
(!avatarUrl || emoji || imgError) && "bg-muted text-muted-foreground",
diff --git a/packages/ui/components/ui/empty.tsx b/packages/ui/components/ui/empty.tsx
index 42537bb0ad..efa6f79608 100644
--- a/packages/ui/components/ui/empty.tsx
+++ b/packages/ui/components/ui/empty.tsx
@@ -6,6 +6,8 @@ function Empty({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="empty"
+ data-mc="empty-state"
+ data-variant="page"
className={cn(
"flex w-full min-w-0 flex-1 flex-col items-center justify-center gap-4 rounded-xl border-dashed p-6 text-center text-balance",
className
diff --git a/packages/ui/components/ui/sidebar.tsx b/packages/ui/components/ui/sidebar.tsx
index 720268a799..e9db976a5c 100644
--- a/packages/ui/components/ui/sidebar.tsx
+++ b/packages/ui/components/ui/sidebar.tsx
@@ -30,6 +30,9 @@ const SIDEBAR_WIDTH_DEFAULT = 240
const SIDEBAR_WIDTH_MIN = 200
const SIDEBAR_WIDTH_MAX = 320
const SIDEBAR_WIDTH_STORAGE_KEY = "sidebar_width"
+// Until the person drags the edge, a theme picks the width (docs/theming.md).
+// Keep the bounds and default in step with the three constants above.
+const SIDEBAR_WIDTH_THEMED = "clamp(200px, var(--sidebar-panel-width, 240px), 320px)"
// List columns (Inbox, Chat) hold two-line rows with an avatar, so they get
// their own width instead of the nav's: one shared value is either too narrow
// for the rows or too wide for the nav's short labels.
@@ -75,12 +78,14 @@ function useStoredWidth(
clamp: (width: number) => number
) {
const [width, setWidth] = React.useState(defaultWidth)
+ const [stored, setStored] = React.useState(false)
React.useEffect(() => {
- const stored = localStorage.getItem(storageKey)
- if (stored) {
- const storedWidth = Number(stored)
+ const raw = localStorage.getItem(storageKey)
+ if (raw) {
+ const storedWidth = Number(raw)
if (Number.isFinite(storedWidth)) {
setWidth(clamp(storedWidth))
+ setStored(true)
}
}
}, [storageKey, clamp])
@@ -88,11 +93,12 @@ function useStoredWidth(
(w: number) => {
const clamped = clamp(w)
setWidth(clamped)
+ setStored(true)
localStorage.setItem(storageKey, String(clamped))
},
[storageKey, clamp]
)
- return [width, commit] as const
+ return [width, commit, stored] as const
}
type SidebarContextProps = {
@@ -179,7 +185,7 @@ function SidebarProvider({
const isCompact = useIsCompact()
const [openMobile, setOpenMobile] = React.useState(false)
- const [width, commitWidth] = useStoredWidth(
+ const [width, commitWidth, widthStored] = useStoredWidth(
SIDEBAR_WIDTH_STORAGE_KEY,
SIDEBAR_WIDTH_DEFAULT,
clampSidebarWidth
@@ -293,7 +299,7 @@ function SidebarProvider({
data-slot="sidebar-wrapper"
style={
{
- "--sidebar-width": `${width}px`,
+ "--sidebar-width": widthStored ? `${width}px` : SIDEBAR_WIDTH_THEMED,
"--list-column-width": `${listWidth}px`,
"--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
...style,
diff --git a/packages/views/agents/components/agent-detail-page.tsx b/packages/views/agents/components/agent-detail-page.tsx
index 2a4a70300a..d8566c0ad5 100644
--- a/packages/views/agents/components/agent-detail-page.tsx
+++ b/packages/views/agents/components/agent-detail-page.tsx
@@ -336,6 +336,7 @@ export function AgentDetailPage({ agentId }: AgentDetailPageProps) {
if (!agent && (agentsLoading || detailQuery.isPending)) {
return (
<ObjectPage
+ type="agent"
layoutId={AGENT_DETAIL_LAYOUT_ID}
segments={[listSegment]}
leaf={<Skeleton className="h-4 w-40" />}
@@ -349,6 +350,7 @@ export function AgentDetailPage({ agentId }: AgentDetailPageProps) {
if (!agent && isForbidden) {
return (
<ObjectPage
+ type="agent"
layoutId={AGENT_DETAIL_LAYOUT_ID}
segments={[listSegment]}
leaf={
@@ -384,6 +386,7 @@ export function AgentDetailPage({ agentId }: AgentDetailPageProps) {
: t(($) => $.detail.load_failed_title);
return (
<ObjectPage
+ type="agent"
layoutId={AGENT_DETAIL_LAYOUT_ID}
segments={[listSegment]}
leaf={<span className="truncate text-muted-foreground">{title}</span>}
@@ -637,6 +640,7 @@ export function AgentDetailPage({ agentId }: AgentDetailPageProps) {
return (
<>
<ObjectPage
+ type="agent"
scrollRef={setScrollParent}
layoutId={AGENT_DETAIL_LAYOUT_ID}
segments={[listSegment]}
diff --git a/packages/views/autopilots/components/autopilot-detail-page.tsx b/packages/views/autopilots/components/autopilot-detail-page.tsx
index 01bad41b93..bc55b2db99 100644
--- a/packages/views/autopilots/components/autopilot-detail-page.tsx
+++ b/packages/views/autopilots/components/autopilot-detail-page.tsx
@@ -1056,7 +1056,7 @@ export function AutopilotDetailPage({ autopilotId }: { autopilotId: string }) {
const segments = [{ href: wsPaths.autopilots(), label: tLayout(($) => $.panels.autopilots.list) }];
const shell = (leaf: ReactNode, children: ReactNode) => (
- <ObjectPage layoutId={LAYOUT_ID} segments={segments} leaf={leaf}>
+ <ObjectPage type="autopilot" layoutId={LAYOUT_ID} segments={segments} leaf={leaf}>
{children}
</ObjectPage>
);
@@ -1134,6 +1134,7 @@ export function AutopilotDetailPage({ autopilotId }: { autopilotId: string }) {
return (
<ObjectPage
+ type="autopilot"
layoutId={LAYOUT_ID}
segments={segments}
leaf={<span className="min-w-0 truncate">{autopilot.title}</span>}
diff --git a/packages/views/common/appearance-sync.test.tsx b/packages/views/common/appearance-sync.test.tsx
index c27313914c..7c76849deb 100644
--- a/packages/views/common/appearance-sync.test.tsx
+++ b/packages/views/common/appearance-sync.test.tsx
@@ -87,6 +87,7 @@ describe("AppearanceSync", () => {
expect(html().style.getPropertyValue("--font-content-cjk")).toBe("var(--font-cjk-serif)");
expect(html().style.getPropertyValue("--font-scale")).toBe(String(15 / 14));
expect(html().style.getPropertyValue("--issue-row-height")).toBe("42px");
+ expect(html().style.getPropertyValue("--nav-item-height")).toBe("2.25rem");
expect(themeCss()?.textContent).toContain("--button-primary:");
expect(themeCss()?.textContent).toContain('[data-mc="issue-group-header"]');
expect(sheet()?.textContent).toContain("--muted-foreground: color-mix(");
diff --git a/packages/views/common/color-picker.test.tsx b/packages/views/common/color-picker.test.tsx
index 232553941a..70f5bd5ec5 100644
--- a/packages/views/common/color-picker.test.tsx
+++ b/packages/views/common/color-picker.test.tsx
@@ -3,6 +3,7 @@
import { cleanup, fireEvent, screen } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { renderWithI18n } from "../test/i18n";
+import { PALETTE_PRESETS, PALETTE_SLOTS } from "@multica/core/appearance";
import { ColorPickerPanel, COLOR_PICKER_PRESETS } from "./color-picker";
afterEach(cleanup);
@@ -50,6 +51,10 @@ describe("ColorPickerPanel", () => {
}
});
+ it("offers one preset per theme colour slot, in slot order", () => {
+ expect([...COLOR_PICKER_PRESETS]).toEqual(PALETTE_SLOTS.map((slot) => PALETTE_PRESETS[slot]));
+ });
+
it("uses localized labels", () => {
renderWithI18n(<ColorPickerPanel value="#3b82f6" onChange={() => {}} />, {
locale: "zh-Hans",
diff --git a/packages/views/common/embed-theme.test.ts b/packages/views/common/embed-theme.test.ts
new file mode 100644
index 0000000000..48c2d7273b
--- /dev/null
+++ b/packages/views/common/embed-theme.test.ts
@@ -0,0 +1,88 @@
+// @vitest-environment jsdom
+
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { readEmbedTheme } from "./embed-theme";
+
+/** A browser's resolution of `var()` against the host's variables, enough for these tests. */
+function resolve(value: string, vars: Record<string, string>, inherited: string): string {
+ if (value === "inherit") return inherited;
+ const match = /^var\((--[\w-]+)(?:,\s*(.*))?\)$/.exec(value.trim());
+ if (!match) return value;
+ const own = vars[match[1]!];
+ if (own !== undefined) return resolve(own, vars, inherited);
+ return match[2] === undefined ? "" : resolve(match[2], vars, inherited);
+}
+
+function stubHost(vars: Record<string, string>, { colorScheme = "light", fontFamily = "Inter, sans-serif" } = {}) {
+ const host = document.createElement("div");
+ document.body.appendChild(host);
+ vi.spyOn(window, "getComputedStyle").mockImplementation((element: Element) => {
+ if (element === host) {
+ return { colorScheme, fontFamily, getPropertyValue: (name: string) => vars[name] ?? "" } as CSSStyleDeclaration;
+ }
+ const style = (element as HTMLElement).style;
+ return {
+ getPropertyValue: (property: string) => resolve(style.getPropertyValue(property), vars, fontFamily),
+ } as CSSStyleDeclaration;
+ });
+ return { host };
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ document.body.innerHTML = "";
+ document.documentElement.classList.remove("dark");
+});
+
+describe("readEmbedTheme", () => {
+ it("resolves the contract where the host sits and leaves no probe behind", () => {
+ const { host } = stubHost({ "--foreground": "rgb(10, 10, 10)", "--info": "rgb(0, 0, 255)", "--radius": "10px" });
+ const { tokens, colorScheme } = readEmbedTheme(host);
+ expect(colorScheme).toBe("light");
+ expect(tokens).toMatchObject({
+ "--foreground": "rgb(10, 10, 10)",
+ "--status-done": "rgb(0, 0, 255)",
+ "--palette-red": "#ef4444",
+ "--font-ui": "Inter, sans-serif",
+ "--font-sans": "Inter, sans-serif",
+ "--radius": "10px",
+ "--color-scheme": "light",
+ });
+ expect(tokens).not.toHaveProperty("--chart-1");
+ expect(host.childElementCount).toBe(0);
+ });
+
+ it("follows a theme's values and the dark fallbacks", () => {
+ document.documentElement.classList.add("dark");
+ const { host } = stubHost({ "--palette-red": "rgb(200, 80, 80)" }, { colorScheme: "dark" });
+ const { tokens, colorScheme } = readEmbedTheme(host);
+ expect(colorScheme).toBe("dark");
+ expect(tokens["--palette-red"]).toBe("rgb(200, 80, 80)");
+ expect(tokens["--code-keyword"]).toBe("oklch(0.7 0.14 255)");
+ expect(tokens["--color-scheme"]).toBe("dark");
+ });
+
+ it("lets --background carry another host token", () => {
+ const { host } = stubHost({ "--background": "white", "--surface": "rgb(250, 250, 250)" });
+ expect(readEmbedTheme(host).tokens["--background"]).toBe("white");
+ expect(readEmbedTheme(host, { background: "--surface" }).tokens["--background"]).toBe("rgb(250, 250, 250)");
+ });
+
+ it("never passes on a value that is not plain", () => {
+ const { host } = stubHost({
+ "--foreground": "url(https://evil.test/x.png)",
+ "--muted": "var(--elsewhere)",
+ "--border": "red; background: blue",
+ "--brand": "rgb(1, 2, 3)",
+ });
+ const { tokens } = readEmbedTheme(host);
+ expect(tokens).not.toHaveProperty("--foreground");
+ expect(tokens).not.toHaveProperty("--border");
+ expect(tokens["--brand"]).toBe("rgb(1, 2, 3)");
+ expect(Object.values(tokens).some((value) => /url\(|var\(|;/.test(value))).toBe(false);
+ });
+
+ it("reads nothing without a host", () => {
+ expect(readEmbedTheme(null)).toEqual({ tokens: {}, colorScheme: "light" });
+ });
+});
diff --git a/packages/views/common/embed-theme.ts b/packages/views/common/embed-theme.ts
new file mode 100644
index 0000000000..8630dd33d1
--- /dev/null
+++ b/packages/views/common/embed-theme.ts
@@ -0,0 +1,77 @@
+import { EMBED_TOKENS, isPlainEmbedValue, type EmbedTokenKind } from "@multica/core/appearance";
+
+/** The host's theme as a sandboxed embed receives it (docs/theming.md, "Embedded content"). */
+export interface EmbedTheme {
+ /** Token name (with `--`) to a resolved, plain value. */
+ tokens: Record<string, string>;
+ colorScheme: "light" | "dark";
+}
+
+export interface ReadEmbedThemeOptions {
+ /** The host token `--background` carries, when the embed sits on something else. */
+ background?: string;
+}
+
+/** The property each kind is resolved through, so the browser computes it. */
+const PROBE_PROPERTY: Record<Exclude<EmbedTokenKind, "keyword">, string> = {
+ color: "color",
+ length: "border-top-left-radius",
+ font: "font-family",
+};
+
+const PROBE_STYLE =
+ "position:absolute;width:0;height:0;overflow:hidden;visibility:hidden;pointer-events:none;contain:strict";
+
+export function colorSchemeOf(scheme: string | undefined): "light" | "dark" {
+ const value = scheme ?? "";
+ return /\bdark\b/.test(value) && !/\blight\b/.test(value) ? "dark" : "light";
+}
+
+/**
+ * Resolves the embed token contract where `host` sits, so a theme's scoped
+ * overrides apply. Each token is computed on a throwaway probe inside the host
+ * and read back as the browser resolved it: a colour, a length in px, a font
+ * stack. What is not plain after that (a `var()`, anything that could load a
+ * resource) is dropped, and so is a token the host does not define, so an
+ * author's own `var(--x, fallback)` still applies.
+ */
+export function readEmbedTheme(host: Element | null, { background }: ReadEmbedThemeOptions = {}): EmbedTheme {
+ if (!host || typeof getComputedStyle !== "function") return { tokens: {}, colorScheme: "light" };
+ const hostStyle = getComputedStyle(host);
+ const colorScheme = colorSchemeOf(hostStyle.colorScheme);
+ const dark = host.closest(".dark") !== null;
+ const doc = host.ownerDocument;
+ const probe = doc.createElement("div");
+ probe.setAttribute("aria-hidden", "true");
+ probe.style.cssText = PROBE_STYLE;
+
+ const pending: { name: string; element: HTMLElement; property: string }[] = [];
+ for (const token of EMBED_TOKENS) {
+ if (token.kind === "keyword") continue;
+ const from = token.name === "--background" && background ? background : null;
+ let source = from ? null : (dark && token.darkSource) || token.source;
+ if (!source) {
+ const name = from ?? token.name;
+ if (!hostStyle.getPropertyValue(name).trim()) continue;
+ source = `var(${name})`;
+ }
+ const element = doc.createElement("span");
+ const property = PROBE_PROPERTY[token.kind];
+ element.style.setProperty(property, source);
+ probe.appendChild(element);
+ pending.push({ name: token.name, element, property });
+ }
+
+ const tokens: Record<string, string> = {};
+ host.appendChild(probe);
+ try {
+ for (const { name, element, property } of pending) {
+ const value = getComputedStyle(element).getPropertyValue(property).trim();
+ if (isPlainEmbedValue(value)) tokens[name] = value;
+ }
+ } finally {
+ probe.remove();
+ }
+ tokens["--color-scheme"] = colorScheme;
+ return { tokens, colorScheme };
+}
diff --git a/packages/views/common/embed-tokens.test.ts b/packages/views/common/embed-tokens.test.ts
new file mode 100644
index 0000000000..201e6236ab
--- /dev/null
+++ b/packages/views/common/embed-tokens.test.ts
@@ -0,0 +1,94 @@
+import { readFileSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+import {
+ EMBED_TOKENS,
+ EMBED_TOKEN_GROUPS,
+ EMBED_TOKEN_NAMES,
+ THEME_VARIABLES,
+ embedTokenDeclarations,
+ isPlainEmbedValue,
+} from "@multica/core/appearance";
+
+/**
+ * EMBED_TOKENS is the public contract for plugin surfaces and HTML blocks.
+ * This keeps it resolvable and its reference in docs/theming.md generated.
+ * Run with UPDATE_THEME_DOCS=1 to rewrite the table.
+ */
+
+const REPO = join(__dirname, "../../..");
+const read = (path: string) => readFileSync(join(REPO, path), "utf8");
+const foundationCss = ["tokens.css", "appearance.css"].map((f) => read(`packages/ui/styles/${f}`)).join("\n");
+
+const START = "<!-- embed-tokens:start (generated by packages/views/common/embed-tokens.test.ts) -->";
+const END = "<!-- embed-tokens:end -->";
+
+const KIND_TEXT = { color: "colour", length: "length (px)", font: "font stack", keyword: "keyword" } as const;
+
+function referenceTables(): string {
+ const parts: string[] = [];
+ for (const [key, title] of Object.entries(EMBED_TOKEN_GROUPS)) {
+ parts.push(`### ${title}`, "", "| Token | Kind | Use |", "| --- | --- | --- |");
+ for (const token of EMBED_TOKENS.filter((t) => t.group === key)) {
+ parts.push(`| \`${token.name}\` | ${KIND_TEXT[token.kind]} | ${token.description.replace(/\|/g, "\\|")} |`);
+ }
+ parts.push("");
+ }
+ return parts.join("\n");
+}
+
+describe("embed tokens", () => {
+ it("has no duplicates", () => {
+ expect(EMBED_TOKEN_NAMES.size).toBe(EMBED_TOKENS.length);
+ });
+
+ it("keeps every token the plugin surfaces and HTML blocks had before", () => {
+ const before = [
+ "--background", "--foreground", "--surface", "--muted", "--muted-foreground", "--border", "--primary",
+ "--primary-foreground", "--secondary", "--secondary-foreground", "--accent", "--accent-foreground",
+ "--destructive", "--success", "--warning", "--info", "--brand", "--chart-1", "--chart-2", "--chart-3",
+ "--chart-4", "--chart-5", "--radius", "--text-caption", "--text-body", "--font-sans",
+ ];
+ expect(before.filter((name) => !EMBED_TOKEN_NAMES.has(name))).toEqual([]);
+ });
+
+ it("reads each token from something the app declares or a fallback", () => {
+ const unresolvable = EMBED_TOKENS.filter((t) => t.kind !== "keyword" && !t.source)
+ .filter((t) => !new RegExp(`${t.name}:\\s*[^;]+;`).test(foundationCss))
+ .map((t) => t.name);
+ expect(unresolvable).toEqual([]);
+ });
+
+ it("reads theme variables with the app's own fallbacks", () => {
+ for (const token of EMBED_TOKENS.filter((t) => t.group === "status" || t.group === "code")) {
+ const variable = THEME_VARIABLES.find((v) => `--${v.name}` === token.name)!;
+ expect(variable, token.name).toBeDefined();
+ if (variable.default) expect(token.source).toBe(`var(${token.name}, ${variable.default})`);
+ if (variable.darkDefault) expect(token.darkSource).toBe(`var(${token.name}, ${variable.darkDefault})`);
+ }
+ });
+
+ it("passes only plain values", () => {
+ for (const value of ["oklch(0.5 0.1 200)", "rgb(1 2 3 / 50%)", "12px", '"Inter Variable", system-ui, sans-serif', "dark"]) {
+ expect(isPlainEmbedValue(value), value).toBe(true);
+ }
+ for (const value of ["url(x.png)", "URL (x)", "image-set(a 1x)", "var(--x)", "red;}", "a</style>", "\\61", "/* */", "", "x".repeat(600)]) {
+ expect(isPlainEmbedValue(value), value).toBe(false);
+ }
+ expect(embedTokenDeclarations({ "--foreground": "red", "--evil": "blue", "--muted": "url(x)" })).toBe("--foreground:red");
+ });
+
+ it("keeps the reference in docs/theming.md generated", () => {
+ const docs = read("docs/theming.md");
+ const start = docs.indexOf(START);
+ const end = docs.indexOf(END);
+ expect(start, "docs/theming.md is missing the generated embed token markers").toBeGreaterThanOrEqual(0);
+ const expected = `${START}\n\n${referenceTables()}\n${END}`;
+ const current = docs.slice(start, end + END.length);
+ if (process.env.UPDATE_THEME_DOCS && current !== expected) {
+ writeFileSync(join(REPO, "docs/theming.md"), docs.slice(0, start) + expected + docs.slice(end + END.length));
+ return;
+ }
+ expect(current).toBe(expected);
+ });
+});
diff --git a/packages/views/editor/bubble-menu.tsx b/packages/views/editor/bubble-menu.tsx
index 8083ec5001..12d32fcdc0 100644
--- a/packages/views/editor/bubble-menu.tsx
+++ b/packages/views/editor/bubble-menu.tsx
@@ -612,6 +612,8 @@ function EditorBubbleMenu({
return (
<div
ref={floatingRef}
+ data-mc="editor-toolbar"
+ data-mode={mode === "link-edit" ? "link" : "format"}
style={{
position: "fixed",
zIndex: 50,
diff --git a/packages/views/editor/code-block-iframe.tsx b/packages/views/editor/code-block-iframe.tsx
index 259ba13e1c..50c21809f6 100644
--- a/packages/views/editor/code-block-iframe.tsx
+++ b/packages/views/editor/code-block-iframe.tsx
@@ -5,7 +5,8 @@
*
* Used by:
* - HtmlPreviewBody (the attachment viewer's html kind)
- * - CodeBlockView for fenced ```html blocks (editable Tiptap NodeView)
+ * - CodeBlockView for fenced ```html blocks (editable Tiptap NodeView),
+ * fed the same themed document as HtmlBlockPreview
* - HtmlBlockPreview for fenced ```html blocks (RichContent), which also
* listens to the size/error bridge in utils/html-block-document.ts
*
diff --git a/packages/views/editor/extensions/code-block-view.test.tsx b/packages/views/editor/extensions/code-block-view.test.tsx
index 1fe4ffe34f..05c7056199 100644
--- a/packages/views/editor/extensions/code-block-view.test.tsx
+++ b/packages/views/editor/extensions/code-block-view.test.tsx
@@ -28,6 +28,15 @@ vi.mock("@tiptap/react", () => {
return { NodeViewWrapper, NodeViewContent };
});
+// jsdom resolves no theme, so the embed theme reports a scheme the test sets.
+const embedScheme = vi.hoisted(() => ({ current: "light" as "light" | "dark" }));
+vi.mock("../../common/embed-theme", () => ({
+ readEmbedTheme: () => ({
+ tokens: { "--color-scheme": embedScheme.current },
+ colorScheme: embedScheme.current,
+ }),
+}));
+
vi.mock("../mermaid-diagram", () => ({
MermaidDiagram: () => null,
}));
@@ -92,6 +101,52 @@ describe("CodeBlockView — html language toggle", () => {
expect(pre?.className).toContain("sr-only");
});
+ it("gives the preview the embed tokens, like a read-only html block", () => {
+ render(
+ <CodeBlockView {...makeProps("html", '<p style="color: var(--foreground)">hi</p>')} />,
+ );
+ act(() => {
+ vi.advanceTimersByTime(250);
+ });
+ const srcdoc = document.querySelector("iframe")?.getAttribute("srcdoc") ?? "";
+ expect(srcdoc).toMatch(/^<style>:root\{[^}]*--color-scheme:light;color-scheme:light\}<\/style>/);
+ expect(srcdoc).toContain('<p style="color: var(--foreground)">hi</p>');
+ });
+
+ it("keeps the document of HTML that reads no token across a theme switch", async () => {
+ render(<CodeBlockView {...makeProps("html", '<input value="initial">')} />);
+ act(() => {
+ vi.advanceTimersByTime(250);
+ });
+ const frame = document.querySelector("iframe")!;
+ const before = frame.getAttribute("srcdoc");
+ expect(before).toMatch(/^<style>:root\{\}<\/style>/);
+
+ embedScheme.current = "dark";
+ document.documentElement.classList.add("dark");
+ await act(() => Promise.resolve());
+ expect(document.querySelector("iframe")).toBe(frame);
+ expect(frame.getAttribute("srcdoc")).toBe(before);
+ document.documentElement.classList.remove("dark");
+ embedScheme.current = "light";
+ });
+
+ it("rebuilds the document of HTML that reads a token when the theme switches", async () => {
+ render(<CodeBlockView {...makeProps("html", '<p style="color: var(--foreground)">hi</p>')} />);
+ act(() => {
+ vi.advanceTimersByTime(250);
+ });
+ const frame = document.querySelector("iframe")!;
+ expect(frame.getAttribute("srcdoc")).toContain("color-scheme:light");
+
+ embedScheme.current = "dark";
+ document.documentElement.classList.add("dark");
+ await act(() => Promise.resolve());
+ expect(frame.getAttribute("srcdoc")).toContain("color-scheme:dark");
+ document.documentElement.classList.remove("dark");
+ embedScheme.current = "light";
+ });
+
it("toggles to source view without unloading the preview or editor content", () => {
render(<CodeBlockView {...makeProps("html", "<p>hello</p>")} />);
act(() => {
@@ -129,7 +184,7 @@ describe("CodeBlockView — html language toggle", () => {
const frame = dialog.querySelector("iframe");
expect(frame).toBe(original);
expect(document.querySelectorAll("iframe")).toHaveLength(1);
- expect(frame?.getAttribute("srcdoc")).toBe("<p>latest</p>");
+ expect(frame?.getAttribute("srcdoc")).toContain("<p>latest</p>");
expect(frame?.getAttribute("sandbox")).toBe("allow-scripts");
expect(screen.getByTestId("nvc")).toBe(editorContent);
expect(document.querySelector("iframe")).toBe(original);
@@ -164,7 +219,7 @@ describe("CodeBlockView — html language toggle", () => {
fireEvent.click(screen.getByRole("button", { name: "Reload" }));
const inline = document.querySelector("iframe");
expect(inline).not.toBe(original);
- expect(inline?.getAttribute("srcdoc")).toBe("<p>hello</p>");
+ expect(inline?.getAttribute("srcdoc")).toContain("<p>hello</p>");
expect(screen.getByTestId("nvc")).toBe(content);
fireEvent.click(screen.getByRole("button", { name: "Show source" }));
@@ -193,23 +248,23 @@ describe("CodeBlockView — html language toggle", () => {
rerender(<CodeBlockView {...makeProps("html", "<p>pending</p>")} />);
fireEvent.click(screen.getByRole("button", { name: "Show source" }));
act(() => vi.advanceTimersByTime(250));
- expect(frame.getAttribute("srcdoc")).toBe("<p>initial</p>");
+ expect(frame.getAttribute("srcdoc")).toContain("<p>initial</p>");
rerender(<CodeBlockView {...makeProps("html", "<p>edited</p>")} />);
act(() => vi.advanceTimersByTime(250));
- expect(frame.getAttribute("srcdoc")).toBe("<p>initial</p>");
+ expect(frame.getAttribute("srcdoc")).toContain("<p>initial</p>");
fireEvent.click(screen.getByRole("button", { name: "Fullscreen" }));
act(() => vi.advanceTimersByTime(250));
- expect(frame.getAttribute("srcdoc")).toBe("<p>edited</p>");
+ expect(frame.getAttribute("srcdoc")).toContain("<p>edited</p>");
expect(screen.getByRole("dialog").querySelector("iframe")).toBe(frame);
fireEvent.click(screen.getByRole("button", { name: "Close" }));
rerender(<CodeBlockView {...makeProps("html", "<p>latest</p>")} />);
act(() => vi.advanceTimersByTime(250));
- expect(frame.getAttribute("srcdoc")).toBe("<p>edited</p>");
+ expect(frame.getAttribute("srcdoc")).toContain("<p>edited</p>");
fireEvent.click(screen.getByRole("button", { name: "Show preview" }));
act(() => vi.advanceTimersByTime(250));
- expect(frame.getAttribute("srcdoc")).toBe("<p>latest</p>");
+ expect(frame.getAttribute("srcdoc")).toContain("<p>latest</p>");
expect(document.querySelector("iframe")).toBe(frame);
expect(screen.getByTestId("nvc")).toBe(editorContent);
});
diff --git a/packages/views/editor/extensions/code-block-view.tsx b/packages/views/editor/extensions/code-block-view.tsx
index c750be8dfa..c08b13fa01 100644
--- a/packages/views/editor/extensions/code-block-view.tsx
+++ b/packages/views/editor/extensions/code-block-view.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useState } from "react";
+import { useEffect, useRef, useState } from "react";
import { NodeViewWrapper, NodeViewContent } from "@tiptap/react";
import type { NodeViewProps } from "@tiptap/react";
import { Code as CodeIcon, Copy, Check, Eye, Maximize2, RotateCw } from "@multica/ui/icons";
@@ -13,6 +13,15 @@ import { useDebouncedValue } from "../../common/use-debounced-value";
import { useT } from "../../i18n";
import { MermaidDiagram } from "../mermaid-diagram";
import { CodeBlockIframe } from "../code-block-iframe";
+import { useThemeVersion } from "../hooks/use-theme-version";
+import { readEmbedTheme } from "../../common/embed-theme";
+import {
+ HTML_BLOCK_EMBED_OPTIONS,
+ NO_HTML_BLOCK_THEME,
+ buildHtmlBlockDocument,
+ htmlBlockTheme,
+ mentionsThemeTokens,
+} from "../utils/html-block-document";
// Coalesces fast keystrokes before re-rendering live previews.
// `mermaid.initialize()` mutates a process-global config, so back-to-back
@@ -50,6 +59,24 @@ function CodeBlockView({ node }: NodeViewProps) {
PREVIEW_DEBOUNCE_MS,
showHtmlPreview || fullscreen,
);
+ // The same document a read-only ```html block gets, so the embed tokens
+ // resolve while the block is being edited too. HTML that names no token
+ // gets the same document under every theme: a new srcDoc reloads the frame
+ // and loses whatever was typed or toggled in it.
+ const previewRef = useRef<HTMLDivElement>(null);
+ const themeVersion = useThemeVersion();
+ const [srcDoc, setSrcDoc] = useState("");
+ useEffect(() => {
+ const host = previewRef.current;
+ if (!host || !debouncedHtml) {
+ setSrcDoc("");
+ return;
+ }
+ const theme = mentionsThemeTokens(debouncedHtml)
+ ? htmlBlockTheme(readEmbedTheme(host, HTML_BLOCK_EMBED_OPTIONS))
+ : NO_HTML_BLOCK_THEME;
+ setSrcDoc(buildHtmlBlockDocument(debouncedHtml, theme));
+ }, [debouncedHtml, themeVersion]);
const handleCopy = async () => {
const text = node.textContent;
@@ -78,6 +105,7 @@ function CodeBlockView({ node }: NodeViewProps) {
// unmounting either side would either lose ProseMirror bindings
// (source) or thrash iframe.srcDoc (preview).
<div
+ ref={previewRef}
contentEditable={false}
className={showHtmlPreview ? "mb-1" : undefined}
hidden={!showHtmlPreview && !fullscreen}
@@ -91,7 +119,7 @@ function CodeBlockView({ node }: NodeViewProps) {
>
<CodeBlockIframe
key={reloadKey}
- html={debouncedHtml}
+ html={srcDoc}
title={t(($) => $.code_block.html_preview)}
heightClassName={fullscreen ? "h-full" : "h-[480px]"}
className={fullscreen ? "rounded-none border-0" : undefined}
diff --git a/packages/views/editor/extensions/mention-suggestion.test.tsx b/packages/views/editor/extensions/mention-suggestion.test.tsx
index 1ea13332a4..7f3b5406d1 100644
--- a/packages/views/editor/extensions/mention-suggestion.test.tsx
+++ b/packages/views/editor/extensions/mention-suggestion.test.tsx
@@ -685,7 +685,7 @@ describe("createMentionSuggestion", () => {
.getByText("MUL-6956")
.closest("button")
?.querySelector("svg");
- expect(statusIcon).toHaveStyle({ color: "#f97316" });
+ expect(statusIcon?.style.color).toBe("var(--palette-orange, #f97316)");
});
it("does not inject current/recent chat context into the normal @ results", () => {
diff --git a/packages/views/editor/extensions/mention-suggestion.tsx b/packages/views/editor/extensions/mention-suggestion.tsx
index 54cbfeb0e2..a1e004648a 100644
--- a/packages/views/editor/extensions/mention-suggestion.tsx
+++ b/packages/views/editor/extensions/mention-suggestion.tsx
@@ -499,6 +499,8 @@ export const MentionList = forwardRef<MentionListRef, MentionListProps>(
// variant only differs in width / max-height / chrome.
return (
<div
+ data-mc="editor-menu"
+ data-kind="mention"
className={cn(
"flex flex-col overflow-y-auto overscroll-contain border bg-popover py-1",
// Height budget: clamp to whichever is smaller — the design max or the
diff --git a/packages/views/editor/extensions/slash-command-suggestion.tsx b/packages/views/editor/extensions/slash-command-suggestion.tsx
index 8b8eeb65ef..e169e580d9 100644
--- a/packages/views/editor/extensions/slash-command-suggestion.tsx
+++ b/packages/views/editor/extensions/slash-command-suggestion.tsx
@@ -138,7 +138,11 @@ export const SlashCommandList = forwardRef<
// `--suggestion-available-height` from suggestion-popup.tsx's size
// middleware), falling back to the design max when rendered standalone.
// Single height authority — mirrors MentionList.
- <div className="rounded-md border bg-popover py-1 shadow-md w-72 max-h-[min(300px,var(--suggestion-available-height,300px))] overflow-y-auto">
+ <div
+ data-mc="editor-menu"
+ data-kind="slash"
+ className="rounded-md border bg-popover py-1 shadow-md w-72 max-h-[min(300px,var(--suggestion-available-height,300px))] overflow-y-auto"
+ >
{items.map((item, index) => {
const description = describe(item);
return (
diff --git a/packages/views/editor/hooks/use-theme-version.test.ts b/packages/views/editor/hooks/use-theme-version.test.ts
new file mode 100644
index 0000000000..8e8c35c377
--- /dev/null
+++ b/packages/views/editor/hooks/use-theme-version.test.ts
@@ -0,0 +1,38 @@
+import { afterEach, describe, expect, it } from "vitest";
+import { act, renderHook } from "@testing-library/react";
+import { EMBED_TOKEN_INPUTS } from "@multica/core/appearance";
+import { useThemeVersion } from "./use-theme-version";
+
+const root = document.documentElement;
+const settle = () => act(() => Promise.resolve());
+
+afterEach(() => {
+ root.removeAttribute("style");
+});
+
+describe("useThemeVersion", () => {
+ it("watches the variables the radius tokens are resolved from", () => {
+ expect(EMBED_TOKEN_INPUTS).toEqual(
+ expect.arrayContaining(["--radius-card", "--card-radius", "--button-radius", "--input-radius", "--radius"]),
+ );
+ });
+
+ it("bumps when a theme option changes only a token's source", async () => {
+ root.style.setProperty("--card-radius", "8px");
+ const { result } = renderHook(() => useThemeVersion());
+ await settle();
+ root.style.setProperty("--card-radius", "16px");
+ await settle();
+ expect(result.current).toBe(1);
+ });
+
+ it("ignores a dialog's scroll lock on the same style attribute", async () => {
+ const { result } = renderHook(() => useThemeVersion());
+ await settle();
+ root.style.overflow = "hidden";
+ await settle();
+ root.style.removeProperty("overflow");
+ await settle();
+ expect(result.current).toBe(0);
+ });
+});
diff --git a/packages/views/editor/hooks/use-theme-version.ts b/packages/views/editor/hooks/use-theme-version.ts
index c0f0f0ec3a..cab1098706 100644
--- a/packages/views/editor/hooks/use-theme-version.ts
+++ b/packages/views/editor/hooks/use-theme-version.ts
@@ -1,10 +1,12 @@
import { useEffect, useState } from "react";
-import { HTML_BLOCK_THEME_TOKENS } from "../utils/html-block-document";
+import { EMBED_TOKEN_INPUTS } from "@multica/core/appearance";
/**
- * Everything that decides what a sandboxed block copies out of the theme: the
+ * Everything that decides what a sandboxed embed copies out of the theme: the
* attributes that pick a theme, and what it resolves to on the root. Tokens
- * are read resolved so a theme written straight into `style` still counts.
+ * are read resolved so a theme written straight into `style` still counts,
+ * and with the variables they are resolved from, which may be all a theme
+ * option changes.
*/
function readThemeSignature(): string {
const root = document.documentElement;
@@ -16,7 +18,7 @@ function readThemeSignature(): string {
document.body?.getAttribute("data-theme"),
styles.colorScheme,
styles.fontFamily,
- ...HTML_BLOCK_THEME_TOKENS.map((name) => styles.getPropertyValue(name)),
+ ...EMBED_TOKEN_INPUTS.map((name) => styles.getPropertyValue(name)),
].join("|");
}
diff --git a/packages/views/editor/html-block-preview.tsx b/packages/views/editor/html-block-preview.tsx
index d34a3a102a..b108a4c445 100644
--- a/packages/views/editor/html-block-preview.tsx
+++ b/packages/views/editor/html-block-preview.tsx
@@ -39,13 +39,15 @@ import {
type DynamicBlockError,
} from "./dynamic-block";
import { useThemeVersion } from "./hooks/use-theme-version";
+import { readEmbedTheme } from "../common/embed-theme";
import {
+ HTML_BLOCK_EMBED_OPTIONS,
HTML_BLOCK_MESSAGE_KEY,
INITIAL_HTML_BLOCK_HEIGHT,
buildHtmlBlockDocument,
+ htmlBlockTheme,
nextHtmlBlockHeight,
readHtmlBlockMessage,
- readHtmlBlockTheme,
} from "./utils/html-block-document";
import { hashSource } from "./utils/source-hash";
@@ -135,7 +137,7 @@ export function HtmlBlockPreview({ html, title }: HtmlBlockPreviewProps) {
const host = hostRef.current;
if (!host) return;
setError(null);
- setSrcDoc(buildHtmlBlockDocument(html, readHtmlBlockTheme(getComputedStyle(host))));
+ setSrcDoc(buildHtmlBlockDocument(html, htmlBlockTheme(readEmbedTheme(host, HTML_BLOCK_EMBED_OPTIONS))));
}, [html, themeVersion]);
return (
diff --git a/packages/views/editor/utils/html-block-document.test.ts b/packages/views/editor/utils/html-block-document.test.ts
index d47868617d..6b4468a86b 100644
--- a/packages/views/editor/utils/html-block-document.test.ts
+++ b/packages/views/editor/utils/html-block-document.test.ts
@@ -2,14 +2,16 @@
import { runInNewContext } from "node:vm";
import { describe, expect, it, vi } from "vitest";
import {
+ HTML_BLOCK_EMBED_OPTIONS,
HTML_BLOCK_MAX_CONTENT_PX,
HTML_BLOCK_MESSAGE_KEY,
INITIAL_HTML_BLOCK_HEIGHT,
__HTML_BLOCK_BRIDGE__,
buildHtmlBlockDocument,
+ htmlBlockTheme,
nextHtmlBlockHeight,
readHtmlBlockMessage,
- readHtmlBlockTheme,
+ mentionsThemeTokens,
usesThemeTokens,
} from "./html-block-document";
import { __FRAGMENT_NAV_SHIM__ } from "./iframe-fragment-nav";
@@ -84,47 +86,54 @@ describe("buildHtmlBlockDocument", () => {
});
});
+describe("mentionsThemeTokens", () => {
+ it("finds a token named in CSS or in a script", () => {
+ expect(mentionsThemeTokens("fill: var(--chart-2)")).toBe(true);
+ expect(mentionsThemeTokens("style.getPropertyValue('--foreground')")).toBe(true);
+ expect(mentionsThemeTokens('<input value="initial">')).toBe(false);
+ expect(mentionsThemeTokens("color: var(--chart-20)")).toBe(false);
+ });
+});
+
describe("usesThemeTokens", () => {
it("matches whole token names only", () => {
expect(usesThemeTokens("fill: var(--chart-2)")).toBe(true);
expect(usesThemeTokens("color: var( --muted-foreground )")).toBe(true);
expect(usesThemeTokens("font-family: var(--font-sans)")).toBe(true);
+ expect(usesThemeTokens("stroke: var(--status-done)")).toBe(true);
+ expect(usesThemeTokens("color: var(--code-keyword)")).toBe(true);
expect(usesThemeTokens("border-radius: var(--border-radius)")).toBe(false);
expect(usesThemeTokens("--foreground: red")).toBe(false);
});
});
-describe("readHtmlBlockTheme", () => {
- const styles = (values: Record<string, string>, fontFamily = "Inter, sans-serif", colorScheme = "light") => ({
- getPropertyValue: (name: string) => values[name] ?? "",
- fontFamily,
- colorScheme,
- });
+describe("htmlBlockTheme", () => {
+ const embed = (tokens: Record<string, string>, colorScheme: "light" | "dark" = "light") => ({ tokens, colorScheme });
- it("copies the defined tokens and the font, skipping undefined ones", () => {
- const theme = readHtmlBlockTheme(styles({ "--foreground": " oklch(0.2 0 0) ", "--chart-1": "blue" }));
- expect(theme.declarations).toBe(
- "--foreground:oklch(0.2 0 0);--chart-1:blue;--font-sans:Inter, sans-serif",
- );
+ it("declares the resolved tokens in contract order", () => {
+ const theme = htmlBlockTheme(embed({ "--chart-1": "blue", "--foreground": " oklch(0.2 0 0) ", "--font-sans": "Inter, sans-serif" }));
+ expect(theme.declarations).toBe("--foreground:oklch(0.2 0 0);--chart-1:blue;--font-sans:Inter, sans-serif");
});
- it("gives --background the block's surface color", () => {
- const theme = readHtmlBlockTheme(styles({ "--background": "gray", "--surface": "white" }));
- expect(theme.declarations).toContain("--background:white;--surface:white");
- expect(readHtmlBlockTheme(styles({ "--background": "gray" })).declarations).toContain(
- "--background:gray",
+ it("drops a value that could break out of the style rule or reach outside the frame", () => {
+ const theme = htmlBlockTheme(
+ embed({
+ "--foreground": "red}</style><script>",
+ "--muted": "url(https://evil.test/x)",
+ "--border": "var(--secret)",
+ "--brand": "blue",
+ "--not-in-the-contract": "red",
+ }),
);
+ expect(theme.declarations).toBe("--brand:blue");
});
- it("drops a value that could break out of the style rule", () => {
- const theme = readHtmlBlockTheme(styles({ "--foreground": "red}</style><script>" }));
- expect(theme.declarations).not.toContain("script");
+ it("passes the host's scheme through", () => {
+ expect(htmlBlockTheme(embed({}, "dark")).colorScheme).toBe("dark");
});
- it("reads dark only when the host is dark", () => {
- expect(readHtmlBlockTheme(styles({}, "", "dark")).colorScheme).toBe("dark");
- expect(readHtmlBlockTheme(styles({}, "", "light dark")).colorScheme).toBe("light");
- expect(readHtmlBlockTheme(styles({}, "", "normal")).colorScheme).toBe("light");
+ it("reads --background from the block's surface", () => {
+ expect(HTML_BLOCK_EMBED_OPTIONS.background).toBe("--surface");
});
});
diff --git a/packages/views/editor/utils/html-block-document.ts b/packages/views/editor/utils/html-block-document.ts
index 9bfac86b6e..ca4ccf809f 100644
--- a/packages/views/editor/utils/html-block-document.ts
+++ b/packages/views/editor/utils/html-block-document.ts
@@ -1,3 +1,5 @@
+import { EMBED_TOKENS, embedTokenDeclarations } from "@multica/core/appearance";
+import type { EmbedTheme } from "../../common/embed-theme";
import { withFragmentNavShim } from "./iframe-fragment-nav";
/**
@@ -11,9 +13,10 @@ import { withFragmentNavShim } from "./iframe-fragment-nav";
* first uncaught error. The parent treats both as untrusted input — it checks
* the message source and clamps every value (see readHtmlBlockMessage).
*
- * The prefix also carries the app's theme tokens as CSS custom properties, so
- * HTML written against `var(--foreground)` / `var(--chart-1)` follows light and
- * dark mode. Using a token is the opt-in: only then does the document also get
+ * The prefix also carries the app's theme tokens as CSS custom properties (the
+ * embed token contract, EMBED_TOKENS), so HTML written against
+ * `var(--foreground)` / `var(--chart-1)` follows the theme and light and dark
+ * mode. Using a token is the opt-in: only then does the document also get
* the app's `color-scheme`. That matters in dark mode, where a light document
* inside a dark page is painted on an opaque white canvas — right for HTML
* that was written for white, wrong for HTML that asked for the theme. HTML
@@ -23,36 +26,6 @@ import { withFragmentNavShim } from "./iframe-fragment-nav";
/** Marker on every bridge message; anything without it is ignored. */
export const HTML_BLOCK_MESSAGE_KEY = "__multicaHtmlBlock";
-/**
- * Theme tokens copied into the sandbox. Only color and shape tokens: a chart
- * needs these to match the page, and every one resolves to a plain value.
- */
-export const HTML_BLOCK_THEME_TOKENS = [
- "--background",
- "--foreground",
- "--surface",
- "--muted",
- "--muted-foreground",
- "--border",
- "--primary",
- "--primary-foreground",
- "--secondary",
- "--secondary-foreground",
- "--accent",
- "--accent-foreground",
- "--destructive",
- "--success",
- "--warning",
- "--info",
- "--brand",
- "--chart-1",
- "--chart-2",
- "--chart-3",
- "--chart-4",
- "--chart-5",
- "--radius",
-] as const;
-
// The bridge is one line on purpose: it sits on the author's first line, so a
// script error's line number still points at the author's own source.
//
@@ -99,48 +72,25 @@ const DOCTYPE_RE = /^\s*<!doctype[^>]*>/i;
* The host's theme as the sandbox receives it.
*/
export interface HtmlBlockTheme {
- /** `:root` declarations for the theme tokens (and `--font-sans`). */
+ /** `:root` declarations for the theme tokens. */
declarations: string;
colorScheme: "light" | "dark";
}
-// A value that could close the <style> element or the rule is dropped. Token
-// values come from the app's own stylesheet, so this is a backstop only.
-const UNSAFE_CSS_VALUE = /[<>{};]/;
+/** Read the host's tokens with `readEmbedTheme(host, HTML_BLOCK_EMBED_OPTIONS)`. */
+export const HTML_BLOCK_EMBED_OPTIONS = {
+ // Inside a block the page is the block: a document that paints
+ // `var(--background)` sits flush in its frame instead of showing a slightly
+ // different panel.
+ background: "--surface",
+} as const;
-/**
- * Reads the theme from the host's computed style. Tokens the host does not
- * define are skipped rather than emitted empty, so an author's own fallback in
- * `var(--x, fallback)` still applies.
- *
- * Inside a block the page is the block, so `--background` carries the block's
- * surface color: a document that paints `var(--background)` sits flush in its
- * frame instead of showing a slightly different panel.
- */
-export function readHtmlBlockTheme(
- styles: Pick<CSSStyleDeclaration, "getPropertyValue" | "fontFamily" | "colorScheme">,
-): HtmlBlockTheme {
- const declarations: string[] = [];
- for (const name of HTML_BLOCK_THEME_TOKENS) {
- const value = (
- (name === "--background" && styles.getPropertyValue("--surface")) ||
- styles.getPropertyValue(name)
- ).trim();
- if (value && !UNSAFE_CSS_VALUE.test(value)) declarations.push(`${name}:${value}`);
- }
- const fontFamily = styles.fontFamily.trim();
- if (fontFamily && !UNSAFE_CSS_VALUE.test(fontFamily)) {
- declarations.push(`--font-sans:${fontFamily}`);
- }
- const scheme = styles.colorScheme ?? "";
- return {
- declarations: declarations.join(";"),
- colorScheme: /\bdark\b/.test(scheme) && !/\blight\b/.test(scheme) ? "dark" : "light",
- };
+export function htmlBlockTheme({ tokens, colorScheme }: EmbedTheme): HtmlBlockTheme {
+ return { declarations: embedTokenDeclarations(tokens), colorScheme };
}
const THEME_TOKEN_USE = new RegExp(
- `var\\(\\s*(?:${[...HTML_BLOCK_THEME_TOKENS, "--font-sans"].join("|")})(?![\\w-])`,
+ `var\\(\\s*(?:${EMBED_TOKENS.map((token) => token.name).join("|")})(?![\\w-])`,
);
/** Whether the HTML reads any theme token, which opts it into the app's scheme. */
@@ -148,6 +98,21 @@ export function usesThemeTokens(html: string): boolean {
return THEME_TOKEN_USE.test(html);
}
+const THEME_TOKEN_MENTION = new RegExp(
+ `(?:${EMBED_TOKENS.map((token) => token.name).join("|")})(?![\\w-])`,
+);
+
+/**
+ * Whether the HTML names a theme token anywhere, in CSS or in a script's
+ * `getPropertyValue`. HTML that names none cannot read the theme.
+ */
+export function mentionsThemeTokens(html: string): boolean {
+ return THEME_TOKEN_MENTION.test(html);
+}
+
+/** The theme for a document that reads none of it. */
+export const NO_HTML_BLOCK_THEME: HtmlBlockTheme = { declarations: "", colorScheme: "light" };
+
/**
* The srcdoc for a ```html block: theme tokens and the bridge in front of the
* author's markup (after a leading doctype, which must stay first), and the
diff --git a/packages/views/issues/components/board-card.tsx b/packages/views/issues/components/board-card.tsx
index 00c7e07776..a11257842a 100644
--- a/packages/views/issues/components/board-card.tsx
+++ b/packages/views/issues/components/board-card.tsx
@@ -206,7 +206,7 @@ export const BoardCardContent = memo(function BoardCardContent({
data-status={issue.status}
data-priority={issue.priority}
data-assignee-type={issue.assignee_type ?? "none"}
- className="rounded-board-card border-[0.5px] border-board-card-border bg-board-card py-3 px-2.5 shadow-[var(--board-card-shadow,var(--surface-shadow))] transition-colors group-hover/card:border-foreground/15 group-hover/card:bg-board-card-hover group-data-[popup-open]/card:border-foreground/15 group-data-[popup-open]/card:bg-board-card-hover group-data-[peeked]/card:ring-2 group-data-[peeked]/card:ring-brand/50">
+ className="rounded-board-card border-[0.5px] border-board-card-border bg-board-card py-[var(--board-card-padding-y,var(--space-sm,0.75rem))] px-[var(--board-card-padding-x,0.625rem)] shadow-[var(--board-card-shadow,var(--surface-shadow))] transition-colors group-hover/card:border-foreground/15 group-hover/card:bg-board-card-hover group-data-[popup-open]/card:border-foreground/15 group-data-[popup-open]/card:bg-board-card-hover group-data-[peeked]/card:ring-2 group-data-[peeked]/card:ring-brand/50">
{/* Row 1: priority + identifier (left), agent activity + assignee (right) */}
<div className="flex items-center justify-between gap-2">
<div className="flex items-center gap-1.5 min-w-0">
diff --git a/packages/views/issues/components/board-column.tsx b/packages/views/issues/components/board-column.tsx
index aef4daf6a3..4915017e7b 100644
--- a/packages/views/issues/components/board-column.tsx
+++ b/packages/views/issues/components/board-column.tsx
@@ -36,6 +36,7 @@ import { VirtuosoSeed } from "../../common/virtuoso-seed";
import { useBoardWorkflow } from "./board-workflow-context";
import { ColumnHandoff } from "../../workflows/column-handoff";
import type { IssueCreateDefaults } from "../surface/types";
+import { paletteColor } from "@multica/core/appearance";
// Insertion-position prediction intentionally omitted. The server's
// ORDER BY uses PostgreSQL's en_US.utf8 collation (glibc), which
@@ -183,10 +184,10 @@ export const BoardColumn = memo(function BoardColumn({
const computeItemKey = (_index: number, issue: Issue) => issue.id;
const itemContent = (index: number, issue: Issue) => (
- // pt-2 on every card but the first reproduces the previous `space-y-2`
+ // Top padding on every card but the first reproduces the previous `space-y-2`
// gap; padding (not margin) is inside Virtuoso's measured item box so its
// height math stays correct.
- <div className={index === 0 ? undefined : "pt-2"}>
+ <div className={index === 0 ? undefined : "pt-[var(--board-card-gap,var(--space-xs,0.5rem))]"}>
<DraggableBoardCard
issue={issue}
childProgress={childProgressMap?.get(issue.id)}
@@ -420,7 +421,7 @@ function BoardGroupHeading({
<div className="flex min-w-0 items-center gap-2">
<span
className="size-2.5 shrink-0 rounded-full bg-muted-foreground/30"
- style={group.propertyOptionColor ? { backgroundColor: group.propertyOptionColor } : undefined}
+ style={group.propertyOptionColor ? { backgroundColor: paletteColor(group.propertyOptionColor) } : undefined}
/>
<TruncatedTooltip content={group.title}>
<span className="truncate text-body font-medium">
diff --git a/packages/views/issues/components/filter-chips-bar.tsx b/packages/views/issues/components/filter-chips-bar.tsx
index dbbd57410b..150f12c051 100644
--- a/packages/views/issues/components/filter-chips-bar.tsx
+++ b/packages/views/issues/components/filter-chips-bar.tsx
@@ -53,6 +53,7 @@ import { PriorityIcon } from "./priority-icon";
import { ActorAvatar } from "../../common/actor-avatar";
import { useProjectStatusLabels } from "../../projects/components/labels";
import { useT } from "../../i18n";
+import { paletteColor } from "@multica/core/appearance";
/** One rendered chip: a dimension with its selected values summarised. */
export interface FilterChip {
@@ -194,7 +195,7 @@ function DotStack({ colors }: { colors: string[] }) {
<span
key={i}
className="size-2.5 rounded-full"
- style={{ backgroundColor: color }}
+ style={{ backgroundColor: paletteColor(color) }}
/>
))}
</IconStack>
diff --git a/packages/views/issues/components/filter-field-options.tsx b/packages/views/issues/components/filter-field-options.tsx
index 3eb74e825f..01d7edb30c 100644
--- a/packages/views/issues/components/filter-field-options.tsx
+++ b/packages/views/issues/components/filter-field-options.tsx
@@ -41,6 +41,7 @@ import { ActorAvatar } from "../../common/actor-avatar";
import { ProjectIcon } from "../../projects/components/project-icon";
import { StatusIcon } from "./status-icon";
import { PriorityIcon } from "./priority-icon";
+import { paletteColor } from "@multica/core/appearance";
export const FILTER_FIELD_ICONS: Record<NegatableFilterDimension, IconComponent> = {
status: CircleDot,
@@ -224,7 +225,7 @@ export function useFilterValueCatalog(
label: labels.map((l) => ({
value: l.id,
label: l.name,
- icon: <span className="size-2 rounded-full" style={{ backgroundColor: l.color }} />,
+ icon: <span className="size-2 rounded-full" style={{ backgroundColor: paletteColor(l.color) }} />,
})),
relation: ISSUE_RELATION_FILTERS.map((relation) => {
const Icon = RELATION_ICONS[relation];
diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsx
index 36bf2b71f8..fb10d24103 100644
--- a/packages/views/issues/components/issue-detail.test.tsx
+++ b/packages/views/issues/components/issue-detail.test.tsx
@@ -2618,7 +2618,7 @@ describe("IssueDetail (shared)", () => {
screen.getByText(/from In Review to Awaiting Response/i),
).toBeInTheDocument();
});
- expect(statusChangeIcon("Awaiting Response").style.color).toBe("rgb(255, 0, 0)");
+ expect(statusChangeIcon("Awaiting Response").style.color).toBe("var(--palette-red, #ff0000)");
});
it("leaves a built-in status-change activity on its semantic token colour", async () => {
diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsx
index 110afda93b..80de2819e9 100644
--- a/packages/views/issues/components/issue-detail.tsx
+++ b/packages/views/issues/components/issue-detail.tsx
@@ -1428,7 +1428,7 @@ export function IssueDetailSkeleton({
{/* Width and gutters match the loaded column exactly (see its
comment), so the skeleton doesn't reflow sideways when real
content mounts. */}
- <div className={cn(READING_COLUMN, "px-3 py-6 space-y-6 md:px-8 md:py-8")}>
+ <div className={cn(READING_COLUMN, "px-[var(--space-sm,0.75rem)] py-[var(--space-lg,1.5rem)] space-y-6 md:px-[var(--space-xl,2rem)] md:py-[var(--space-xl,2rem)]")}>
<Skeleton className="h-8 w-3/4" />
<div className="space-y-2">
<Skeleton className="h-4 w-full" />
@@ -3497,7 +3497,13 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
const detailContent = (
<CurrentIssueRenderContextProvider value={currentIssueRenderContext}>
- <div className="relative flex h-full min-w-0 flex-1 flex-col">
+ <div
+ data-mc="issue-detail"
+ data-status={issue.status}
+ data-priority={issue.priority}
+ data-view={isPeek ? "peek" : "page"}
+ className="relative flex h-full min-w-0 flex-1 flex-col"
+ >
{/* In-page find bar — floats over the top-right of the content column
(below the breadcrumb header), outside the scroll container so it
stays put while the timeline scrolls and its own text isn't walked.
@@ -3623,7 +3629,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
// and never reaches the chat launcher's corner (see IssuePeekHost).
isPeek
? "mx-auto w-full px-6 py-5"
- : cn(READING_COLUMN, "px-3 py-6 max-md:pb-chat-launcher md:px-8 md:py-8"),
+ : cn(READING_COLUMN, "px-[var(--space-sm,0.75rem)] py-[var(--space-lg,1.5rem)] max-md:pb-chat-launcher md:px-[var(--space-xl,2rem)] md:py-[var(--space-xl,2rem)]"),
)}
>
<IssueDuplicateBanner
@@ -3636,6 +3642,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
}
/>
<div id={descriptionSectionId}>
+ <div data-mc="issue-title">
{titleLazy.active && (
<div className={titleLazy.ready ? undefined : "hidden"}>
<TitleEditor
@@ -3690,6 +3697,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
{issue.title}
</div>
)}
+ </div>
{titleConflictDraft !== null ? (
<RevisionConflictCompare
className="mt-2"
@@ -4004,7 +4012,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
<div className="my-8 border-t" />
{/* Activity / Comments */}
- <div data-comment-images={commentImageLayout}>
+ <div data-mc="issue-activity" data-comment-images={commentImageLayout}>
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<h2 className="text-title-sm font-semibold">{t(($) => $.detail.activity_section)}</h2>
diff --git a/packages/views/issues/components/issue-sidebar-settings.tsx b/packages/views/issues/components/issue-sidebar-settings.tsx
index e9ba0817c0..a9237d0edb 100644
--- a/packages/views/issues/components/issue-sidebar-settings.tsx
+++ b/packages/views/issues/components/issue-sidebar-settings.tsx
@@ -105,7 +105,7 @@ export function IssueSidebarSections({
);
return (
- <div ref={containerRef} className="relative">
+ <div ref={containerRef} data-mc="issue-properties" className="relative">
<IssueSidebarSettings
available={available}
getEmptySections={getEmptySections}
diff --git a/packages/views/issues/components/pickers/custom-property-picker.tsx b/packages/views/issues/components/pickers/custom-property-picker.tsx
index 9f1f7c2c56..302f73ba86 100644
--- a/packages/views/issues/components/pickers/custom-property-picker.tsx
+++ b/packages/views/issues/components/pickers/custom-property-picker.tsx
@@ -26,6 +26,7 @@ import { useLocale, useT } from "../../../i18n";
import { matchesPinyin } from "../../../editor/extensions/pinyin-match";
import { PropertyPicker, PickerItem, PickerEmpty } from "./property-picker";
import { ActorPropertyPicker, ActorPropertyDisplay } from "./actor-property-picker";
+import { paletteColor } from "@multica/core/appearance";
const EDITABLE_PROPERTY_TYPES = [
"select",
@@ -238,7 +239,7 @@ export function CustomPropertyValueInput({
setOpen(false);
}}
>
- <span className="size-2.5 shrink-0 rounded-full" style={{ backgroundColor: option.color }} />
+ <span className="size-2.5 shrink-0 rounded-full" style={{ backgroundColor: paletteColor(option.color) }} />
<span className="truncate">{option.name}</span>
</PickerItem>
))}
@@ -274,7 +275,7 @@ export function CustomPropertyValueInput({
disabled={atCapacity && !selected.includes(option.id)}
onClick={() => toggle(option.id)}
>
- <span className="size-2.5 shrink-0 rounded-full" style={{ backgroundColor: option.color }} />
+ <span className="size-2.5 shrink-0 rounded-full" style={{ backgroundColor: paletteColor(option.color) }} />
<span className="truncate">{option.name}</span>
</PickerItem>
))}
@@ -688,7 +689,7 @@ export function CustomPropertyValueDisplay({
}
return (
<span className="flex min-w-0 items-center gap-1.5">
- <span className="size-2.5 shrink-0 rounded-full" style={{ backgroundColor: option.color }} />
+ <span className="size-2.5 shrink-0 rounded-full" style={{ backgroundColor: paletteColor(option.color) }} />
<span className="truncate">{option.name}</span>
</span>
);
@@ -710,7 +711,7 @@ export function CustomPropertyValueDisplay({
key={option.id}
className="inline-flex max-w-32 items-center gap-1 rounded-full border border-surface-border px-1.5 py-px text-micro"
>
- <span className="size-2 shrink-0 rounded-full" style={{ backgroundColor: option.color }} />
+ <span className="size-2 shrink-0 rounded-full" style={{ backgroundColor: paletteColor(option.color) }} />
<span className="truncate">{option.name}</span>
</span>
))}
diff --git a/packages/views/issues/components/pickers/label-picker.tsx b/packages/views/issues/components/pickers/label-picker.tsx
index b2709da068..c0f9caa26d 100644
--- a/packages/views/issues/components/pickers/label-picker.tsx
+++ b/packages/views/issues/components/pickers/label-picker.tsx
@@ -26,6 +26,7 @@ import {
PickerEmpty,
} from "./property-picker";
import { useT } from "../../../i18n";
+import { paletteColor } from "@multica/core/appearance";
interface LabelPickerProps {
/**
@@ -306,7 +307,7 @@ export function LabelPicker({
>
<span
className="inline-block h-3 w-3 shrink-0 rounded-full"
- style={{ backgroundColor: label.color }}
+ style={{ backgroundColor: paletteColor(label.color) }}
aria-hidden
/>
<span className="truncate">{label.name}</span>
@@ -322,7 +323,7 @@ export function LabelPicker({
</span>
<span
className="ml-auto inline-block h-3 w-3 shrink-0 rounded-full"
- style={{ backgroundColor: pickInlineColor(query) }}
+ style={{ backgroundColor: paletteColor(pickInlineColor(query)) }}
aria-hidden
/>
</PickerItem>
diff --git a/packages/views/issues/components/pickers/status-picker.test.tsx b/packages/views/issues/components/pickers/status-picker.test.tsx
index 1ad8be9c58..c1b47a4fd8 100644
--- a/packages/views/issues/components/pickers/status-picker.test.tsx
+++ b/packages/views/issues/components/pickers/status-picker.test.tsx
@@ -126,7 +126,7 @@ describe("StatusPicker trigger color", () => {
const trigger = iconOf(container);
const row = iconOf(optionRow("QA"));
- expect(trigger?.style.color).toBe("rgb(236, 122, 45)");
+ expect(trigger?.style.color).toBe("var(--palette-orange, #ec7a2d)");
expect(row?.style.color).toBe(trigger?.style.color);
expect(trigger?.querySelector("line")).not.toBeNull();
expect(row?.innerHTML).toBe(trigger?.innerHTML);
diff --git a/packages/views/issues/components/property-filter-options.tsx b/packages/views/issues/components/property-filter-options.tsx
index 55921c1be4..c02aa78e2e 100644
--- a/packages/views/issues/components/property-filter-options.tsx
+++ b/packages/views/issues/components/property-filter-options.tsx
@@ -26,6 +26,7 @@ import { FILTER_ITEM_CLASS, HoverCheck } from "../../common/hover-check";
import { useT } from "../../i18n";
import type { ActorFilterValue } from "@multica/core/issues/stores/view-store";
import { NO_PROPERTY_VALUE } from "../utils/filter";
+import { paletteColor } from "@multica/core/appearance";
/**
* Names one property filter value the way chips and advanced conditions show
@@ -385,7 +386,7 @@ export function PropertyFilterOptions({
{option.color && (
<span
className="size-2.5 shrink-0 rounded-full"
- style={{ backgroundColor: option.color }}
+ style={{ backgroundColor: paletteColor(option.color) }}
/>
)}
<span className="truncate">{option.name}</span>
diff --git a/packages/views/issues/components/status-icon.test.tsx b/packages/views/issues/components/status-icon.test.tsx
index affbf1661e..1fd6f7b864 100644
--- a/packages/views/issues/components/status-icon.test.tsx
+++ b/packages/views/issues/components/status-icon.test.tsx
@@ -14,7 +14,21 @@ describe("issue icons", () => {
const geometry = container.querySelector("svg")!.innerHTML;
rerender(<StatusIcon status="qa" category="closed" color="#123456" icon={icon} />);
expect(container.querySelector("svg")!.innerHTML).toBe(geometry);
- expect(container.querySelector("svg")).toHaveStyle({ color: "#123456" });
+ expect(container.querySelector("svg")!.style.color).toBe("var(--palette-blue, #123456)");
+ });
+
+ it("names a custom colour's slot so a theme can recolour it", () => {
+ const { container, rerender } = render(<StatusIcon status="qa" category="started" color="#ef4444" />);
+ const svg = container.querySelector("svg")!;
+ expect(svg).toHaveAttribute("data-color", "#ef4444");
+ expect(svg).toHaveAttribute("data-palette", "red");
+ expect(svg.style.color).toBe("var(--palette-red, #ef4444)");
+ rerender(<StatusIcon status="qa" category="started" color="#ef4444" inheritColor />);
+ expect(svg).toHaveAttribute("data-palette", "red");
+ expect(svg.style.color).toBe("");
+ rerender(<StatusIcon status="done" color="#ef4444" />);
+ expect(svg).not.toHaveAttribute("data-color");
+ expect(svg).not.toHaveAttribute("data-palette");
});
it("keeps built-in geometry and token color locked", () => {
diff --git a/packages/views/issues/components/status-icon.tsx b/packages/views/issues/components/status-icon.tsx
index 867ef9e5e8..50268d0157 100644
--- a/packages/views/issues/components/status-icon.tsx
+++ b/packages/views/issues/components/status-icon.tsx
@@ -7,6 +7,7 @@ import type {
IssueStatusIcon,
} from "@multica/core/types";
import { STATUS_CONFIG } from "@multica/core/issues/config";
+import { paletteColor, paletteSlot } from "@multica/core/appearance";
// Geometry constants (viewBox 0 0 14 14, center 7,7)
@@ -212,13 +213,16 @@ export function StatusIcon({
// A custom color wins over the category's token, but only when the caller
// isn't already forcing the glyph to inherit (selected rows, dark chips).
const useCustomColor = !builtIn && !inheritColor && Boolean(color);
+ const customColor = !builtIn && color ? color : undefined;
return (
<svg
data-mc="status-icon"
+ data-color={customColor}
+ data-palette={customColor ? (paletteSlot(customColor) ?? undefined) : undefined}
viewBox="0 0 14 14"
fill="none"
- style={useCustomColor ? { color: color ?? undefined } : undefined}
+ style={useCustomColor ? { color: paletteColor(color) } : undefined}
className={`${className} ${
inheritColor || useCustomColor
? ""
diff --git a/packages/views/labels/label-chip.test.tsx b/packages/views/labels/label-chip.test.tsx
index 8a6a33d71c..66e049ad7c 100644
--- a/packages/views/labels/label-chip.test.tsx
+++ b/packages/views/labels/label-chip.test.tsx
@@ -12,18 +12,26 @@ describe("LabelChip", () => {
it("paints from --label-color, not an inline background, so themes can restyle it", () => {
const el = chip(renderWithI18n(<LabelChip label={label("#8b5cf6")} />).container);
- expect(el.style.getPropertyValue("--label-color")).toBe("#8b5cf6");
+ expect(el.style.getPropertyValue("--label-color")).toBe("var(--palette-purple, #8b5cf6)");
expect(el.style.backgroundColor).toBe("");
expect(el.className).toContain("bg-(--label-color)");
expect(el).toHaveAttribute("data-color", "#8b5cf6");
});
- it("sets a readable text colour as --label-foreground", () => {
+ it("paints through its colour slot, falling back to the colour as picked", () => {
+ const el = chip(renderWithI18n(<LabelChip label={label("#ef4444")} />).container);
+
+ expect(el).toHaveAttribute("data-palette", "red");
+ expect(el.style.getPropertyValue("--label-color")).toBe("var(--palette-red, #ef4444)");
+ });
+
+ it("sets a readable text colour as --label-foreground, which --label-chip-color overrides", () => {
const dark = chip(renderWithI18n(<LabelChip label={label("#1e3a8a")} />).container);
const light = chip(renderWithI18n(<LabelChip label={label("#fde68a")} />).container);
- expect(dark.style.getPropertyValue("--label-foreground")).toBe("#f9fafb");
- expect(light.style.getPropertyValue("--label-foreground")).toBe("#111827");
+ expect(dark.style.getPropertyValue("--label-foreground")).toBe("var(--label-chip-color, #f9fafb)");
+ expect(light.style.getPropertyValue("--label-foreground")).toBe("var(--label-chip-color, #111827)");
+ expect(light).toHaveAttribute("data-palette", "yellow");
expect(dark.style.color).toBe("");
expect(dark.className).toContain("text-(--label-foreground)");
});
diff --git a/packages/views/labels/label-chip.tsx b/packages/views/labels/label-chip.tsx
index 245281a2a2..d69abf0f00 100644
--- a/packages/views/labels/label-chip.tsx
+++ b/packages/views/labels/label-chip.tsx
@@ -2,41 +2,12 @@
import type { CSSProperties } from "react";
import type { Label } from "@multica/core/types";
+import { labelTextColor, paletteColor, paletteSlot } from "@multica/core/appearance";
import { X } from "@multica/ui/icons";
import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";
import { useT } from "../i18n";
import { TruncatedTooltip } from "@multica/ui/components/common/truncated-tooltip";
-/**
- * Map a label's `#rrggbb` color to a readable text color.
- *
- * Uses the ITU-R BT.601 perceived-luminance formula: colors above the
- * threshold get dark text (#111827), colors below get light text (#f9fafb).
- * This works for both pastel and saturated palettes without a hard lookup
- * table.
- *
- * The malformed-hex fallback returns dark-on-default which is readable on
- * the default `--label-color` rendering path — better than pure black
- * which disappears on dark chips.
- *
- * SECURITY INVARIANT: `LabelChip` sets the color as the `--label-color`
- * custom property and paints with `var(--label-color)`, trusting the backend's
- * color format. The backend's `normalizeColor` regex pins the value to
- * `^#?[0-9a-fA-F]{6}$`. A custom property is substituted wherever a theme's
- * CSS reads it, not only in this chip's background, so if that regex ever
- * loosens (named colors, `url(...)`, etc.) this becomes an injection vector
- * into every rule that uses the variable.
- */
-function contrastTextColor(hex: string): string {
- const h = hex.replace("#", "");
- if (h.length !== 6) return "#111827";
- const r = parseInt(h.slice(0, 2), 16) / 255;
- const g = parseInt(h.slice(2, 4), 16) / 255;
- const b = parseInt(h.slice(4, 6), 16) / 255;
- const luminance = 0.299 * r + 0.587 * g + 0.114 * b;
- return luminance > 0.55 ? "#111827" : "#f9fafb";
-}
-
interface LabelChipProps {
label: Label;
onRemove?: () => void;
@@ -54,16 +25,26 @@ interface LabelChipProps {
* Renders a single label as a colored pill. If `onRemove` is provided, shows
* an × button that calls it. Used in the issue-detail sidebar, the picker,
* and the management dialog.
+ *
+ * SECURITY INVARIANT: `LabelChip` sets the color as the `--label-color`
+ * custom property (`paletteColor` passes anything that is not a hex through)
+ * and paints with `var(--label-color)`, trusting the backend's color format.
+ * The backend's `normalizeColor` regex pins the value to
+ * `^#?[0-9a-fA-F]{6}$`. A custom property is substituted wherever a theme's
+ * CSS reads it, not only in this chip's background, so if that regex ever
+ * loosens (named colors, `url(...)`, etc.) this becomes an injection vector
+ * into every rule that uses the variable.
*/
export function LabelChip({ label, onRemove, className, fullName }: LabelChipProps) {
const { t } = useT("labels");
- const textColor = contrastTextColor(label.color);
+ const textColor = labelTextColor(label.color);
const nameClass = fullName ? "break-all" : "truncate max-w-[12rem]";
return (
<span
data-slot="label-chip"
data-mc="label-chip"
data-color={label.color}
+ data-palette={paletteSlot(label.color) ?? undefined}
// `min-w-0` lets the chip shrink when it is a flex item in a width-capped
// container (the create toolbar's label pill). Without it the chip keeps
// its content width and the parent clips it mid-shape; with it the inner
@@ -71,7 +52,12 @@ export function LabelChip({ label, onRemove, className, fullName }: LabelChipPro
// Custom properties rather than inline colors, so a theme can restyle the
// chip from `var(--label-color)` without `!important`.
className={`inline-flex min-w-0 items-center gap-1 rounded-label bg-(--label-color) px-2 py-0.5 text-caption font-medium text-(--label-foreground) ${className ?? ""}`}
- style={{ "--label-color": label.color, "--label-foreground": textColor } as CSSProperties}
+ style={
+ {
+ "--label-color": paletteColor(label.color),
+ "--label-foreground": `var(--label-chip-color, ${textColor})`,
+ } as CSSProperties
+ }
// aria-label exposes the full name to screen readers when the span
// visually truncates; sighted users get it from the hover tooltip,
// which only opens when the name is actually cut off.
diff --git a/packages/views/labels/label-manager.tsx b/packages/views/labels/label-manager.tsx
index ba6c5b2d27..afbae9ac07 100644
--- a/packages/views/labels/label-manager.tsx
+++ b/packages/views/labels/label-manager.tsx
@@ -43,6 +43,7 @@ import {
} from "@multica/ui/components/ui/dropdown-menu";
import { ColorPicker, COLOR_PICKER_PRESETS } from "../common/color-picker";
import { useLocale, useT } from "../i18n";
+import { paletteColor } from "@multica/core/appearance";
/**
* Label catalogs a user can manage. Narrower than `LabelResourceType`:
@@ -144,7 +145,7 @@ export function LabelManager({ scope }: { scope: LabelScope }) {
<div className="flex min-w-0 items-center gap-3">
<span
className="size-2.5 shrink-0 rounded-full"
- style={{ backgroundColor: label.color }}
+ style={{ backgroundColor: paletteColor(label.color) }}
/>
<span className="truncate text-body font-medium">{label.name}</span>
</div>
diff --git a/packages/views/layout/list-column.test.tsx b/packages/views/layout/list-column.test.tsx
index 7bde55749a..58707be69b 100644
--- a/packages/views/layout/list-column.test.tsx
+++ b/packages/views/layout/list-column.test.tsx
@@ -15,6 +15,9 @@ function Reader() {
return null;
}
+/** No stored width: the theme's, or 240px when it sets none. */
+const UNSTORED_SIDEBAR_WIDTH = "clamp(200px, var(--sidebar-panel-width, 240px), 320px)";
+
describe("ListColumn", () => {
it("collapses the list column from its edge, like the space panel", () => {
const { container } = renderWithI18n(
@@ -61,7 +64,7 @@ describe("ListColumn", () => {
expect(localStorage.getItem("list_column_width")).toBe("480");
expect(localStorage.getItem("sidebar_width")).toBeNull();
expect(wrapper.style.getPropertyValue("--list-column-width")).toBe("480px");
- expect(wrapper.style.getPropertyValue("--sidebar-width")).toBe("240px");
+ expect(wrapper.style.getPropertyValue("--sidebar-width")).toBe(UNSTORED_SIDEBAR_WIDTH);
});
it("restores a stored list width within its bounds", () => {
diff --git a/packages/views/layout/object-page.test.tsx b/packages/views/layout/object-page.test.tsx
index edcc338b97..f8da37a94f 100644
--- a/packages/views/layout/object-page.test.tsx
+++ b/packages/views/layout/object-page.test.tsx
@@ -28,6 +28,7 @@ function renderPage(panel?: React.ReactNode) {
return renderWithI18n(
<NavigationProvider value={makeAdapter()}>
<ObjectPage
+ type="agent"
layoutId="test_object_page"
segments={[{ href: "/acme/agents", label: "Agents" }]}
leaf={<span>Lambda</span>}
diff --git a/packages/views/layout/object-page.tsx b/packages/views/layout/object-page.tsx
index ef4ea79062..aee3056a35 100644
--- a/packages/views/layout/object-page.tsx
+++ b/packages/views/layout/object-page.tsx
@@ -34,9 +34,14 @@ import {
import { BreadcrumbHeader, type BreadcrumbSegment } from "./breadcrumb-header";
/** The reading column of an object page; the header above it stays full width. */
-export const OBJECT_PAGE_BODY = "mx-auto w-full max-w-[760px] px-6 py-8";
+export const OBJECT_PAGE_BODY =
+ "mx-auto w-full max-w-[var(--object-page-max-width,760px)] px-[var(--space-lg,1.5rem)] py-[var(--space-xl,2rem)]";
+
+/** What an object page shows, as themes see it on `data-type`. */
+export type ObjectPageType = "project" | "agent" | "squad" | "runtime" | "member" | "autopilot" | "skill";
interface ObjectPageProps {
+ type: ObjectPageType;
/** The lists this object was opened from, each one a link back. */
segments: BreadcrumbSegment[];
/** The object's own crumb. */
@@ -65,7 +70,7 @@ interface ObjectPageProps {
* right panel the header toggles — the layout the issue page already uses.
* There are no tabs: what a tab would hold is a section of the body.
*/
-export function ObjectPage({ segments, leaf, actions, panel, layoutId, children, scrollRef }: ObjectPageProps) {
+export function ObjectPage({ type, segments, leaf, actions, panel, layoutId, children, scrollRef }: ObjectPageProps) {
const { t } = useT("layout");
const isMobile = useIsMobile();
const { defaultLayout, onLayoutChanged } = useDefaultLayout({ id: layoutId });
@@ -134,7 +139,7 @@ export function ObjectPage({ segments, leaf, actions, panel, layoutId, children,
if (!panel) {
return (
- <div className="flex min-h-0 flex-1 flex-col">
+ <div data-mc="object-page" data-type={type} className="flex min-h-0 flex-1 flex-col">
{header}
{body}
</div>
@@ -142,7 +147,7 @@ export function ObjectPage({ segments, leaf, actions, panel, layoutId, children,
}
return (
- <div ref={shortcutTargetRef} className="flex min-h-0 flex-1 flex-col">
+ <div ref={shortcutTargetRef} data-mc="object-page" data-type={type} className="flex min-h-0 flex-1 flex-col">
{header}
<ResizablePanelGroup
orientation="horizontal"
@@ -311,6 +316,8 @@ export function ObjectSectionEmpty({
}) {
return (
<div
+ data-mc="empty-state"
+ data-variant="section"
className={cn(
"flex min-h-13 items-center gap-3 rounded-lg border border-dashed border-input py-2.5 pr-2.5 pl-3.5 text-muted-foreground",
className,
diff --git a/packages/views/layout/page-header.tsx b/packages/views/layout/page-header.tsx
index 4c7e9b1e6d..9d8605bfcd 100644
--- a/packages/views/layout/page-header.tsx
+++ b/packages/views/layout/page-header.tsx
@@ -21,7 +21,7 @@ import { useAppShell } from "./app-shell-context";
* anywhere that edge matters instead of writing the class again; a page that
* spells its own gutter is the bug coming back.
*/
-export const PAGE_GUTTER = "px-4";
+export const PAGE_GUTTER = "px-[var(--page-padding-x,var(--space-md,1rem))]";
/**
* The centred column a detail page reads inside: `runtimes`, and the agent and
diff --git a/packages/views/layout/panel-nav.tsx b/packages/views/layout/panel-nav.tsx
index e085b94a3f..f2c192d3e4 100644
--- a/packages/views/layout/panel-nav.tsx
+++ b/packages/views/layout/panel-nav.tsx
@@ -148,7 +148,7 @@ export function PanelList({
}
export const PANEL_ROW_CLASS =
- "flex min-h-[var(--nav-item-height,2rem)] w-full items-center gap-2.5 rounded-nav-item px-3 py-1.5 text-left text-body transition-colors outline-none focus-visible:outline-2 focus-visible:outline-ring";
+ "flex min-h-[var(--nav-item-height,2rem)] w-full items-center gap-2.5 rounded-nav-item px-3 py-[var(--nav-item-padding-y,0.375rem)] text-left text-body transition-colors outline-none focus-visible:outline-2 focus-visible:outline-ring";
/** The `nav-item` theme anchor; every row with an active state carries it. */
export function panelRowAnchor(active: boolean) {
diff --git a/packages/views/layout/reading-column.ts b/packages/views/layout/reading-column.ts
index 19237f924a..292f49bdb8 100644
--- a/packages/views/layout/reading-column.ts
+++ b/packages/views/layout/reading-column.ts
@@ -9,4 +9,4 @@
* Everything in the column shares its edges, prose included. The upper bound
* is what keeps lines of text readable, so raise it with that in mind.
*/
-export const READING_COLUMN = "mx-auto w-full max-w-[clamp(56rem,70cqi,70rem)]";
+export const READING_COLUMN = "mx-auto w-full max-w-[var(--content-max-width,clamp(56rem,70cqi,70rem))]";
diff --git a/packages/views/layout/sidebar-resize.test.tsx b/packages/views/layout/sidebar-resize.test.tsx
index fa2e64a934..4877fce4b1 100644
--- a/packages/views/layout/sidebar-resize.test.tsx
+++ b/packages/views/layout/sidebar-resize.test.tsx
@@ -9,6 +9,9 @@ import {
} from "@multica/ui/components/ui/sidebar";
import { renderWithI18n } from "../test/i18n";
+/** No stored width: the theme's, or 240px when it sets none. */
+const UNSTORED_SIDEBAR_WIDTH = "clamp(200px, var(--sidebar-panel-width, 240px), 320px)";
+
describe("left sidebar resizing", () => {
beforeEach(() => {
localStorage.clear();
@@ -85,7 +88,7 @@ describe("left sidebar resizing", () => {
expect(
liveWidthConsumer.style.getPropertyValue("--sidebar-live-width"),
).toBe("300px");
- expect(wrapper.style.getPropertyValue("--sidebar-width")).toBe("240px");
+ expect(wrapper.style.getPropertyValue("--sidebar-width")).toBe(UNSTORED_SIDEBAR_WIDTH);
expect(localStorage.getItem("sidebar_width")).toBeNull();
expect(stableConsumerRender).toHaveBeenCalledTimes(1);
@@ -157,7 +160,7 @@ describe("left sidebar resizing", () => {
expect(
liveWidthConsumer.style.getPropertyValue("--sidebar-live-width"),
).toBe("");
- expect(wrapper.style.getPropertyValue("--sidebar-width")).toBe("240px");
+ expect(wrapper.style.getPropertyValue("--sidebar-width")).toBe(UNSTORED_SIDEBAR_WIDTH);
expect(localStorage.getItem("sidebar_width")).toBeNull();
expect(wrapper).not.toHaveAttribute("data-sidebar-resizing");
expect(document.documentElement).not.toHaveAttribute("data-sidebar-resizing");
diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.json
index 91dbf844ea..9af1409ff5 100644
--- a/packages/views/locales/en/settings.json
+++ b/packages/views/locales/en/settings.json
@@ -355,7 +355,7 @@
},
"density": {
"title": "Density",
- "description": "Row height in issue lists and search.",
+ "description": "Row height in issue lists, search and the sidebar, and spacing on the board.",
"compact": "Compact",
"default": "Default",
"comfortable": "Comfortable"
diff --git a/packages/views/locales/es/settings.json b/packages/views/locales/es/settings.json
index 7034fe2725..e770182037 100644
--- a/packages/views/locales/es/settings.json
+++ b/packages/views/locales/es/settings.json
@@ -355,7 +355,7 @@
},
"density": {
"title": "Densidad",
- "description": "Altura de las filas en listas de incidencias y búsqueda.",
+ "description": "Altura de las filas en listas de incidencias, búsqueda y la barra lateral, y espaciado en el tablero.",
"compact": "Compacta",
"default": "Predeterminada",
"comfortable": "Amplia"
diff --git a/packages/views/locales/fr/settings.json b/packages/views/locales/fr/settings.json
index 69e1e1f400..888e17b30b 100644
--- a/packages/views/locales/fr/settings.json
+++ b/packages/views/locales/fr/settings.json
@@ -355,7 +355,7 @@
},
"density": {
"title": "Densité",
- "description": "Hauteur des lignes dans les listes de tickets et la recherche.",
+ "description": "Hauteur des lignes dans les listes de tickets, la recherche et la barre latérale, et espacement du tableau.",
"compact": "Compacte",
"default": "Par défaut",
"comfortable": "Aérée"
diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.json
index df88fb2a4c..e8b2493437 100644
--- a/packages/views/locales/ja/settings.json
+++ b/packages/views/locales/ja/settings.json
@@ -349,7 +349,7 @@
},
"density": {
"title": "表示密度",
- "description": "課題リストと検索結果の行の高さ。",
+ "description": "課題リスト、検索結果、サイドバーの行の高さと、ボードの余白。",
"compact": "コンパクト",
"default": "標準",
"comfortable": "ゆったり"
diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.json
index 937d37145f..b9f071e545 100644
--- a/packages/views/locales/ko/settings.json
+++ b/packages/views/locales/ko/settings.json
@@ -349,7 +349,7 @@
},
"density": {
"title": "밀도",
- "description": "이슈 목록과 검색 결과의 행 높이.",
+ "description": "이슈 목록, 검색 결과, 사이드바의 행 높이와 보드의 간격.",
"compact": "좁게",
"default": "기본",
"comfortable": "넓게"
diff --git a/packages/views/locales/ru/settings.json b/packages/views/locales/ru/settings.json
index be2ad2e771..29c3443ae4 100644
--- a/packages/views/locales/ru/settings.json
+++ b/packages/views/locales/ru/settings.json
@@ -366,7 +366,7 @@
},
"density": {
"title": "Плотность",
- "description": "Высота строк в списках задач и поиске.",
+ "description": "Высота строк в списках задач, поиске и боковой панели, а также отступы на доске.",
"compact": "Компактная",
"default": "По умолчанию",
"comfortable": "Свободная"
diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.json
index 18435c7033..47fd0f62b2 100644
--- a/packages/views/locales/zh-Hans/settings.json
+++ b/packages/views/locales/zh-Hans/settings.json
@@ -349,7 +349,7 @@
},
"density": {
"title": "信息密度",
- "description": "任务列表和搜索结果的行高。",
+ "description": "任务列表、搜索结果和侧边栏的行高,以及看板的间距。",
"compact": "紧凑",
"default": "标准",
"comfortable": "宽松"
diff --git a/packages/views/locales/zh-Hant/settings.json b/packages/views/locales/zh-Hant/settings.json
index 2b387fe5d7..c999c4c75e 100644
--- a/packages/views/locales/zh-Hant/settings.json
+++ b/packages/views/locales/zh-Hant/settings.json
@@ -349,7 +349,7 @@
},
"density": {
"title": "資訊密度",
- "description": "任務清單和搜尋結果的列高。",
+ "description": "任務清單、搜尋結果和側邊欄的列高,以及看板的間距。",
"compact": "緊湊",
"default": "標準",
"comfortable": "寬鬆"
diff --git a/packages/views/members/member-detail-page.tsx b/packages/views/members/member-detail-page.tsx
index f555a91304..f54074d2a8 100644
--- a/packages/views/members/member-detail-page.tsx
+++ b/packages/views/members/member-detail-page.tsx
@@ -72,6 +72,7 @@ export function MemberDetailPage({ userId }: { userId: string }) {
if (isLoading) {
return (
<ObjectPage
+ type="member"
layoutId={LAYOUT_ID}
segments={segments}
leaf={<Skeleton className="h-4 w-32" />}
@@ -88,6 +89,7 @@ export function MemberDetailPage({ userId }: { userId: string }) {
return (
<ObjectPage
+ type="member"
layoutId={LAYOUT_ID}
segments={segments}
leaf={
@@ -131,6 +133,7 @@ function MemberIssues({
return (
<ObjectPage
+ type="member"
layoutId={LAYOUT_ID}
segments={segments}
leaf={
diff --git a/packages/views/plugins/plugin-surface-frame.tsx b/packages/views/plugins/plugin-surface-frame.tsx
index f2648d1b18..e6fec56d05 100644
--- a/packages/views/plugins/plugin-surface-frame.tsx
+++ b/packages/views/plugins/plugin-surface-frame.tsx
@@ -8,6 +8,7 @@ import { cn } from "@multica/ui/lib/utils";
import { useT } from "../i18n";
import { buildSurfaceFrameDocument, readThemeTokens } from "./surface-document";
import { createSurfaceBridge } from "./surface-bridge";
+import { useThemeVersion } from "../editor/hooks/use-theme-version";
const DEFAULT_HEIGHT = 220;
@@ -89,7 +90,7 @@ export function PluginSurfaceFrame({ wsId, installation, surface, issueId, class
// Terminal events and the bridge are both armed before srcdoc is assigned,
// so even a first-line plugin failure or navigation cannot outrun the host.
window.addEventListener("message", onMessage);
- bridge.connect(frame, readThemeTokens(anchorRef.current));
+ bridge.connect(frame, () => readThemeTokens(anchorRef.current));
frame.srcdoc = surfaceDocument;
return () => {
window.removeEventListener("message", onMessage);
@@ -102,6 +103,13 @@ export function PluginSurfaceFrame({ wsId, installation, surface, issueId, class
if (navigated) bridge.close();
}, [navigated, bridge]);
+ // A connected surface follows theme and mode switches live; before it
+ // connects, connect() sends the theme current at that moment.
+ const themeVersion = useThemeVersion();
+ useEffect(() => {
+ if (themeVersion > 0) bridge.pushTheme(readThemeTokens(anchorRef.current));
+ }, [themeVersion, bridge]);
+
if (navigated) {
return (
<div ref={anchorRef} className={cn("rounded-lg border border-surface-border px-4 py-3 text-caption text-muted-foreground", className)}>
diff --git a/packages/views/plugins/surface-bridge.test.ts b/packages/views/plugins/surface-bridge.test.ts
index 0be2a427b3..cd9ad4da10 100644
--- a/packages/views/plugins/surface-bridge.test.ts
+++ b/packages/views/plugins/surface-bridge.test.ts
@@ -101,6 +101,26 @@ describe("surface bridge", () => {
expect(heights).toEqual([4000, 0]);
});
+ it("sends the theme current at connection, then each pushed change", async () => {
+ const bridge = createSurfaceBridge({ installationId: "installation-1", bridgeToken: TOKEN });
+ const frame = { contentWindow: {} } as unknown as HTMLIFrameElement;
+ const themes: unknown[] = [];
+ const channel = new MessageChannel();
+ channel.port2.onmessage = (event) => {
+ if ((event.data as { kind?: string } | null)?.kind === "theme") themes.push(event.data.theme);
+ };
+ channel.port2.start();
+ let current = { "--foreground": "black" };
+ bridge.pushTheme({ "--foreground": "ignored before connecting" });
+ bridge.connect(frame, () => current);
+ current = { "--foreground": "white" };
+ connectMessage(frame.contentWindow, channel.port1);
+ bridge.pushTheme({ "--foreground": "red" });
+ await vi.waitFor(() => expect(themes).toHaveLength(2));
+ expect(themes).toEqual([{ "--foreground": "white" }, { "--foreground": "red" }]);
+ bridge.close();
+ });
+
it("refuses the wrong frame, protocol, challenge, and a replay", async () => {
const bridge = createSurfaceBridge({ installationId: "installation-1", bridgeToken: TOKEN });
const frame = { contentWindow: {} } as unknown as HTMLIFrameElement;
diff --git a/packages/views/plugins/surface-bridge.ts b/packages/views/plugins/surface-bridge.ts
index b88a946581..89cbdd1e16 100644
--- a/packages/views/plugins/surface-bridge.ts
+++ b/packages/views/plugins/surface-bridge.ts
@@ -70,9 +70,10 @@ export interface SurfaceBridge {
/**
* Arms the listener before the trusted outer document is assigned. The guest
* creates the channel; the host accepts its port only once all launch proofs
- * match.
+ * match. `theme` is read when the guest connects, so the first push is
+ * current even if the theme changed while the surface loaded.
*/
- connect(frame: HTMLIFrameElement, theme: Record<string, string>): void;
+ connect(frame: HTMLIFrameElement, theme: Record<string, string> | (() => Record<string, string>)): void;
/** Pushes a theme change to an already-connected frame. */
pushTheme(theme: Record<string, string>): void;
close(): void;
@@ -135,7 +136,7 @@ export function createSurfaceBridge(options: SurfaceBridgeOptions): SurfaceBridg
void handle(portEvent.data, guestPort);
};
port.start();
- port.postMessage({ kind: "theme", theme });
+ port.postMessage({ kind: "theme", theme: typeof theme === "function" ? theme() : theme });
};
connectListeners.push(onConnect);
window.addEventListener("message", onConnect);
diff --git a/packages/views/plugins/surface-document.ts b/packages/views/plugins/surface-document.ts
index 16861061b4..975f5005d9 100644
--- a/packages/views/plugins/surface-document.ts
+++ b/packages/views/plugins/surface-document.ts
@@ -1,30 +1,11 @@
-/** Design tokens forwarded over the bridge so a surface looks native. */
-export const SURFACE_THEME_TOKENS = [
- "--background",
- "--foreground",
- "--muted",
- "--muted-foreground",
- "--border",
- "--primary",
- "--primary-foreground",
- "--destructive",
- "--radius",
- "--text-caption",
- "--text-body",
-] as const;
+import { readEmbedTheme } from "../common/embed-theme";
export const SURFACE_BRIDGE_CONNECT_MESSAGE = "multica:plugin-bridge-connect";
export const SURFACE_BRIDGE_PROTOCOL_VERSION = 2;
+/** Design tokens forwarded over the bridge so a surface looks native: the embed token contract. */
export function readThemeTokens(element: Element | null): Record<string, string> {
- if (!element || typeof getComputedStyle !== "function") return {};
- const computed = getComputedStyle(element);
- const tokens: Record<string, string> = {};
- for (const name of SURFACE_THEME_TOKENS) {
- const value = computed.getPropertyValue(name).trim();
- if (value) tokens[name] = value;
- }
- return tokens;
+ return readEmbedTheme(element).tokens;
}
function escapeAttribute(value: string): string {
diff --git a/packages/views/projects/components/project-detail.tsx b/packages/views/projects/components/project-detail.tsx
index 42f807681c..66c911a401 100644
--- a/packages/views/projects/components/project-detail.tsx
+++ b/packages/views/projects/components/project-detail.tsx
@@ -549,7 +549,14 @@ export function ProjectDetail({ projectId }: { projectId: string }) {
return (
<>
- <ResizablePanelGroup orientation="horizontal" className="flex-1 min-h-0" defaultLayout={defaultLayout} onLayoutChanged={onLayoutChanged}>
+ <ResizablePanelGroup
+ data-mc="object-page"
+ data-type="project"
+ orientation="horizontal"
+ className="flex-1 min-h-0"
+ defaultLayout={defaultLayout}
+ onLayoutChanged={onLayoutChanged}
+ >
<ResizablePanel id="content" minSize="50%">
<div ref={rightSidebarShortcutTargetRef} className="flex h-full flex-col">
<IssueSurface
diff --git a/packages/views/runtimes/components/qoder-detail-page.tsx b/packages/views/runtimes/components/qoder-detail-page.tsx
index 5dcd8e238f..ea6950d999 100644
--- a/packages/views/runtimes/components/qoder-detail-page.tsx
+++ b/packages/views/runtimes/components/qoder-detail-page.tsx
@@ -111,7 +111,7 @@ export function QoderDetailPage() {
if (connection.isPending || runtimesLoading) {
return (
- <ObjectPage layoutId={LAYOUT_ID} segments={segments} leaf={leaf}>
+ <ObjectPage type="runtime" layoutId={LAYOUT_ID} segments={segments} leaf={leaf}>
<QoderBodySkeleton />
</ObjectPage>
);
@@ -119,7 +119,7 @@ export function QoderDetailPage() {
const data = connection.data;
if (connection.isError || data?.available !== true) {
return (
- <ObjectPage layoutId={LAYOUT_ID} segments={segments} leaf={leaf}>
+ <ObjectPage type="runtime" layoutId={LAYOUT_ID} segments={segments} leaf={leaf}>
<CollectionPageState
icon={AlertCircle}
tone="destructive"
@@ -167,6 +167,7 @@ export function QoderDetailPage() {
return (
<ObjectPage
+ type="runtime"
layoutId={LAYOUT_ID}
segments={segments}
leaf={leaf}
diff --git a/packages/views/runtimes/components/runtime-detail-page.tsx b/packages/views/runtimes/components/runtime-detail-page.tsx
index f94c29d583..c7709abb9f 100644
--- a/packages/views/runtimes/components/runtime-detail-page.tsx
+++ b/packages/views/runtimes/components/runtime-detail-page.tsx
@@ -224,6 +224,7 @@ export function RuntimeDetailPage({
if (isLoading) {
return (
<ObjectPage
+ type="runtime"
layoutId={LAYOUT_ID}
segments={segments}
leaf={<Skeleton className="h-4 w-40" />}
@@ -237,6 +238,7 @@ export function RuntimeDetailPage({
if (!machine) {
return (
<ObjectPage
+ type="runtime"
layoutId={LAYOUT_ID}
segments={segments}
leaf={
@@ -280,6 +282,7 @@ export function RuntimeDetailPage({
return (
<>
<ObjectPage
+ type="runtime"
layoutId={LAYOUT_ID}
segments={segments}
leaf={
diff --git a/packages/views/runtimes/components/runtime-detail.tsx b/packages/views/runtimes/components/runtime-detail.tsx
index 679aa705fb..34938a037a 100644
--- a/packages/views/runtimes/components/runtime-detail.tsx
+++ b/packages/views/runtimes/components/runtime-detail.tsx
@@ -167,6 +167,7 @@ export function RuntimeDetail({
return (
<>
<ObjectPage
+ type="runtime"
layoutId="multica_runtime_detail_layout"
segments={[
{ href: paths.runtimes(), label: t(($) => $.page.title) },
diff --git a/packages/views/runtimes/components/runtime-settings-page.tsx b/packages/views/runtimes/components/runtime-settings-page.tsx
index 71c47a713a..a9254ce266 100644
--- a/packages/views/runtimes/components/runtime-settings-page.tsx
+++ b/packages/views/runtimes/components/runtime-settings-page.tsx
@@ -36,6 +36,7 @@ export function RuntimeSettingsPage({
if (isLoading) {
return (
<ObjectPage
+ type="runtime"
layoutId="multica_runtime_detail_layout"
segments={segments}
leaf={<Skeleton className="h-4 w-40" />}
@@ -62,6 +63,7 @@ export function RuntimeSettingsPage({
if (!target) {
return (
<ObjectPage
+ type="runtime"
layoutId="multica_runtime_detail_layout"
segments={segments}
leaf={
diff --git a/packages/views/search/pages/issue-pages.tsx b/packages/views/search/pages/issue-pages.tsx
index c5282648b2..4ec8ebe568 100644
--- a/packages/views/search/pages/issue-pages.tsx
+++ b/packages/views/search/pages/issue-pages.tsx
@@ -35,6 +35,7 @@ import { AgentPresenceText, ActorRow, IssueResultRow } from "../result-rows";
import { useActorDirectory } from "../use-actor-directory";
import { useServerSearch } from "../use-server-search";
import type { IssueTarget } from "../types";
+import { paletteColor } from "@multica/core/appearance";
/** The value every target issue shares, or undefined when they differ. */
function common<T>(issues: Issue[], pick: (issue: Issue) => T): T | undefined {
@@ -115,6 +116,8 @@ export function IssueStatusPage({ target, query }: { target: IssueTarget; query:
<PaletteGroup heading={t(($) => $.pages.status)}>
{visible.map((option) => (
<CommandPrimitive.Item
+ data-mc="palette-item"
+ data-type="option"
key={option.key}
value={`status:${option.key}`}
onSelect={() => select(option.key)}
@@ -153,6 +156,8 @@ export function IssuePriorityPage({ target, query }: { target: IssueTarget; quer
<PaletteGroup heading={t(($) => $.pages.priority)}>
{options.map(({ priority, label }) => (
<CommandPrimitive.Item
+ data-mc="palette-item"
+ data-type="option"
key={priority}
value={`priority:${priority}`}
onSelect={() => {
@@ -208,6 +213,8 @@ export function IssueAssigneePage({ target, query }: { target: IssueTarget; quer
{showUnassigned && (
<PaletteGroup heading={t(($) => $.pages.assignee)}>
<CommandPrimitive.Item
+ data-mc="palette-item"
+ data-type="option"
value="assignee:none"
onSelect={() => select(null, null)}
className={ROW_CLASS}
@@ -343,6 +350,8 @@ export function IssueLabelsPage({ target, query }: { target: IssueTarget; query:
const onAll = issues.every((issue) => labelIdsOf(issue).has(label.id));
return (
<CommandPrimitive.Item
+ data-mc="palette-item"
+ data-type="option"
key={label.id}
value={`label:${label.id}`}
onSelect={() => toggle(label)}
@@ -350,7 +359,7 @@ export function IssueLabelsPage({ target, query }: { target: IssueTarget; query:
>
<span
className="mx-1 size-2.5 shrink-0 rounded-full"
- style={{ backgroundColor: label.color }}
+ style={{ backgroundColor: paletteColor(label.color) }}
/>
<span className="min-w-0 flex-1 truncate">
<HighlightText text={label.name} query={query} />
@@ -387,6 +396,8 @@ export function IssueDueDatePage({ target, query }: { target: IssueTarget; query
<PaletteGroup heading={t(($) => $.pages.due_date)}>
{options.map((option) => (
<CommandPrimitive.Item
+ data-mc="palette-item"
+ data-type="option"
key={option.id}
value={`due:${option.id}`}
onSelect={() => {
@@ -425,6 +436,8 @@ export function IssueProjectPage({ target, query }: { target: IssueTarget; query
<PaletteGroup heading={t(($) => $.pages.project)}>
{(!q || scoreText(noProjectLabel, q) > 0) && (
<CommandPrimitive.Item
+ data-mc="palette-item"
+ data-type="option"
value="project:none"
onSelect={() => {
palette.close();
@@ -439,6 +452,8 @@ export function IssueProjectPage({ target, query }: { target: IssueTarget; query
)}
{visible.map((project) => (
<CommandPrimitive.Item
+ data-mc="palette-item"
+ data-type="option"
key={project.id}
value={`project:${project.id}`}
onSelect={() => {
@@ -474,6 +489,8 @@ export function IssueParentPage({ target, query }: { target: IssueTarget; query:
{hasParent && !query.trim() && (
<PaletteGroup heading={t(($) => $.pages.parent)}>
<CommandPrimitive.Item
+ data-mc="palette-item"
+ data-type="option"
value="parent:none"
onSelect={() => {
palette.close();
@@ -531,6 +548,8 @@ export function IssueQuickActionPage({ issue, query }: { issue: Issue; query: st
const targetName = action.target_name || tIssues(($) => $.detail.quick_action_target_fallback);
return (
<CommandPrimitive.Item
+ data-mc="palette-item"
+ data-type="option"
key={action.id}
value={`quick-action:${action.id}`}
onSelect={() => {
diff --git a/packages/views/search/pages/other-pages.tsx b/packages/views/search/pages/other-pages.tsx
index 95eb204a74..6ddf83d4d1 100644
--- a/packages/views/search/pages/other-pages.tsx
+++ b/packages/views/search/pages/other-pages.tsx
@@ -56,6 +56,8 @@ export function ThemePage({ query }: { query: string }) {
<PaletteGroup heading={tLayout(($) => $.account.mode)}>
{visibleModes.map((option) => (
<CommandPrimitive.Item
+ data-mc="palette-item"
+ data-type="option"
key={option.value}
value={`theme:${option.value}`}
onSelect={() => {
@@ -77,6 +79,8 @@ export function ThemePage({ query }: { query: string }) {
<PaletteGroup heading={tLayout(($) => $.account.theme)}>
{visibleThemes.map((manifest) => (
<CommandPrimitive.Item
+ data-mc="palette-item"
+ data-type="option"
key={manifest.id}
value={`color-theme:${manifest.id}`}
onSelect={() => {
@@ -111,6 +115,8 @@ export function ProjectStatusPage({ project, query }: { project: Project; query:
<PaletteGroup heading={t(($) => $.pages.project_status)}>
{visible.map((status) => (
<CommandPrimitive.Item
+ data-mc="palette-item"
+ data-type="option"
key={status}
value={`project-status:${status}`}
onSelect={() => {
@@ -171,6 +177,8 @@ export function AgentAssignIssuePage({ agent, query }: { agent: Agent; query: st
{(!q || scoreText(newIssueLabel, q) > 0) && (
<PaletteGroup heading={t(($) => $.groups.new)}>
<CommandPrimitive.Item
+ data-mc="palette-item"
+ data-type="option"
value="agent-new-issue"
onSelect={() => {
palette.close();
@@ -232,13 +240,15 @@ export function ChatProjectPage({
return (
<PaletteGroup heading={t(($) => $.pages.project)}>
{current && (!q || scoreText(noProjectLabel, q) > 0) && (
- <CommandPrimitive.Item value="chat-project:none" onSelect={() => select(null)} className={ROW_CLASS}>
+ <CommandPrimitive.Item data-mc="palette-item" data-type="option" value="chat-project:none" onSelect={() => select(null)} className={ROW_CLASS}>
<FolderMinus className={ROW_ICON_CLASS} />
<span className="min-w-0 flex-1 truncate text-muted-foreground">{noProjectLabel}</span>
</CommandPrimitive.Item>
)}
{visible.map((project) => (
<CommandPrimitive.Item
+ data-mc="palette-item"
+ data-type="option"
key={project.id}
value={`chat-project:${project.id}`}
onSelect={() => select(project.id)}
diff --git a/packages/views/search/result-rows.tsx b/packages/views/search/result-rows.tsx
index 1b23010fd6..98601b0275 100644
--- a/packages/views/search/result-rows.tsx
+++ b/packages/views/search/result-rows.tsx
@@ -65,6 +65,8 @@ export function ProjectResultRow({
return (
<CommandPrimitive.Item
+ data-mc="palette-item"
+ data-type="project"
value={`project:${project.id}`}
disabled={disabled}
onSelect={onSelect}
@@ -116,6 +118,8 @@ export function IssueResultRow({
"matched_comment_snippet" in issue ? issue.matched_comment_snippet : undefined;
return (
<CommandPrimitive.Item
+ data-mc="palette-item"
+ data-type="issue"
value={value ?? issue.id}
disabled={disabled}
onSelect={onSelect}
@@ -206,7 +210,14 @@ export function ActorRow({
showStatusDot?: boolean;
}) {
return (
- <CommandPrimitive.Item value={value} disabled={disabled} onSelect={onSelect} className={ROW_CLASS}>
+ <CommandPrimitive.Item
+ data-mc="palette-item"
+ data-type={actorType}
+ value={value}
+ disabled={disabled}
+ onSelect={onSelect}
+ className={ROW_CLASS}
+ >
<ActorAvatar
actorType={actorType}
actorId={actorId}
@@ -246,7 +257,14 @@ export function ObjectRow({
disabled?: boolean;
}) {
return (
- <CommandPrimitive.Item value={value} disabled={disabled} onSelect={onSelect} className={ROW_CLASS}>
+ <CommandPrimitive.Item
+ data-mc="palette-item"
+ data-type="object"
+ value={value}
+ disabled={disabled}
+ onSelect={onSelect}
+ className={ROW_CLASS}
+ >
{icon}
<span className="min-w-0 shrink truncate">
<HighlightText text={title} query={query} />
diff --git a/packages/views/search/root-view.tsx b/packages/views/search/root-view.tsx
index c6987cadc1..cc2f292023 100644
--- a/packages/views/search/root-view.tsx
+++ b/packages/views/search/root-view.tsx
@@ -91,6 +91,8 @@ export function RootView({ model, rawQuery }: { model: RootModel; rawQuery: stri
const PageIcon = routeIconForPath(p[page.key]());
return (
<CommandPrimitive.Item
+ data-mc="palette-item"
+ data-type="page"
key={page.key}
value={`page:${page.key}`}
onSelect={() => palette.navigate(p[page.key]())}
@@ -323,6 +325,8 @@ export function RootView({ model, rawQuery }: { model: RootModel; rawQuery: stri
<PaletteGroup key="workspaces" heading={t(($) => $.groups.workspaces)}>
{objects.workspaces.map(({ item: ws }) => (
<CommandPrimitive.Item
+ data-mc="palette-item"
+ data-type="workspace"
key={ws.id}
value={`workspace:${ws.id}`}
// Web lands on the target's Issues; the desktop adapter reads
@@ -409,6 +413,8 @@ function HandToAgentRow({ seed, disabled }: { seed: HandToAgentSeed; disabled: b
return (
<div className="px-2 py-1">
<CommandPrimitive.Item
+ data-mc="palette-item"
+ data-type="command"
// cmdk picks a default selection only when an item mounts, so the row
// remounts on enable to become the selection when nothing else matched.
key={disabled ? "disabled" : "enabled"}
@@ -559,6 +565,8 @@ function BestMatchGroups({
<AssignActionRow key={action.id} label={action.label} target={target} best={best} query={query} />
) : (
<CommandPrimitive.Item
+ data-mc="palette-item"
+ data-type="command"
key={action.id}
value={`best-action:${action.id}`}
onSelect={action.run}
@@ -592,6 +600,8 @@ function AssignActionRow({
const writer = useIssueTargetWriter(target);
return (
<CommandPrimitive.Item
+ data-mc="palette-item"
+ data-type="command"
value="best-action:assign"
onSelect={() => {
palette.close();
diff --git a/packages/views/search/rows.tsx b/packages/views/search/rows.tsx
index 133d0e11ee..d909abf27e 100644
--- a/packages/views/search/rows.tsx
+++ b/packages/views/search/rows.tsx
@@ -71,6 +71,8 @@ export function CommandRow({
const Icon = command.icon;
return (
<CommandPrimitive.Item
+ data-mc="palette-item"
+ data-type="command"
value={scope ? `command:${scope}:${command.id}` : `command:${command.id}`}
onSelect={() => {
if (command.page) {
diff --git a/packages/views/search/search-command.tsx b/packages/views/search/search-command.tsx
index 305f72fed1..6fb2817386 100644
--- a/packages/views/search/search-command.tsx
+++ b/packages/views/search/search-command.tsx
@@ -179,6 +179,7 @@ function PaletteFrame({
return (
<>
<CommandPrimitive
+ data-mc="command-palette"
key={stack.length}
label={t(($) => $.title)}
shouldFilter={false}
diff --git a/packages/views/settings/components/properties-tab.tsx b/packages/views/settings/components/properties-tab.tsx
index 3319395074..7de99d09f8 100644
--- a/packages/views/settings/components/properties-tab.tsx
+++ b/packages/views/settings/components/properties-tab.tsx
@@ -79,6 +79,7 @@ import {
} from "../../common/property-icon";
import { useLocale, useT } from "../../i18n";
import { SettingsReadOnlyNotice, SettingsTab } from "./settings-layout";
+import { paletteColor } from "@multica/core/appearance";
const MAX_ACTIVE_PROPERTIES = 20;
@@ -240,7 +241,7 @@ export function PropertiesTab() {
>
<span
className="size-2 rounded-full"
- style={{ backgroundColor: option.color }}
+ style={{ backgroundColor: paletteColor(option.color) }}
/>
{option.name}
</span>
diff --git a/packages/views/skills/components/skill-detail-page.tsx b/packages/views/skills/components/skill-detail-page.tsx
index cee6fea7cd..73ed2f4e1a 100644
--- a/packages/views/skills/components/skill-detail-page.tsx
+++ b/packages/views/skills/components/skill-detail-page.tsx
@@ -748,6 +748,7 @@ export function SkillDetailPage({ skillId }: { skillId: string }) {
if (isLoading) {
return (
<ObjectPage
+ type="skill"
layoutId={SKILL_DETAIL_LAYOUT_ID}
segments={[listSegment]}
leaf={<Skeleton className="h-4 w-40" />}
@@ -773,6 +774,7 @@ export function SkillDetailPage({ skillId }: { skillId: string }) {
if (error || !skill) {
return (
<ObjectPage
+ type="skill"
layoutId={SKILL_DETAIL_LAYOUT_ID}
segments={[listSegment]}
leaf={
@@ -1062,6 +1064,7 @@ export function SkillDetailPage({ skillId }: { skillId: string }) {
// same rule as the skills list batch toolbar).
<div className="relative flex min-h-0 flex-1 flex-col">
<ObjectPage
+ type="skill"
layoutId={SKILL_DETAIL_LAYOUT_ID}
segments={
subView
diff --git a/packages/views/squads/components/squad-detail-page.tsx b/packages/views/squads/components/squad-detail-page.tsx
index d26972aa7d..70e3e68dd5 100644
--- a/packages/views/squads/components/squad-detail-page.tsx
+++ b/packages/views/squads/components/squad-detail-page.tsx
@@ -252,6 +252,7 @@ export function SquadDetailPage() {
if (squadError) {
return (
<ObjectPage
+ type="squad"
layoutId={layoutId}
segments={segments}
leaf={
@@ -278,6 +279,7 @@ export function SquadDetailPage() {
}
return (
<ObjectPage
+ type="squad"
layoutId={layoutId}
segments={segments}
leaf={<Skeleton className="h-4 w-32" />}
@@ -323,6 +325,7 @@ export function SquadDetailPage() {
return (
<ObjectPage
+ type="squad"
layoutId={layoutId}
segments={segments}
leaf={