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
+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"