diff --git a/docs/design-decisions.md b/docs/design-decisions.md index 656cd62..e906475 100644 --- a/docs/design-decisions.md +++ b/docs/design-decisions.md @@ -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. diff --git a/docs/guides/themes.md b/docs/guides/themes.md index 85acffd..e4de9f8 100644 --- a/docs/guides/themes.md +++ b/docs/guides/themes.md @@ -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**. diff --git a/docs/menu-surfaces.json b/docs/menu-surfaces.json index 3b4c38a..42e96a0 100644 --- a/docs/menu-surfaces.json +++ b/docs/menu-surfaces.json @@ -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": { diff --git a/docs/ui-design.md b/docs/ui-design.md index 44ab75c..1d39887 100644 --- a/docs/ui-design.md +++ b/docs/ui-design.md @@ -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 diff --git a/src/lib/i18n/messages.ts b/src/lib/i18n/messages.ts index 09388b1..0adc1ff 100644 --- a/src/lib/i18n/messages.ts +++ b/src/lib/i18n/messages.ts @@ -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, Record> = { fr: Object.fromEntries(messageRows.map(row => [row[0], row[1]])), diff --git a/src/lib/layout/Workbench.svelte b/src/lib/layout/Workbench.svelte index d8b1cca..1f32059 100644 --- a/src/lib/layout/Workbench.svelte +++ b/src/lib/layout/Workbench.svelte @@ -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(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; } diff --git a/src/lib/plugins/external.ts b/src/lib/plugins/external.ts index 9ced007..2d99cf4 100644 --- a/src/lib/plugins/external.ts +++ b/src/lib/plugins/external.ts @@ -14,7 +14,7 @@ import type { PluginModule, PluginSnapshot, InstalledPlugin, Dispose, PluginView export const installedPlugins = writable({ root: "", plugins: [] }); export const externalErrors = writable>({}); export const pluginTools = writable([]); -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(null); export function closePluginSidebar() { pluginSidebar.set(null); } export const pluginView = writable(null); @@ -78,7 +78,7 @@ export const pluginEditorActive = writable(false); export const pluginServiceError = writable(""); export const restartPlugins = writable([]); /** 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(); const failures = new Map(); const errors: Record = {}; @@ -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(); }; diff --git a/src/lib/theme/AppearanceSettings.svelte b/src/lib/theme/AppearanceSettings.svelte index 2cbcf3e..9a995e9 100644 --- a/src/lib/theme/AppearanceSettings.svelte +++ b/src/lib/theme/AppearanceSettings.svelte @@ -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({ ...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 @@

{$t("Appearance")}

{$t("Choose a color theme variant.")}

