Add the theme editor tab and theme preview cards

Phase 5a-5.

- Settings → Appearance shows a preview card for each theme. The cards
  are one radio group. The arrow keys move and select, and the current
  card has the selection outline and a check mark (UI-047).
- Edit theme opens the theme editor as a workbench tab in the window
  that opened Settings. The window shows each change at once.
- The editor shows all 51 color roles in seven groups. Each role has a
  color picker, a hex field, its lowest readability result, and a reset
  button. A failure shows a warning icon and its ratio, or "Too close".
- Save writes a short schema 3 theme with the built-in theme as its
  base. A built-in theme does not change. Discard returns to the saved
  colors, and Duplicate saves a copy.
- The editor is a built-in package, like the browser, so it uses the
  editor tab code of plugins.
- 23 new catalog rows with French, Japanese, and Simplified Chinese.
- The smoke harness sends emit to every page and emit_to to the pages
  with the target window label.
- Docs: UI-047, ui-design.md, and "Edit a theme" in guides/themes.md.

New tests: appearance/themeEditor and tests/unit/theme/themeEditor.spec.ts.
Six smoke tests use the cards instead of the theme menu.
This commit is contained in:
Knotty Wyvern
2026-10-28 18:13:57 -07:00
parent d160568249
commit 5483881bc2
26 changed files with 722 additions and 97 deletions
+17
View File
@@ -886,3 +886,20 @@ Native shell, background image, and desktop acceptance remain open.
- Evidence: `tests/unit/theme/contrast.spec.ts` applies the new checks to every built-in palette. Screenshots are in `output/phase-5a/5a-4/match-fill/` in the main checkout.
- Replaces / replaced by: None.
- Limits: Browser checks use desktop service mocks. Native desktop acceptance remains open.
### UI-047 — Theme editor tab and theme cards
- 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-5: the editor is a workbench tab, and the picker shows preview cards with a check mark.
- Previous rule: Appearance chose the theme from a text menu. A custom theme came only from an edited JSON file.
- New rule: Appearance shows a preview card for each theme. The cards are one radio group: the arrow keys move and select, and the current card has the selection outline and a check mark. **Edit theme** opens the theme editor as a workbench tab in the window that opened Settings.
- Editor: Seven groups show every color role. Each role has a color picker, a hex field, the lowest result of the readability rules that it takes part in, and a reset button after a change. A warning icon and the text of the result mark a failure, not color alone. The window shows each change at once. Save writes a short schema 3 theme with the built-in theme as its base. A built-in theme does not change: Save creates a custom theme. Discard returns to the saved colors. Duplicate saves a copy. Closing the tab without a save returns the window to the saved theme.
- Implementation: The editor is a built-in package, like the browser. Its view uses the editor tab code of plugins. The Settings window sends `runestone-theme-editor-open` to the window that opened it. The in-window Settings dialog closes when the editor opens.
- Reason: The real window is the preview. The cards show each theme before a choice.
- Scope: Settings → Appearance and the theme editor tab.
- Shared implementation: `ThemePicker.svelte`, `ThemeEditor.svelte`, `themeEditor.ts`, `editorView.ts`, `themeEditorRequest.ts`, `appearance.ts` (`applyThemeColors`), and the built-in activation in `plugins/external.ts`.
- Evidence: `tests/smoke/appearance/themeEditor.smoke.mjs` and `tests/unit/theme/themeEditor.spec.ts`. Screenshots are in `output/phase-5a/5a-5/` in the main checkout.
- Replaces / replaced by: The theme choice in the action menu rule of "Choice lists and pickers". Other short choices stay in the action menu.
- Limits: The editor changes colors, not fonts. Browser checks use desktop service mocks. Native desktop acceptance remains open.
+20 -3
View File
@@ -2,7 +2,7 @@
[RuneStone](../../README.md) · [User guide](../user-guide.md)
This guide explains how to choose colors, set a background image, and create or share a custom theme.
This guide explains how to choose colors, set a background image, and edit, create, or share a custom theme.
Open **Settings → Appearance**. Appearance settings apply to all workspaces on this computer and to all open windows.
@@ -15,11 +15,14 @@ Open **Settings → Appearance**. Appearance settings apply to all workspaces on
| Sakura | Light only |
| Harvest Moon, Crimson Pilot, Silver Serpent | Dark only |
Select a theme card to use that theme. A check mark shows the current theme. In the cards, the arrow keys move to the next theme and select it.
Each named theme has its own fonts and syntax colors. Fonts come from your computer. RuneStone does not download fonts.
## Adjust transparency
**Transparent surfaces** tints menus, work areas with a background image, and compatible plugin surfaces.
**Transparent surfaces** tints work areas with a background image and compatible plugin surfaces.
Menus stay opaque. With a background image, menus are at least 92% opaque and blur the image.
Set **Transparency amount** from 0% to 100%. The default is 18%.
Turn off **Transparent surfaces** for opaque surfaces. Text and icons stay opaque in both cases.
@@ -33,7 +36,21 @@ Turn off **Transparent surfaces** for opaque surfaces. Text and icons stay opaqu
The image shows in new tabs. RuneStone keeps it on this computer.
The Project Management plugin can keep a separate image for a board. The Background Slideshow plugin can replace the image for a time.
## Create a theme
## Edit a theme
1. Select the theme that you want to start from.
2. Choose **Edit theme**. The theme editor opens as a tab in the workspace window.
3. Change a color with its swatch or its hex value. The window shows each change at once.
4. Choose **Save**.
A built-in theme does not change. **Save** creates a custom theme from it, with only the colors that you changed. The built-in theme stays its base.
- Each color shows its lowest contrast result. A warning icon marks a color that fails a [readability rule](../ui-color.md#readability-rules). Point to the result to see the failed checks.
- The reset button returns a color to the value of the base theme.
- **Discard** returns to the saved colors. **Duplicate** saves a copy and selects it.
- If you close the tab without **Save**, the window returns to the saved theme.
## Create a theme file
1. Select the theme and appearance that you want to start from.
2. Choose **Export theme template**.
+4 -4
View File
@@ -147,11 +147,11 @@
},
"RuneStone/src/lib/theme/AppearanceSettings.svelte": {
"counts": {
"action": 2,
"localPopup": 3
"action": 1,
"localPopup": 2
},
"design": "Shared action menu",
"check": "tests/smoke/appearance/characterThemes.smoke.mjs"
"design": "Shared action menu for image position and size. Theme choice uses preview cards (UI-047).",
"check": "tests/smoke/appearance/backgroundImages.smoke.mjs"
},
"RuneStone/src/lib/ui/actionMenu.ts": {
"counts": {
+5 -2
View File
@@ -120,7 +120,8 @@ Use one menu design for context menus, action menus, and their submenus in the h
### Choice lists and pickers
- Use the shared action menu for short option lists, such as board, list, theme, appearance, and language choices.
- Use the shared action menu for short option lists, such as board, list, appearance, and language choices.
- Visual choices, such as themes, use preview cards. The cards are one radio group, and a check mark marks the current choice.
- Use a searchable picker for long lists.
- Replace native selects with the shared action menu wherever the host API exists. Native selects stay only as documented fallbacks for older plugin hosts.
- Rich pickers and dialogs can have their own layout when they contain search fields, descriptions, or forms. These layouts do not need an exception entry.
@@ -156,9 +157,11 @@ 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.
- Appearance shows a preview card for each theme. The arrow keys move between the cards and select a theme. The current card has the selection outline and a check mark.
- **Edit theme** opens the theme editor as a workbench tab in the window that opened Settings. The editor shows every color role in groups, with a swatch, a hex field, the lowest contrast result, and a reset button. Each change shows at once in that window. Save writes a short schema 3 theme with a base.
- 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), [UI-042](design-decisions.md#ui-042--theme-file-format-3-and-terminal-colors).
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), [UI-047](design-decisions.md#ui-047--theme-editor-tab-and-theme-cards).
## Typography and tables
+24 -1
View File
@@ -3468,7 +3468,30 @@ export const messageRows: [string, string, string, string][] = [
["Resolve the disk changes before saving.", "Résolvez les modifications sur le disque avant d’enregistrer.", "保存する前にディスク上の変更を解決してください。", "保存前请先处理磁盘上的更改。"],
["Open a workspace first.", "Ouvrez d’abord un espace de travail.", "先にワークスペースを開いてください。", "请先打开工作区。"],
["Collapse backlinks", "Réduire les liens entrants", "バックリンクを折りたたむ", "折叠反向链接"],
["Expand backlinks", "Développer les liens entrants", "バックリンクを展開", "展开反向链接"]
["Expand backlinks", "Développer les liens entrants", "バックリンクを展開", "展开反向链接"],
["Edit theme", "Modifier le thème", "テーマを編集", "编辑主题"],
["Theme editor", "Éditeur de thème", "テーマエディター", "主题编辑器"],
["My theme", "Mon thème", "マイテーマ", "我的主题"],
["Saved {name}.", "{name} enregistré.", "{name} を保存しました。", "已保存 {name}。"],
["Could not save the theme: {error}", "Impossible d’enregistrer le thème : {error}", "テーマを保存できませんでした: {error}", "无法保存主题:{error}"],
["Changes discarded.", "Modifications annulées.", "変更を破棄しました。", "已放弃更改。"],
["{name} copy", "Copie de {name}", "{name} のコピー", "{name} 副本"],
["Theme name", "Nom du thème", "テーマ名", "主题名称"],
["Discard", "Annuler les modifications", "破棄", "放弃"],
["Duplicate", "Dupliquer", "複製", "复制副本"],
["Built-in themes stay unchanged. Save creates a custom theme from this one.", "Les thèmes intégrés ne changent pas. Enregistrer crée un thème personnalisé à partir de celui-ci.", "組み込みテーマは変更されません。保存すると、このテーマからカスタムテーマを作成します。", "内置主题保持不变。保存会基于此主题创建自定义主题。"],
["Based on {name}. Reset a color to take the value of the base theme again.", "Basé sur {name}. Réinitialisez une couleur pour reprendre la valeur du thème de base.", "{name} がベースです。色をリセットすると、ベーステーマの値に戻ります。", "基于 {name}。重置颜色可恢复基础主题的值。"],
["{count} readability checks fail.", "{count} contrôles de lisibilité échouent.", "{count} 件の読みやすさチェックが失敗しています。", "{count} 项可读性检查未通过。"],
["All readability checks pass.", "Tous les contrôles de lisibilité réussissent.", "すべての読みやすさチェックに合格しています。", "所有可读性检查均已通过。"],
["Pick a color for {role}", "Choisir une couleur pour {role}", "{role} の色を選択", "为 {role} 选择颜色"],
["Hex value of {role}", "Valeur hexadécimale de {role}", "{role} の 16 進値", "{role} 的十六进制值"],
["Too close", "Trop proche", "近すぎます", "过于接近"],
["Reset {role}", "Réinitialiser {role}", "{role} をリセット", "重置 {role}"],
["Surfaces", "Surfaces", "サーフェス", "表面"],
["Text", "Texte", "テキスト", "文本"],
["Accents", "Accents", "アクセント", "强调色"],
["Selection and highlight", "Sélection et surlignage", "選択と強調表示", "选择和高亮"],
["Status", "État", "ステータス", "状态"]
];
export const catalogs: Record<Exclude<Locale, 'en'>, Record<string, string>> = {
fr: Object.fromEntries(messageRows.map(row => [row[0], row[1]])),
+7
View File
@@ -31,6 +31,7 @@
import TemplateManager from "./TemplateManager.svelte";
import WorkspacePicker from "./WorkspacePicker.svelte";
import SettingsDialog from "./SettingsDialog.svelte";
import { THEME_EDITOR_EVENT } from "$lib/theme/themeEditorRequest";
import BrowserSlot from "$lib/plugins/BrowserSlot.svelte";
import { DEFAULT_SETTINGS, readSettings, saveSettings, type AppSettings } from "$lib/workspace/settings";
import { onSettingsChange, takeSettingsNotice } from "$lib/settings/store";
@@ -74,6 +75,12 @@
let workspace = $state<WorkspaceInfo | null>(null);
let workspacePicker: WorkspacePicker;
let preferences = $state<"settings" | "help" | null>(null);
// The theme editor opens as a tab. Close the in-window Settings dialog, so the tab shows.
$effect(() => {
const close = () => { preferences = null; };
window.addEventListener(THEME_EDITOR_EVENT, close);
return () => window.removeEventListener(THEME_EDITOR_EVENT, close);
});
let openingSettings = false;
async function openSettings() {
if (!desktop) { preferences = "settings"; return; }
+9 -4
View File
@@ -14,7 +14,7 @@ import type { PluginModule, PluginSnapshot, InstalledPlugin, Dispose, PluginView
export const installedPlugins = writable<PluginSnapshot>({ root: "", plugins: [] });
export const externalErrors = writable<Record<string, string>>({});
export const pluginTools = writable<PluginTool[]>([]);
export interface OpenPluginView { key: string; owner: string; id: string; title: string; placement: "dialog" | "editor" | "sidebar"; document?: PluginDocumentContext; icon?: "kanban" | "file" | "globe" | "git"; iconImage?: string | null; pinned?: boolean; draggable?: boolean }
export interface OpenPluginView { key: string; owner: string; id: string; title: string; placement: "dialog" | "editor" | "sidebar"; document?: PluginDocumentContext; icon?: "kanban" | "file" | "globe" | "git" | "palette"; iconImage?: string | null; pinned?: boolean; draggable?: boolean }
export const pluginSidebar = writable<OpenPluginView | null>(null);
export function closePluginSidebar() { pluginSidebar.set(null); }
export const pluginView = writable<OpenPluginView | null>(null);
@@ -78,7 +78,7 @@ export const pluginEditorActive = writable(false);
export const pluginServiceError = writable("");
export const restartPlugins = writable<string[]>([]);
/** Old packages of features that RuneStone now includes. The host never loads their code. */
export const builtInPackages: readonly string[] = ["runestone.browser", "runestone.table-formulas"];
export const builtInPackages: readonly string[] = ["runestone.browser", "runestone.table-formulas", "runestone.theme-editor"];
const sessions = new Map<string, { hash: string; session: ExternalSession }>();
const failures = new Map<string, string>();
const errors: Record<string, string> = {};
@@ -218,7 +218,7 @@ function show(owner: string, id: string, options?: PluginViewOpenOptions) {
}
if (placement === "editor") {
const existing = get(pluginEditors).find(item => item.owner === owner && item.id === id && !item.document);
const editor: OpenPluginView = existing ?? { key: crypto.randomUUID(), owner, id, title: view.title, placement, pinned: !!view.pinned, draggable: true, iconImage: view.iconImage, ...(["globe", "kanban", "git"].includes(view.icon ?? "") ? { icon: view.icon as "globe" | "kanban" | "git" } : {}) };
const editor: OpenPluginView = existing ?? { key: crypto.randomUUID(), owner, id, title: view.title, placement, pinned: !!view.pinned, draggable: true, iconImage: view.iconImage, ...(["globe", "kanban", "git", "palette"].includes(view.icon ?? "") ? { icon: view.icon as "globe" | "kanban" | "git" | "palette" } : {}) };
if (!existing && options) {
const source = get(pluginEditors).find(item => item.owner === owner && item.id === options.relativeTo);
if (!source || !["right", "down"].includes(options.split)) throw new Error("The source pane is unavailable.");
@@ -244,7 +244,7 @@ function replaceEditorView(owner: string, current: OpenPluginView | undefined, n
for (const duplicate of get(pluginEditors)) {
if (duplicate.owner === owner && duplicate.id === nextId && !duplicate.document && duplicate.key !== current.key) closePluginEditor(duplicate.key);
}
const replacement: OpenPluginView = { ...current, id: nextId, title: next.title, document: undefined, iconImage: next.iconImage, icon: ["globe", "kanban", "git"].includes(next.icon ?? "") ? next.icon as "globe" | "kanban" | "git" : undefined };
const replacement: OpenPluginView = { ...current, id: nextId, title: next.title, document: undefined, iconImage: next.iconImage, icon: ["globe", "kanban", "git", "palette"].includes(next.icon ?? "") ? next.icon as "globe" | "kanban" | "git" | "palette" : undefined };
pluginEditors.update(views => views.map(view => view.key === current.key ? replacement : view));
selectPluginEditor(replacement);
}
@@ -377,6 +377,11 @@ export function startExternalPlugins(allowed?: string[]): () => void {
const module = await import("../browser/index");
await activate({ manifest: { schemaVersion: 1, id: "runestone.browser", name: "Browser", author: "RuneStone", description: "Built-in browser", version: "0.0.0", apiVersion: 1, entry: "builtin", access: "full-app" }, hash: "builtin", enabled: true, installedAt: null, path: "", error: null, removal: false }, module);
}).catch(reason => report("runestone.browser", reason));
queue = queue.then(async () => {
if (disposed || (allowed && !allowed.includes("runestone.theme-editor"))) return;
const module = await import("../theme/editorView");
await activate({ manifest: { schemaVersion: 1, id: "runestone.theme-editor", name: "Theme editor", author: "RuneStone", description: "Built-in theme editor", version: "0.0.0", apiVersion: 1, entry: "builtin", access: "full-app" }, hash: "builtin", enabled: true, installedAt: null, path: "", error: null, removal: false }, module);
}).catch(reason => report("runestone.theme-editor", reason));
void refreshPlugins();
// Scans run at start, on window focus, on Refresh, and on `plugins-changed`. There is no timed scan.
const focus = () => { void refreshPlugins(); };
+6 -12
View File
@@ -8,6 +8,8 @@
import { showActionMenu } from '$lib/ui/managedActionMenu';
import { saveBackgroundImage, removeBackgroundImage } from './backgroundImages';
import { onSettingsChange } from '$lib/settings/store';
import ThemePicker from './ThemePicker.svelte';
import { requestThemeEditor } from './themeEditorRequest';
import { DEFAULT_APPEARANCE, BUILTIN_THEMES, themeModes, themeNotice, BACKGROUND_POSITIONS, BACKGROUND_SIZES, readAppearance, normalizeAppearance, saveAppearance, exportAppearanceTheme, type Appearance, type ThemeName } from './appearance';
let appearance = $state<Appearance>({ ...DEFAULT_APPEARANCE });
let error = $state('');
@@ -24,14 +26,6 @@
}))));
const notice = $derived(themeNotice(appearance.theme));
onDestroy(() => closePicker());
function picker(event: MouseEvent) {
closePicker();
const anchor = event.currentTarget as HTMLButtonElement;
const bounds = anchor.getBoundingClientRect();
closePicker = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: $t('Color theme'), parent: anchor.closest('dialog') ?? undefined,
items: themes.map(choice => ({ label: choice.name, radio: true, checked: choice.theme === appearance.theme && choice.mode === appearance.mode,
run: () => change({ ...appearance, theme: choice.theme, mode: choice.mode }) })) }).close;
}
const positionLabels = $derived([$t('Center'), $t('Top left'), $t('Top center'), $t('Top right'), $t('Center left'), $t('Center right'), $t('Bottom left'), $t('Bottom center'), $t('Bottom right')]);
const sizeLabels = $derived([$t('Fill'), $t('Fit'), $t('Actual size')]);
function backgroundPicker(event: MouseEvent, field: 'position' | 'size') {
@@ -115,15 +109,14 @@
</script>
<h2>{$t("Appearance")}</h2>
<p>{$t("Choose a color theme variant.")}</p>
<div class="card">
<div class="setting-row"><span>{$t("Color theme")}</span><button class="picker" aria-label={$t("Color theme")} aria-haspopup="menu" onclick={event => picker(event)}>{themes.find(theme => theme.theme === appearance.theme && theme.mode === appearance.mode)?.name ?? 'RuneStone Dark'}<Icon icon="chevron-down" /></button></div>
</div>
<ThemePicker choices={themes} current={appearance} onSelect={choice => change({ ...appearance, theme: choice.theme, mode: choice.mode })} />
<div class="theme-preview" role="img" aria-label={$t("Color theme preview")}>
<div class="preview-sidebar" aria-hidden="true"><span></span><span></span><span></span></div>
<div class="preview-document" aria-hidden="true"><strong>RuneStone</strong><span class="preview-prose">{$t("A place for your ideas.")}</span><span class="preview-selection">{$t("Selected text")}</span><span class="preview-link">{$t("Link")}</span><code class="preview-code"><span class="preview-keyword">const</span> name = <span class="preview-string">"RuneStone"</span>;<br /><span class="preview-function">show</span>(name, <span class="preview-number">42</span>);</code></div>
</div>
<div class="theme-actions">
<input bind:this={themeInput} type="file" accept=".json,application/json" aria-label={$t("Theme JSON file")} hidden onchange={event => { void importTheme(event.currentTarget.files?.[0]); }} />
<button onclick={() => void requestThemeEditor()}><Icon icon="palette" />{$t("Edit theme")}</button>
<button onclick={() => themeInput.click()}>{$t("Install theme")}</button>
<button disabled={exporting} onclick={() => void exportTemplate()}>{exporting ? $t('Exporting…') : $t('Export theme template')}</button>
{#if appearance.theme.startsWith('custom:')}<IconButton icon="trash" label={$t("Remove custom theme")} onclick={() => {
@@ -199,7 +192,8 @@
.overlay-value input:focus-visible{outline:2px solid var(--rs-focus);outline-offset:2px}
[role=alert]{color:var(--rs-error)}
.theme-actions{display:flex;gap:var(--rs-settings-gap);flex-wrap:wrap;margin-top:var(--rs-settings-gap)}
.theme-actions 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);padding:4px 8px}
.theme-actions button{display:inline-flex;align-items:center;gap:6px;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);padding:4px 8px}
.theme-actions button :global(svg){width:14px;height:14px;fill:none;stroke:currentColor;stroke-width:2}
h3{margin-top:var(--rs-settings-section-gap);font-size:14px}.background-preview{height:120px;background-color:var(--rs-bg);background-image:var(--rs-background-image,none);background-size:100% 100%,var(--rs-background-size,cover);background-position:center,var(--rs-background-position,center);background-repeat:no-repeat;border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);display:grid;place-items:center;margin-bottom:var(--rs-settings-gap)}.background-preview span{padding:8px 14px;background:var(--rs-bg-elevated);border-radius:var(--rs-control-radius)}
</style>
+200
View File
@@ -0,0 +1,200 @@
<script lang="ts">
// The theme editor tab. Each change shows at once in this window. Save writes a custom theme.
import { onDestroy, onMount } from 'svelte';
import { t } from '$lib/i18n';
import Icon from '$lib/ui/Icon.svelte';
import IconButton from '$lib/ui/IconButton.svelte';
import { onSettingsChange } from '$lib/settings/store';
import { isHex, normalizeHex, parseHex, withAlpha } from './color';
import type { Role } from './roles';
import { BUILTIN_THEMES, builtinTheme, type BuiltinThemeId } from './themes/index';
import { customThemes, installTheme } from './customThemes';
import { applyAppearance, applyThemeColors, readAppearance, saveAppearance, themeModes } from './appearance';
import { ROLE_GROUPS, builtinDraft, customDraft, draftColors, draftTheme, roleStatus, uniqueThemeId, type ThemeDraft } from './themeEditor';
import { checkTheme } from './contrast';
let { onTitle }: { onTitle?: (title: string) => void } = $props();
let saved = $state<ThemeDraft | null>(null);
let draft = $state<ThemeDraft | null>(null);
let status = $state('');
let error = $state('');
let invalid = $state<Partial<Record<Role, boolean>>>({});
let applying = false;
const colors = $derived(draft ? draftColors(draft) : null);
const findings = $derived(draft && colors ? checkTheme(colors, draft.mode) : []);
const failures = $derived(findings.filter(finding => !finding.pass));
const dirty = $derived(!!draft && !!saved && JSON.stringify({ ...draft, overrides: sorted(draft.overrides) }) !== JSON.stringify({ ...saved, overrides: sorted(saved.overrides) }));
const baseName = $derived(draft ? builtinTheme(draft.base)?.name ?? '' : '');
function sorted(value: object) { return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b))); }
/** The draft of the theme that this window shows now. */
function load() {
const appearance = readAppearance();
if (appearance.theme.startsWith('custom:')) {
const theme = customThemes().find(item => `custom:${item.id}` === appearance.theme);
if (theme) { saved = customDraft(theme); draft = customDraft(theme); return; }
}
const theme = builtinTheme(appearance.theme) ?? BUILTIN_THEMES[0];
const mode = themeModes(theme.id).includes(appearance.mode) ? appearance.mode : themeModes(theme.id)[0];
const label = themeModes(theme.id).length > 1 ? `${theme.name} ${mode === 'light' ? $t('Light') : $t('Dark')}` : theme.name;
// Save copies a built-in theme, so the draft starts with the name of the copy.
const name = $t('{name} copy', { name: label });
saved = builtinDraft(theme.id as BuiltinThemeId, mode, name);
draft = builtinDraft(theme.id as BuiltinThemeId, mode, name);
}
onMount(() => {
load();
// A theme change in another place starts a new draft, unless this draft has changes.
const stop = onSettingsChange('appearance', () => { if (!dirty && !applying) load(); });
return stop;
});
// The window keeps the saved theme when the editor closes.
onDestroy(() => { applyAppearance(readAppearance()); });
$effect(() => { if (colors) applyThemeColors(colors); });
$effect(() => { onTitle?.(`${dirty ? '• ' : ''}${$t('Theme editor')}`); });
function setRole(role: Role, value: string) {
if (!draft) return;
if (!isHex(value)) { invalid = { ...invalid, [role]: true }; return; }
invalid = { ...invalid, [role]: false };
draft = { ...draft, overrides: { ...draft.overrides, [role]: normalizeHex(value) } };
status = '';
}
/** The color input has no alpha. Keep the alpha of the current color. */
function pickRole(role: Role, value: string) {
if (!colors) return;
setRole(role, withAlpha(value, parseHex(colors[role])[3]));
}
function resetRole(role: Role) {
if (!draft) return;
const { [role]: _, ...rest } = draft.overrides;
draft = { ...draft, overrides: rest };
invalid = { ...invalid, [role]: false };
}
async function save() {
if (!draft) return;
error = ''; status = '';
const name = draft.name.trim() || $t('My theme');
const id = draft.id ?? uniqueThemeId(name, customThemes().map(theme => theme.id));
try {
applying = true;
await installTheme(draftTheme(draft, id, name));
await saveAppearance({ ...readAppearance(), theme: `custom:${id}`, mode: draft.mode });
draft = { ...draft, id, name };
saved = { ...draft, overrides: { ...draft.overrides } };
status = $t('Saved {name}.', { name });
} catch (reason) { error = $t('Could not save the theme: {error}', { error: String(reason) }); }
finally { applying = false; }
}
function discard() {
if (!saved) return;
draft = { ...saved, overrides: { ...saved.overrides } };
invalid = {}; status = $t('Changes discarded.');
}
async function duplicate() {
if (!draft) return;
const name = $t('{name} copy', { name: draft.name.trim() || $t('My theme') });
draft = { ...draft, id: null, name };
await save();
}
</script>
{#if draft && colors}
<section class="theme-editor" aria-label={$t('Theme editor')}>
<div class="editor-content">
<header>
<label class="name"><span>{$t('Theme name')}</span><input value={draft.name} oninput={event => { draft = { ...draft!, name: event.currentTarget.value }; }} /></label>
<div class="actions">
<button class="primary" disabled={!dirty && draft.id !== null} onclick={() => void save()}><Icon icon="save" />{$t('Save')}</button>
<button disabled={!dirty} onclick={discard}><Icon icon="undo" />{$t('Discard')}</button>
<button onclick={() => void duplicate()}><Icon icon="copy" />{$t('Duplicate')}</button>
</div>
</header>
<p class="note">
{#if draft.id === null}{$t('Built-in themes stay unchanged. Save creates a custom theme from this one.')}{:else}{$t('Based on {name}. Reset a color to take the value of the base theme again.', { name: baseName })}{/if}
</p>
<p class="summary" class:fail={failures.length > 0} role="status">
<Icon icon={failures.length ? 'alert' : 'check'} />
{failures.length ? $t('{count} readability checks fail.', { count: failures.length }) : $t('All readability checks pass.')}
{#if status}<span>{status}</span>{/if}
</p>
{#if error}<p class="error" role="alert">{error}</p>{/if}
{#each ROLE_GROUPS as group (group.label)}
<h3>{$t(group.label)}</h3>
<div class="roles">
{#each group.roles as role (role)}
{@const result = roleStatus(role, findings)}
{@const changed = role in draft.overrides}
{@const failed = result.failures.map(finding => `${finding.subject}: ${finding.value.toFixed(2)}`).join('\n') || undefined}
<div class="role" class:changed>
<input type="color" aria-label={$t('Pick a color for {role}', { role })} value={colors[role].slice(0, 7)} oninput={event => pickRole(role, event.currentTarget.value)} />
<!-- The group heading names Code and Terminal, so the row leaves out the prefix. -->
<code class="role-name" title={role}>{role.replace(/^(syntax|ansi)-/, '')}</code>
<input class="hex" spellcheck="false" aria-label={$t('Hex value of {role}', { role })} aria-invalid={invalid[role] ? 'true' : undefined} value={colors[role]}
onchange={event => setRole(role, event.currentTarget.value.trim())} />
<!-- A failing contrast shows its ratio. A failing pair, such as two status colors that are too close, shows "Too close". -->
{#if result.lowest && !result.lowest.pass}
<span class="badge fail" title={failed}><Icon icon="alert" />{result.lowest.value.toFixed(1)}:1</span>
{:else if result.failures.length}
<span class="badge fail" title={failed}><Icon icon="alert" />{$t('Too close')}</span>
{:else if result.lowest}
<span class="badge"><Icon icon="check" />{result.lowest.value.toFixed(1)}:1</span>
{:else}<span class="badge empty"></span>{/if}
{#if changed}<IconButton icon="undo" label={$t('Reset {role}', { role })} onclick={() => resetRole(role)} />{:else}<span class="reset-space"></span>{/if}
</div>
{/each}
</div>
{/each}
</div>
</section>
{/if}
<style>
.theme-editor { container-type: inline-size; box-sizing: border-box; height: 100%; overflow: auto; background: var(--rs-bg); color: var(--rs-text); font: 13px/1.4 var(--rs-font-ui); }
.editor-content { padding: 16px 20px 32px; }
header { display: flex; flex-wrap: wrap; align-items: end; gap: 12px; justify-content: space-between; }
.name { display: grid; gap: 4px; flex: 1 1 220px; min-width: 0; max-width: 360px; }
.name input { min-width: 0; }
.name span { color: var(--rs-text-dim); font-size: 12px; }
input:not([type=color]), button { box-sizing: border-box; min-height: var(--rs-settings-control-height); padding: 3px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); color: var(--rs-text); font: inherit; }
.actions { display: flex; flex-wrap: wrap; gap: 8px; }
button { display: inline-flex; align-items: center; gap: 6px; cursor: pointer; }
button :global(svg) { width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-width: 2; }
button.primary { background: var(--rs-accent); border-color: var(--rs-accent); color: var(--rs-on-accent); }
button:disabled { cursor: default; color: var(--rs-text-dim); background: var(--rs-bg-elevated); border-color: var(--rs-border); }
button:hover:not(:disabled) { background: var(--rs-bg-active); }
button.primary:hover:not(:disabled) { background: var(--rs-accent); filter: brightness(1.08); }
button:focus-visible, input:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 1px; }
.note { color: var(--rs-text-dim); }
.summary { display: flex; align-items: center; gap: 6px; color: var(--rs-ok); }
.summary.fail { color: var(--rs-warn); }
.summary span { margin-left: 8px; color: var(--rs-text-dim); }
.summary :global(svg), .badge :global(svg) { width: 14px; height: 14px; flex: 0 0 14px; fill: none; stroke: currentColor; stroke-width: 2; }
.error { color: var(--rs-error); }
h3 { margin: 20px 0 8px; font-size: 14px; color: var(--rs-text-strong); }
.roles { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 340px), 1fr)); gap: 4px 24px; }
/* A row wraps in a narrow pane, so the editor never scrolls sideways. */
.role { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 8px; min-height: 32px; padding: 2px 4px; border-radius: var(--rs-control-radius); }
.role-name { flex: 1 1 72px; min-width: 0; }
.role.changed .role-name { color: var(--rs-text-strong); font-weight: 600; }
input[type=color] { width: 32px; height: 26px; padding: 0; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: transparent; cursor: pointer; }
.role-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--rs-text); font-family: var(--rs-font-mono); font-size: 12px; }
.hex { width: 96px; max-width: 100%; font-family: var(--rs-font-mono); font-size: 12px; }
.badge { min-width: 60px; }
.hex[aria-invalid=true] { border-color: var(--rs-error); }
.badge { display: inline-flex; align-items: center; gap: 4px; color: var(--rs-ok); font-size: 12px; white-space: nowrap; }
.badge.fail { color: var(--rs-warn); }
.reset-space { width: 28px; }
/* A very narrow pane keeps every control inside it. */
@container (max-width: 240px) {
.editor-content { padding: 8px; }
button { min-width: 0; max-width: 100%; white-space: normal; text-align: left; }
.editor-content, button { overflow-wrap: anywhere; }
}
</style>
+69
View File
@@ -0,0 +1,69 @@
<script lang="ts">
// Theme preview cards. The cards are one radio group: arrow keys move and select, and a check mark shows the current theme.
import { t } from '$lib/i18n';
import Icon from '$lib/ui/Icon.svelte';
import { resolveTheme, type ThemeName } from './appearance';
import type { Mode, ResolvedColors } from './roles';
type Choice = { theme: ThemeName; mode: Mode; name: string };
let { choices, current, onSelect }: { choices: Choice[]; current: { theme: ThemeName; mode: Mode }; onSelect: (choice: Choice) => void } = $props();
let group: HTMLDivElement;
const cards = $derived(choices.map(choice => ({ ...choice, colors: resolveTheme(choice.theme, choice.mode).colors })));
const selectedIndex = $derived(cards.findIndex(card => card.theme === current.theme && card.mode === current.mode));
const CARD_ROLES = ['bg', 'bg-elevated', 'border', 'text', 'text-dim', 'accent', 'syntax-keyword', 'syntax-string', 'syntax-number'] as const;
const style = (colors: ResolvedColors) => CARD_ROLES.map(role => `--card-${role}:${colors[role]}`).join(';');
function keydown(event: KeyboardEvent) {
const steps: Record<string, number> = { ArrowRight: 1, ArrowDown: 1, ArrowLeft: -1, ArrowUp: -1 };
if (!(event.key in steps) && event.key !== 'Home' && event.key !== 'End') return;
event.preventDefault();
const radios = [...group.querySelectorAll<HTMLButtonElement>('[role=radio]')];
const index = radios.indexOf(document.activeElement as HTMLButtonElement);
const next = event.key === 'Home' ? 0 : event.key === 'End' ? radios.length - 1 : (Math.max(index, 0) + steps[event.key] + radios.length) % radios.length;
radios[next].focus();
onSelect(cards[next]);
}
</script>
<div class="theme-cards" role="radiogroup" aria-label={$t('Color theme')} bind:this={group} tabindex="-1" onkeydown={keydown}>
{#each cards as card, index (card.theme + card.mode)}
{@const selected = index === selectedIndex}
<button type="button" role="radio" aria-checked={selected} tabindex={selected || (selectedIndex < 0 && index === 0) ? 0 : -1}
class="theme-card" class:selected style={style(card.colors)} onclick={() => onSelect(card)}>
<span class="card-preview" aria-hidden="true">
<span class="card-pane"><i></i><i></i><i></i></span>
<span class="card-page">
<i class="card-title"></i><i class="card-line"></i><i class="card-line short"></i>
<span class="card-swatches"><i class="card-accent"></i><i class="card-keyword"></i><i class="card-string"></i><i class="card-number"></i></span>
</span>
</span>
<span class="card-name"><span>{card.name}</span>{#if selected}<Icon icon="check" />{/if}</span>
</button>
{/each}
</div>
<style>
.theme-cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 150px), 1fr)); gap: var(--rs-settings-gap); margin-top: var(--rs-settings-gap); }
.theme-card { display: flex; flex-direction: column; gap: 6px; min-width: 0; padding: 6px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); color: var(--rs-text); font: inherit; text-align: left; cursor: pointer; }
.theme-card:hover { background: var(--rs-bg-active); }
.theme-card.selected { border-color: var(--rs-item-selection-border); box-shadow: inset 0 0 0 1px var(--rs-item-selection-border); }
.theme-card:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; }
.card-preview { display: flex; height: 64px; overflow: hidden; border: 1px solid var(--card-border); border-radius: var(--rs-control-radius); background: var(--card-bg); }
.card-pane { display: flex; flex-direction: column; gap: 5px; width: 30%; padding: 7px 6px; background: var(--card-bg-elevated); border-right: 1px solid var(--card-border); }
.card-pane i, .card-page i { display: block; height: 4px; border-radius: 2px; background: var(--card-text-dim); }
.card-pane i:first-child { background: var(--card-accent); }
.card-page { display: flex; flex: 1; flex-direction: column; gap: 5px; min-width: 0; padding: 7px 8px; }
.card-page .card-title { width: 55%; height: 6px; background: var(--card-text); }
.card-page .card-line { width: 85%; }
.card-page .card-line.short { width: 60%; }
.card-swatches { display: flex; gap: 4px; margin-top: auto; }
.card-swatches i { width: 10px; height: 10px; border-radius: 50%; }
.card-swatches .card-accent { width: 22px; border-radius: 5px; background: var(--card-accent); }
.card-swatches .card-keyword { background: var(--card-syntax-keyword); }
.card-swatches .card-string { background: var(--card-syntax-string); }
.card-swatches .card-number { background: var(--card-syntax-number); }
.card-name { display: flex; align-items: center; justify-content: space-between; gap: 6px; min-height: 18px; font-size: 12px; }
.card-name span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.card-name :global(svg) { flex: 0 0 14px; width: 14px; height: 14px; fill: none; stroke: var(--rs-accent); stroke-width: 2.5; }
</style>
+4
View File
@@ -158,6 +158,10 @@ export function applyAppearance(value: Appearance, root = document.documentEleme
root.dataset.palette = theme;
root.style.colorScheme = mode;
FONT_ROLES.forEach(role => root.style.setProperty(`--rs-font-${role}`, fonts[role]));
applyThemeColors(colors, root);
}
/** Set every color token. The theme editor uses it for its live preview, without a save. */
export function applyThemeColors(colors: ResolvedColors, root = document.documentElement) {
// Text selection keeps the theme hue and shows the background beneath it.
const applied = appliedColors(colors);
for (const role of ROLES) root.style.setProperty(`--rs-${role}`, applied[role]);
+20
View File
@@ -0,0 +1,20 @@
// The theme editor is a built-in package. Its view opens as a workbench tab, so the window shows each change at once.
import { mount, unmount } from 'svelte';
import { getCurrentWebviewWindow } from '@tauri-apps/api/webviewWindow';
import { tr } from '../i18n/index.ts';
import type { PluginApi, PluginView } from '$lib/plugins/sdk';
import ThemeEditor from './ThemeEditor.svelte';
import { THEME_EDITOR_EVENT } from './themeEditorRequest';
export async function activate(api: PluginApi) {
// The palette icon is a host icon. The public SDK icon list does not name it.
const icon = 'palette' as PluginView['icon'];
api.registerView({ id: 'editor', title: tr('Theme editor'), placement: 'editor', icon, launcher: false, mount: container => {
const instance = mount(ThemeEditor, { target: container, props: { onTitle: (title: string) => api.updateViewTitle?.('editor', title) } });
return () => { void unmount(instance); };
} });
const open = () => api.openView('editor');
window.addEventListener(THEME_EDITOR_EVENT, open);
api.onDispose(() => window.removeEventListener(THEME_EDITOR_EVENT, open));
api.onDispose(await getCurrentWebviewWindow().listen(THEME_EDITOR_EVENT, open));
}
+79
View File
@@ -0,0 +1,79 @@
// The model of the theme editor: role groups, the draft of one theme, and the readability results of each role.
import { message } from '../i18n/index.ts';
import { ANSI_COLORS, SYNTAX_ROLES, resolveColors, type Mode, type ResolvedColors, type Role, type ThemeColors } from './roles.ts';
import { checkTheme, type Finding, type Surface } from './contrast.ts';
import { builtinTheme, type BuiltinThemeId } from './themes/index.ts';
import type { CustomTheme, ThemeFonts } from './customThemes.ts';
/** The editor shows every role once, in these groups. */
export const ROLE_GROUPS: readonly { label: string; roles: readonly Role[] }[] = [
{ label: message('Surfaces'), roles: ['bg', 'bg-elevated', 'bg-active', 'border', 'line-highlight', 'scrim'] },
{ label: message('Text'), roles: ['text', 'text-dim', 'text-strong'] },
{ label: message('Accents'), roles: ['accent', 'accent-2', 'accent-dim', 'accent-deep', 'link', 'focus', 'on-accent'] },
{ label: message('Selection and highlight'), roles: ['selection', 'item-selection-bg', 'highlight'] },
{ label: message('Status'), roles: ['error', 'warn', 'warn-hot', 'ok', 'special'] },
{ label: message('Code'), roles: SYNTAX_ROLES.map(role => `syntax-${role}` as const) },
{ label: message('Terminal'), roles: ANSI_COLORS.flatMap(color => [`ansi-${color}`, `ansi-bright-${color}`] as const) },
];
/** One theme while the editor changes it. `id` is null for a built-in theme, which Save copies to a custom theme. */
export type ThemeDraft = { id: string | null; name: string; mode: Mode; base: BuiltinThemeId; overrides: ThemeColors; fonts?: ThemeFonts };
export function builtinDraft(id: BuiltinThemeId, mode: Mode, name: string): ThemeDraft {
return { id: null, name, mode, base: id, overrides: {} };
}
export function customDraft(theme: CustomTheme): ThemeDraft {
return { id: theme.id, name: theme.name, mode: theme.mode, base: (theme.base ?? 'default') as BuiltinThemeId, overrides: { ...theme.colors }, ...(theme.fonts ? { fonts: { ...theme.fonts } } : {}) };
}
/** Every role of the draft: its own colors, then the base theme, then the derivation rule. */
export function draftColors(draft: ThemeDraft): ResolvedColors {
return resolveColors(draft.overrides, draft.mode, builtinTheme(draft.base)?.variants[draft.mode] ?? {});
}
/** The schema 3 theme file of a draft. It keeps only the changed colors, and the base gives the others. */
export function draftTheme(draft: ThemeDraft, id: string, name: string): CustomTheme {
return { schema: 3, id, name, mode: draft.mode, base: draft.base, colors: { ...draft.overrides }, ...(draft.fonts ? { fonts: draft.fonts } : {}) };
}
/** A theme ID from a name, different from every ID in `taken`. */
export function uniqueThemeId(name: string, taken: Iterable<string>): string {
const used = new Set(taken);
const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
// An ID starts with a letter.
const stem = (!slug ? 'theme' : /^[a-z]/.test(slug) ? slug : `t-${slug}`).slice(0, 56).replace(/-+$/, '');
for (let index = 1; ; index++) {
const id = index === 1 ? stem : `${stem}-${index}`;
if (!used.has(id)) return id;
}
}
/** The surfaces that a role paints. A rule that measures text on one of them counts for the role. */
const SURFACE_ROLES: Partial<Record<Role, readonly Surface[]>> = {
bg: ['bg'], 'bg-elevated': ['bg-elevated'], 'bg-active': ['bg-active'], selection: ['selection'], 'line-highlight': ['line-highlight'],
highlight: ['highlight'], 'item-selection-bg': ['item-selection', 'match'],
};
/** The readability results that a role takes part in, as a foreground, a surface, or a pair. */
export function roleFindings(role: Role, findings: readonly Finding[]): Finding[] {
const surfaces = SURFACE_ROLES[role] ?? [];
return findings.filter(finding => {
const subject = finding.subject;
if (subject.startsWith(`${role} on `) || subject.startsWith(`${role} and `) || subject.endsWith(` and ${role}`)) return true;
if (subject.startsWith(`${role} lighter than `) || subject.endsWith(` lighter than ${role}`)) return true;
return surfaces.some(surface => finding.subject.endsWith(` on ${surface}`));
});
}
/** The lowest contrast result of a role, and every result that fails. */
export function roleStatus(role: Role, findings: readonly Finding[]) {
const own = roleFindings(role, findings);
const ratios = own.filter(finding => finding.min > 1);
const lowest = ratios.length ? ratios.reduce((low, finding) => finding.value / finding.min < low.value / low.min ? finding : low) : undefined;
return { lowest, failures: own.filter(finding => !finding.pass) };
}
export function draftFindings(draft: ThemeDraft): Finding[] {
return checkTheme(draftColors(draft), draft.mode);
}
+13
View File
@@ -0,0 +1,13 @@
// Opens the theme editor tab. The Settings window asks the workspace window that opened it.
import { isTauri } from '@tauri-apps/api/core';
import { emitTo } from '@tauri-apps/api/event';
import { getCurrentWebviewWindow } from '@tauri-apps/api/webviewWindow';
export const THEME_EDITOR_EVENT = 'runestone-theme-editor-open';
export async function requestThemeEditor() {
const label = isTauri() ? getCurrentWebviewWindow().label : '';
// Settings window labels are settings-<owner> (src-tauri/src/settings.rs).
if (label.startsWith('settings-')) await emitTo(label.slice('settings-'.length), THEME_EDITOR_EVENT);
else window.dispatchEvent(new Event(THEME_EDITOR_EVENT));
}
+8
View File
@@ -38,6 +38,14 @@
<rect x="5" y="5" width="14" height="14" />
{:else if icon === "window-restore"}
<path d="M9 8V4h11v11h-4" /><rect x="4" y="9" width="11" height="11" />
{:else if icon === "check"}
<path d="M5 12.5 9.5 17 19 7" />
{:else if icon === "alert"}
<path d="M12 3 2.5 20h19Z" /><path d="M12 10v4M12 17h.01" />
{:else if icon === "palette"}
<path d="M12 3a9 9 0 0 0 0 18c1.1 0 1.6-.8 1.6-1.6 0-.5-.2-.8-.5-1.2-.3-.4-.5-.7-.5-1.2 0-.9.7-1.6 1.6-1.6H16a5 5 0 0 0 5-5c0-4.1-4-7.4-9-7.4Z" /><circle cx="7.5" cy="11" r="1" /><circle cx="10.5" cy="7.5" r="1" /><circle cx="15" cy="8" r="1" />
{:else if icon === "undo"}
<path d="M9 14 4 9l5-5" /><path d="M4 9h10.5a5.5 5.5 0 0 1 0 11H11" />
{:else if icon === "restore"}
<path d="M3 8h5V3M21 8h-5V3M16 21v-5h5M3 16h5v5" />
{:else if icon === "split"}
+4
View File
@@ -3,6 +3,10 @@
import Icon from "./Icon.svelte";
export type IconName =
| "globe"
| "check"
| "alert"
| "palette"
| "undo"
| "git"
| "arrow-left"
| "arrow-right"
+10 -3
View File
@@ -177,8 +177,8 @@ function installMock(options, commands) {
// `crypto.randomUUID` needs a secure context, which `about:blank` is not.
const pageId = `${Date.now()}-${Math.random().toString(16).slice(2)}`;
const channel = typeof BroadcastChannel === "function" ? new BroadcastChannel("runestone-smoke-host") : { postMessage() {} };
channel.addEventListener?.("message", ({ data }) => { if (!data.target || data.target === pageId) emit(data.event, data.payload); });
// `target` is a page ID. Without it, every page of the context receives the event, this page too.
channel.addEventListener?.("message", ({ data }) => { if ((!data.target || data.target === pageId) && (!data.label || data.label === options.label)) emit(data.event, data.payload); });
// `target` is a page ID. Without it, every page of the context receives the event, this page too. `label` limits the event to pages with that window label.
const broadcast = (event, payload, target) => {
if (!target || target === pageId) emit(event, payload);
if (target !== pageId) channel.postMessage({ event, payload, target });
@@ -267,7 +267,14 @@ function installMock(options, commands) {
return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return null; }
if (command === "plugin:event|emit" || command === "plugin:event|emit_to") { emit(args.event, args.payload); return null; }
// An app event reaches every window. A targeted event reaches the windows with the target label (Tauri emit and emitTo).
if (command === "plugin:event|emit") { broadcast(args.event, args.payload); return null; }
if (command === "plugin:event|emit_to") {
const label = typeof args.target === "string" ? args.target : args.target?.label;
if (!label || label === options.label) emit(args.event, args.payload);
channel.postMessage({ event: args.event, payload: args.payload, label });
return null;
}
const handler = typeof table[command] === "function" ? table[command] : defaults[command];
if (typeof handler === "function") {
const result = await handler(args, test);
@@ -76,14 +76,14 @@ await runSmoke('appearance/backgroundImages', async ({ browser }) => {
await settings.getByLabel('Image overlay', { exact: true }).fill('-40');
await main.waitForFunction(() => getComputedStyle(document.querySelector('.workarea-background')).backgroundImage.includes('255, 255, 255, 0.4'));
// The Color theme picker now chooses the theme and its light or dark mode together (src/lib/theme/AppearanceSettings.svelte:20, 113).
// A theme card chooses the theme and its light or dark mode together (src/lib/theme/ThemePicker.svelte).
for (const mode of ['dark', 'light']) {
await picker('Color theme').click();
await settings.getByRole('menuitemradio', { name: mode === 'dark' ? 'RuneStone Dark' : 'RuneStone Light', exact: true }).click();
await settings.getByRole('radio', { name: mode === 'dark' ? 'RuneStone Dark' : 'RuneStone Light', exact: true }).click();
await main.waitForFunction(mode => document.documentElement.dataset.theme === mode, mode);
assert.equal(await background(), url, 'Theme changes reuse the current image URL');
await main.screenshot({ path: `${output}/background-${mode}.png` });
for (const name of ['Color theme']) {
// The image position menu is a shared menu of Appearance settings.
for (const name of ['Image position']) {
await picker(name).click();
const menu = settings.getByRole('menu', { name, exact: true });
assert.equal(await menu.evaluate(node => getComputedStyle(node).fontSize), '13px');
@@ -99,8 +99,9 @@ await runSmoke('appearance/backgroundImages', async ({ browser }) => {
}
await settings.setViewportSize({ width: 360, height: 480 });
await settings.getByRole('button', { name: 'Color theme', exact: true }).click();
const box = await settings.getByRole('menu', { name: 'Color theme', exact: true }).boundingBox();
await picker('Image position').scrollIntoViewIfNeeded();
await picker('Image position').click();
const box = await settings.getByRole('menu', { name: 'Image position', exact: true }).boundingBox();
assert.ok(box.x >= 0 && box.x + box.width <= 360 && box.y + box.height <= 480);
await settings.screenshot({ path: `${output}/menu-narrow.png` });
await settings.keyboard.press('Escape');
@@ -1,4 +1,4 @@
// Character themes: colors, fonts, IDE syntax, export, window sync, narrow menus, selection fills, and legacy or removed theme IDs.
// Character themes: colors, fonts, IDE syntax, export, window sync, narrow theme cards, selection fills, and legacy or removed theme IDs.
import assert from 'node:assert/strict';
import path from 'node:path';
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
@@ -47,11 +47,9 @@ await runSmoke('appearance/characterThemes', async ({ browser }) => {
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
await settings.getByRole('img', { name: 'Color theme preview' }).waitFor();
};
const picker = name => settings.locator('.picker').and(settings.getByRole('button', { name, exact: true }));
const choose = async (name, value) => {
await picker(name).click();
await settings.getByRole('menuitemradio', { name: value, exact: true }).click();
};
// The Color theme cards are one radio group (src/lib/theme/ThemePicker.svelte).
const card = name => settings.getByRole('radiogroup', { name: 'Color theme', exact: true }).getByRole('radio', { name, exact: true });
const choose = async (_, value) => { await card(value).click(); };
const waitForAppearance = (theme, mode) => Promise.all(pages.map(page => page.waitForFunction(({ theme, mode }) => document.documentElement.dataset.palette === theme && document.documentElement.dataset.theme === mode, { theme, mode })));
// Settings and the app import external.ts with a version query, so reuse the loaded module URL.
const setPluginTools = count => settings.evaluate(async count => {
@@ -60,13 +58,11 @@ await runSmoke('appearance/characterThemes', async ({ browser }) => {
}, count);
await openSettings();
await picker('Color theme').click();
assert.equal(await settings.getByRole('menuitemradio', { name: 'Renamon', exact: true }).count(), 0);
assert.equal(await settings.getByRole('menuitemradio', { name: 'Asuka School Uniform', exact: true }).count(), 0);
assert.equal(await card('Renamon').count(), 0);
assert.equal(await card('Asuka School Uniform').count(), 0);
for (const label of ['Holo', 'Asuka Langley Soryu', 'Malfoid']) {
assert.equal(await settings.getByRole('menuitemradio', { name: label, exact: true }).count(), 0);
assert.equal(await card(label).count(), 0);
}
await settings.keyboard.press('Escape');
const cases = [
['harvest-moon', 'Harvest Moon', 'dark', { ui: 'Candara', prose: 'Constantia', heading: 'Constantia' }],
['crimson-pilot', 'Crimson Pilot', 'dark', { ui: 'Bahnschrift', prose: 'Segoe UI', heading: 'Bahnschrift' }],
@@ -164,25 +160,22 @@ await runSmoke('appearance/characterThemes', async ({ browser }) => {
await main.screenshot({ path: path.join(output, `${theme}-${mode}-document.png`) });
await settings.reload();
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
assert.equal((await picker('Color theme').textContent()).trim(), label);
assert.equal(await card(label).getAttribute('aria-checked'), 'true');
await settings.setViewportSize({ width: 360, height: 480 });
const content = settings.locator('dialog .content');
assert(await content.evaluate(node => node.scrollWidth <= node.clientWidth), 'Narrow settings fit the content area');
await picker('Color theme').scrollIntoViewIfNeeded();
await picker('Color theme').focus();
await settings.keyboard.press('Enter');
const current = settings.getByRole('menuitemradio', { name: label, exact: true });
await current.waitFor();
assert.equal(await current.getAttribute('aria-checked'), 'true');
assert(await current.evaluate(node => document.activeElement === node), 'The menu focuses the current theme');
const bounds = await settings.getByRole('menu', { name: 'Color theme', exact: true }).boundingBox();
assert(bounds.x >= 0 && bounds.x + bounds.width <= 360 && bounds.y >= 0 && bounds.y + bounds.height <= 480, 'The menu stays within the viewport');
await settings.screenshot({ path: path.join(output, `${theme}-${mode}-360-menu.png`) });
await settings.keyboard.press('ArrowDown');
await settings.keyboard.press('ArrowUp');
assert(await current.evaluate(node => document.activeElement === node));
await settings.keyboard.press('Escape');
assert(await picker('Color theme').evaluate(node => document.activeElement === node), 'Dismissal returns focus');
// The current card is the one Tab stop of the group, and its focus outline shows.
const current = card(label);
await current.scrollIntoViewIfNeeded();
await current.focus();
// Reach the card with the keyboard, so :focus-visible applies.
await settings.keyboard.press('Shift+Tab');
await settings.keyboard.press('Tab');
assert(await current.evaluate(node => document.activeElement === node), 'Tab returns to the current card');
assert.equal(await current.getAttribute('tabindex'), '0');
assert.notEqual(await current.evaluate(node => getComputedStyle(node).outlineStyle), 'none', 'Keyboard focus shows an outline');
const bounds = await settings.getByRole('radiogroup', { name: 'Color theme', exact: true }).boundingBox();
assert(bounds.x >= 0 && bounds.x + bounds.width <= 360, 'The cards stay within the viewport');
await settings.screenshot({ path: path.join(output, `${theme}-${mode}-360-focus.png`) });
await setPluginTools(16);
const navigation = settings.locator('dialog aside');
@@ -192,12 +185,12 @@ await runSmoke('appearance/characterThemes', async ({ browser }) => {
await settings.getByRole('button', { name: 'Plugin settings 16', exact: true }).scrollIntoViewIfNeeded();
await settings.screenshot({ path: path.join(output, `${theme}-${mode}-360-long-navigation.png`) });
await setPluginTools(0);
console.log(`PASS: ${theme} ${mode}, colors, fonts, IDE syntax, export, saved state, window sync, narrow menu, keyboard and focus`);
console.log(`PASS: ${theme} ${mode}, colors, fonts, IDE syntax, export, saved state, window sync, narrow theme cards, keyboard and focus`);
}
for (const [previous, theme, label] of [['holo', 'harvest-moon', 'Harvest Moon'], ['asuka', 'crimson-pilot', 'Crimson Pilot'], ['malfoid', 'silver-serpent', 'Silver Serpent']]) {
await settings.evaluate(theme => window.__TEST__.writeSettings('appearance', { theme, mode: 'dark' }), previous);
await openSettings();
assert.equal((await picker('Color theme').textContent()).trim(), label);
assert.equal(await card(label).getAttribute('aria-checked'), 'true');
assert.equal(await settings.evaluate(() => document.documentElement.dataset.palette), theme);
await choose('Color theme', label);
assert.equal(await settings.evaluate(() => window.__TEST__.settings('appearance').theme), theme);
@@ -207,7 +200,7 @@ await runSmoke('appearance/characterThemes', async ({ browser }) => {
await settings.setViewportSize({ width: 1100, height: 780 });
await openSettings();
await waitForAppearance('default', mode);
assert.equal((await picker('Color theme').textContent()).trim(), `RuneStone ${mode === 'light' ? 'Light' : 'Dark'}`);
assert.equal(await card(`RuneStone ${mode === 'light' ? 'Light' : 'Dark'}`).getAttribute('aria-checked'), 'true');
assert((await settings.evaluate(() => getComputedStyle(document.body).fontFamily)).includes('Segoe UI'), 'The default font returns after a palette change');
await settings.screenshot({ path: path.join(output, `${removed}-fallback-${mode}-settings.png`) });
await settings.setViewportSize({ width: 360, height: 480 });
@@ -1,4 +1,4 @@
// The Color theme menu in Settings works from the keyboard, has no color inputs, and the main window's empty tab uses the new theme background.
// The Color theme cards in Settings work from the keyboard, Settings has no color inputs, and the main window's empty tab uses the new theme background.
import assert from "node:assert/strict";
import { mockTauri, openPage, runSmoke, smokeUrl } from "../_harness/index.mjs";
@@ -18,11 +18,10 @@ await runSmoke("appearance/colorThemeMenu", async ({ browser }) => {
const settings = await openPage(context);
await settings.goto(smokeUrl + "/?settingsWindow=true");
await settings.getByRole("button", { name: "Appearance", exact: true }).click();
await settings.getByRole("button", { name: "Color theme", exact: true }).click();
// Menu entries now name the mode ("RuneStone Dark" is the default; src/lib/theme/AppearanceSettings.svelte:20-22). The next entry is Claude Light.
await settings.getByRole("menuitemradio", { name: "RuneStone Dark", exact: true }).focus();
// Cards name the mode ("RuneStone Dark" is the default). The next card is Claude Light, and an arrow key selects it (src/lib/theme/ThemePicker.svelte).
await settings.getByRole("radio", { name: "RuneStone Dark", exact: true }).focus();
await settings.keyboard.press("ArrowDown");
await settings.keyboard.press("Enter");
await settings.waitForFunction(() => document.documentElement.dataset.palette === "claude");
assert.equal(await settings.evaluate(() => document.documentElement.dataset.palette), "claude");
assert.equal(await settings.locator("input[type=color]").count(), 0);
await page.getByRole("button", { name: "New tab (Ctrl T)", exact: true }).click();
+8 -9
View File
@@ -51,14 +51,15 @@ await runSmoke("appearance/palettes", async ({ browser }) => {
}
const themeName = (theme, mode) => theme === "sakura" ? "Sakura" : `${({ default: "RuneStone", claude: "Claude" })[theme]} ${mode === "light" ? "Light" : "Dark"}`;
const picker = (page, name) => page.locator(".picker").filter({ has: page.locator("svg") }).and(page.getByRole("button", { name, exact: true }));
// The Color theme cards are one radio group (src/lib/theme/ThemePicker.svelte).
const card = (page, name) => page.getByRole("radiogroup", { name: "Color theme", exact: true }).getByRole("radio", { name, exact: true });
async function choose(page, theme, mode) {
await picker(page, "Color theme").click();
await page.getByRole("menuitemradio", { name: themeName(theme, mode), exact: true }).click();
await card(page, themeName(theme, mode)).click();
}
async function openAppearance(page) {
await page.goto(`${smokeUrl}/?settingsWindow=true`);
await page.getByRole("button", { name: "Appearance", exact: true }).click();
await picker(page, "Color theme").waitFor();
await page.getByRole("radiogroup", { name: "Color theme", exact: true }).waitFor();
}
await openCode(0);
await openAppearance(settings);
@@ -68,7 +69,7 @@ await runSmoke("appearance/palettes", async ({ browser }) => {
await page.waitForFunction(({ theme, mode }) => document.documentElement.dataset.palette === theme && document.documentElement.dataset.theme === mode, { theme, mode });
assert.equal(await page.evaluate(() => getComputedStyle(document.documentElement).colorScheme), mode);
}
assert.equal((await picker(secondSettings, "Color theme").textContent()).trim(), themeName(theme, mode));
assert.equal(await card(secondSettings, themeName(theme, mode)).getAttribute("aria-checked"), "true");
await main.waitForFunction(() => {
const root = document.documentElement;
const probe = document.createElement("i");
@@ -121,9 +122,7 @@ await runSmoke("appearance/palettes", async ({ browser }) => {
}
}
assert.equal(backgrounds.size, 5, "All supported combinations have distinct backgrounds");
await picker(settings, "Color theme").click();
assert.deepEqual(await settings.getByRole("menuitemradio").allTextContents(), ["RuneStone Light", "RuneStone Dark", "Claude Light", "Claude Dark", "Sakura", "Harvest Moon", "Crimson Pilot", "Silver Serpent"]);
await settings.keyboard.press("Escape");
assert.deepEqual((await settings.getByRole("radiogroup", { name: "Color theme", exact: true }).getByRole("radio").allTextContents()).map(name => name.trim()), ["RuneStone Light", "RuneStone Dark", "Claude Light", "Claude Dark", "Sakura", "Harvest Moon", "Crimson Pilot", "Silver Serpent"]);
assert.equal(await picker(settings, "Appearance").count(), 0);
assert.equal(await picker(secondSettings, "Appearance").count(), 0);
const sakura = await settings.evaluate(() => {
@@ -151,10 +150,10 @@ await runSmoke("appearance/palettes", async ({ browser }) => {
await settings.setViewportSize({ width: 360, height: 480 });
assert(await settings.evaluate(() => document.documentElement.scrollWidth <= innerWidth), "Narrow settings do not overflow the viewport");
assert(await settings.locator("dialog .content").evaluate(node => node.scrollWidth <= node.clientWidth), "Appearance controls do not overflow the content area");
const control = picker(settings, "Color theme");
const control = card(settings, themeName(theme, mode));
await control.scrollIntoViewIfNeeded();
const bounds = await control.boundingBox();
assert(bounds.x >= 0 && bounds.x + bounds.width <= 360 && bounds.height >= 28, "Color theme remains reachable at 360px");
assert(bounds.x >= 0 && bounds.x + bounds.width <= 360 && bounds.height >= 28, "The current theme card remains reachable at 360px");
await settings.screenshot({ path: path.join(output, `appearance-${theme}-${mode}-360.png`) });
}
assert.deepEqual(pages.flatMap(page => page.errors), []);
@@ -0,0 +1,112 @@
// Theme picker cards and the theme editor tab: keyboard selection, the check mark, a live preview, contrast badges, Save, Discard, Duplicate, and narrow windows.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("appearance/themeEditor", async ({ browser }) => {
const output = await outputDir("appearance/themeEditor");
const context = await browser.newContext({ viewport: { width: 1200, height: 820 } });
const commands = test => ({
...test.workspace({ root: "C:\\theme-editor", files: { "a.md": "# Note\n\nSome text with a [link](https://example.com).\n" } }),
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
spelling_menu_install: () => null,
"plugin:window|is_maximized": () => false,
});
// The Settings window label names the window that opened it (src-tauri/src/settings.rs).
const main = await openPage(context);
await mockTauri(main, { label: "main", commands });
const settings = await openPage(context);
await mockTauri(settings, { label: "settings-main", commands });
await main.goto(smokeUrl);
await main.locator('[data-tree-rel="a.md"]').waitFor();
await settings.goto(smokeUrl + "/?settingsWindow=true");
await settings.getByRole("button", { name: "Appearance", exact: true }).click();
const token = (page, role) => page.evaluate(role => getComputedStyle(document.documentElement).getPropertyValue(`--rs-${role}`).trim(), role);
// Picker cards: one radio group with a check mark on the current theme.
const cards = settings.getByRole("radiogroup", { name: "Color theme", exact: true });
const card = name => cards.getByRole("radio", { name, exact: true });
assert.equal(await card("RuneStone Dark").getAttribute("aria-checked"), "true");
assert.equal(await card("RuneStone Dark").locator(".card-name svg").count(), 1, "The current card shows a check mark");
assert.equal(await card("Claude Light").locator(".card-name svg").count(), 0);
await card("RuneStone Dark").focus();
await settings.keyboard.press("ArrowRight");
await settings.waitForFunction(() => document.documentElement.dataset.palette === "claude" && document.documentElement.dataset.theme === "light");
assert.equal(await card("Claude Light").evaluate(node => node === document.activeElement && node.getAttribute("aria-checked") === "true"), true);
await settings.keyboard.press("ArrowLeft");
await settings.waitForFunction(() => document.documentElement.dataset.palette === "default" && document.documentElement.dataset.theme === "dark");
await main.waitForFunction(() => document.documentElement.dataset.palette === "default");
await settings.screenshot({ path: path.join(output, "picker-cards.png") });
// Edit theme opens the editor tab in the window that opened Settings.
await settings.getByRole("button", { name: "Edit theme", exact: true }).click();
const editor = main.getByRole("region", { name: "Theme editor", exact: true });
await editor.waitFor();
await main.getByRole("tab", { name: /Theme editor/ }).waitFor();
assert.equal(await editor.getByRole("textbox", { name: "Theme name", exact: true }).inputValue(), "RuneStone Dark copy");
assert.match(await editor.getByRole("status").textContent(), /All readability checks pass/);
// A change shows at once in this window, and not in Settings before a save.
const hex = role => editor.getByRole("textbox", { name: `Hex value of ${role}`, exact: true });
await hex("accent").fill("#ff7a1a");
await hex("accent").press("Tab");
await main.waitForFunction(() => getComputedStyle(document.documentElement).getPropertyValue("--rs-accent").trim() === "#ff7a1a");
assert.equal(await token(settings, "accent"), "#55dcf5");
await main.getByRole("tab", { name: "• Theme editor", exact: true }).waitFor();
// A color that fails a rule shows the failure on its row and in the summary. Reset takes the base color again.
await hex("text-dim").fill("#3a3a3a");
await hex("text-dim").press("Tab");
await editor.getByRole("status").filter({ hasText: /readability checks fail/ }).waitFor();
const dimRow = hex("text-dim").locator("xpath=..");
assert.equal(await dimRow.locator(".badge.fail").count(), 1);
await main.screenshot({ path: path.join(output, "editor-failing-role.png") });
await editor.getByRole("button", { name: "Reset text-dim", exact: true }).click();
assert.equal(await dimRow.locator(".badge.fail").count(), 0);
assert.equal(await token(main, "text-dim"), "#ababab");
// Save copies the built-in theme to a custom theme with a base, and every window selects it.
await editor.getByRole("button", { name: "Save", exact: true }).click();
await editor.getByRole("status").filter({ hasText: "Saved RuneStone Dark copy." }).waitFor();
await settings.waitForFunction(() => document.documentElement.dataset.palette === "custom:runestone-dark-copy");
assert.equal(await token(settings, "accent"), "#ff7a1a");
const saved = await main.evaluate(() => window.__TEST__.settings("customThemes"));
assert.deepEqual(saved.map(theme => [theme.id, theme.base, theme.mode, theme.colors]), [["runestone-dark-copy", "default", "dark", { accent: "#ff7a1a" }]]);
assert.equal(await card("RuneStone Dark copy").getAttribute("aria-checked"), "true");
await main.getByRole("tab", { name: "Theme editor", exact: true }).waitFor();
// Discard returns to the saved colors.
await hex("bg").fill("#202040");
await hex("bg").press("Tab");
await main.waitForFunction(() => getComputedStyle(document.documentElement).getPropertyValue("--rs-bg").trim() === "#202040");
await editor.getByRole("button", { name: "Discard", exact: true }).click();
await main.waitForFunction(() => getComputedStyle(document.documentElement).getPropertyValue("--rs-bg").trim() === "#151617");
// Duplicate saves a copy and selects it.
await editor.getByRole("button", { name: "Duplicate", exact: true }).click();
await editor.getByRole("status").filter({ hasText: "Saved RuneStone Dark copy copy." }).waitFor();
await settings.waitForFunction(() => document.documentElement.dataset.palette === "custom:runestone-dark-copy-copy");
assert.equal((await main.evaluate(() => window.__TEST__.settings("customThemes"))).length, 2);
// Narrow windows keep the editor inside the window, and keyboard focus is visible.
await main.setViewportSize({ width: 600, height: 760 });
await hex("accent").focus();
assert.equal(await editor.evaluate(node => node.scrollWidth <= node.clientWidth + 1), true, "The editor does not scroll sideways at 600 pixels");
assert.notEqual(await hex("accent").evaluate(node => getComputedStyle(node).outlineStyle), "none");
await main.screenshot({ path: path.join(output, "editor-600.png") });
await settings.setViewportSize({ width: 360, height: 640 });
assert.equal(await settings.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true, "Narrow settings do not overflow");
const box = await cards.boundingBox();
assert(box.x >= 0 && box.x + box.width <= 360, "The cards fit at 360 pixels");
await settings.screenshot({ path: path.join(output, "picker-cards-360.png") });
// Closing the editor with a change keeps the saved theme in the window.
await hex("accent").fill("#00ff00");
await hex("accent").press("Tab");
await main.waitForFunction(() => getComputedStyle(document.documentElement).getPropertyValue("--rs-accent").trim() === "#00ff00");
await main.getByRole("button", { name: /^Close .*Theme editor$/ }).click();
await editor.waitFor({ state: "detached" });
await main.waitForFunction(() => getComputedStyle(document.documentElement).getPropertyValue("--rs-accent").trim() === "#ff7a1a");
assert.deepEqual([...main.errors, ...settings.errors], []);
console.log("PASS: picker cards, the editor tab, live preview, contrast badges, Save, Discard, Duplicate, and narrow windows");
});
+2 -3
View File
@@ -22,9 +22,8 @@ await runSmoke(name, async ({ page }) => {
await page.waitForFunction(() => document.documentElement.dataset.palette === "custom:smoke");
assert.equal(await background(), "#181820");
// A custom theme now keeps one palette. A schema 1 file converts with the current mode (src/lib/theme/customThemes.ts:38,
// src/lib/theme/AppearanceSettings.svelte:70), and the light/dark select became the Color theme menu (AppearanceSettings.svelte:20-31, :113).
await page.getByRole("button", { name: "Color theme", exact: true }).click();
await page.getByRole("menuitemradio", { name: "RuneStone Light", exact: true }).click();
// src/lib/theme/AppearanceSettings.svelte), and the light/dark select became the Color theme cards (src/lib/theme/ThemePicker.svelte).
await page.getByRole("radio", { name: "RuneStone Light", exact: true }).click();
await page.waitForFunction(() => document.documentElement.dataset.palette !== "custom:smoke");
await importTheme();
await page.waitForFunction(() => document.documentElement.dataset.palette === "custom:smoke");
+7 -10
View File
@@ -51,7 +51,7 @@ await runSmoke('appearance/typography', async ({ browser }) => {
const { pluginTools } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
pluginTools.set(Array.from({ length: count }, (_, index) => ({ owner: 'org.example.font-check', id: `settings-${index}`, title: `Plugin settings ${index + 1}`, surface: 'settings' })));
}, count);
const selectors = { ui: '.picker[aria-label="Color theme"]', prose: '.cm-line:not(.writer-heading):not(.writer-blank)', heading: '.writer-h1' };
const selectors = { ui: '.theme-actions button', prose: '.cm-line:not(.writer-heading):not(.writer-blank)', heading: '.writer-h1' };
const cases = [
['harvest-moon', 'Harvest Moon', 'Constantia', 'Candara', 'Constantia', 'Constantia'],
['crimson-pilot', 'Crimson Pilot', 'Bahnschrift', 'Bahnschrift', 'Segoe UI', 'Bahnschrift'],
@@ -59,9 +59,7 @@ await runSmoke('appearance/typography', async ({ browser }) => {
];
for (const [theme, label, oldFont, ui, prose, heading] of cases) {
await settings.setViewportSize({ width: 1100, height: 780 });
const picker = settings.locator('.picker').and(settings.getByRole('button', { name: 'Color theme', exact: true }));
await picker.click();
await settings.getByRole('menuitemradio', { name: label, exact: true }).click();
await settings.getByRole('radio', { name: label, exact: true }).click();
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(); });
@@ -104,13 +102,12 @@ await runSmoke('appearance/typography', async ({ browser }) => {
await settings.setViewportSize({ width: 360, height: 480 });
const content = settings.locator('dialog .content');
assert(await content.evaluate(node => node.scrollWidth <= node.clientWidth), `${theme}: narrow overflow`);
await picker.scrollIntoViewIfNeeded(); await picker.focus(); await settings.keyboard.press('Enter');
const current = settings.getByRole('menuitemradio', { name: label, exact: true });
await current.waitFor();
// The current theme card stays reachable from the keyboard in a narrow window.
const current = settings.getByRole('radio', { name: label, exact: true });
await current.scrollIntoViewIfNeeded(); await current.focus();
assert.equal(await current.getAttribute('aria-checked'), 'true');
assert(await current.evaluate(node => node === document.activeElement));
await settings.screenshot({ path: path.join(output, `${theme}-narrow-menu.png`) });
await settings.keyboard.press('Escape');
assert(await picker.evaluate(node => node === document.activeElement));
await settings.screenshot({ path: path.join(output, `${theme}-narrow-cards.png`) });
await setPluginTools(16);
const bodyBounds = await settings.locator('dialog .body').boundingBox();
assert((await settings.locator('dialog aside').boundingBox()).height <= bodyBounds.height * .4 + 1);
+13 -5
View File
@@ -85,14 +85,22 @@ await runSmoke('settings/displayLanguage', async ({ browser }) => {
assert.equal(await settings.locator('html').getAttribute('data-transparency'), 'off');
await main.waitForFunction(() => document.documentElement.dataset.transparency === 'off');
assert.equal(await surfaceOpacity(), '100%');
await settings.locator('.picker').first().click();
const bg = await settings.getByRole('menu').evaluate(node => getComputedStyle(node).backgroundColor);
assert(!bg.endsWith('/ 0.82)') && !bg.startsWith('rgba'), `Opaque menu: ${bg}`);
await settings.screenshot({ path: path.join(output, `${language}-${mode}-opaque-menu.png`) });
await settings.keyboard.press('Escape');
// Without a background image, menus are opaque at every transparency amount (UI-043).
const menuBackground = async () => {
await main.locator('.source-editor .cm-content').click({ button: 'right' });
const bg = await main.locator('.rs-menu').first().evaluate(node => getComputedStyle(node).backgroundColor);
await main.keyboard.press('Escape');
return bg;
};
let bg = await menuBackground();
assert(bg.startsWith('rgb('), `Opaque menu: ${bg}`);
await toggle.check();
await settings.locator('#surface-transparency').fill('30');
assert.equal(await surfaceOpacity(), '70%');
await main.waitForFunction(() => getComputedStyle(document.documentElement).getPropertyValue('--rs-surface-opacity').trim() === '70%');
bg = await menuBackground();
assert(bg.startsWith('rgb('), `Opaque menu at 30% transparency: ${bg}`);
await main.screenshot({ path: path.join(output, `${language}-${mode}-opaque-menu.png`) });
await settings.setViewportSize({ width: 360, height: 640 });
await settings.locator('#surface-transparency').scrollIntoViewIfNeeded();
assert(await settings.locator('.content').evaluate(node => node.scrollWidth <= node.clientWidth), `${language} ${mode}: narrow overflow`);
+47
View File
@@ -0,0 +1,47 @@
// The theme editor model (src/lib/theme/themeEditor.ts): role groups, drafts, saved files, and the results of each role.
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { ROLE_GROUPS, builtinDraft, customDraft, draftColors, draftFindings, draftTheme, roleStatus, uniqueThemeId } from '../../../src/lib/theme/themeEditor.ts';
import { ROLES, resolveColors } from '../../../src/lib/theme/roles.ts';
import { parseCustomTheme } from '../../../src/lib/theme/customThemes.ts';
import { BUILTIN_THEMES } from '../../../src/lib/theme/themes/index.ts';
test('The editor groups show every role once', () => {
const shown = ROLE_GROUPS.flatMap(group => group.roles);
assert.equal(new Set(shown).size, shown.length);
assert.deepEqual([...shown].sort(), [...ROLES].sort());
});
test('A built-in draft has the colors of its theme', () => {
for (const theme of BUILTIN_THEMES) for (const [mode, colors] of Object.entries(theme.variants)) {
const draft = builtinDraft(theme.id, mode as 'light' | 'dark', theme.name);
assert.deepEqual(draftColors(draft), resolveColors(colors!, mode as 'light' | 'dark'));
}
});
test('A saved draft is a short schema 3 theme that the parser accepts and that keeps its colors', () => {
const draft = { ...builtinDraft('harvest-moon', 'dark', 'Harvest Moon copy'), overrides: { accent: '#00c8ff', selection: '#20406080' } };
const theme = draftTheme(draft, 'harvest-moon-copy', 'Harvest Moon copy');
assert.deepEqual(theme, { schema: 3, id: 'harvest-moon-copy', name: 'Harvest Moon copy', mode: 'dark', base: 'harvest-moon', colors: { accent: '#00c8ff', selection: '#20406080' } });
const parsed = parseCustomTheme(theme);
assert.deepEqual(draftColors(customDraft(parsed)), draftColors(draft));
});
test('Theme IDs from names are valid and unique', () => {
assert.equal(uniqueThemeId('RuneStone Dark copy', []), 'runestone-dark-copy');
assert.equal(uniqueThemeId('RuneStone Dark copy', ['runestone-dark-copy', 'runestone-dark-copy-2']), 'runestone-dark-copy-3');
assert.equal(uniqueThemeId('2026 theme', []), 't-2026-theme');
assert.equal(uniqueThemeId('桜', []), 'theme');
for (const name of ['RuneStone Dark copy', '2026 theme', '桜', 'x'.repeat(100), '--Ünïcode--']) assert.match(uniqueThemeId(name, []), /^[a-z][a-z0-9-]{0,63}$/);
});
test('A role shows the results where it is the color, the surface, or one of a pair', () => {
const draft = { ...builtinDraft('default', 'dark', 'Test'), overrides: { 'text-dim': '#3a3a3a', ok: '#55dcf5' } };
const findings = draftFindings(draft);
const dim = roleStatus('text-dim', findings);
assert(dim.failures.length > 0 && dim.failures.every(finding => finding.subject.startsWith('text-dim on ')));
assert(dim.lowest && dim.lowest.value < 4.5);
assert(roleStatus('bg', findings).failures.some(finding => finding.subject === 'text-dim on bg'), 'A surface shows the text that fails on it');
assert(roleStatus('ok', findings).failures.some(finding => finding.subject === 'accent and ok'), 'A status color shows a pair that is too close');
assert.deepEqual(roleStatus('syntax-keyword', findings).failures, []);
});