Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(theme): check contrast of tooltips and pressed display chips (MUL-9035) (#10367)
Jiayuan Zhang94a7648ad29c
diff --git a/apps/docs/content/docs/developers/themes.fr.mdx b/apps/docs/content/docs/developers/themes.fr.mdxindex e340c063f7..b3181806a7 100644--- a/apps/docs/content/docs/developers/themes.fr.mdx+++ b/apps/docs/content/docs/developers/themes.fr.mdx@@ -178,7 +178,7 @@ Tout ce qui charge une ressource est refusé, car le CSS peut lire le contenu de- utilise une variable non publique, sauf si c'est un id d'option ou si le thème la lit lui-même avec `var()` ;- définit des variables ailleurs que sur `.theme-light` et `.theme-dark` sans sélecteur descendant, ce qui empêche le sélecteur de thème de relire ses couleurs ;- nomme une famille générique (`sans-serif`, `serif`, …) ou un mot-clé `ui-*` dans une pile de polices, ce qui écraserait la police CJK choisie ;-- n'atteint pas le contraste WCAG AA dans un des modes : `--foreground` et `--muted-foreground` demandent 4,5:1 sur chaque surface, `--brand` 4,5:1 sur les surfaces de lecture, le libellé du bouton principal 4,5:1 sur le bouton, et `--faint-foreground` 3:1.+- n'atteint pas le contraste WCAG AA dans un des modes : `--foreground` et `--muted-foreground` demandent 4,5:1 sur chaque surface, `--brand` 4,5:1 sur les surfaces de lecture, le libellé du bouton principal 4,5:1 sur le bouton, et `--faint-foreground` 3:1. Le texte des infobulles demande 4,5:1 sur `--tooltip`, et celui d'une puce d'affichage enfoncée 4,5:1 sur son fond. Les infobulles utilisent toujours le texte du mode sombre : définissez `--tooltip-foreground` pour le changer. Une puce enfoncée prend `--input` comme fond, sauf si vous définissez `--display-chip-pressed-background`.## Vérifier et prévisualiserdiff --git a/apps/docs/content/docs/developers/themes.ja.mdx b/apps/docs/content/docs/developers/themes.ja.mdxindex adce91ccf5..94dfeca0f6 100644--- a/apps/docs/content/docs/developers/themes.ja.mdx+++ b/apps/docs/content/docs/developers/themes.ja.mdx@@ -178,7 +178,7 @@ paper/- 公開されていない変数を使っている(オプションの id か、テーマ自身が `var()` で読む変数を除く)。- `.theme-light` と `.theme-dark` 以外の場所で、子孫セレクタなしに変数を設定している。テーマピッカーがテーマの色を読み取れなくなります。- フォントスタックに汎用ファミリー(`sans-serif`、`serif` …)や `ui-*` キーワードがある。本人が選んだ CJK フォントが効かなくなります。-- どちらかのモードで WCAG AA のコントラストを満たさない:`--foreground` と `--muted-foreground` はすべてのサーフェスで 4.5:1、`--brand` は読むためのサーフェスで 4.5:1、プライマリボタンのラベルはボタン上で 4.5:1、`--faint-foreground` は 3:1 が必要です。+- どちらかのモードで WCAG AA のコントラストを満たさない:`--foreground` と `--muted-foreground` はすべてのサーフェスで 4.5:1、`--brand` は読むためのサーフェスで 4.5:1、プライマリボタンのラベルはボタン上で 4.5:1、`--faint-foreground` は 3:1 が必要です。ツールチップの文字は `--tooltip` 上で 4.5:1、押された表示設定チップの文字はその塗りの上で 4.5:1 が必要です。ツールチップは常にダークモードの文字色を使うため、変えるには `--tooltip-foreground` を設定します。押されたチップは `--display-chip-pressed-background` を設定しない限り `--input` で塗られます。## チェックとプレビューdiff --git a/apps/docs/content/docs/developers/themes.ko.mdx b/apps/docs/content/docs/developers/themes.ko.mdxindex 05879c6cfb..6c974e9f79 100644--- a/apps/docs/content/docs/developers/themes.ko.mdx+++ b/apps/docs/content/docs/developers/themes.ko.mdx@@ -178,7 +178,7 @@ paper/- 공개되지 않은 변수를 쓰는 경우. 옵션 id이거나 테마가 직접 `var()`로 읽는 변수는 예외입니다.- `.theme-light`와 `.theme-dark`가 아닌 곳에 하위 선택자 없이 변수를 설정한 경우. 테마 선택기가 테마의 색을 읽어 올 수 없게 됩니다.- 글꼴 스택에 일반 글꼴 계열(`sans-serif`, `serif`, …)이나 `ui-*` 키워드를 쓴 경우. 사용자가 고른 CJK 글꼴이 적용되지 않게 됩니다.-- 어느 한 모드에서 WCAG AA 대비를 충족하지 못하는 경우: `--foreground`와 `--muted-foreground`는 모든 표면에서 4.5:1, `--brand`는 읽기 표면에서 4.5:1, 기본 버튼 라벨은 버튼 위에서 4.5:1, `--faint-foreground`는 3:1이 필요합니다.+- 어느 한 모드에서 WCAG AA 대비를 충족하지 못하는 경우: `--foreground`와 `--muted-foreground`는 모든 표면에서 4.5:1, `--brand`는 읽기 표면에서 4.5:1, 기본 버튼 라벨은 버튼 위에서 4.5:1, `--faint-foreground`는 3:1이 필요합니다. 툴팁 글자는 `--tooltip` 위에서 4.5:1, 눌린 표시 설정 칩의 글자는 칩 배경 위에서 4.5:1이 필요합니다. 툴팁은 항상 다크 모드 글자색을 쓰므로 바꾸려면 `--tooltip-foreground`를 설정하세요. 눌린 칩은 `--display-chip-pressed-background`를 설정하지 않으면 `--input`으로 채워집니다.## 검사와 미리보기diff --git a/apps/docs/content/docs/developers/themes.mdx b/apps/docs/content/docs/developers/themes.mdxindex d7931cc7fa..b169ff7480 100644--- a/apps/docs/content/docs/developers/themes.mdx+++ b/apps/docs/content/docs/developers/themes.mdx@@ -178,7 +178,7 @@ Escapes, case, and comments don't get around the check; it reads the CSS the way- uses a variable that isn't public, unless it is an option id or the theme reads it itself with `var()`;- sets variables anywhere other than `.theme-light` and `.theme-dark` without a descendant selector, so the theme picker can't read the theme's colors back;- names a generic family (`sans-serif`, `serif`, …) or a `ui-*` keyword in a font stack, which would override the person's CJK font;-- misses WCAG AA contrast in either mode: `--foreground` and `--muted-foreground` need 4.5:1 on every surface, `--brand` 4.5:1 on reading surfaces, the primary button label 4.5:1 on the button, and `--faint-foreground` 3:1.+- misses WCAG AA contrast in either mode: `--foreground` and `--muted-foreground` need 4.5:1 on every surface, `--brand` 4.5:1 on reading surfaces, the primary button label 4.5:1 on the button, and `--faint-foreground` 3:1. Tooltip text needs 4.5:1 on `--tooltip`, and a pressed display chip's text 4.5:1 on its fill. Tooltips always use dark-mode text, so set `--tooltip-foreground` to change it; pressed chips fill with `--input` unless you set `--display-chip-pressed-background`.## Check and previewdiff --git a/apps/docs/content/docs/developers/themes.zh-Hant.mdx b/apps/docs/content/docs/developers/themes.zh-Hant.mdxindex b53d3b91b6..f204ab4272 100644--- a/apps/docs/content/docs/developers/themes.zh-Hant.mdx+++ b/apps/docs/content/docs/developers/themes.zh-Hant.mdx@@ -178,7 +178,7 @@ paper/- 使用了非公開變數,除非它是選項 id,或者主題自己用 `var()` 讀取它;- 在 `.theme-light` 和 `.theme-dark` 以外的地方設定變數而沒有後代選擇器,主題選擇器就讀不出主題的顏色;- 在字型棧裡寫了通用字型族(`sans-serif`、`serif` …)或 `ui-*` 關鍵字,這會蓋掉使用者選的中文字型;-- 任一模式下沒達到 WCAG AA 對比度:`--foreground` 和 `--muted-foreground` 在每個表面上需要 4.5:1,`--brand` 在閱讀表面上需要 4.5:1,主按鈕文字在按鈕上需要 4.5:1,`--faint-foreground` 需要 3:1。+- 任一模式下沒達到 WCAG AA 對比度:`--foreground` 和 `--muted-foreground` 在每個表面上需要 4.5:1,`--brand` 在閱讀表面上需要 4.5:1,主按鈕文字在按鈕上需要 4.5:1,`--faint-foreground` 需要 3:1。提示框文字在 `--tooltip` 上需要 4.5:1,按下狀態的顯示設定標籤,文字在其底色上需要 4.5:1。提示框始終使用深色模式的文字顏色,要修改請設定 `--tooltip-foreground`;按下的標籤預設用 `--input` 作底色,可以用 `--display-chip-pressed-background` 單獨設定。## 檢查與預覽diff --git a/apps/docs/content/docs/developers/themes.zh.mdx b/apps/docs/content/docs/developers/themes.zh.mdxindex 28f50115fe..d2bec9be00 100644--- a/apps/docs/content/docs/developers/themes.zh.mdx+++ b/apps/docs/content/docs/developers/themes.zh.mdx@@ -178,7 +178,7 @@ paper/- 使用了非公开变量,除非它是选项 id,或者主题自己用 `var()` 读取它;- 在 `.theme-light` 和 `.theme-dark` 以外的地方设置变量而没有后代选择器,主题选择器就读不出主题的颜色;- 在字体栈里写了通用字体族(`sans-serif`、`serif` …)或 `ui-*` 关键字,这会盖掉用户选的中文字体;-- 任一模式下没达到 WCAG AA 对比度:`--foreground` 和 `--muted-foreground` 在每个表面上需要 4.5:1,`--brand` 在阅读表面上需要 4.5:1,主按钮文字在按钮上需要 4.5:1,`--faint-foreground` 需要 3:1。+- 任一模式下没达到 WCAG AA 对比度:`--foreground` 和 `--muted-foreground` 在每个表面上需要 4.5:1,`--brand` 在阅读表面上需要 4.5:1,主按钮文字在按钮上需要 4.5:1,`--faint-foreground` 需要 3:1。提示框文字在 `--tooltip` 上需要 4.5:1,按下状态的显示设置标签,文字在其底色上需要 4.5:1。提示框始终使用深色模式的文字颜色,要修改请设置 `--tooltip-foreground`;按下的标签默认用 `--input` 作底色,可以用 `--display-chip-pressed-background` 单独设置。## 检查与预览diff --git a/docs/theming.md b/docs/theming.mdindex dbbedd00ff..1f499d3fc1 100644--- a/docs/theming.md+++ b/docs/theming.md@@ -316,6 +316,25 @@ names the value it comes from, for example(`color`, `variable-select`, `number`, `slider`, `text`, `font`) are measuredat their defaults only, so check the other values you offer yourself.+Contrast covers the page, the frame, and two places a theme reaches only+indirectly:++- **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+ modes, not the theme's `.theme-dark` one. The text is measured on+ `--tooltip` in each mode. Set `--tooltip-foreground` to choose it.+- **Pressed display chips** (the on/off chips in the Display and sidebar+ settings popovers) fill with `--input`, the input border colour, and use+ `--foreground`. They are measured inside the popover, with the rules a+ theme sets on `[data-slot="popover-content"]`. Set+ `--display-chip-pressed-background` and `--display-chip-pressed-color` to+ colour them apart from input borders.++Rules on a slot are applied by specificity, then order, as the browser+does. A variable set on `<html>` reaches the slot with the value it has+there: `--display-chip-pressed-color: var(--foreground)` on `.theme-light`+keeps the page's `--foreground`, even if the popover sets its own.+To see the theme the way the theme store shows it:```sh@@ -396,7 +415,7 @@ and dark differ, both defaults are given.| `--accent` | `oklch(0.967 0.001 286.375)` / `oklch(0.274 0.006 286.033)` | Hover fill in menus and lists. || `--accent-foreground` | `oklch(0.21 0.006 285.885)` / `oklch(0.985 0 0)` | Text on accent. || `--border` | `oklch(0.945 0.003 286.32)` / `oklch(1 0 0 / 6%)` | Dividers and table borders. |-| `--input` | `oklch(0.92 0.004 286.32)` / `oklch(1 0 0 / 15%)` | Input borders. |+| `--input` | `oklch(0.92 0.004 286.32)` / `oklch(1 0 0 / 15%)` | Input borders, and pressed display chips unless `display-chip-pressed-background` is set. || `--ring` | `oklch(0.705 0.015 286.067)` / `oklch(0.552 0.016 285.938)` | Focus ring. || `--sidebar` | `oklch(0.964435 0.001327 286.375)` / `oklch(0.21 0.006 285.885)` | Sidebar background (shadcn sidebar). || `--sidebar-foreground` | `oklch(0.141 0.005 285.823)` / `oklch(0.985 0 0)` | Sidebar text. |@@ -453,6 +472,7 @@ and dark differ, both defaults are given.| `--floating-shadow` | `0 16px 40px rgb(15 23 42 / 0.14), 0 3px 10px rgb(15 23 42 / 0.08)` / `0 20px 48px rgb(0 0 0 / 0.46), 0 4px 12px rgb(0 0 0 / 0.28)` | Dialogs and sheets. || `--menu-shadow` | `0 8px 24px rgb(15 23 42 / 0.08), 0 2px 6px rgb(15 23 42 / 0.05)` / `0 10px 28px rgb(0 0 0 / 0.3), 0 2px 8px rgb(0 0 0 / 0.18)` | Menus, selects and popovers. || `--tooltip` | `oklch(0.21 0.006 285.885)` / `oklch(0.3 0.006 286.033)` | Tooltip fill (dark in both modes). |+| `--tooltip-foreground` | `var(--foreground)` | Tooltip text. Unset, it is the app's dark-mode `--foreground` in both modes, whatever the theme sets on `.theme-dark`. || `--tooltip-shadow` | `0 4px 12px rgb(15 23 42 / 0.16), 0 1px 3px rgb(15 23 42 / 0.12)` / `0 0 0 1px oklch(1 0 0 / 10%), 0 8px 24px rgb(0 0 0 / 0.4)` | Tooltip shadow. || `--icon-stroke-width` | `2` | Stroke width of line icons. |@@ -512,6 +532,8 @@ and dark differ, both defaults are given.| `--menu-item-radius` | `calc(var(--radius) * 0.75)` | Items inside a menu. || `--menu-item-hover-background` | `var(--accent)` | Highlighted menu item. || `--menu-item-hover-color` | `var(--accent-foreground)` | Text of the highlighted menu item. |+| `--display-chip-pressed-background` | `var(--input)` | Fill of a pressed on/off chip in the Display and sidebar settings popovers. |+| `--display-chip-pressed-color` | `var(--foreground)` | Text of a pressed display chip. || `--popover-radius` | `var(--radius)` | Popovers. || `--floating-border-color` | `color-mix(in oklab, var(--surface-border), var(--foreground) 6%)` | Hairline around layers that float over the page without a backdrop: menus, popovers, select lists and floating panels. || `--dialog-radius` | `calc(var(--radius) * 1.5)` | Dialogs and alert dialogs. |diff --git a/packages/core/appearance/built-in-themes.ts b/packages/core/appearance/built-in-themes.tsindex 6c169a2079..9121925e4d 100644--- a/packages/core/appearance/built-in-themes.ts+++ b/packages/core/appearance/built-in-themes.ts@@ -75,6 +75,8 @@ const POP_SHARED: ThemeTokens = {"menu-item-radius": "0.125rem","menu-item-hover-background": "var(--surface-selected)","menu-item-hover-color": "var(--foreground)",+ "display-chip-pressed-background": "var(--surface-selected)",+ "display-chip-pressed-color": "var(--foreground)","label-radius": "0.25rem","board-column-radius": "0.25rem","board-card-radius": "0.25rem",diff --git a/packages/core/appearance/theme-check.test.ts b/packages/core/appearance/theme-check.test.tsindex 1ea7c5544a..73555ce9d7 100644--- a/packages/core/appearance/theme-check.test.ts+++ b/packages/core/appearance/theme-check.test.ts@@ -133,6 +133,7 @@ describe("theme check", () => {]) {expect(errors(css, { options })).toEqual([expect.stringMatching(/^Contrast, light mode \(Ink = Pale\): --foreground is below 4\.5:1 on .*--page-canvas \(1\.0\d:1\)/),+ expect.stringMatching(/^Contrast, light mode \(display chip, Ink = Pale\): --foreground is below 4\.5:1 on --input/),]);}const report = check(':root[data-theme-option-ink="soft"].theme-light { --muted-foreground: #bbbbbb; }', { options });@@ -270,6 +271,72 @@ describe("theme check", () => {expect(found.some((m) => /light mode \(frame\): --foreground is below 4\.5:1 on --app-shell/.test(m))).toBe(true);});+ it("measures tooltips with the dark-mode text they always use", () => {+ const pale = ".theme-light { --tooltip: #f4f4f4; }";+ expect(errors(pale)).toEqual([+ expect.stringMatching(/^Contrast, light mode \(tooltip\): --foreground is below 4\.5:1 on --tooltip \(1\.\d\d:1\)\. .*--tooltip-foreground/),+ ]);+ // MS-DOS 1.0.0: a grey tooltip under the app's near-white dark-mode text.+ expect(errors(".theme-dark { --tooltip: #aaaaaa; }")).toEqual([+ expect.stringMatching(/^Contrast, dark mode \(tooltip\): --foreground is below 4\.5:1 on --tooltip/),+ ]);+ expect(check(`${pale}\n.theme-light { --tooltip-foreground: #111111; }`)).toMatchObject({ ok: true, issues: [] });+ expect(check(`${pale}\n.theme-light [data-slot="tooltip-content"] { --foreground: #111111; }`)).toMatchObject({+ ok: true,+ issues: [],+ });+ const tip = check(`${pale}\n[data-slot='tooltip-content'] { --tooltip-foreground: #111111; }`).contrast.filter(+ (c) => c.area === "tooltip",+ );+ expect(tip.map((c) => [c.mode, c.foreground, c.background])).toEqual([+ ["light", "--tooltip-foreground", "--tooltip"],+ ["dark", "--tooltip-foreground", "--tooltip"],+ ]);+ });++ it("measures pressed display chips in the popover they sit in", () => {+ expect(errors(".theme-light { --input: #111111; }")).toEqual([+ expect.stringMatching(+ /^Contrast, light mode \(display chip\): --foreground is below 4\.5:1 on --input \(1\.\d\d:1\)\. .*--display-chip-pressed-background/,+ ),+ ]);+ expect(errors('.theme-dark [data-slot="popover-content"] { --input: oklch(0.985 0 0); }')).toEqual([+ expect.stringMatching(/^Contrast, dark mode \(display chip\): --foreground is below 4\.5:1 on --input \(1\.00:1\)/),+ ]);+ const split = ".theme-light { --input: #111111; --display-chip-pressed-background: #e6e6e6; }";+ expect(check(split)).toMatchObject({ ok: true, issues: [] });+ expect(errors(`${split}\n.theme-light { --display-chip-pressed-color: #ffffff; }`)).toEqual([+ expect.stringMatching(/^Contrast, light mode \(display chip\): --display-chip-pressed-color is below 4\.5:1 on --display-chip-pressed-background/),+ ]);+ // A variable set on <html> is inherited as computed there, not re-read in the popover.+ expect(+ errors(+ [+ ".theme-light { --display-chip-pressed-color: var(--foreground); --display-chip-pressed-background: #111111; }",+ '.theme-light [data-slot="popover-content"] { --foreground: #ffffff; }',+ ].join("\n"),+ ),+ ).toEqual([expect.stringMatching(/^Contrast, light mode \(display chip\): --display-chip-pressed-color is below 4\.5:1 .*\(1\.\d\d:1\)/)]);+ // The more specific slot rule wins over a later, less specific one.+ expect(+ errors(+ [+ '.theme-light [data-slot="popover-content"] { --display-chip-pressed-background: #ffffff; --display-chip-pressed-color: #ffffff; }',+ '[data-slot="popover-content"] { --display-chip-pressed-background: #111111; --display-chip-pressed-color: #ffffff; }',+ ].join("\n"),+ ),+ ).toEqual([expect.stringMatching(/^Contrast, light mode \(display chip\): .*\(1\.00:1\)/)]);+ // Slot rules follow option attributes like rules on <html>.+ const options = [{ id: "ink", type: "select", label: "Ink", default: "dark", choices: [{ value: "dark", label: "Dark" }, { value: "pale", label: "Pale" }] }];+ expect(errors(':root[data-theme-option-ink="pale"] [data-slot="popover-content"] { --input: #111111; }', { options })).toEqual([+ expect.stringMatching(/^Contrast, light mode \(display chip, Ink = Pale\): --foreground is below 4\.5:1 on --input/),+ ]);+ // Dark mode's default --input is translucent; it is measured over the popover.+ const chips = check("").contrast.filter((c) => c.area === "display chip");+ expect(chips.map((c) => c.mode)).toEqual(["light", "dark"]);+ expect(chips.every((c) => c.ratio >= c.required)).toBe(true);+ });+describe("rail items", () => {const rail = (declarations: string) => `.theme-light [data-mc="app-rail"] { ${declarations} }`;const fills = "--rail-item-hover-background: #000000; --rail-item-active-background: #000000;";diff --git a/packages/core/appearance/theme-check.ts b/packages/core/appearance/theme-check.tsindex 56c4e6509c..b3405cd560 100644--- a/packages/core/appearance/theme-check.ts+++ b/packages/core/appearance/theme-check.ts@@ -1,7 +1,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 } from "./theme-contrast";+import { contrastRatio, paintOver, resolveColor, type BasePalette, type Rgba } from "./theme-contrast";import {THEME_OPTION_ATTR_PREFIX,localizedText,@@ -38,8 +38,11 @@ export interface ContrastVariant {export interface ContrastCheck {mode: "light" | "dark";- /** Where the pair is painted: the page, or the frame (rail, toolbar, tabs). */- area: "page" | "frame";+ /**+ * Where the pair is painted: the page, the frame (rail, toolbar, tabs),+ * a tooltip, or a pressed chip in a display popover.+ */+ area: "page" | "frame" | "tooltip" | "display chip";foreground: string;background: string;ratio: number;@@ -93,6 +96,21 @@ const GENERIC_FAMILY =/^(?:serif|sans-serif|monospace|cursive|fantasy|system-ui|math|emoji|fangsong|ui-[a-z-]+)$/i;const LATIN_STACKS = new Set(["font-ui", "font-content-latin"]);const FRAME_ANCHOR = /data-mc="(?:app-rail|window-toolbar|tab-bar|bottom-bar)"/;+const SLOT = /^\[data-slot=(["']?)([\w-]+)\1\]$/;+/** Slots portalled to <body> whose own variables the check follows. */+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 {+ 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.";+ }+ return "";+}const isRecord = (v: unknown): v is Record<string, unknown> =>typeof v === "object" && v !== null && !Array.isArray(v);@@ -173,6 +191,14 @@ function splitSelectors(prelude: string): string[] {* follows, then a frame anchor below it. Empty for any other selector.*/function frameModes(selector: string, attributes: ReadonlyMap<string, string>): Mode[] {+ const i = firstCombinator(selector);+ if (i < 0 || !FRAME_ANCHOR.test(selector.slice(i))) return [];+ const head = rootSelector(selector.slice(0, i), attributes);+ return head && head !== "inactive" ? head.modes : [];+}++/** Where the first descendant combinator outside brackets and quotes is, or -1. */+function firstCombinator(selector: string): number {let depth = 0;let quote = "";for (let i = 0; i < selector.length; i += 1) {@@ -182,13 +208,34 @@ function frameModes(selector: string, attributes: ReadonlyMap<string, string>):} else if (c === '"' || c === "'") quote = c;else if (c === "(" || c === "[") depth += 1;else if (c === ")" || c === "]") depth = Math.max(0, depth - 1);- else if (/\s/.test(c) && depth === 0) {- if (!FRAME_ANCHOR.test(selector.slice(i))) return [];- const head = rootSelector(selector.slice(0, i), attributes);- return head && head !== "inactive" ? head.modes : [];- }+ else if (/\s/.test(c) && depth === 0) return i;}- return [];+ return -1;+}++/**+ * The slots a rule sets variables on, in which modes, and how specific it+ * is: `[data-slot="x"]`, alone or in an `:is()` / `:where()` list, either+ * bare or below a selector on <html> that `rootSelector` follows.+ * `"inactive"` when that selector does not match; null for any other.+ */+function slotSelector(+ selector: string,+ attributes: ReadonlyMap<string, string>,+): { modes: Mode[]; slots: Slot[]; specificity: number } | "inactive" | null {+ const i = firstCombinator(selector);+ const head = i < 0 ? null : rootSelector(selector.slice(0, i), attributes);+ if (i >= 0 && !head) return null;+ const target = (i < 0 ? selector : selector.slice(i)).trim();+ const list = /^:(is|where)\(([\s\S]*)\)$/.exec(target);+ const args = list ? splitSelectors(list[2]!) : [target];+ const slots = args.map((s) => SLOT.exec(s)?.[2]).filter((s): s is Slot => SLOTS.includes(s as Slot));+ if (slots.length === 0) return null;+ if (head === "inactive") return "inactive";+ // `:is()` counts as its most specific argument and `:where()` as nothing;+ // the arguments here are attribute selectors, as specific as a class.+ const own = list?.[1] === "where" ? 0 : Math.max(...args.map((s) => (s.match(/\[|\.|:(?!:)/g)?.length ?? 0) * 10));+ return { modes: head ? head.modes : ["light", "dark"], slots, specificity: (head ? head.specificity : 0) + own };}/** A palette that records which variables a contrast check read. */@@ -204,6 +251,42 @@ class ReadTracker extends Map<string, string> {}}+/**+ * The variables of an element below <html>, as the browser computes them:+ * its own declarations, resolved on the element, and everything else+ * inherited with the value already computed on <html>.+ */+class ScopePalette extends ReadTracker {+ private readonly parent: Map<string, string>;+ constructor(read: Set<string>, parent: Map<string, string>, own: Iterable<readonly [string, string]>) {+ super(read, own);+ this.parent = parent;+ }+ override get(name: string) {+ if (super.has(name)) return super.get(name);+ if (!this.parent.has(name)) return undefined;+ const inherited = resolveColor(this.parent, name);+ if (!("color" in inherited)) return this.parent.get(name);+ const { r, g, b, a } = inherited.color;+ return `rgb(${r} ${g} ${b} / ${a})`;+ }+ override has(name: string) {+ return super.has(name) || this.parent.has(name);+ }+}++/** Declarations by name, the most specific winning and, at equal specificity, the later one. */+type Cascade = Map<string, { value: string; specificity: number }>;++function cascadeSet(cascade: Cascade, entries: Iterable<readonly [string, string]>, specificity: number) {+ for (const [name, value] of entries) {+ const current = cascade.get(name);+ if (!current || specificity >= current.specificity) cascade.set(name, { value, specificity });+ }+}++const cascadeValues = (cascade: Cascade) => [...cascade].map(([name, { value }]) => [name, value] as const);+/** Rules that hold declarations, top-level or nested, enough to find variables. */function rules(css: string): Rule[] {const out: Rule[] = [];@@ -343,6 +426,18 @@ function measureContrast(dark: new Map([...base.dark].map(([name, value]) => [name, { value, specificity: 10 }])),};const frame = { light: [] as [string, string][], dark: [] as [string, string][] };+ // What the theme declares on each slot, per mode. The tooltip starts from+ // `.dark` in tokens.css, which the theme's CSS follows at equal specificity.+ const slotted = (seed: Iterable<readonly [string, string]>) => {+ const out = { light: new Map() as Cascade, dark: new Map() as Cascade };+ cascadeSet(out.light, seed, 10);+ cascadeSet(out.dark, seed, 10);+ return out;+ };+ const slots: Record<Slot, Record<Mode, Cascade>> = {+ "tooltip-content": slotted(base.darkScope),+ "popover-content": slotted([]),+ };const unmodelled = new Map<string, string>();const attributes = new Map<string, string>();for (const [name, value] of Object.entries(theme ? themeOptionAttributes(theme, chosen) : {})) {@@ -352,14 +447,13 @@ function measureContrast(for (const selector of rule.selectors) {const target = rule.nested ? null : rootSelector(selector, attributes);if (target === "inactive") continue;+ const slot = rule.nested || target ? null : slotSelector(selector, attributes);+ if (slot === "inactive") continue;if (target) {- for (const m of target.modes) {- for (const [name, value] of declarations(rule.body)) {- const current = cascade[m].get(name);- if (!current || target.specificity >= current.specificity) {- cascade[m].set(name, { value, specificity: target.specificity });- }- }+ for (const m of target.modes) cascadeSet(cascade[m], declarations(rule.body), target.specificity);+ } else if (slot) {+ for (const s of slot.slots) {+ for (const m of slot.modes) cascadeSet(slots[s][m], declarations(rule.body), slot.specificity);}} else if (!/[\s>+~]/.test(selector)) {// Sets variables on <html> or <body> in a way the check does not follow.@@ -381,16 +475,15 @@ function measureContrast(for (const m of ["light", "dark"] as const) {// Option values are written after the theme as `:root.theme-<mode>`, so they win.- const palette = new ReadTracker(read, [- ...[...cascade[m]].map(([name, { value }]) => [name, value] as const),- ...Object.entries(options[m]),- ]);+ const palette = new ReadTracker(read, [...cascadeValues(cascade[m]), ...Object.entries(options[m])]);const measure = (area: ContrastCheck["area"],p: Map<string, string>,foreground: string,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 } = {},) => {const fg = resolveColor(p, foreground);if ("unresolved" in fg) {@@ -398,16 +491,21 @@ function measureContrast(return;}for (const background of backgrounds) {- const bg = resolveColor(p, background);+ const bg = resolveColor(surface, background);if ("unresolved" in bg) {unresolved.add(`${m}: ${bg.unresolved}`);continue;}- if (bg.color.a < 1) {+ let fill: Rgba = bg.color;+ if (fill.a < 1 && under) {+ const floor = resolveColor(surface, under);+ if ("color" in floor && floor.color.a === 1) fill = paintOver(fill, floor.color);+ }+ if (fill.a < 1) {unresolved.add(`${m}: ${background} is translucent, so its contrast depends on what is underneath`);continue;}- const ratio = contrastRatio(fg.color, bg.color);+ const ratio = contrastRatio(fg.color, fill);results.push({mode: m,area,@@ -463,6 +561,21 @@ function measureContrast(TEXT,);}++ // The tooltip is a `.dark` scope in both modes: its text takes the app's+ // dark tokens, and the theme's values only through rules on the tooltip or+ // --tooltip-foreground. Its fill is resolved outside, in the page's mode.+ const tooltip = new ScopePalette(read, palette, cascadeValues(slots["tooltip-content"][m]));+ const tipText = tooltip.has("--tooltip-foreground") ? "--tooltip-foreground" : "--foreground";+ measure("tooltip", tooltip, tipText, ["--tooltip"], TEXT, { surface: palette });++ // Display chips sit in popovers; pressed, they fill with+ // --display-chip-pressed-background, which defaults to --input (translucent+ // in dark mode, over the popover's --surface-raised).+ const popover = new ScopePalette(read, palette, cascadeValues(slots["popover-content"][m]));+ 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" });}for (const [name, where] of unmodelled) {@@ -485,10 +598,10 @@ function reportFailing(checks: readonly ContrastCheck[], issues: ThemeCheckIssueconst { mode: m, area, foreground, required, variant } = group[0]!;const surfaces = group.map((c) => `${c.background} (${c.ratio.toFixed(2)}:1)`);const list = surfaces.length > 1 ? `${surfaces.slice(0, -1).join(", ")} and ${surfaces.at(-1)}` : surfaces[0];- const where = [...(area === "frame" ? ["frame"] : []), ...(variant ? [variant.label] : [])];+ const where = [...(area === "page" ? [] : [area]), ...(variant ? [variant.label] : [])];issues.push({level: "error",- message: `Contrast, ${m} mode${where.length > 0 ? ` (${where.join(", ")})` : ""}: ${foreground} is below ${required}:1 on ${list}.`,+ message: `Contrast, ${m} mode${where.length > 0 ? ` (${where.join(", ")})` : ""}: ${foreground} is below ${required}:1 on ${list}.${contrastHint(group[0]!)}`,});}}diff --git a/packages/core/appearance/theme-contrast.ts b/packages/core/appearance/theme-contrast.tsindex edb6b52724..ae00380c76 100644--- a/packages/core/appearance/theme-contrast.ts+++ b/packages/core/appearance/theme-contrast.ts@@ -167,10 +167,16 @@ export function readDeclarations(css: string, selector: string): Map<string, strexport interface BasePalette {light: Palette;dark: Palette;+ /**+ * What `.dark` declares, alone. An element with the `dark` class, such as+ * the tooltip, resets these to the app's dark values in either mode.+ */+ darkScope: Palette;}/** Reads the base palette from packages/ui/styles/tokens.css. */export function basePaletteFromTokens(tokensCss: string): BasePalette {const light = readDeclarations(tokensCss, ":root");- return { light, dark: new Map([...light, ...readDeclarations(tokensCss, ".dark")]) };+ const darkScope = readDeclarations(tokensCss, ".dark");+ return { light, dark: new Map([...light, ...darkScope]), darkScope };}diff --git a/packages/core/appearance/theme-variables.ts b/packages/core/appearance/theme-variables.tsindex a664f65206..1b6235370b 100644--- a/packages/core/appearance/theme-variables.ts+++ b/packages/core/appearance/theme-variables.ts@@ -100,7 +100,7 @@ const COLORS: Entry[] = [["accent", "Hover fill in menus and lists."],["accent-foreground", "Text on accent."],["border", "Dividers and table borders."],- ["input", "Input borders."],+ ["input", "Input borders, and pressed display chips unless `display-chip-pressed-background` is set."],["ring", "Focus ring."],["sidebar", "Sidebar background (shadcn sidebar)."],["sidebar-foreground", "Sidebar text."],@@ -153,6 +153,7 @@ const SHAPE: Entry[] = [["floating-shadow", "Dialogs and sheets."],["menu-shadow", "Menus, selects and popovers."],["tooltip", "Tooltip fill (dark in both modes)."],+ ["tooltip-foreground", "Tooltip text. Unset, it is the app's dark-mode `--foreground` in both modes, whatever the theme sets on `.theme-dark`.", "var(--foreground)"],["tooltip-shadow", "Tooltip shadow."],["icon-stroke-width", "Stroke width of line icons.", "2"],];@@ -208,6 +209,8 @@ const CONTROLS: Entry[] = [["menu-item-radius", "Items inside a menu.", "calc(var(--radius) * 0.75)"],["menu-item-hover-background", "Highlighted menu item.", "var(--accent)"],["menu-item-hover-color", "Text of the highlighted menu item.", "var(--accent-foreground)"],+ ["display-chip-pressed-background", "Fill of a pressed on/off chip in the Display and sidebar settings popovers.", "var(--input)"],+ ["display-chip-pressed-color", "Text of a pressed display chip.", "var(--foreground)"],["popover-radius", "Popovers.", "var(--radius)"],["floating-border-color", "Hairline around layers that float over the page without a backdrop: menus, popovers, select lists and floating panels.", "color-mix(in oklab, var(--surface-border), var(--foreground) 6%)"],["dialog-radius", "Dialogs and alert dialogs.", "calc(var(--radius) * 1.5)"],diff --git a/packages/ui/components/ui/tooltip.tsx b/packages/ui/components/ui/tooltip.tsxindex 310305f7eb..b0a8765ff7 100644--- a/packages/ui/components/ui/tooltip.tsx+++ b/packages/ui/components/ui/tooltip.tsx@@ -80,7 +80,8 @@ function TooltipContent({// The popup is a `.dark` scope, so the text, status colors, and keycaps// inside it take dark-theme values against the dark tooltip surface in both// page themes. Its own fill and shadow are resolved on the positioner, which- // is still in the page theme.+ // is still in the page theme. A theme's --tooltip-foreground is never+ // declared by `.dark`, so it reaches the text from either mode.return (<TooltipPrimitive.Portal><TooltipPrimitive.Positioner@@ -94,7 +95,7 @@ function TooltipContent({<TooltipPrimitive.Popupdata-slot="tooltip-content"className={cn(- "dark z-50 inline-flex w-fit max-w-xs origin-(--transform-origin) items-center gap-1.5 rounded-tooltip bg-(--tooltip-fill) px-2.5 py-1 text-caption text-foreground shadow-(--tooltip-elevation) has-data-[slot=kbd]:pr-1.5 data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 **:data-[slot=kbd]:relative **:data-[slot=kbd]:isolate **:data-[slot=kbd]:z-50 **:data-[slot=kbd]:rounded-sm data-[state=delayed-open]:animate-in data-[state=delayed-open]:fade-in-0 data-[state=delayed-open]:zoom-in-95 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",+ "dark z-50 inline-flex w-fit max-w-xs origin-(--transform-origin) items-center gap-1.5 rounded-tooltip bg-(--tooltip-fill) px-2.5 py-1 text-caption text-tooltip-foreground shadow-(--tooltip-elevation) has-data-[slot=kbd]:pr-1.5 data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 **:data-[slot=kbd]:relative **:data-[slot=kbd]:isolate **:data-[slot=kbd]:z-50 **:data-[slot=kbd]:rounded-sm data-[state=delayed-open]:animate-in data-[state=delayed-open]:fade-in-0 data-[state=delayed-open]:zoom-in-95 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",className)}{...props}diff --git a/packages/ui/styles/theme-variables.css b/packages/ui/styles/theme-variables.cssindex 0389d04d72..2756ffd8ef 100644--- a/packages/ui/styles/theme-variables.css+++ b/packages/ui/styles/theme-variables.css@@ -31,6 +31,9 @@--color-floating-border: var(--floating-border-color, color-mix(in oklab, var(--surface-border), var(--foreground) 6%));--color-menu-item-hover: var(--menu-item-hover-background, var(--accent));--color-menu-item-hover-foreground: var(--menu-item-hover-color, var(--accent-foreground));+ --color-tooltip-foreground: var(--tooltip-foreground, var(--foreground));+ --color-display-chip-pressed: var(--display-chip-pressed-background, var(--input));+ --color-display-chip-pressed-foreground: var(--display-chip-pressed-color, var(--foreground));--color-nav-item: var(--nav-item-color, var(--muted-foreground));--color-nav-item-hover: var(--nav-item-hover-background, var(--surface-hover));--color-nav-item-hover-foreground: var(--nav-item-hover-color, var(--foreground));diff --git a/packages/views/chat/components/chat-input.test.tsx b/packages/views/chat/components/chat-input.test.tsxindex 010143cede..dd9322a1c6 100644--- a/packages/views/chat/components/chat-input.test.tsx+++ b/packages/views/chat/components/chat-input.test.tsx@@ -763,7 +763,7 @@ describe("ChatInput page context", () => {fireEvent.click(sendButton());await waitFor(() => expect(onSend).toHaveBeenCalledTimes(1));expect(onSend.mock.calls[0]![0]).toBe("[MUL-1](mention://issue/issue-1)\n\nwhy is this slow?");- expect(pageChip()).toBeNull();+ await waitFor(() => expect(pageChip()).toBeNull());});it("leaves Tab alone when the editor already used it, or it came from outside the editor", () => {diff --git a/packages/views/issues/components/display-parts.tsx b/packages/views/issues/components/display-parts.tsxindex 723ab600cd..6a9d95368e 100644--- a/packages/views/issues/components/display-parts.tsx+++ b/packages/views/issues/components/display-parts.tsx@@ -18,7 +18,7 @@ export function DisplayChip({ className, ...props }: ComponentProps<typeof Togglsize="sm"variant="outline"className={cn(- "h-6 max-w-40 gap-1.5 rounded-md px-2 text-caption text-muted-foreground hover:border-foreground/25 hover:bg-transparent hover:text-foreground aria-pressed:border-transparent aria-pressed:bg-input aria-pressed:text-foreground aria-pressed:hover:bg-input/70",+ "h-6 max-w-40 gap-1.5 rounded-md px-2 text-caption text-muted-foreground hover:border-foreground/25 hover:bg-transparent hover:text-foreground aria-pressed:border-transparent aria-pressed:bg-display-chip-pressed aria-pressed:text-display-chip-pressed-foreground aria-pressed:hover:bg-display-chip-pressed/70",className,)}{...props}diff --git a/scripts/theme-check.mjs b/scripts/theme-check.mjsindex 886fbf0d4b..70023d213e 100644--- a/scripts/theme-check.mjs+++ b/scripts/theme-check.mjs@@ -59,7 +59,7 @@ if (json) {const failing = contrast.filter((c) => c.ratio < c.required).length;const lowest = [...contrast].sort((a, b) => a.ratio / a.required - b.ratio / b.required)[0];const values = new Set(contrast.filter((c) => c.variant).map((c) => c.variant.label)).size;- const where = [lowest.mode, ...(lowest.area === "frame" ? ["frame"] : [])].join(" ");+ const where = [lowest.mode, ...(lowest.area === "page" ? [] : [lowest.area])].join(" ");console.log(` contrast ${contrast.length} pairs checked at the default options${values > 0 ? ` and ${values} other option value${values === 1 ? "" : "s"}` : ""}, ${failing} below WCAG AA. Lowest: ${lowest.foreground} on ${lowest.background}, ${where}${lowest.variant ? ` (${lowest.variant.label})` : ""}, ${lowest.ratio.toFixed(2)}:1 (needs ${lowest.required}:1)`,);diff --git a/scripts/theme-preview.test.mjs b/scripts/theme-preview.test.mjsindex 46e549cc36..349394e076 100644--- a/scripts/theme-preview.test.mjs+++ b/scripts/theme-preview.test.mjs@@ -169,6 +169,9 @@ const NOT_DRAWN = {"nav-item-hover": "hover","nav-item-hover-foreground": "hover","rail-item-hover": "hover",+ "tooltip-foreground": "no tooltip is open",+ "display-chip-pressed": "no display popover is open",+ "display-chip-pressed-foreground": "no display popover is open","issue-row-hover": "hover","issue-group-header-hover": "hover","board-column": "the page shows the list, not the board",