-
-
{$t("Color theme")}
-
+ change({ ...appearance, theme: choice.theme, mode: choice.mode })} />
{ void importTheme(event.currentTarget.files?.[0]); }} /> + {#if appearance.theme.startsWith('custom:')} { @@ -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)} diff --git a/src/lib/theme/ThemeEditor.svelte b/src/lib/theme/ThemeEditor.svelte new file mode 100644 index 0000000..013376f --- /dev/null +++ b/src/lib/theme/ThemeEditor.svelte @@ -0,0 +1,200 @@ + + +{#if draft && colors} +
+
+
+ +
+ + + +
+
+

+ {#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} +

+

0} role="status"> + + {failures.length ? $t('{count} readability checks fail.', { count: failures.length }) : $t('All readability checks pass.')} + {#if status}{status}{/if} +

+ {#if error}{/if} + {#each ROLE_GROUPS as group (group.label)} +

{$t(group.label)}

+
+ {#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} +
+ pickRole(role, event.currentTarget.value)} /> + + {role.replace(/^(syntax|ansi)-/, '')} + setRole(role, event.currentTarget.value.trim())} /> + + {#if result.lowest && !result.lowest.pass} + {result.lowest.value.toFixed(1)}:1 + {:else if result.failures.length} + {$t('Too close')} + {:else if result.lowest} + {result.lowest.value.toFixed(1)}:1 + {:else}{/if} + {#if changed} resetRole(role)} />{:else}{/if} +
+ {/each} +
+ {/each} +
+
+{/if} + + diff --git a/src/lib/theme/ThemePicker.svelte b/src/lib/theme/ThemePicker.svelte new file mode 100644 index 0000000..fea9f00 --- /dev/null +++ b/src/lib/theme/ThemePicker.svelte @@ -0,0 +1,69 @@ + + +
+ {#each cards as card, index (card.theme + card.mode)} + {@const selected = index === selectedIndex} + + {/each} +
+ + diff --git a/src/lib/theme/appearance.ts b/src/lib/theme/appearance.ts index e953f67..571317f 100644 --- a/src/lib/theme/appearance.ts +++ b/src/lib/theme/appearance.ts @@ -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]); diff --git a/src/lib/theme/editorView.ts b/src/lib/theme/editorView.ts new file mode 100644 index 0000000..82db199 --- /dev/null +++ b/src/lib/theme/editorView.ts @@ -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)); +} diff --git a/src/lib/theme/themeEditor.ts b/src/lib/theme/themeEditor.ts new file mode 100644 index 0000000..02515b3 --- /dev/null +++ b/src/lib/theme/themeEditor.ts @@ -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 { + 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> = { + 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); +} diff --git a/src/lib/theme/themeEditorRequest.ts b/src/lib/theme/themeEditorRequest.ts new file mode 100644 index 0000000..ac9f6bd --- /dev/null +++ b/src/lib/theme/themeEditorRequest.ts @@ -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- (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)); +} diff --git a/src/lib/ui/Icon.svelte b/src/lib/ui/Icon.svelte index e06d22f..011dcb2 100644 --- a/src/lib/ui/Icon.svelte +++ b/src/lib/ui/Icon.svelte @@ -38,6 +38,14 @@ {:else if icon === "window-restore"} + {:else if icon === "check"} + + {:else if icon === "alert"} + + {:else if icon === "palette"} + + {:else if icon === "undo"} + {:else if icon === "restore"} {:else if icon === "split"} diff --git a/src/lib/ui/IconButton.svelte b/src/lib/ui/IconButton.svelte index 9f02a7e..1409116 100644 --- a/src/lib/ui/IconButton.svelte +++ b/src/lib/ui/IconButton.svelte @@ -3,6 +3,10 @@ import Icon from "./Icon.svelte"; export type IconName = | "globe" + | "check" + | "alert" + | "palette" + | "undo" | "git" | "arrow-left" | "arrow-right" diff --git a/tests/smoke/_harness/index.mjs b/tests/smoke/_harness/index.mjs index c9a7bd2..77fe5b1 100644 --- a/tests/smoke/_harness/index.mjs +++ b/tests/smoke/_harness/index.mjs @@ -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); diff --git a/tests/smoke/appearance/backgroundImages.smoke.mjs b/tests/smoke/appearance/backgroundImages.smoke.mjs index 5831a04..e04f16d 100644 --- a/tests/smoke/appearance/backgroundImages.smoke.mjs +++ b/tests/smoke/appearance/backgroundImages.smoke.mjs @@ -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'); diff --git a/tests/smoke/appearance/characterThemes.smoke.mjs b/tests/smoke/appearance/characterThemes.smoke.mjs index ee4dbc4..dd8d899 100644 --- a/tests/smoke/appearance/characterThemes.smoke.mjs +++ b/tests/smoke/appearance/characterThemes.smoke.mjs @@ -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 }); diff --git a/tests/smoke/appearance/colorThemeMenu.smoke.mjs b/tests/smoke/appearance/colorThemeMenu.smoke.mjs index c219778..5bc734e 100644 --- a/tests/smoke/appearance/colorThemeMenu.smoke.mjs +++ b/tests/smoke/appearance/colorThemeMenu.smoke.mjs @@ -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(); diff --git a/tests/smoke/appearance/palettes.smoke.mjs b/tests/smoke/appearance/palettes.smoke.mjs index 9e8d506..ab48e19 100644 --- a/tests/smoke/appearance/palettes.smoke.mjs +++ b/tests/smoke/appearance/palettes.smoke.mjs @@ -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), []); diff --git a/tests/smoke/appearance/themeEditor.smoke.mjs b/tests/smoke/appearance/themeEditor.smoke.mjs new file mode 100644 index 0000000..cb4fb80 --- /dev/null +++ b/tests/smoke/appearance/themeEditor.smoke.mjs @@ -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"); +}); diff --git a/tests/smoke/appearance/themeImport.smoke.mjs b/tests/smoke/appearance/themeImport.smoke.mjs index f1fc931..19aa7a4 100644 --- a/tests/smoke/appearance/themeImport.smoke.mjs +++ b/tests/smoke/appearance/themeImport.smoke.mjs @@ -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"); diff --git a/tests/smoke/appearance/typography.smoke.mjs b/tests/smoke/appearance/typography.smoke.mjs index 6b6f4b7..b0faeb1 100644 --- a/tests/smoke/appearance/typography.smoke.mjs +++ b/tests/smoke/appearance/typography.smoke.mjs @@ -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); diff --git a/tests/smoke/settings/displayLanguage.smoke.mjs b/tests/smoke/settings/displayLanguage.smoke.mjs index 389cf35..c67f116 100644 --- a/tests/smoke/settings/displayLanguage.smoke.mjs +++ b/tests/smoke/settings/displayLanguage.smoke.mjs @@ -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`); diff --git a/tests/unit/theme/themeEditor.spec.ts b/tests/unit/theme/themeEditor.spec.ts new file mode 100644 index 0000000..9b54adc --- /dev/null +++ b/tests/unit/theme/themeEditor.spec.ts @@ -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, []); +});