diff --git a/docs/design-decisions.md b/docs/design-decisions.md index 0e63bf8..97be5a8 100644 --- a/docs/design-decisions.md +++ b/docs/design-decisions.md @@ -565,6 +565,7 @@ Replaced by: [UI-024](#ui-024--assertive-functional-color-by-default) strengthen - Evidence: tests/smoke/settings/displayLanguage.smoke.mjs, tests/unit/theme/customThemes.spec.ts, and the affected cards retain checks and screenshots. - Follow-up evidence: Cards 5a56a250-b46a-4319-8f25-5f6ac4362a32, 682ad51f-66a1-477d-b02e-c1acb1c14d4e, and 97fe6f6b-5780-436e-abd8-a8135efbbe87 cover the full range, themed slider, and missing font stacks. `tests/smoke/appearance/themeVariants.smoke.mjs` checks the exact controls and exports. - Limits: Browser checks use desktop mocks. Native display and user acceptance remain open. +- Replaced by: [UI-042](#ui-042--theme-file-format-3-and-terminal-colors) replaces the template format. The transparency rule remains. ### UI-029 — Text selection transparency @@ -773,3 +774,39 @@ Native shell, background image, and desktop acceptance remain open. - Evidence files: output/smoke/editor/listNesting/. - Replaces / replaced by: None. - Limits: Source has no minimap, no command palette, and no bracket pair colors. Browser checks use desktop service mocks. Native desktop acceptance remains open. + +### UI-041 — Theme roles and theme data + +- Type: Rule change +- Date: 2026-10-28 +- Status: Implemented for user review +- Decision source: The approved Phase 5a plan of 2026-10-28, stage 5a-1. +- Previous rule: `appearance.ts` kept palettes as arrays with fixed slot positions. Branches on theme IDs chose the secondary accent, status, syntax, and font values. `tokens.css` repeated the fonts and the selection fill for each palette. The contrast tests covered only the character palettes. +- New rule: Each built-in theme is a data file in `src/lib/theme/themes/`. `roles.ts` names each color role and the one rule that fills a missing role. No code outside the theme data names a theme ID. `contrast.ts` holds the readability rules, and a test applies them to every palette. +- New roles: `--rs-link`, `--rs-focus`, `--rs-on-accent`, `--rs-highlight`, and `--rs-scrim`. `--rs-item-selection-bg` and `--rs-line-highlight` are now roles. `--rs-danger` is removed, and its users take `--rs-error`. +- Reason: One definition for each color, and one place to correct it. The rules show which palettes fail and why. +- Scope: Built-in and custom themes, link text, focus outlines, dialog backdrops, highlighted text, and plugin views through the tokens. +- Shared implementation: `roles.ts`, `color.ts`, `contrast.ts`, `themes/`, `appearance.ts`, and `tokens.css`. [Theme tokens](plugin-development.md#theme-tokens) lists the tokens for plugin authors. +- Visible changes: The save conflict banner uses `--rs-warn` for its line. It used the fallback of the undefined token `--rs-warning`. Highlighted text in Write takes its color from `--rs-highlight` (`#edc65b` instead of `#e7c56a`, with the same 22% fill). Plugin Manager and image viewer backdrops use the shared 53% scrim instead of 60%. +- Custom themes: A theme export now writes the colors that the app applies. A derived role follows the theme's own colors, not the RuneStone colors. +- Evidence: A comparison of the applied colors before and after the change gives the same values for every built-in theme and mode. `tests/unit/theme/contrast.spec.ts` lists 29 rule failures of the current palettes as `todo`. Stages 5a-3 and 5a-4 remove them. +- Replaces / replaced by: None. +- Limits: Browser checks use desktop service mocks. Native desktop acceptance remains open. + +### UI-042 — Theme file format 3 and terminal colors + +- Type: Rule change +- Date: 2026-10-28 +- Status: Implemented for user review +- Decision source: The approved Phase 5a plan of 2026-10-28, stage 5a-2, and card 90906e18. The owner approved the terminal roles on 2026-10-28. +- Previous rule: Theme files used schema 2: one `colors` palette with 26 keys and no mode. A custom theme took missing colors from RuneStone in the mode of its background. Five syntax keys had Monaco names, and two of them had no use in Source. +- New rule: Theme files use schema 3 with `mode`, an optional built-in `base`, and `colors` keys equal to the role names. The export writes every role and font. An import takes the missing colors and fonts from the base theme, by default RuneStone. Built-in themes pass the same parser. +- Syntax roles: `variable`, `property`, `constant`, `punctuation`, and `heading` replace `local`, `instance`, and `global`. `parameter` and `static` are gone. Schema 1 and 2 files convert on import. +- Terminal roles: `--rs-ansi-*` and `--rs-ansi-bright-*` give the 16 terminal colors. Red, green, and yellow follow the status colors. Blue, magenta, and cyan have their own defaults, so a red accent no longer makes terminal blue red. +- Reason: Short theme files that build on a built-in theme. One name for each color in the file, the CSS token, and the docs. Terminal colors that keep their meaning in every theme. +- Scope: Theme import, export, saved custom themes, Source syntax colors, and the terminal tokens. The Terminal plugin adopts the terminal roles in its own repository. +- Shared implementation: `customThemes.ts`, `roles.ts`, `appearance.ts`, `contrast.ts`, and `sourceView.ts`. +- Visible changes: None in the app. Exported files and import error messages change. The terminal colors change only after the Terminal plugin uses the new tokens. +- Evidence: The applied colors and the Source colors of each tag group are the same as before stage 5a-1, for every built-in theme and a saved schema 2 custom theme. `tests/unit/theme/customThemes.spec.ts` covers schema 3, `base`, and the conversion of old syntax names. +- Replaces / replaced by: The template format of [UI-028](#ui-028--adjustable-surface-transparency-and-fixed-custom-palettes). Its transparency rule remains. +- Limits: Browser checks use desktop service mocks. Native desktop acceptance remains open. diff --git a/docs/guides/themes.md b/docs/guides/themes.md index 8e25309..85acffd 100644 --- a/docs/guides/themes.md +++ b/docs/guides/themes.md @@ -40,25 +40,22 @@ The Project Management plugin can keep a separate image for a board. The Backgro 3. Edit the saved JSON file in a text editor. 4. Choose **Install theme** and select the file. -The template contains one `colors` palette and the current `fonts`. A custom theme has one fixed palette, without separate light and dark versions. +The template contains every color and font of the theme. A custom theme has one fixed mode: light or dark. -Example (a minimal theme file): +A theme file can also be short. It gives only the colors that differ from its `base` theme. The base theme gives all other colors and its fonts. + +Example (a short theme file that changes two colors of Harvest Moon): ```json { - "schema": 2, + "schema": 3, "id": "harbor", "name": "Harbor", + "mode": "dark", + "base": "harvest-moon", "colors": { - "bg": "#141414", - "bg-elevated": "#1c1c1c", - "bg-active": "#2a2a2a", - "border": "#454545", - "text": "#e6e6e6", - "text-dim": "#b0b0b0", - "text-strong": "#ffffff", "accent": "#00c8ff", - "selection": "#264f78" + "link": "#5cd6ff" } } ``` @@ -68,26 +65,33 @@ Example (a minimal theme file): | Field | Rule | | --- | --- | | File | JSON, smaller than 64 KiB | -| `schema` | `2`. RuneStone also imports schema 1 files and converts them to one palette for the current appearance. | +| `schema` | `3`. RuneStone also imports schema 1 and 2 files and converts them. A schema 1 file gives the palette of the current appearance. | | `id` | Starts with a lowercase letter. Lowercase letters, numbers, and hyphens. Up to 64 characters. A theme with the same ID replaces the installed theme. | | `name` | Up to 80 characters | -| `colors` | Must contain `bg`, `text`, and `accent`. Each value is a hexadecimal color with 3, 4, 6, or 8 digits. | -| `fonts` | Optional. Font stacks for `ui`, `prose`, `heading`, and `mono`, such as `"mono": "Cascadia Mono, monospace"`. | +| `mode` | `light` or `dark` | +| `base` | Optional. The ID of a built-in theme that has a palette in `mode`: `default` (RuneStone), `claude`, `sakura`, `harvest-moon`, `crimson-pilot`, or `silver-serpent`. Without `base`, RuneStone is the base. | +| `colors` | The colors that differ from the base theme. Each value is a hexadecimal color with 3, 4, 6, or 8 digits. | +| `fonts` | Optional. Font stacks for `ui`, `prose`, `heading`, and `mono`, such as `"mono": "Cascadia Mono, monospace"`. Without a stack, the base theme gives it. | An unknown key or a color that is not valid stops the installation with an error. -If you omit an optional color, RuneStone uses the color of the base appearance. If you omit `fonts`, the theme uses the normal fonts. +Some colors come from other colors when neither the file nor the base theme gives them. For example, `link` and `focus` come from `accent`. Font stacks name fonts that are installed on the computer. A theme file cannot install fonts or contain scripts, style rules, or plugin code. ### Color keys | Keys | Use | | --- | --- | -| `bg`, `bg-elevated`, `bg-active`, `border` | Surfaces and borders | +| `bg`, `bg-elevated`, `bg-active`, `border` | The page, side panes and menus, hover fills, and borders | | `text`, `text-dim`, `text-strong` | Normal, secondary, and prominent text | -| `accent`, `accent-2`, `selection` | Links, accents, and editor selection | +| `accent`, `accent-2`, `accent-dim`, `accent-deep` | Theme colors for active states, indicators, and icons | +| `link`, `focus`, `on-accent` | Link text, keyboard focus outlines, and text on an accent fill | +| `selection`, `item-selection-bg`, `line-highlight`, `highlight`, `scrim` | Text selection, selected rows, the current line in Source, highlighted text, and the backdrop behind dialogs | | `error`, `warn`, `warn-hot`, `ok`, `special` | Status and special content | -| `syntax-parameter`, `syntax-keyword`, `syntax-local`, `syntax-static`, `syntax-instance`, `syntax-global` | Code identifiers and keywords | -| `syntax-string`, `syntax-number`, `syntax-comment`, `syntax-type`, `syntax-function` | Code values, comments, types, and functions | +| `syntax-keyword`, `syntax-string`, `syntax-number`, `syntax-comment`, `syntax-type`, `syntax-function` | Code keywords, values, comments, types, and functions | +| `syntax-property`, `syntax-variable`, `syntax-constant`, `syntax-punctuation`, `syntax-heading` | Code properties, variables, constants, punctuation, and Markdown headings | +| `ansi-black` to `ansi-white`, `ansi-bright-black` to `ansi-bright-white` | The 16 terminal colors: black, red, green, yellow, blue, magenta, cyan, and white, and a bright variant of each | + +Schema 1 and 2 files used other names for some code colors. RuneStone converts them: `syntax-local` to `syntax-variable`, `syntax-instance` to `syntax-property`, and `syntax-global` to `syntax-constant` and `syntax-punctuation`. Source never used `syntax-parameter` and `syntax-static`, so RuneStone ignores them. Before you share a theme, check text, links, focus outlines, selections, and surfaces with a background image. Keep informative text and symbols opaque. See the [functional color requirements](../ui-color.md). diff --git a/docs/plugin-development.md b/docs/plugin-development.md index ce11c31..f7367f2 100644 --- a/docs/plugin-development.md +++ b/docs/plugin-development.md @@ -392,6 +392,36 @@ Only one enabled plugin can own each key. The host removes contributions before A terminal contribution must stop its controls and native sessions before its cleanup finishes. +### Theme tokens + +Style plugin views with the host CSS custom properties. The host sets them on the root element for the current theme. +Do not hard-code colors, and do not choose colors from a theme ID. + +| Token | Use | +| --- | --- | +| `--rs-bg` | The page: document and editor surfaces | +| `--rs-bg-elevated` | Side panes, menus, cards, and dialogs | +| `--rs-bg-active` | Hover and pressed fills | +| `--rs-border` | Dividers and control borders | +| `--rs-text`, `--rs-text-dim`, `--rs-text-strong` | Body text, secondary text, and headings | +| `--rs-accent`, `--rs-accent-2` | Theme identity: active states, indicators, and icons | +| `--rs-link` | Link and action text | +| `--rs-focus` | Keyboard focus outlines | +| `--rs-on-accent` | Text and icons on an accent fill | +| `--rs-selection`, `--rs-selection-text` | Text selection. The fill is at most 65% opaque. | +| `--rs-item-selection-bg`, `--rs-item-selection-border` | Selected rows, cards, and cells | +| `--rs-highlight` | Highlighted text | +| `--rs-scrim` | The backdrop behind a dialog | +| `--rs-error`, `--rs-warn`, `--rs-warn-hot`, `--rs-ok` | Status. Show an icon or text with each status color. | +| `--rs-special` | One more distinct color, for example for numbers | +| `--rs-syntax-*` | Code colors. [Functional color](ui-color.md#roles-and-tokens) lists the roles. | +| `--rs-ansi-black` to `--rs-ansi-white`, `--rs-ansi-bright-black` to `--rs-ansi-bright-white` | The 16 terminal colors. Each keeps its ANSI hue in every theme. | + +[Interface design](ui-design.md#shared-components-and-tokens) lists the size, menu, settings, and tooltip tokens. + +The root element also has `data-theme` (`light` or `dark`) and `data-palette` (the theme ID). Use `data-theme` for differences between light and dark. +The window sends a `runestone-theme-changed` event after each theme change. A plugin that copies token values, for example into a canvas or a terminal, reads them again on that event. + ## Use the SDK instead of native calls Do not call `invoke`, `listen`, or other `@tauri-apps/api` functions from a plugin. Do not read the private files of other plugins. diff --git a/docs/ui-color.md b/docs/ui-color.md index 719fd58..dab54f0 100644 --- a/docs/ui-color.md +++ b/docs/ui-color.md @@ -16,20 +16,30 @@ Agents also apply the user-level `ui-functional-color` skill. This guide adds th ## Roles and tokens -All tokens are in `src/lib/theme/tokens.css`, unless the table names another file. Correct a wrong token at its source. Do not add local saturation or opacity overrides. +A theme is data. Each built-in theme is one file in `src/lib/theme/themes/`, with one palette for each mode that it offers. +`src/lib/theme/roles.ts` lists the color roles. Each role is the CSS token `--rs-`. +A theme gives the base roles. One rule for all themes fills each other role from the base roles, unless the theme gives a value. +No code outside the theme data names a theme ID. `tests/unit/theme/contrast.spec.ts` checks this. + +Correct a wrong color in the theme data or in the derivation rule. Do not add local saturation or opacity overrides. | Role | Tokens | Requirement | | --- | --- | --- | -| Theme identity | `--rs-accent`, `--rs-accent-2`, palette surfaces in `src/lib/theme/characterThemes.ts` | Keep the characteristic hues of the reference at their strength. | +| Theme identity | `--rs-accent`, `--rs-accent-2` | Keep the characteristic hues of the reference at their strength. | | Status | `--rs-error`, `--rs-warn`, `--rs-warn-hot`, `--rs-ok` | Use clear, assertive colors. Pair color with a shape or text. | | Priority (Project Management) | `--pm-priority-color` in the plugin `src/style.css` | Full saturation and value, with opaque symbols and readable text. | -| Links and actions | `--rs-accent` | Keep actionable text distinct and readable on its actual surface. | -| Selection and focus | `--rs-item-selection-*`, `--rs-selection`, `--rs-selection-text` | Show a clear state change and boundary. Content inside the selection stays readable. | +| Links and actions | `--rs-link` (from `--rs-accent` unless the theme sets it) | Keep actionable text distinct and readable on its actual surface. | +| Text on an accent fill | `--rs-on-accent` (black or white, whichever is more readable) | Readable text and icons on accent buttons and badges. | +| Focus | `--rs-focus` (from `--rs-accent` unless the theme sets it) | A visible outline on every surface. | +| Selection | `--rs-item-selection-*`, `--rs-selection`, `--rs-selection-text` | Show a clear state change and boundary. Content inside the selection stays readable. | +| Highlighted text | `--rs-highlight` | A fill that keeps the text readable. | | Syntax | `--rs-syntax-*`, one for each role in `SYNTAX_ROLES` | Give each meaning a distinct color. A palette has at least 7 distinct syntax colors. | -| Surfaces and dividers | `--rs-bg`, `--rs-bg-elevated`, `--rs-bg-active`, `--rs-border`, `--rs-image-*` tints | Support the content. Choose their strength by function. | +| Terminal | `--rs-ansi-*` and `--rs-ansi-bright-*`, one for each color in `ANSI_COLORS` | Each color keeps its ANSI hue in every theme. Blue stays blue, also in a red theme. | +| Surfaces and dividers | `--rs-bg`, `--rs-bg-elevated`, `--rs-bg-active`, `--rs-border`, `--rs-line-highlight`, `--rs-scrim`, `--rs-image-*` tints | Support the content. Choose their strength by function. | | Disabled states | Role tokens of the control | Keep labels readable. Do not apply disabled opacity to enabled content. | Do not fade a whole badge, row, or container when only its background needs transparency. +Plugins use the same tokens. [Theme tokens](plugin-development.md#theme-tokens) lists them for plugin authors. ## Theme references @@ -51,15 +61,29 @@ The October 13 review found these problems. The values record that correction. T The [October 13 menu and color review](archive/menu-audit-2026-10-13.md) holds the measurements and the image-surface limits. -## Contrast thresholds +## Readability rules -| Pair | Minimum | Test | +`src/lib/theme/contrast.ts` holds these rules. `tests/unit/theme/contrast.spec.ts` applies them to every built-in palette. The theme editor can show the same results. +Each surface is the color that the app draws: a translucent role is composited onto `bg`. Text selection is at most 65% opaque. + +| Rule | Check | Minimum | | --- | --- | --- | -| `text`, `text-dim`, `text-strong`, and `accent` on `bg`, `bg-elevated`, `bg-active`, and `selection` | 4.5:1 | `tests/unit/theme/appearance.spec.ts`, `tests/unit/theme/themePalette.spec.ts` | -| Each syntax role on `bg` and `bg-active` | 4.5:1 | `tests/unit/theme/appearance.spec.ts` | -| Accent selection perimeter on the selection fill | 3:1 | `tests/unit/theme/malfoidPalette.spec.ts` | +| `text` | `text`, `text-dim`, and `text-strong` on `bg`, `bg-elevated`, `bg-active`, and `selection` | 4.5:1 | +| `accent-text` | `accent` and `link` on `bg`, `bg-elevated`, and `bg-active` | 4.5:1 | +| `status-text` | `error`, `warn`, and `ok` on `bg` and `bg-elevated` | 4.5:1 | +| `syntax` | Each syntax role on `bg`, `bg-active`, and `line-highlight` | 4.5:1 | +| `ansi` | Red, green, yellow, blue, magenta, and cyan terminal colors, and their bright variants, on `bg` | 4.5:1 | +| `focus` | `focus` on `bg`, `bg-elevated`, and `bg-active` | 3:1 | +| `on-accent` | `on-accent` on `accent` | 4.5:1 | +| `highlight` | `text` on highlighted text | 4.5:1 | +| `selection-outline` | `accent` on the item selection fill over `bg-elevated` | 3:1 | +| `status-distinct` | OKLab distance between `accent`, `error`, `warn`, and `ok`, in pairs | 0.1 | +| `syntax-variety` | Distinct syntax colors | 7 | +| `light-page` | In a light palette, `bg` is lighter than `bg-elevated` and `bg-active` | — | `accent` on `selection` is exempt from the 4.5:1 text check. Run the tests with `pnpm test`. +The test lists the failures of current palettes as `todo`. A palette change removes its entries. The test fails when a listed rule passes, so the list cannot go stale. +`tests/unit/theme/characterPalettes.spec.ts` adds the checks of each character palette, for example over image tints. Over a user image, contrast depends on the composite surface. Measure the 82% and 90% tints over the image that the change uses. Do not claim contrast over every possible image or overlay. When contrast fails, change the foreground, background, surface, or role before you reduce color strength. diff --git a/docs/ui-design.md b/docs/ui-design.md index 01514ac..b2c4004 100644 --- a/docs/ui-design.md +++ b/docs/ui-design.md @@ -31,7 +31,8 @@ Do not copy feature-specific colors into a shared control. | Undo, Redo, clipboard, and search rows | `src/lib/ui/menuItems.ts` | | Menu and picker presentation | `src/lib/ui/menu.css` | | Find | `src/lib/editor/FindPanel.svelte` and `src/lib/ui/find.css`. Write and Source search with `editorSearch.ts`. Read and plugin views search with `readingSearch.ts`. | -| Dimensions and colors | `src/lib/theme/tokens.css` | +| Dimensions and fixed colors | `src/lib/theme/tokens.css` | +| Theme colors | The roles in `src/lib/theme/roles.ts` and the theme data in `src/lib/theme/themes/`. See [Functional color](ui-color.md#roles-and-tokens). | | Token | Default | Use | | --- | --- | --- | @@ -153,9 +154,9 @@ Decisions: [UI-004](design-decisions.md#ui-004--detached-tab-work-area), [UI-039 - Controls wrap at narrow widths, and the content area scrolls. Long navigation must leave room for the selected page. - General offers the interface language through the shared action menu. - The transparency slider covers 0% to 100% and uses the accent and surface tokens of the current theme. -- Custom theme templates use schema 2: one fixed `colors` palette and `fonts` stacks for interface, prose, headings, and code. A schema 1 import selects the palette of the current appearance. +- Custom theme files use schema 3: one `mode`, an optional built-in `base` theme, the `colors` that differ from the base, and `fonts` stacks for interface, prose, headings, and code. The export writes every color and font. Schema 1 and 2 imports convert to schema 3. A schema 1 import selects the palette of the current appearance. -Decisions: [UI-028](design-decisions.md#ui-028--adjustable-surface-transparency-and-fixed-custom-palettes). +Decisions: [UI-028](design-decisions.md#ui-028--adjustable-surface-transparency-and-fixed-custom-palettes), [UI-042](design-decisions.md#ui-042--theme-file-format-3-and-terminal-colors). ## Typography and tables diff --git a/src/lib/browser/Bookmarks.svelte b/src/lib/browser/Bookmarks.svelte index 4f87ae9..c36feea 100644 --- a/src/lib/browser/Bookmarks.svelte +++ b/src/lib/browser/Bookmarks.svelte @@ -17,5 +17,5 @@ diff --git a/src/lib/browser/Browser.svelte b/src/lib/browser/Browser.svelte index 38a64e9..2acecdb 100644 --- a/src/lib/browser/Browser.svelte +++ b/src/lib/browser/Browser.svelte @@ -293,13 +293,13 @@ .toolbar,.findbar{display:flex;align-items:center;gap:4px;padding:5px 8px;border-bottom:1px solid var(--rs-border);background:var(--rs-bg-elevated)} .toolbar{flex-wrap:wrap}.toolbar input{flex:1 1 120px}.findbar input{max-width:320px}.find-count{font-size:12px;white-space:nowrap;color:var(--rs-text-dim);min-width:66px} input,.profile-choice{min-width:0;border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg);color:var(--rs-text);font:inherit;padding:5px 8px} - input{flex:1}.profile-choice{max-width:160px;display:flex;align-items:center;gap:var(--rs-menu-icon-gap);cursor:pointer}input:focus-visible,.profile-choice:focus-visible{outline:2px solid var(--rs-accent)} + input{flex:1}.profile-choice{max-width:160px;display:flex;align-items:center;gap:var(--rs-menu-icon-gap);cursor:pointer}input:focus-visible,.profile-choice:focus-visible{outline:2px solid var(--rs-focus)} .surface{position:relative;flex:1;min-height:0;overflow:hidden;outline:none;background:var(--rs-bg)}.surface:focus-visible{box-shadow:inset 0 0 0 1px var(--rs-accent)} .browser.blank,.blank .surface{background:transparent} .surface.autoscroll{cursor:all-scroll}.scroll-anchor{position:absolute;transform:translate(-50%,-50%);display:grid;place-items:center;width:24px;height:24px;border:1px solid var(--rs-text);border-radius:50%;background:var(--rs-bg-elevated);color:var(--rs-text);font-size:20px;pointer-events:none;box-shadow:0 1px 4px #0006} img{display:block;pointer-events:none;user-select:none;will-change:transform}img.exact{image-rendering:pixelated}.error{margin:0;padding:5px 10px;color:var(--rs-error);font-size:12px} .error p{margin:4px 0}.status,.diagnostics{margin:0;padding:8px 10px;font-size:12px;color:var(--rs-text-dim)} .reconnect{padding:6px 12px;margin:4px 0;border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg-elevated);color:var(--rs-text);cursor:pointer} - .reconnect:focus-visible,summary:focus-visible{outline:2px solid var(--rs-accent);outline-offset:2px}summary{cursor:pointer} + .reconnect:focus-visible,summary:focus-visible{outline:2px solid var(--rs-focus);outline-offset:2px}summary{cursor:pointer} dl{display:grid;grid-template-columns:auto 1fr;gap:4px 12px}dd{margin:0;overflow-wrap:anywhere;user-select:text} diff --git a/src/lib/browser/Settings.svelte b/src/lib/browser/Settings.svelte index c899948..ef6f130 100644 --- a/src/lib/browser/Settings.svelte +++ b/src/lib/browser/Settings.svelte @@ -75,7 +75,7 @@ p{color:var(--rs-text-dim);font-size:var(--rs-settings-description-size);line-height:1.6}.card{padding:0 var(--rs-settings-row-padding);background:var(--rs-bg-elevated);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius)} .row{display:flex;justify-content:space-between;align-items:center;gap:var(--rs-settings-gap);padding:var(--rs-settings-row-padding) 0}.row+.row{border-top:1px solid var(--rs-border)} input,textarea,button{border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg);color:var(--rs-text);font:inherit;box-sizing:border-box;min-height:var(--rs-settings-control-height);padding:4px 8px} - button{display:inline-flex;align-items:center;gap:7px;background:var(--rs-bg-elevated);cursor:pointer}button:hover{background:var(--rs-bg-active)}button:focus-visible,input:focus-visible,textarea:focus-visible{outline:2px solid var(--rs-accent);outline-offset:1px} + button{display:inline-flex;align-items:center;gap:7px;background:var(--rs-bg-elevated);cursor:pointer}button:hover{background:var(--rs-bg-active)}button:focus-visible,input:focus-visible,textarea:focus-visible{outline:2px solid var(--rs-focus);outline-offset:1px} .picker{justify-content:space-between;min-width:140px;max-width:100%;overflow-wrap:anywhere;text-align:left} .rules{display:flex;flex-direction:column;gap:7px;margin:16px 0}.profiles{padding-top:16px;padding-bottom:8px}.profiles label,.profile-choice{display:flex;flex-direction:column;gap:7px;margin-bottom:14px} .actions{display:flex;flex-wrap:wrap;gap:8px}.note{margin-bottom:0} diff --git a/src/lib/browser/WebData.svelte b/src/lib/browser/WebData.svelte index ef0b6df..5049afc 100644 --- a/src/lib/browser/WebData.svelte +++ b/src/lib/browser/WebData.svelte @@ -60,7 +60,7 @@ section{margin-top:var(--rs-settings-section-gap)}.toolbar{display:flex;align-items:end;gap:var(--rs-settings-gap);flex-wrap:wrap} label,.choice{display:flex;flex-direction:column;gap:4px}.search{flex:1;min-width:150px}input,button{min-height:var(--rs-settings-control-height);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg-elevated);color:var(--rs-text);font:inherit;padding:4px 8px} button{display:inline-flex;align-items:center;justify-content:center;gap:6px;flex:none;cursor:pointer}button:hover{background:var(--rs-bg-active)}button:disabled{opacity:.6;cursor:wait} - button:focus-visible,input:focus-visible{outline:2px solid var(--rs-accent);outline-offset:1px} + button:focus-visible,input:focus-visible{outline:2px solid var(--rs-focus);outline-offset:1px} p,small{font-size:var(--rs-settings-description-size);color:var(--rs-text-dim);line-height:1.5}.entries{max-height:320px;overflow:auto;border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);padding:0 var(--rs-settings-row-padding)} .entry{display:flex;gap:var(--rs-settings-gap);align-items:center;padding:var(--rs-settings-row-padding) 0}.entry+.entry{border-top:1px solid var(--rs-border)}.entry>div{flex:1;min-width:0;overflow-wrap:anywhere}small{display:block}strong{font-weight:500}[role=alert]{color:var(--rs-error)} @media(max-width:450px){.entry{flex-wrap:wrap}.entry>div{flex-basis:100%}} diff --git a/src/lib/completion/input.ts b/src/lib/completion/input.ts index 4da9785..a6aa279 100644 --- a/src/lib/completion/input.ts +++ b/src/lib/completion/input.ts @@ -5,7 +5,7 @@ export const registerCompletionInput: CompletionApi["registerInput"] = (element, let revision = 0, composing = false; const hint = document.createElement("div"); hint.className = "rs-completion-hint"; - hint.style.cssText = "position:fixed;z-index:10000;pointer-events:none;max-width:40em;padding:6px 10px;border-radius:var(--rs-control-radius,6px);background:var(--rs-bg,#20242a);color:var(--rs-text,#eee);border:1px solid currentColor;font:inherit;white-space:pre-wrap"; + hint.style.cssText = "position:fixed;z-index:10000;pointer-events:none;max-width:40em;padding:6px 10px;border-radius:var(--rs-control-radius);background:var(--rs-bg);color:var(--rs-text);border:1px solid currentColor;font:inherit;white-space:pre-wrap"; hint.hidden = true; hint.setAttribute("aria-hidden", "true"); document.body.append(hint); diff --git a/src/lib/editor/DocumentEditor.svelte b/src/lib/editor/DocumentEditor.svelte index 6d8f9ec..c444ed7 100644 --- a/src/lib/editor/DocumentEditor.svelte +++ b/src/lib/editor/DocumentEditor.svelte @@ -469,8 +469,8 @@ .live-writer :global(.writer-strong) { font-weight: 600; color: var(--rs-text-strong); } .live-writer :global(.writer-emphasis) { font-style: italic; } .live-writer :global(.writer-strike), .live-writer :global(.writer-completed) { text-decoration: line-through; color: var(--rs-text-dim); } - .live-writer :global(.writer-link) { color: var(--rs-accent); text-decoration: underline; text-underline-offset: 3px; } - .live-writer :global(.writer-link-source) { color: var(--rs-accent); } + .live-writer :global(.writer-link) { color: var(--rs-link); text-decoration: underline; text-underline-offset: 3px; } + .live-writer :global(.writer-link-source) { color: var(--rs-link); } .live-writer :global(.writer-link-target) { text-decoration: underline; text-underline-offset: 3px; } .live-writer :global(.writer-inline-code), .live-writer :global(.writer-code-source) { font-family: var(--rs-font-mono); font-size: .9em; } .live-writer :global(.writer-inline-code) { background: var(--rs-bg-elevated); border-radius: 3px; } @@ -479,8 +479,8 @@ .live-writer :global(.writer-code-last) { padding-bottom: 10px; border-bottom: 1px solid var(--rs-border); border-radius: 0 0 var(--rs-control-radius) var(--rs-control-radius); } .live-writer :global(.writer-code-fence) { color: var(--rs-text-dim); } .live-writer :global(.writer-code-copy) { top: 4px; border-radius: var(--rs-control-radius); } - .live-writer :global(.writer-code-copy:focus-visible) { outline: 1px solid var(--rs-accent); outline-offset: -2px; } - .live-writer :global(.writer-highlight) { background: #e7c56a38; color: var(--rs-text-strong); } + .live-writer :global(.writer-code-copy:focus-visible) { outline: 1px solid var(--rs-focus); outline-offset: -2px; } + .live-writer :global(.writer-highlight) { background: color-mix(in srgb, var(--rs-highlight) 22%, transparent); color: var(--rs-text-strong); } .live-writer :global(.writer-math) { font-family: var(--rs-font-mono); font-style: italic; } .live-writer :global(.writer-comment) { color: var(--rs-text-dim); background: var(--rs-bg-active); } .live-writer :global(.writer-divider-line) { display: flex; align-items: center; } diff --git a/src/lib/editor/headingFolding.css b/src/lib/editor/headingFolding.css index 4989c55..dcb28cd 100644 --- a/src/lib/editor/headingFolding.css +++ b/src/lib/editor/headingFolding.css @@ -4,7 +4,7 @@ .live-writer .rs-heading-toggle { top: .7em; } .rs-heading-toggle { position: absolute; inset-inline-start: -30px; top: 0; width: 28px; height: 28px; padding: 6px; border: 0; border-radius: var(--rs-control-radius); color: var(--rs-text-dim); background: transparent; cursor: pointer; display: inline-flex; align-items: center; justify-content: center; vertical-align: middle; } .rs-heading-toggle:hover, .rs-heading-toggle:focus-visible { color: var(--rs-text); background: var(--rs-bg-active); } -.rs-heading-toggle:focus-visible { outline: 1px solid var(--rs-accent); outline-offset: 1px; } +.rs-heading-toggle:focus-visible { outline: 1px solid var(--rs-focus); outline-offset: 1px; } .rs-heading-toggle svg { width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; } .rs-heading-toggle[aria-expanded="true"] svg { transform: rotate(90deg); } .rs-heading-collapsed::after { content: " …"; color: var(--rs-text-dim); font-weight: normal; } @@ -16,4 +16,4 @@ .reading .md-footnotes li { padding-inline-start: .3em; } .reading .md-footnotes li > p:last-of-type { display: inline; } .reading .md-footnote-back { margin-inline-start: .4em; } -.reading .md-footnote-ref a:focus-visible, .reading .md-footnote-back:focus-visible { outline: 1px solid var(--rs-accent); outline-offset: 3px; border-radius: var(--rs-control-radius); } +.reading .md-footnote-ref a:focus-visible, .reading .md-footnote-back:focus-visible { outline: 1px solid var(--rs-focus); outline-offset: 3px; border-radius: var(--rs-control-radius); } diff --git a/src/lib/editor/imageControls.css b/src/lib/editor/imageControls.css index 9597cef..306beaa 100644 --- a/src/lib/editor/imageControls.css +++ b/src/lib/editor/imageControls.css @@ -11,11 +11,11 @@ .md-image-frame:hover .md-image-actions, .md-image-frame:focus-within .md-image-actions { opacity: 1; } .image-action { position: relative; display: inline-grid; place-items: center; flex: 0 0 34px; width: 34px; height: 34px; padding: 6px; color: var(--rs-text); border: 0; border-radius: 4px; background: transparent; cursor: pointer; } .image-action:hover, .image-action:focus-visible { background: var(--rs-bg-active); color: var(--rs-text-strong); } -.image-action:focus-visible { outline: 2px solid var(--rs-accent); outline-offset: 1px; } +.image-action:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 1px; } .image-action:disabled { opacity: .4; cursor: default; } -.image-lightbox { position: fixed; inset: 0; width: 100vw; height: 100vh; max-width: none; max-height: none; margin: 0; padding: 0; border: 0; background: #090a0de8; color: var(--rs-text); } +.image-lightbox { position: fixed; inset: 0; width: 100vw; height: 100vh; max-width: none; max-height: none; margin: 0; padding: 0; border: 0; background: var(--rs-image-viewer-bg); color: var(--rs-text); } .image-lightbox[open] { display: flex; flex-direction: column; } -.image-lightbox::backdrop { background: #0009; } +.image-lightbox::backdrop { background: var(--rs-scrim); } .image-lightbox-toolbar { display: flex; align-items: center; gap: 6px; padding: 8px 16px; background: var(--rs-bg-elevated); z-index: 1; } .image-lightbox-name { margin-right: auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .image-lightbox-scale { min-width: 44px; text-align: center; font-size: 12px; } diff --git a/src/lib/editor/noteTitle.css b/src/lib/editor/noteTitle.css index 3b6d94f..a6e2921 100644 --- a/src/lib/editor/noteTitle.css +++ b/src/lib/editor/noteTitle.css @@ -2,8 +2,8 @@ .note-title-button { position: relative; display: inline-flex; align-items: center; gap: 12px; max-width: 100%; padding: 0; border: 0; background: transparent; color: inherit; font: inherit; text-align: left; overflow-wrap: anywhere; cursor: text; } .note-title-button .action-icon { opacity: .45; } .note-title-button:hover .action-icon, .note-title-button:focus-visible .action-icon { opacity: 1; color: var(--rs-accent); } -.note-title-button:focus-visible { outline: 1px solid var(--rs-accent); outline-offset: 4px; border-radius: 3px; } +.note-title-button:focus-visible { outline: 1px solid var(--rs-focus); outline-offset: 4px; border-radius: 3px; } .note-title-input { box-sizing: border-box; width: 100%; min-width: 0; padding: 0; border: 0; border-radius: 2px; outline: 1px solid var(--rs-accent); outline-offset: 4px; background: transparent; color: inherit; font: inherit; } -.note-title-input[aria-invalid] { outline-color: var(--rs-danger, #e57878); } -.note-title-error { margin: -.8em 0 1em; color: var(--rs-danger, #e57878); font: 13px/1.5 var(--rs-font-ui); } +.note-title-input[aria-invalid] { outline-color: var(--rs-error); } +.note-title-error { margin: -.8em 0 1em; color: var(--rs-error); font: 13px/1.5 var(--rs-font-ui); } .note-title-button[hidden], .note-title-input[hidden], .note-title-error[hidden] { display: none; } diff --git a/src/lib/editor/sourceView.ts b/src/lib/editor/sourceView.ts index 4479c7b..9780b22 100644 --- a/src/lib/editor/sourceView.ts +++ b/src/lib/editor/sourceView.ts @@ -13,20 +13,20 @@ const syntax = (role: string, fallback: string) => `var(--rs-syntax-${role}, ${f /** Syntax colors come from the theme tokens, so a theme change needs no editor update. */ const sourceHighlight = HighlightStyle.define([ { tag: [tags.keyword, tags.modifier, tags.operatorKeyword, tags.controlKeyword, tags.definitionKeyword, tags.moduleKeyword, tags.tagName], color: syntax("keyword", "var(--rs-accent)") }, - { tag: tags.heading, color: syntax("keyword", "var(--rs-accent)"), fontWeight: "600" }, + { tag: tags.heading, color: syntax("heading", "var(--rs-accent)"), fontWeight: "600" }, { tag: [tags.string, tags.special(tags.string), tags.regexp, tags.attributeValue, tags.url, tags.monospace], color: syntax("string", "var(--rs-ok)") }, { tag: [tags.number, tags.bool, tags.null, tags.atom, tags.unit], color: syntax("number", "var(--rs-special)") }, { tag: tags.comment, color: syntax("comment", "var(--rs-text-dim)") }, { tag: [tags.typeName, tags.className, tags.namespace], color: syntax("type", "var(--rs-accent-2)") }, { tag: [tags.function(tags.variableName), tags.function(tags.propertyName), tags.macroName], color: syntax("function", "var(--rs-accent-2)") }, - { tag: [tags.propertyName, tags.attributeName], color: syntax("instance", "var(--rs-accent-2)") }, - { tag: [tags.standard(tags.variableName), tags.self, tags.special(tags.variableName)], color: syntax("global", "var(--rs-text-dim)") }, - { tag: tags.variableName, color: syntax("local", "var(--rs-text)") }, - { tag: [tags.punctuation, tags.operator, tags.meta, tags.processingInstruction], color: syntax("global", "var(--rs-text-dim)") }, + { tag: [tags.propertyName, tags.attributeName], color: syntax("property", "var(--rs-accent-2)") }, + { tag: [tags.standard(tags.variableName), tags.self, tags.special(tags.variableName)], color: syntax("constant", "var(--rs-text-dim)") }, + { tag: tags.variableName, color: syntax("variable", "var(--rs-text)") }, + { tag: [tags.punctuation, tags.operator, tags.meta, tags.processingInstruction], color: syntax("punctuation", "var(--rs-text-dim)") }, { tag: tags.emphasis, fontStyle: "italic" }, { tag: tags.strong, fontWeight: "600" }, { tag: tags.strikethrough, textDecoration: "line-through" }, - { tag: tags.link, color: "var(--rs-accent)", textDecoration: "underline" }, + { tag: tags.link, color: "var(--rs-link)", textDecoration: "underline" }, { tag: tags.invalid, color: "var(--rs-error)" }, ]); diff --git a/src/lib/formulas/formulas.css b/src/lib/formulas/formulas.css index a660554..fd0e3a0 100644 --- a/src/lib/formulas/formulas.css +++ b/src/lib/formulas/formulas.css @@ -1,12 +1,12 @@ /* Table formula results and help below a table. */ .md-table-formula { color: var(--rs-accent); font-variant-numeric: tabular-nums; } -.md-table-formula.is-error { color: var(--rs-danger, #ed8796); text-decoration: underline dotted; } +.md-table-formula.is-error { color: var(--rs-error); text-decoration: underline dotted; } .table-footer { display: grid; gap: 8px; margin: 0 26px 1.4em; min-width: 0; font: 12px/1.5 var(--rs-font-ui); color: var(--rs-text-dim); white-space: normal; overflow-wrap: anywhere; } .table-formula-tools { display: flex; align-items: center; flex-wrap: wrap; gap: 8px 16px; min-width: 0; } .table-formula-help { min-width: 0; } .table-formula-help summary { display: flex; align-items: center; gap: 5px; cursor: pointer; min-height: 28px; border-radius: 4px; } .table-formula-help summary:hover, .table-formula-help summary:focus-visible { color: var(--rs-accent); } -.table-formula-help summary:focus-visible { outline: 1px solid var(--rs-accent); outline-offset: 2px; } +.table-formula-help summary:focus-visible { outline: 1px solid var(--rs-focus); outline-offset: 2px; } .table-formula-help[open] { flex-basis: 100%; } .table-formula-instructions { display: grid; gap: 12px; max-width: 680px; padding: 12px; border: 1px solid var(--rs-border); border-radius: 6px; line-height: 1.7; color: var(--rs-text); background: var(--rs-bg-elevated); } .table-formula-instructions p, .table-formula-instructions dl, .table-formula-instructions dd { margin: 0; } diff --git a/src/lib/i18n/messages.ts b/src/lib/i18n/messages.ts index bb086ff..09388b1 100644 --- a/src/lib/i18n/messages.ts +++ b/src/lib/i18n/messages.ts @@ -3454,7 +3454,10 @@ export const messageRows: [string, string, string, string][] = [ ["Image clipboard is unavailable.", "Le presse-papiers d’images n’est pas disponible.", "画像のクリップボードを利用できません。", "图像剪贴板不可用。"], ["Choose an image of 50 MiB or less.", "Choisissez une image de 50 Mio au plus.", "50 MiB 以下の画像を選択してください。", "请选择 50 MiB 或更小的图像。"], ["Choose a RuneStone theme JSON file.", "Choisissez un fichier de thème RuneStone au format JSON.", "RuneStone のテーマ JSON ファイルを選択してください。", "请选择 RuneStone 主题 JSON 文件。"], - ["The theme needs schema 2, an ID, and a name.", "Le thème nécessite le schéma 2, un identifiant et un nom.", "テーマにはスキーマ 2、ID、名前が必要です。", "主题需要架构 2、ID 和名称。"], + ["The theme needs a schema number, an ID, and a name.", "Le thème nécessite un numéro de schéma, un identifiant et un nom.", "テーマにはスキーマ番号、ID、名前が必要です。", "主题需要架构编号、ID 和名称。"], + ["Use light or dark for the theme mode.", "Utilisez light ou dark pour le mode du thème.", "テーマのモードには light または dark を使用してください。", "主题模式请使用 light 或 dark。"], + ["Use a built-in theme with a {mode} palette as the base.", "Utilisez comme base un thème intégré qui a une palette {mode}.", "{mode} パレットを持つ組み込みテーマをベースとして使用してください。", "请使用具有 {mode} 调色板的内置主题作为基础。"], + ["Use an object for theme colors.", "Utilisez un objet pour les couleurs du thème.", "テーマの色にはオブジェクトを使用してください。", "主题颜色请使用对象。"], ["The theme needs {mode} colors.", "Le thème nécessite des couleurs {mode}.", "テーマには {mode} の色が必要です。", "主题需要 {mode} 颜色。"], ["Unknown theme color: {key}", "Couleur de thème inconnue : {key}", "不明なテーマの色: {key}", "未知的主题颜色:{key}"], ["Use a hexadecimal color for {key}.", "Utilisez une couleur hexadécimale pour {key}.", "{key} には16進数の色を使用してください。", "请为 {key} 使用十六进制颜色。"], diff --git a/src/lib/layout/Backlinks.svelte b/src/lib/layout/Backlinks.svelte index 12518c9..7a8b23f 100644 --- a/src/lib/layout/Backlinks.svelte +++ b/src/lib/layout/Backlinks.svelte @@ -67,12 +67,12 @@ .content[hidden] { display: none; } ul { list-style: none; padding: 2px 6px 6px; margin: 0; } .source { width: 100%; display: block; padding: 6px; border: 0; border-radius: var(--rs-control-radius); background: transparent; color: var(--rs-text); text-align: left; font: inherit; } - .source-title { display: flex; align-items: center; gap: 6px; color: var(--rs-accent); } + .source-title { display: flex; align-items: center; gap: 6px; color: var(--rs-link); } .source-title > span:first-of-type { min-width: 0; overflow-wrap: anywhere; } .line { margin-left: auto; color: var(--rs-text-dim); font-variant-numeric: tabular-nums; } .excerpt { display: -webkit-box; line-clamp: 2; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; margin-top: 3px; font-size: 12px; overflow-wrap: anywhere; } .toggle:hover, .source:hover { background: var(--rs-bg-active); } - .toggle:focus-visible, .source:focus-visible { outline: 2px solid var(--rs-accent); outline-offset: -2px; } + .toggle:focus-visible, .source:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: -2px; } .placeholder, .error { margin: 8px 12px; font-size: 12px; overflow-wrap: anywhere; } .placeholder { color: var(--rs-text-dim); } .error { color: var(--rs-error); } diff --git a/src/lib/layout/QuickOpen.svelte b/src/lib/layout/QuickOpen.svelte index 770678b..53e6f9e 100644 --- a/src/lib/layout/QuickOpen.svelte +++ b/src/lib/layout/QuickOpen.svelte @@ -56,7 +56,7 @@ diff --git a/src/lib/layout/TextDialog.svelte b/src/lib/layout/TextDialog.svelte index 3acd93b..e0e882e 100644 --- a/src/lib/layout/TextDialog.svelte +++ b/src/lib/layout/TextDialog.svelte @@ -27,7 +27,7 @@ diff --git a/src/lib/plugins/PluginManager.svelte b/src/lib/plugins/PluginManager.svelte index 73427b2..fdb34db 100644 --- a/src/lib/plugins/PluginManager.svelte +++ b/src/lib/plugins/PluginManager.svelte @@ -223,7 +223,7 @@ input[role=switch]:checked { background: var(--rs-accent); border-color: var(--rs-accent); } input[role=switch]:checked::before { transform: translateX(16px); background: var(--rs-bg); } dialog { width: min(650px, 90vw); max-height: 85vh; padding: 16px; color: var(--rs-text); background: var(--rs-bg); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); } - dialog::backdrop { background: #0009; } + dialog::backdrop { background: var(--rs-scrim); } footer { justify-content: flex-end; margin-top: var(--rs-settings-section-gap); } .candidate { padding: var(--rs-settings-row-padding) 0; border-bottom: 1px solid var(--rs-border); } .candidate label { display: flex; gap: 8px; } diff --git a/src/lib/plugins/PluginTools.svelte b/src/lib/plugins/PluginTools.svelte index 64f1f82..fedbcdd 100644 --- a/src/lib/plugins/PluginTools.svelte +++ b/src/lib/plugins/PluginTools.svelte @@ -33,7 +33,7 @@ {/if} diff --git a/tests/smoke/appearance/characterThemes.smoke.mjs b/tests/smoke/appearance/characterThemes.smoke.mjs index eedd573..4583791 100644 --- a/tests/smoke/appearance/characterThemes.smoke.mjs +++ b/tests/smoke/appearance/characterThemes.smoke.mjs @@ -76,13 +76,13 @@ await runSmoke('appearance/characterThemes', async ({ browser }) => { await settings.setViewportSize({ width: 1100, height: 780 }); await choose('Color theme', label); await waitForAppearance(theme, mode); - // The export is now one theme template, { schema, id, name, colors, fonts }, for the theme's own mode (src/lib/theme/appearance.ts:76-91). + // The export is one schema 3 theme file with every role, for the theme's own mode (exportAppearanceTheme in src/lib/theme/appearance.ts). const template = await settings.evaluate(async theme => { const { exportAppearanceTheme } = await import('/src/lib/theme/appearance.ts'); return exportAppearanceTheme(theme); }, theme); const colors = template.colors; - // The applied selection color caps its alpha at a6 so text backgrounds show through (src/lib/theme/appearance.ts:197-203). + // The applied selection color caps its alpha at a6 so text backgrounds show through (appliedColors in src/lib/theme/contrast.ts). const applied = { ...colors, selection: `${colors.selection.slice(0, 7)}a6` }; const actual = await settings.evaluate(keys => { const css = getComputedStyle(document.documentElement); diff --git a/tests/smoke/appearance/palettes.smoke.mjs b/tests/smoke/appearance/palettes.smoke.mjs index d9e1b3a..c5e53de 100644 --- a/tests/smoke/appearance/palettes.smoke.mjs +++ b/tests/smoke/appearance/palettes.smoke.mjs @@ -128,10 +128,10 @@ await runSmoke("appearance/palettes", async ({ browser }) => { assert.equal(await picker(secondSettings, "Appearance").count(), 0); const sakura = await settings.evaluate(() => { const css = getComputedStyle(document.documentElement); - return Object.fromEntries(["bg", "border", "selection", "bg-active", "syntax-parameter", "syntax-keyword", "syntax-local", "syntax-static", "syntax-instance", "syntax-global"].map(key => [key, css.getPropertyValue(`--rs-${key}`).trim()])); + return Object.fromEntries(["bg", "border", "selection", "bg-active", "syntax-keyword", "syntax-variable", "syntax-property", "syntax-constant", "syntax-punctuation"].map(key => [key, css.getPropertyValue(`--rs-${key}`).trim()])); }); - // The applied selection color caps its alpha at a6 so text backgrounds show through (src/lib/theme/appearance.ts:197-203). - assert.deepEqual(sakura, { bg: "#fefcfc", border: "#f8dbe6", selection: "#ffc9dca6", "bg-active": "#dbeacb", "syntax-parameter": "#cb6b91", "syntax-keyword": "#98556c", "syntax-local": "#618c71", "syntax-static": "#69a2bd", "syntax-instance": "#607fa9", "syntax-global": "#687788" }); + // The applied selection color caps its alpha at a6 so text backgrounds show through (appliedColors in src/lib/theme/contrast.ts). + assert.deepEqual(sakura, { bg: "#fefcfc", border: "#f8dbe6", selection: "#ffc9dca6", "bg-active": "#dbeacb", "syntax-keyword": "#98556c", "syntax-variable": "#618c71", "syntax-property": "#607fa9", "syntax-constant": "#687788", "syntax-punctuation": "#687788" }); for (const [theme, savedMode, expectedTheme, mode] of [ ["gpt", "light", "default", "light"], ["terminal", "dark", "default", "dark"], diff --git a/tests/smoke/appearance/themeExport.smoke.mjs b/tests/smoke/appearance/themeExport.smoke.mjs index d5086e0..ec2d93e 100644 --- a/tests/smoke/appearance/themeExport.smoke.mjs +++ b/tests/smoke/appearance/themeExport.smoke.mjs @@ -19,8 +19,8 @@ await runSmoke("appearance/themeExport", async ({ page }) => { await page.getByRole("button", { name: "Appearance", exact: true }).click(); await exportButton.click(); await page.getByRole("status").filter({ hasText: "Theme saved to" }).waitFor(); - // Exported templates use theme schema 2 (src/lib/theme/appearance.ts:90). - assert.equal(await page.evaluate(() => JSON.parse(window.__TEST__.calls.find(call => call.command === "theme_export").args.contents).schema), 2); + // Exported templates use theme schema 3 (exportAppearanceTheme in src/lib/theme/appearance.ts). + assert.equal(await page.evaluate(() => JSON.parse(window.__TEST__.calls.find(call => call.command === "theme_export").args.contents).schema), 3); await page.evaluate(() => { window.__TEST__.state.exportResult = null; }); await exportButton.click(); await page.getByText("Export canceled.", { exact: true }).waitFor(); diff --git a/tests/smoke/appearance/themeImport.smoke.mjs b/tests/smoke/appearance/themeImport.smoke.mjs index 730bf90..aaeb482 100644 --- a/tests/smoke/appearance/themeImport.smoke.mjs +++ b/tests/smoke/appearance/themeImport.smoke.mjs @@ -1,4 +1,4 @@ -// Import a custom theme JSON in Settings > Appearance; its dark and light backgrounds apply. +// Import custom theme files in Settings > Appearance: schema 1 palettes for each mode, and a short schema 3 file with a base theme. import assert from "node:assert/strict"; import path from "node:path"; import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs"; @@ -15,8 +15,9 @@ await runSmoke(name, async ({ page }) => { await page.goto(smokeUrl + "/?settingsWindow=true"); await page.getByRole("button", { name: "Appearance", exact: true }).click(); const theme = { schema: 1, id: "smoke", name: "Smoke theme", light: { bg: "#fefefe", text: "#222222", accent: "#334499" }, dark: { bg: "#181820", text: "#eeeeee", accent: "#aabbff" } }; - const importTheme = () => page.locator('input[type=file][aria-label="Theme JSON file"]').setInputFiles({ name: "smoke.json", mimeType: "application/json", buffer: Buffer.from(JSON.stringify(theme)) }); - const background = () => page.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue("--rs-bg").trim()); + const importTheme = (file = theme) => page.locator('input[type=file][aria-label="Theme JSON file"]').setInputFiles({ name: "smoke.json", mimeType: "application/json", buffer: Buffer.from(JSON.stringify(file)) }); + const token = name => page.evaluate(name => getComputedStyle(document.documentElement).getPropertyValue(`--rs-${name}`).trim(), name); + const background = () => token("bg"); await importTheme(); await page.waitForFunction(() => document.documentElement.dataset.palette === "custom:smoke"); assert.equal(await background(), "#181820"); @@ -29,5 +30,18 @@ await runSmoke(name, async ({ page }) => { await page.waitForFunction(() => document.documentElement.dataset.palette === "custom:smoke"); assert.equal(await background(), "#fefefe"); await page.screenshot({ path: path.join(output, "custom-theme-light.png") }); - console.log("PASS: custom theme import applies its dark and light backgrounds"); + + // A short schema 3 file takes the missing colors and fonts from its base theme. An earlier theme ID names the base. + await importTheme({ schema: 3, id: "short", name: "Short theme", mode: "dark", base: "holo", colors: { accent: "#00c8ff" } }); + await page.waitForFunction(() => document.documentElement.dataset.palette === "custom:short"); + assert.deepEqual([await background(), await token("accent"), await token("link"), await token("syntax-keyword")], ["#251b17", "#00c8ff", "#00c8ff", "#ff6740"]); + assert.match(await token("font-ui"), /Candara/); + assert.equal(await page.evaluate(() => document.documentElement.dataset.theme), "dark"); + await page.screenshot({ path: path.join(output, "custom-theme-short.png") }); + + // A base without a palette in the file's mode stops the installation with an error. + await importTheme({ schema: 3, id: "wrong", name: "Wrong base", mode: "dark", base: "sakura", colors: {} }); + await page.getByRole("alert").filter({ hasText: "Use a built-in theme with a dark palette as the base." }).waitFor(); + assert.equal(await page.evaluate(() => document.documentElement.dataset.palette), "custom:short"); + console.log("PASS: custom theme import applies schema 1 palettes, a short schema 3 file with a base, and rejects a wrong base"); }, { timeout: 15000 }); diff --git a/tests/smoke/appearance/typography.smoke.mjs b/tests/smoke/appearance/typography.smoke.mjs index 7ca3e45..6b6f4b7 100644 --- a/tests/smoke/appearance/typography.smoke.mjs +++ b/tests/smoke/appearance/typography.smoke.mjs @@ -65,14 +65,17 @@ await runSmoke('appearance/typography', async ({ browser }) => { await main.waitForFunction(theme => document.documentElement.dataset.palette === theme, theme); await main.getByRole('textbox', { name: 'Writing editor', exact: true }).press('Control+Home'); await main.evaluate(() => { getSelection().removeAllRanges(); document.activeElement?.blur(); }); + // The theme sets its fonts as inline properties of the root. Put back those values after each temporary change. for (const page of [main, settings]) { - await page.evaluate(font => { - for (const role of ['ui', 'prose', 'heading']) document.documentElement.style.setProperty(`--rs-font-${role}`, `"${font}"`); - }, oldFont); + const saved = await page.evaluate(font => ['ui', 'prose', 'heading'].map(role => { + const value = document.documentElement.style.getPropertyValue(`--rs-font-${role}`); + document.documentElement.style.setProperty(`--rs-font-${role}`, `"${font}"`); + return value; + }), oldFont); await page.screenshot({ path: path.join(output, `${theme}-before-${page === main ? 'document' : 'settings'}.png`) }); - await page.evaluate(() => { - for (const role of ['ui', 'prose', 'heading']) document.documentElement.style.removeProperty(`--rs-font-${role}`); - }); + await page.evaluate(saved => { + ['ui', 'prose', 'heading'].forEach((role, index) => document.documentElement.style.setProperty(`--rs-font-${role}`, saved[index])); + }, saved); } const roles = { ui: await rendered(settings, selectors.ui), @@ -118,14 +121,14 @@ await runSmoke('appearance/typography', async ({ browser }) => { // Drop the first family from each stack and check that the fallback still renders glyphs. const fallback = {}; for (const [role, page] of [['ui', settings], ['prose', main], ['heading', main]]) { - await page.evaluate(role => { - const css = getComputedStyle(document.documentElement); - const stack = css.getPropertyValue(`--rs-font-${role}`); + const stack = await page.evaluate(role => { + const stack = getComputedStyle(document.documentElement).getPropertyValue(`--rs-font-${role}`); document.documentElement.style.setProperty(`--rs-font-${role}`, stack.slice(stack.indexOf(',') + 1)); + return stack; }, role); fallback[role] = await rendered(page, selectors[role]); assert(fallback[role].rendered.length > 0); - await page.evaluate(role => document.documentElement.style.removeProperty(`--rs-font-${role}`), role); + await page.evaluate(([role, stack]) => document.documentElement.style.setProperty(`--rs-font-${role}`, stack), [role, stack]); } report.push({ theme, oldFont, roles, fallback }); console.log(`PASS ${theme}: real UI and prose sizes, rendered fonts, shared monospace, selection, narrow settings, keyboard focus, long plugin navigation`); diff --git a/tests/unit/settings/migration.spec.ts b/tests/unit/settings/migration.spec.ts index c3931c0..efb407b 100644 --- a/tests/unit/settings/migration.spec.ts +++ b/tests/unit/settings/migration.spec.ts @@ -18,7 +18,7 @@ test('Migration reads the four old keys and the theme backup, and normalizes eac assert.deepEqual(sections, { general: { autosaveEnabled: false, autosaveSeconds: 5, showInternalFolder: false, tableFormulas: true }, language: 'fr', - customThemes: [custom], + customThemes: [{ ...custom, schema: 3, mode: 'dark' }], customThemesLegacy: [{ schema: 1, id: 'kept' }], // The mode comes from the migrated custom theme, not from a store that is still empty. appearance: { theme: 'custom:night', mode: 'dark', transparency: { enabled: true, amount: 100 } }, @@ -32,7 +32,7 @@ test('Migration of version 1 themes keeps the saved palette and adds the origina 'runestone.custom-themes': JSON.stringify([legacy]), 'runestone.custom-themes.legacy': JSON.stringify([legacy]), })); - assert.deepEqual(sections.customThemes, [{ schema: 2, id: 'old', name: 'Old', colors: legacy.light }]); + assert.deepEqual(sections.customThemes, [{ schema: 3, id: 'old', name: 'Old', mode: 'light', colors: legacy.light }]); assert.deepEqual(sections.customThemesLegacy, [legacy]); assert.deepEqual(sections.appearance, { theme: 'custom:old', mode: 'light' }); }); diff --git a/tests/unit/theme/appearance.spec.ts b/tests/unit/theme/appearance.spec.ts index 85f4e16..10b57cd 100644 --- a/tests/unit/theme/appearance.spec.ts +++ b/tests/unit/theme/appearance.spec.ts @@ -1,7 +1,7 @@ import assert from 'node:assert/strict'; import { test } from 'node:test'; import { parseCustomTheme } from '../../../src/lib/theme/customThemes.ts'; -import { CHARACTER_THEMES, SYNTAX_ROLES } from '../../../src/lib/theme/characterThemes.ts'; +import { SYNTAX_ROLES } from '../../../src/lib/theme/roles.ts'; import { parseAppearance, normalizeAppearance, exportAppearanceTheme, BUILTIN_THEMES, THEMES, themeModes } from '../../../src/lib/theme/appearance.ts'; test('Removed palettes preserve the saved mode with the default palette', () => { @@ -33,37 +33,17 @@ test('Removed character themes retain the saved background', () => { } }); -function luminance(color: string) { - const rgb = color.slice(1).match(/../g)!.map(value => parseInt(value, 16) / 255) - .map(value => value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4); - return rgb[0] * 0.2126 + rgb[1] * 0.7152 + rgb[2] * 0.0722; -} -function contrast(foreground: string, background: string) { - const values = [luminance(foreground), luminance(background)].sort((a, b) => b - a); - return (values[0] + 0.05) / (values[1] + 0.05); -} -test('Character palettes restore one appearance and export readable surfaces and syntax', () => { - for (const theme of Object.keys(CHARACTER_THEMES) as (keyof typeof CHARACTER_THEMES)[]) { - const exported = exportAppearanceTheme(theme); +// tests/unit/theme/contrast.spec.ts checks the readability of every palette. +test('Single-mode palettes restore their one appearance and export a valid theme', () => { + for (const { id } of BUILTIN_THEMES.filter(item => themeModes(item.id).length === 1)) { + const [only] = themeModes(id); + const exported = exportAppearanceTheme(id); for (const mode of ['light', 'dark'] as const) { - assert.deepEqual(parseAppearance(JSON.stringify({ theme, mode })), { theme, mode: CHARACTER_THEMES[theme].mode }); - const colors = exported.colors; - for (const foreground of ['text', 'text-dim', 'text-strong', 'accent'] as const) { - for (const background of ['bg', 'bg-elevated', 'bg-active', 'selection'] as const) { - if (foreground === 'accent' && background === 'selection') continue; - assert(contrast(colors[foreground]!, colors[background]!) >= 4.5, `${theme} ${mode}: ${foreground} on ${background}`); - } - } + assert.deepEqual(parseAppearance(JSON.stringify({ theme: id, mode })), { theme: id, mode: only }); } - assert.deepEqual(themeModes(theme), [CHARACTER_THEMES[theme].mode]); - assert.equal(exported.schema, 2); + assert.equal(exported.schema, 3); assert.deepEqual(parseCustomTheme(exported), exported); - for (const role of SYNTAX_ROLES) { - for (const background of ['bg', 'bg-active'] as const) { - assert(contrast(exported.colors[`syntax-${role}`]!, exported.colors[background]!) >= 4.5, `${theme}: ${role} on ${background}`); - } - } - assert(new Set(SYNTAX_ROLES.map(role => exported.colors[`syntax-${role}`])).size >= 7); + for (const role of SYNTAX_ROLES) assert.match(exported.colors[`syntax-${role}`] ?? '', /^#[0-9a-f]{6}$/); assert.notDeepEqual(exported.colors, exportAppearanceTheme('default').colors); } }); diff --git a/tests/unit/theme/characterPalettes.spec.ts b/tests/unit/theme/characterPalettes.spec.ts index 4ae4ad5..0805e40 100644 --- a/tests/unit/theme/characterPalettes.spec.ts +++ b/tests/unit/theme/characterPalettes.spec.ts @@ -1,7 +1,14 @@ // Character palettes: WCAG contrast of text and syntax colors on opaque and image-tinted surfaces, plus per-theme palette rules. import assert from 'node:assert/strict'; import { test } from 'node:test'; -import { characterTheme, characterSyntax, SYNTAX_ROLES } from '../../../src/lib/theme/characterThemes.ts'; +import { BUILTIN_THEMES } from '../../../src/lib/theme/themes/index.ts'; +import { SYNTAX_ROLES, resolveColors } from '../../../src/lib/theme/roles.ts'; + +/** Every role of a dark character palette, with the derived roles. */ +function characterTheme(theme: string) { + const palette = BUILTIN_THEMES.find(item => item.id === theme); + return palette && 'dark' in palette.variants ? resolveColors(palette.variants.dark, 'dark') : undefined; +} const rgb = (color: string) => color.slice(1).match(/../g)!.map(value => parseInt(value, 16)); const mix = (foreground: string, background: string, opacity: number) => '#' + rgb(foreground) @@ -19,13 +26,13 @@ function contrast(foreground: string, background: string) { /** Named foreground groups and surfaces of a palette. Image surfaces are tinted over a white image. */ function roles(theme: string) { const palette = characterTheme(theme)!; - const [bg, elevated, active, , dim, text, strong, accent, selection] = palette.surfaces; + const { bg, 'bg-elevated': elevated, 'bg-active': active, 'text-dim': dim, text, 'text-strong': strong, accent, selection } = palette; const editorOnWhite = mix(bg, '#ffffff', 0.9); const panelOnWhite = mix(elevated, '#ffffff', 0.82); const foregrounds = { ui: { dim, text, strong }, - accents: { accent, secondary: palette.secondary }, - syntax: Object.fromEntries(SYNTAX_ROLES.map((role, index) => [`syntax-${role}`, palette.syntax[index]])), + accents: { accent, secondary: palette['accent-2'] }, + syntax: Object.fromEntries(SYNTAX_ROLES.map(role => [`syntax-${role}`, palette[`syntax-${role}`]])), }; const surfaces = { bg, elevated, active, selection, editorOnWhite, panelOnWhite, @@ -69,14 +76,14 @@ for (const { theme, name, checks } of readable) { test('Harvest Moon uses the warm character colors for all palette roles', () => { const palette = characterTheme('harvest-moon')!; - for (const color of [...palette.surfaces, palette.secondary, ...palette.syntax]) { + const identity = ['bg', 'bg-elevated', 'bg-active', 'border', 'text', 'text-dim', 'text-strong', 'accent', 'accent-2', 'selection', ...SYNTAX_ROLES.map(role => `syntax-${role}` as const)] as const; + for (const role of identity) { + const color = palette[role]; assert.match(color, /^#[0-9a-f]{6}$/i); const [red, green, blue] = rgb(color); - assert(red >= green && green >= blue, `${color} must follow the copper, amber, red, or cream palette`); + assert(red >= green && green >= blue, `${role} ${color} must follow the copper, amber, red, or cream palette`); } - assert.equal(palette.mode, 'dark'); - assert.equal(Object.keys(characterSyntax('harvest-moon')).length, SYNTAX_ROLES.length); - assert.deepEqual(characterSyntax('unknown'), {}); + assert.deepEqual(Object.keys(BUILTIN_THEMES.find(item => item.id === 'harvest-moon')!.variants), ['dark']); }); test('Silver Serpent selection has a readable perimeter and a separate fill', () => { diff --git a/tests/unit/theme/contrast.spec.ts b/tests/unit/theme/contrast.spec.ts new file mode 100644 index 0000000..defe82b --- /dev/null +++ b/tests/unit/theme/contrast.spec.ts @@ -0,0 +1,79 @@ +// Readability rules for every built-in theme (src/lib/theme/contrast.ts), and the rule that only theme data names a theme. +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { readdirSync, readFileSync, statSync } from 'node:fs'; +import { join, relative } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { BUILTIN_THEMES } from '../../../src/lib/theme/themes/index.ts'; +import { BASE_ROLES, resolveColors, type Mode } from '../../../src/lib/theme/roles.ts'; +import { RULES, checkTheme } from '../../../src/lib/theme/contrast.ts'; +import { composite, contrast, distance, formatHex, mix, parseHex } from '../../../src/lib/theme/color.ts'; + +// Rules that a palette fails today. Stages 5a-3 and 5a-4 redesign these palettes and remove each entry. +const KNOWN_FAILURES: Record = { + 'default/dark': ['text', 'syntax-variety'], + 'default/light': ['text', 'syntax', 'syntax-variety', 'light-page'], + 'claude/dark': ['accent-text', 'status-text', 'syntax', 'status-distinct', 'syntax-variety'], + 'claude/light': ['accent-text', 'status-text', 'syntax', 'ansi', 'focus', 'selection-outline', 'syntax-variety', 'light-page'], + 'sakura/light': ['text', 'accent-text', 'status-text', 'syntax', 'ansi', 'syntax-variety', 'light-page'], + 'harvest-moon/dark': ['status-text', 'status-distinct'], + 'crimson-pilot/dark': ['status-distinct'], + 'silver-serpent/dark': ['status-text', 'status-distinct'], +}; + +const variants = BUILTIN_THEMES.flatMap(theme => Object.entries(theme.variants).map(([mode, colors]) => ({ key: `${theme.id}/${mode}`, mode: mode as Mode, colors: colors! }))); + +for (const variant of variants) { + const findings = checkTheme(resolveColors(variant.colors, variant.mode), variant.mode); + for (const rule of RULES) { + const results = findings.filter(finding => finding.rule === rule.id); + if (!results.length) continue; + const known = KNOWN_FAILURES[variant.key]?.includes(rule.id); + const failures = results.filter(finding => !finding.pass).map(finding => `${finding.subject}: ${finding.value.toFixed(2)} (minimum ${finding.min})`); + test(`${variant.key} passes the ${rule.id} rule`, known ? { todo: 'Known palette failure. Stages 5a-3 and 5a-4 redesign this palette.' } : {}, () => { + assert.deepEqual(failures, []); + }); + if (known) test(`${variant.key} still fails the known ${rule.id} rule`, () => { + assert(failures.length > 0, `Remove ${rule.id} from KNOWN_FAILURES['${variant.key}'].`); + }); + } +} + +test('Each known failure names a built-in variant and a rule', () => { + for (const [key, rules] of Object.entries(KNOWN_FAILURES)) { + assert(variants.some(variant => variant.key === key), key); + for (const rule of rules) assert(RULES.some(item => item.id === rule), `${key}: ${rule}`); + } +}); + +test('Every built-in variant gives all base roles as hex colors', () => { + for (const variant of variants) { + for (const role of BASE_ROLES) assert.match(variant.colors[role] ?? '', /^#[0-9a-f]{6}$/, `${variant.key}: ${role}`); + } +}); + +test('Color arithmetic matches CSS and WCAG', () => { + assert.deepEqual(parseHex('#0f08'), [0, 255, 0, 136 / 255]); + assert.equal(formatHex([255, 0, 0, 1]), '#ff0000'); + assert.equal(mix('#82aaff', '#141414', 0.8), '#6c8cd0'); + assert.equal(mix('#82aaff', '#0000', 0.2), '#82aaff33'); + assert.equal(composite('#ffffff80', '#000000'), '#808080'); + assert.equal(contrast('#000000', '#ffffff').toFixed(1), '21.0'); + assert(distance('#ff0000', '#ff0000') === 0 && distance('#000000', '#ffffff') > 0.99); +}); + +test('Only theme data names a theme ID', () => { + const root = fileURLToPath(new URL('../../../src', import.meta.url)); + const ids = BUILTIN_THEMES.flatMap(theme => [theme.id, ...('legacyIds' in theme ? theme.legacyIds : [])]).filter(id => id !== 'default'); + const pattern = new RegExp(`(['"\`])(?:${ids.join('|')})\\1|data-palette=`); + const files = (function walk(folder: string): string[] { + return readdirSync(folder).flatMap(name => { + const path = join(folder, name); + return statSync(path).isDirectory() ? walk(path) : /\.(ts|svelte|css)$/.test(name) ? [path] : []; + }); + })(root); + const found = files.filter(file => !relative(root, file).startsWith(join('lib', 'theme', 'themes')) && !file.endsWith('messages.ts')) + .filter(file => pattern.test(readFileSync(file, 'utf8'))) + .map(file => relative(root, file)); + assert.deepEqual(found, []); +}); diff --git a/tests/unit/theme/customThemes.spec.ts b/tests/unit/theme/customThemes.spec.ts index 97d9b58..2006d8c 100644 --- a/tests/unit/theme/customThemes.spec.ts +++ b/tests/unit/theme/customThemes.spec.ts @@ -1,11 +1,44 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; -import { COLOR_TOKENS, parseCustomTheme } from '../../../src/lib/theme/customThemes.ts'; -import { applyTransparency, normalizeAppearance, exportAppearanceTheme, BUILTIN_THEMES, themeModes } from '../../../src/lib/theme/appearance.ts'; +import { parseCustomTheme } from '../../../src/lib/theme/customThemes.ts'; +import { ROLES } from '../../../src/lib/theme/roles.ts'; +import { BUILTIN_THEMES as THEME_DATA } from '../../../src/lib/theme/themes/index.ts'; +import { applyTransparency, normalizeAppearance, exportAppearanceTheme, resolveTheme, BUILTIN_THEMES, themeModes } from '../../../src/lib/theme/appearance.ts'; const palette = { bg: '#123', text: '#abcdef', accent: '#AABBCC' }; const theme = { schema: 2, id: 'my-theme', name: 'My theme', colors: palette }; -test('Fixed theme palettes retain all supplied colors', () => { - assert.deepEqual(parseCustomTheme(theme), theme); +test('Schema 2 palettes convert to schema 3 and retain all supplied colors', () => { + assert.deepEqual(parseCustomTheme(theme), { ...theme, schema: 3, mode: 'dark' }); + assert.equal(parseCustomTheme({ ...theme, colors: { ...palette, bg: '#fafafa' } }).mode, 'light'); +}); +test('Old syntax names convert to the schema 3 roles', () => { + const colors = { ...palette, 'syntax-local': '#111111', 'syntax-instance': '#222222', 'syntax-global': '#333333', 'syntax-parameter': '#444444', 'syntax-static': '#555555', 'syntax-keyword': '#666666' }; + assert.deepEqual(parseCustomTheme({ ...theme, colors }).colors, { + ...palette, 'syntax-variable': '#111111', 'syntax-property': '#222222', 'syntax-constant': '#333333', 'syntax-punctuation': '#333333', 'syntax-keyword': '#666666', + }); + assert.throws(() => parseCustomTheme({ ...theme, colors: { ...palette, 'syntax-variable': '#111111' } }), /Unknown theme color/); +}); +test('Schema 3 files name their mode and can take missing colors from a built-in base', () => { + const file = { schema: 3, id: 'amber', name: 'Amber', mode: 'dark', base: 'holo', colors: { accent: '#00ff00', 'ansi-blue': '#0000ff' } }; + assert.deepEqual(parseCustomTheme(file), { ...file, base: 'harvest-moon' }); + assert.deepEqual(parseCustomTheme({ ...file, base: undefined, colors: {} }), { schema: 3, id: 'amber', name: 'Amber', mode: 'dark', colors: {} }); + for (const invalid of [{ mode: 'dim' }, { mode: undefined }, { base: 'sakura' }, { base: 'unknown' }, { base: 4 }, { colors: [] }, { colors: { 'accent-x': '#000' } }, { colors: { accent: 'red' } }]) { + assert.throws(() => parseCustomTheme({ ...file, ...invalid }), JSON.stringify(invalid)); + } + const previous = globalThis.localStorage; + try { + const stored = new Map([['runestone.custom-themes', JSON.stringify([file])]]); + globalThis.localStorage = { getItem: (key: string) => stored.get(key) ?? null, setItem: (key: string, value: string) => stored.set(key, value) } as unknown as Storage; + const resolved = resolveTheme('custom:amber', 'light'); + const harvest = THEME_DATA.find(item => item.id === 'harvest-moon')!; + assert.equal(resolved.mode, 'dark'); + assert.equal(resolved.colors.bg, harvest.variants.dark.bg); + assert.equal(resolved.colors.accent, '#00ff00'); + assert.equal(resolved.colors['syntax-keyword'], harvest.variants.dark['syntax-keyword']); + assert.equal(resolved.colors.link, '#00ff00', 'A derived role follows the colors of the file'); + assert.equal(resolved.colors['ansi-blue'], '#0000ff'); + assert.match(resolved.fonts.ui, /Candara/); + assert.deepEqual(themeModes('custom:amber'), ['dark']); + } finally { globalThis.localStorage = previous; } }); test('Legacy import selects the current appearance and validates both palettes', () => { const light = { ...palette, bg: '#fff' }; @@ -20,10 +53,11 @@ test('Theme files reject CSS injection, unknown tokens, and incomplete palettes' } assert.throws(() => parseCustomTheme({ ...theme, id: '../unsafe' })); }); -test('Every built-in template contains every current color token and one palette', () => { +test('Every built-in template contains every role and one palette', () => { for (const item of BUILTIN_THEMES) for (const mode of themeModes(item.id)) { const exported = exportAppearanceTheme(item.id, mode); - assert.deepEqual(Object.keys(exported.colors).sort(), [...COLOR_TOKENS].sort()); + assert.deepEqual(Object.keys(exported.colors), [...ROLES]); + assert.equal(exported.mode, mode); assert.deepEqual(parseCustomTheme(exported), exported); assert.equal('light' in exported, false); assert.equal('dark' in exported, false); @@ -86,7 +120,7 @@ test('Saved legacy light themes migrate once and preserve both original palettes const legacy = { schema: 1, id: 'saved-light', name: 'Saved light', light: { ...palette, bg: '#fff' }, dark: { ...palette, bg: '#111' } }; const old = new Map([[CUSTOM_THEMES_KEY, JSON.stringify([legacy])], ['runestone.appearance', JSON.stringify({ theme: 'custom:saved-light', mode: 'light' })]]); const sections = migrateLegacyPreferences(key => old.get(key) ?? null); - assert.equal((sections.customThemes as { schema: number }[])[0].schema, 2); + assert.equal((sections.customThemes as { schema: number }[])[0].schema, 3); assert.deepEqual(sections.customThemesLegacy, [legacy]); assert.deepEqual(sections.appearance, { theme: 'custom:saved-light', mode: 'light' }); // The browser preview store reads the sections from their old keys.