Give themes named color roles, theme data files, and file format 3

Phase 5a-1 and 5a-2.

- roles.ts names 51 color roles. One derivation rule fills the roles
  that a theme does not give, for all themes. tokens.css keeps only the
  root defaults, without theme blocks.
- Each built-in theme is one data file in src/lib/theme/themes/. No code
  outside the theme data names a theme ID. characterThemes.ts is gone.
- New roles: link, focus, on-accent, highlight, scrim, the syntax roles,
  and 16 terminal (ANSI) roles. Stray colors in components use the roles.
- contrast.ts checks each theme against the readability rules of
  docs/ui-color.md. The tests mark the known palette failures as todo,
  and a second test fails when a known failure starts to pass.
- Theme files use schema 3 with a mode and an optional built-in base.
  A short file gets the missing colors and fonts from the base. Schema 1
  and 2 files still import. Old syntax names convert on import.
- Docs: ui-color.md, plugin-development.md (theme tokens), ui-design.md,
  guides/themes.md, and UI-041 and UI-042 in design-decisions.md.

The applied colors stay the same for every built-in theme, except three
small changes: the conflict line uses the warn color, the Write
highlight uses the highlight role, and two dialog backdrops use the
scrim role.

pnpm check passes. pnpm test: 447 pass, 31 todo, 0 fail. Full smoke
suite: 93 passed, 2 known. appearance/palettes read the old syntax
names and passed 3 of 3 times after the fix. workspace/manageTemplates
failed one time and passed on retry.
This commit is contained in:
Knotty Wyvern
2026-10-28 15:50:45 -07:00
parent af68d92969
commit 5bd616d7fd
55 changed files with 928 additions and 355 deletions
+7 -6
View File
@@ -8,7 +8,7 @@
import { showActionMenu } from '$lib/ui/managedActionMenu';
import { saveBackgroundImage, removeBackgroundImage } from './backgroundImages';
import { onSettingsChange } from '$lib/settings/store';
import { DEFAULT_APPEARANCE, BUILTIN_THEMES, themeModes, BACKGROUND_POSITIONS, BACKGROUND_SIZES, readAppearance, normalizeAppearance, saveAppearance, exportAppearanceTheme, type Appearance, type ThemeName } from './appearance';
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('');
let status = $state('');
@@ -22,6 +22,7 @@
themeModes(theme.id).map(mode => ({
theme: theme.id, mode, name: themeModes(theme.id).length === 1 ? theme.name : `${theme.name} ${mode === 'light' ? $t('Light') : $t('Dark')}`,
}))));
const notice = $derived(themeNotice(appearance.theme));
onDestroy(() => closePicker());
function picker(event: MouseEvent) {
closePicker();
@@ -131,7 +132,7 @@
}} />{/if}
</div>
<p>{$t("Edit the exported JSON colors and fonts, then choose Install theme. The template contains one color palette and font families.")}</p>
{#if appearance.theme === 'sakura'}<p>{$t("Sakura uses a light appearance.")}</p>{/if}
{#if notice}<p>{$t(notice)}</p>{/if}
<h3>{$t("Transparency")}</h3>
<div class="card">
<label><span>{$t("Transparent surfaces")}</span><input type="checkbox" role="switch" checked={appearance.transparency?.enabled !== false} onchange={event => change({ ...appearance, transparency: { amount: appearance.transparency?.amount ?? 18, enabled: event.currentTarget.checked } })} /></label>
@@ -165,7 +166,7 @@
.setting-row+.setting-row{border-top:1px solid var(--rs-border)}
.picker{display:flex;align-items:center;gap:8px;min-height:var(--rs-settings-control-height);max-width:100%;padding:4px 8px;background:var(--rs-bg);color:var(--rs-text);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius)}
.picker :global(svg){width:14px;height:14px;flex-shrink:0}
.picker:focus-visible{outline:2px solid var(--rs-accent);outline-offset:2px}
.picker:focus-visible{outline:2px solid var(--rs-focus);outline-offset:2px}
.theme-preview{display:flex;gap:var(--rs-settings-gap);margin-top:var(--rs-settings-gap);padding:var(--rs-settings-row-padding);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg);min-height:100px}
.preview-sidebar{display:flex;flex-direction:column;gap:var(--rs-settings-gap);width:22%;padding:var(--rs-settings-row-padding);background:var(--rs-bg-elevated);border-radius:var(--rs-control-radius)}
.preview-sidebar span{height:6px;background:var(--rs-text-dim);opacity:.5;border-radius:var(--rs-control-radius)}
@@ -174,7 +175,7 @@
.preview-document strong{color:var(--rs-text-strong);font-family:var(--rs-font-heading)}
.preview-prose{font-family:var(--rs-font-prose);color:var(--rs-text)}
.preview-selection{background:var(--rs-selection);color:var(--rs-text);padding:2px 4px;border-radius:var(--rs-item-selection-radius)}
.preview-link{color:var(--rs-accent);font-size:var(--rs-settings-description-size)}
.preview-link{color:var(--rs-link);font-size:var(--rs-settings-description-size)}
.preview-code{font-family:var(--rs-font-mono);font-size:var(--rs-settings-description-size);line-height:1.6;overflow-wrap:anywhere;white-space:normal}
.preview-keyword{color:var(--rs-syntax-keyword)}
.preview-string{color:var(--rs-syntax-string,var(--rs-ok))}
@@ -189,13 +190,13 @@
.overlay-controls input[type=range]::-webkit-slider-thumb{appearance:none;width:18px;height:18px;margin-top:-7px;background:var(--rs-accent);border:2px solid var(--rs-text-strong);border-radius:50%}
.overlay-controls input[type=range]::-moz-range-track{height:4px;background:var(--rs-bg-active);border:1px solid var(--rs-text-dim);border-radius:var(--rs-control-radius)}
.overlay-controls input[type=range]::-moz-range-thumb{width:14px;height:14px;background:var(--rs-accent);border:2px solid var(--rs-text-strong);border-radius:50%}
.overlay-controls input[type=range]:focus-visible{outline:2px solid var(--rs-accent);outline-offset:2px;border-radius:var(--rs-control-radius)}
.overlay-controls input[type=range]:focus-visible{outline:2px solid var(--rs-focus);outline-offset:2px;border-radius:var(--rs-control-radius)}
.overlay-controls input[type=range]:disabled{cursor:default}
.overlay-controls input[type=range]:disabled::-webkit-slider-thumb{background:var(--rs-text-dim)}
.overlay-controls input[type=range]:disabled::-moz-range-thumb{background:var(--rs-text-dim)}
.overlay-value{padding:0;gap:4px;flex-wrap:nowrap}
.overlay-value input{width:64px;min-height:var(--rs-settings-control-height);box-sizing:border-box;padding:4px 6px;background:var(--rs-bg);color:var(--rs-text);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);font:inherit}
.overlay-value input:focus-visible{outline:2px solid var(--rs-accent);outline-offset:2px}
.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}
+44 -95
View File
@@ -1,21 +1,24 @@
import { customThemes, FONT_ROLES, type ThemeFonts, type ThemeColors, type CustomTheme } from './customThemes.ts';
import { customThemes, FONT_ROLES, type ThemeFonts, type CustomTheme } from './customThemes.ts';
import { readBackgroundImage } from './backgroundImages.ts';
import { characterTheme, characterSyntax, SYNTAX_ROLES } from './characterThemes.ts';
import { readSection, writeSection } from '../settings/store.ts';
import { BUILTIN_THEMES as THEME_DATA, DEFAULT_FONTS, DEFAULT_THEME, LEGACY_THEME_IDS, builtinTheme, type BuiltinThemeId } from './themes/index.ts';
import { ROLES, resolveColors, type Mode, type ResolvedColors } from './roles.ts';
import { appliedColors } from './contrast.ts';
/** The old localStorage key. The appearance section of the settings file replaces it. */
export const APPEARANCE_KEY = 'runestone.appearance';
export const THEMES = ['default', 'claude', 'sakura', 'harvest-moon', 'crimson-pilot', 'silver-serpent'] as const;
export const BUILTIN_THEMES = [
{ id: 'default', name: 'RuneStone' }, { id: 'claude', name: 'Claude' }, { id: 'sakura', name: 'Sakura' },
{ id: 'harvest-moon', name: 'Harvest Moon' }, { id: 'crimson-pilot', name: 'Crimson Pilot' }, { id: 'silver-serpent', name: 'Silver Serpent' },
] as const;
// Preserve selections saved before the public palette IDs changed.
const LEGACY_THEME_IDS: Record<string, typeof THEMES[number]> = { holo: 'harvest-moon', asuka: 'crimson-pilot', malfoid: 'silver-serpent' };
export function themeModes(theme: string): readonly ('light' | 'dark')[] {
const character = characterTheme(theme);
return theme.startsWith('custom:') ? [customThemeMode(customThemes().find(item => `custom:${item.id}` === theme)?.colors)] : character ? [character.mode] : theme === 'sakura' ? ['light'] : ['light', 'dark'];
export const THEMES: readonly BuiltinThemeId[] = THEME_DATA.map(theme => theme.id);
export const BUILTIN_THEMES: readonly { id: BuiltinThemeId; name: string }[] = THEME_DATA.map(({ id, name }) => ({ id, name }));
const MODES = ['light', 'dark'] as const;
export function themeModes(theme: string): readonly Mode[] {
if (theme.startsWith('custom:')) return [customThemes().find(item => `custom:${item.id}` === theme)?.mode ?? 'dark'];
const builtin = builtinTheme(theme);
return builtin ? MODES.filter(mode => builtin.variants[mode]) : MODES;
}
export type ThemeName = typeof THEMES[number] | `custom:${string}`;
/** The catalog key of a notice that the Appearance settings show for the theme, if any. */
export function themeNotice(theme: string): string | undefined {
return builtinTheme(theme)?.notice;
}
export type ThemeName = BuiltinThemeId | `custom:${string}`;
export const BACKGROUND_POSITIONS = ['center', 'top left', 'top', 'top right', 'left', 'right', 'bottom left', 'bottom', 'bottom right'] as const;
export const BACKGROUND_SIZES = ['cover', 'contain', 'auto'] as const;
export type Appearance = { transparency?: { enabled: boolean; amount: number }; theme: ThemeName; mode: 'light' | 'dark'; newTabBackground?: { image?: string; imageId?: string; overlay?: number; position?: typeof BACKGROUND_POSITIONS[number]; size?: typeof BACKGROUND_SIZES[number] } };
@@ -25,7 +28,8 @@ export function normalizeAppearance(value: { theme?: unknown; mode?: unknown; ne
const savedTheme = typeof value?.theme === 'string' && Object.hasOwn(LEGACY_THEME_IDS, value.theme) ? LEGACY_THEME_IDS[value.theme] : value?.theme;
const theme: ThemeName = typeof savedTheme === 'string' && (/^custom:[a-z][a-z0-9-]{0,63}$/.test(savedTheme) || (THEMES as readonly string[]).includes(savedTheme)) ? savedTheme as ThemeName : 'default';
const selectedCustom = theme.startsWith('custom:') ? (themes ?? customThemes(value?.mode === 'light' ? 'light' : 'dark')).find(item => `custom:${item.id}` === theme) : undefined;
const result: Appearance = { theme, mode: selectedCustom ? customThemeMode(selectedCustom.colors) : characterTheme(theme)?.mode ?? (theme === 'sakura' || value?.mode === 'light' ? 'light' : 'dark') };
const builtinModes = builtinTheme(theme) ? themeModes(theme) : undefined;
const result: Appearance = { theme, mode: selectedCustom ? selectedCustom.mode : builtinModes?.length === 1 ? builtinModes[0] : value?.mode === 'light' ? 'light' : 'dark' };
if (value?.transparency && typeof value.transparency === 'object') {
const source = value.transparency as { enabled?: unknown; amount?: unknown };
result.transparency = { enabled: source.enabled !== false, amount: typeof source.amount === 'number' && Number.isFinite(source.amount) ? Math.max(0, Math.min(100, Math.round(source.amount))) : 18 };
@@ -51,62 +55,31 @@ export function readAppearance(): Appearance {
const value = readSection('appearance');
return normalizeAppearance(value && typeof value === 'object' && !Array.isArray(value) ? value : null);
}
const keys = ['bg', 'bg-elevated', 'bg-active', 'border', 'text-dim', 'text', 'text-strong', 'accent', 'selection'] as const;
const palettes = {
default: {
dark: ['#141414','#1c1c1c','#2a2a2a','#2e2e2e','#9a9a9a','#e6e6e6','#f3f3f3','#82aaff','#264f78'],
light: ['#f3f3f3','#ffffff','#e8e8e8','#d4d4d4','#626262','#1e1e1e','#111111','#315fb3','#add6ff'],
},
// Anthropic brand guidelines: https://github.com/anthropics/skills/blob/main/skills/brand-guidelines/SKILL.md
claude: {
dark: ['#141413','#20201e','#32322e','#5a5952','#b0aea5','#faf9f5','#faf9f5','#d97757','#674435'],
light: ['#faf9f5','#faf9f5','#e8e6dc','#b0aea5','#67665f','#141413','#141413','#d97757','#e8e6dc'],
},
// Palette from pm-image:7968b79c-9d80-40a5-9e9a-696c26aacfb9. Sakura supports light mode only.
sakura: {
light: ['#fefcfc','#fefcfc','#dbeacb','#f8dbe6','#687788','#513346','#321c2a','#98556c','#ffc9dc'],
},
};
function builtinPalette(theme: ThemeName) {
if (theme === 'sakura') return { light: palettes.sakura.light, dark: palettes.sakura.light };
const character = characterTheme(theme);
if (character) return { light: character.surfaces, dark: character.surfaces };
return palettes[theme === 'claude' ? 'claude' : 'default'];
/**
* Every color role and the font stacks of a theme. A custom theme uses its own mode, and gets missing roles from its base theme.
* `legacyMode` selects the palette of a schema 1 custom theme.
*/
export function resolveTheme(theme: ThemeName, mode: Mode, legacyMode: Mode = mode): { mode: Mode; colors: ResolvedColors; fonts: Required<ThemeFonts> } {
const custom = theme.startsWith('custom:') ? customThemes(legacyMode).find(item => `custom:${item.id}` === theme) : undefined;
if (custom) {
const base = builtinTheme(custom.base ?? DEFAULT_THEME.id)?.variants[custom.mode] ?? DEFAULT_THEME.variants[custom.mode];
return { mode: custom.mode, colors: resolveColors(custom.colors, custom.mode, base), fonts: { ...themeFonts(custom.base ?? DEFAULT_THEME.id), ...custom.fonts } };
}
const builtin = builtinTheme(theme);
if (builtin && !builtin.variants[mode]) mode = themeModes(theme)[0];
return { mode, colors: resolveColors(builtin?.variants[mode] ?? DEFAULT_THEME.variants[mode], mode), fonts: themeFonts(theme) };
}
export function customThemeMode(colors?: ThemeColors): 'light' | 'dark' {
const hex = colors?.bg?.slice(1) ?? '141414';
const full = hex.length <= 4 ? [...hex.slice(0, 3)].map(value => value + value).join('') : hex.slice(0, 6);
const rgb = [0, 2, 4].map(index => parseInt(full.slice(index, index + 2), 16) / 255)
.map(value => value <= .04045 ? value / 12.92 : ((value + .055) / 1.055) ** 2.4);
return rgb[0] * .2126 + rgb[1] * .7152 + rgb[2] * .0722 > .179 ? 'light' : 'dark';
}
export function exportAppearanceTheme(theme: ThemeName, mode: 'light' | 'dark' = 'dark'): CustomTheme {
/** A complete theme file of schema 3, with every role and font stack. */
export function exportAppearanceTheme(theme: ThemeName, mode: Mode = 'dark'): CustomTheme {
const custom = customThemes(mode).find(item => `custom:${item.id}` === theme);
if (custom) mode = customThemeMode(custom.colors);
mode = characterTheme(theme)?.mode ?? (theme === 'sakura' ? 'light' : mode);
const palette = builtinPalette(theme)[mode];
const colors: ThemeColors = Object.fromEntries(keys.map((key, index) => [key, palette[index]]));
colors['accent-2'] = characterTheme(theme)?.secondary ?? (theme === 'claude' ? '#6a9bcc' : theme === 'sakura' ? '#607fa9' : colors.accent);
const semantic = mode === 'light' ? ['#b42323', '#8a5700', '#806600', '#287b29', '#7740a5'] : ['#f44747', '#d68a00', '#cca700', '#89d185', '#c792ea'];
if (theme === 'claude') { semantic[3] = '#788c5d'; semantic[4] = '#6a9bcc'; }
if (theme === 'sakura') { semantic[3] = '#618c71'; semantic[4] = '#cb6b91'; }
(['error', 'warn-hot', 'warn', 'ok', 'special'] as const).forEach((key, index) => colors[key] = semantic[index]);
const syntax = theme === 'sakura' ? ['#cb6b91', '#98556c', '#618c71', '#69a2bd', '#607fa9', '#687788'] : [colors.special, colors.accent, colors.text, colors['accent-2'], colors['accent-2'], colors['text-dim']];
(['parameter', 'keyword', 'local', 'static', 'instance', 'global'] as const).forEach((key, index) => colors[`syntax-${key}`] = syntax[index]);
Object.assign(colors, { 'syntax-string': colors.ok, 'syntax-number': colors.special, 'syntax-comment': colors['text-dim'], 'syntax-type': colors['accent-2'], 'syntax-function': colors['accent-2'] }, characterSyntax(theme));
return { schema: 2, id: custom?.id ?? 'my-theme', name: custom?.name ?? 'My theme', colors: { ...colors, ...custom?.colors }, fonts: { ...themeFonts(theme), ...custom?.fonts } };
const resolved = resolveTheme(theme, mode);
return {
schema: 3, id: custom?.id ?? 'my-theme', name: custom?.name ?? 'My theme', mode: resolved.mode,
colors: Object.fromEntries(ROLES.map(role => [role, resolved.colors[role]])), fonts: resolved.fonts,
};
}
export function themeFonts(theme: ThemeName): Required<ThemeFonts> {
const ui = '"Segoe UI Variable Text", "Segoe UI", ui-sans-serif, system-ui, sans-serif';
const prose = '"Segoe UI Variable Display", "Segoe UI", "Helvetica Neue", ui-sans-serif, system-ui, sans-serif';
const mono = '"Cascadia Mono", "Cascadia Code", "JetBrains Mono", "Fira Code", Consolas, ui-monospace, monospace';
const fonts = { ui, prose, heading: prose, mono };
if (theme === 'claude') return { ...fonts, ui: '"Lora", Georgia, serif', prose: '"Lora", Georgia, serif', heading: '"Poppins", Arial, sans-serif' };
if (theme === 'harvest-moon') return { ...fonts, ui: 'Candara, "Trebuchet MS", "Segoe UI", sans-serif', prose: 'Constantia, Georgia, "Times New Roman", serif', heading: 'Constantia, Georgia, "Times New Roman", serif' };
if (theme === 'crimson-pilot') return { ...fonts, ui: 'Bahnschrift, "Trebuchet MS", Arial, sans-serif', prose: '"Segoe UI", "Helvetica Neue", Arial, sans-serif', heading: 'Bahnschrift, "Trebuchet MS", Arial, sans-serif' };
if (theme === 'silver-serpent') return { ...fonts, ui: 'Corbel, "Segoe UI", "Helvetica Neue", Arial, sans-serif', prose: '"Palatino Linotype", "Book Antiqua", Palatino, Georgia, serif', heading: '"Palatino Linotype", "Book Antiqua", Palatino, Georgia, serif' };
return fonts;
export function themeFonts(theme: string): Required<ThemeFonts> {
return { ...DEFAULT_FONTS, ...builtinTheme(theme)?.fonts };
}
export function applyTransparency(value: Appearance['transparency'], root: HTMLElement) {
const supplied = value?.amount ?? 18;
@@ -168,8 +141,7 @@ function applyBackgroundImage(root: HTMLElement, image?: string) {
export function applyAppearance(value: Appearance, root = document.documentElement) {
const normalized = normalizeAppearance(value);
const { theme, newTabBackground } = normalized;
const custom = theme.startsWith('custom:') ? customThemes(normalized.mode).find(item => item.id === theme.slice(7)) : undefined;
const mode = custom ? customThemeMode(custom.colors) : normalized.mode;
const { mode, colors, fonts } = resolveTheme(theme, normalized.mode);
applyTransparency(normalized.transparency, root);
root.style.setProperty('--rs-new-tab-bg', 'var(--rs-bg)');
const overlay = newTabBackground?.overlay ?? 0;
@@ -182,33 +154,10 @@ export function applyAppearance(value: Appearance, root = document.documentEleme
root.dataset.theme = mode;
root.dataset.palette = theme;
root.style.colorScheme = mode;
const fonts = { ...themeFonts(theme), ...custom?.fonts };
FONT_ROLES.forEach(role => root.style.setProperty(`--rs-font-${role}`, fonts[role]));
const palette = builtinPalette(theme)[mode];
keys.forEach((key, index) => root.style.setProperty(`--rs-${key}`, palette[index]));
root.style.setProperty('--rs-accent-2', characterTheme(theme)?.secondary ?? (theme === 'claude' ? '#6a9bcc' : theme === 'sakura' ? '#607fa9' : 'var(--rs-accent)'));
root.style.setProperty('--rs-accent-dim', 'color-mix(in srgb, var(--rs-accent) 80%, var(--rs-bg))');
root.style.setProperty('--rs-accent-deep', 'color-mix(in srgb, var(--rs-accent) 60%, var(--rs-bg))');
const semantic = mode === 'light' ? ['#b42323', '#8a5700', '#806600', '#287b29', '#7740a5']
: ['#f44747', '#d68a00', '#cca700', '#89d185', '#c792ea'];
if (theme === 'claude') { semantic[3] = '#788c5d'; semantic[4] = '#6a9bcc'; }
if (theme === 'sakura') { semantic[3] = '#618c71'; semantic[4] = '#cb6b91'; }
['error', 'warn-hot', 'warn', 'ok', 'special'].forEach((key, index) => root.style.setProperty(`--rs-${key}`, semantic[index]));
SYNTAX_ROLES.forEach(role => root.style.removeProperty(`--rs-syntax-${role}`));
const syntax = theme === 'sakura'
? ['#cb6b91', '#98556c', '#618c71', '#69a2bd', '#607fa9', '#687788']
: ['var(--rs-special)', 'var(--rs-accent)', 'var(--rs-text)', 'var(--rs-accent-2)', 'var(--rs-accent-2)', 'var(--rs-text-dim)'];
['parameter', 'keyword', 'local', 'static', 'instance', 'global'].forEach((key, index) => root.style.setProperty(`--rs-syntax-${key}`, syntax[index]));
for (const [key, color] of Object.entries(characterSyntax(theme))) root.style.setProperty(`--rs-${key}`, color);
root.style.setProperty('--rs-danger', 'var(--rs-error)');
if (custom) for (const [key, color] of Object.entries(custom.colors)) root.style.setProperty(`--rs-${key}`, color);
// Keep the theme hue while exposing the background beneath selected text.
const selection = root.style.getPropertyValue('--rs-selection').trim().slice(1);
const fullSelection = selection.length <= 4 ? [...selection].map(part => part + part).join('') : selection;
if (/^[0-9a-f]{6}([0-9a-f]{2})?$/i.test(fullSelection)) {
const alpha = Math.min(166, fullSelection.length === 8 ? parseInt(fullSelection.slice(6), 16) : 255);
root.style.setProperty('--rs-selection', `#${fullSelection.slice(0, 6)}${alpha.toString(16).padStart(2, '0')}`);
}
// 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]);
window.dispatchEvent(new CustomEvent('runestone-theme-changed'));
}
/** Save and apply an appearance. Throws at once if browser storage refuses it. The promise reports a failed save. */
+1 -1
View File
@@ -40,7 +40,7 @@ button:disabled {
}
:focus-visible {
outline: 1px solid var(--rs-accent);
outline: 1px solid var(--rs-focus);
outline-offset: -1px;
}
-36
View File
@@ -1,36 +0,0 @@
import type { ThemeColors } from './customThemes.ts';
export const SYNTAX_ROLES = ['parameter', 'keyword', 'local', 'static', 'instance', 'global', 'string', 'number', 'comment', 'type', 'function'] as const;
type CharacterTheme = { mode: 'light' | 'dark'; surfaces: string[]; syntax: string[]; secondary: string };
export const CHARACTER_THEMES = {
'harvest-moon': {
mode: 'dark',
// Current Holo fan art: copper hair, brown tail, cream fur, and red eyes/apple.
// Amber carries active and selected states. Green scenery is outside this palette.
surfaces: ['#251b17', '#382820', '#40291c', '#ae744a', '#d3aa8b', '#eee3d1', '#fff4df', '#ffb52e', '#482714'],
secondary: '#ff6740',
syntax: ['#ffcc66', '#ff6740', '#eee3d1', '#ffe7b3', '#e5ae7e', '#ff8d55', '#ffc45b', '#ffffff', '#d3aa8b', '#ffe19a', '#ffb52e'],
},
'crimson-pilot': {
mode: 'dark',
surfaces: ['#210b10', '#341018', '#461620', '#d93840', '#e0b48e', '#f4ece1', '#ffffff', '#ff5b50', '#122b45'],
secondary: '#ff9b18',
syntax: ['#ffad32', '#ff5b50', '#f4ece1', '#b6dfff', '#efb278', '#83dc52', '#ffe066', '#ff8a3d', '#e0b48e', '#64c9ff', '#559fff'],
},
'silver-serpent': {
mode: 'dark',
surfaces: ['#151c1b', '#1d3029', '#223a32', '#528f74', '#bec8ce', '#e3e7eb', '#fff5d5', '#36e395', '#13533a'],
secondary: '#c5d5e2',
syntax: ['#f5d58c', '#36e395', '#e3e7eb', '#b8cbdd', '#f4c6ae', '#edc45f', '#a7e7c4', '#ffb79b', '#bec8ce', '#ffffff', '#61dfbb'],
},
} satisfies Record<string, CharacterTheme>;
export function characterTheme(theme: string): CharacterTheme | undefined {
return CHARACTER_THEMES[theme as keyof typeof CHARACTER_THEMES];
}
export function characterSyntax(theme: string): ThemeColors {
const palette = characterTheme(theme);
return palette ? Object.fromEntries(SYNTAX_ROLES.map((role, index) => [`syntax-${role}`, palette.syntax[index]])) : {};
}
+92
View File
@@ -0,0 +1,92 @@
// Color arithmetic for theme roles: hex parsing, sRGB mixing, WCAG contrast, and OKLab distance.
/** Red, green, and blue from 0 to 255, and alpha from 0 to 1. */
export type Rgba = [number, number, number, number];
const HEX = /^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
export function isHex(value: unknown): value is string {
return typeof value === 'string' && HEX.test(value);
}
export function parseHex(color: string): Rgba {
if (!isHex(color)) throw new Error(`Not a hexadecimal color: ${color}`);
let digits = color.slice(1);
if (digits.length <= 4) digits = [...digits].map(digit => digit + digit).join('');
const values = digits.match(/../g)!.map(pair => parseInt(pair, 16));
return [values[0], values[1], values[2], values.length === 4 ? values[3] / 255 : 1];
}
/** Six hex digits for an opaque color, eight for a transparent one. */
export function formatHex([red, green, blue, alpha]: Rgba): string {
const channel = (value: number) => Math.max(0, Math.min(255, Math.round(value))).toString(16).padStart(2, '0');
return `#${channel(red)}${channel(green)}${channel(blue)}${alpha >= 1 ? '' : channel(alpha * 255)}`;
}
/** The long form of a hex color, in lowercase. */
export function normalizeHex(color: string): string {
return formatHex(parseHex(color));
}
/** Set the alpha of a color, from 0 to 1. */
export function withAlpha(color: string, alpha: number): string {
const [red, green, blue] = parseHex(color);
return formatHex([red, green, blue, alpha]);
}
/** CSS `color-mix(in srgb, first amount, second)`, with premultiplied alpha. */
export function mix(first: string, second: string, amount: number): string {
const a = parseHex(first), b = parseHex(second);
const alpha = a[3] * amount + b[3] * (1 - amount);
if (alpha === 0) return formatHex([0, 0, 0, 0]);
const channel = (index: number) => (a[index] * a[3] * amount + b[index] * b[3] * (1 - amount)) / alpha;
return formatHex([channel(0), channel(1), channel(2), alpha]);
}
/** The opaque color that a transparent foreground shows over an opaque background. */
export function composite(foreground: string, background: string): string {
const top = parseHex(foreground), bottom = parseHex(background);
const channel = (index: number) => top[index] * top[3] + bottom[index] * (1 - top[3]);
return formatHex([channel(0), channel(1), channel(2), 1]);
}
function linear(value: number) {
const channel = value / 255;
return channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4;
}
/** WCAG relative luminance of an opaque color. */
export function luminance(color: string): number {
const [red, green, blue] = parseHex(color);
return linear(red) * 0.2126 + linear(green) * 0.7152 + linear(blue) * 0.0722;
}
/** WCAG contrast ratio of two opaque colors, from 1 to 21. */
export function contrast(first: string, second: string): number {
const [high, low] = [luminance(first), luminance(second)].sort((a, b) => b - a);
return (high + 0.05) / (low + 0.05);
}
/** OKLab lightness and the a and b axes of an opaque color. */
export function oklab(color: string): [number, number, number] {
const [red, green, blue] = parseHex(color).slice(0, 3).map(linear);
const l = Math.cbrt(0.4122214708 * red + 0.5363325363 * green + 0.0514459929 * blue);
const m = Math.cbrt(0.2119034982 * red + 0.6806995451 * green + 0.1073969566 * blue);
const s = Math.cbrt(0.0883024619 * red + 0.2817188376 * green + 0.6299787005 * blue);
return [
0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s,
1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s,
0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s,
];
}
/** Euclidean distance in OKLab. About 0.02 is the smallest visible step. */
export function distance(first: string, second: string): number {
const a = oklab(first), b = oklab(second);
return Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
}
/** Black or white, whichever has more contrast on the color. */
export function readableOn(color: string): string {
return contrast('#000000', color) >= contrast('#ffffff', color) ? '#000000' : '#ffffff';
}
+88
View File
@@ -0,0 +1,88 @@
// Readability rules for theme roles. The unit tests and the theme editor use the same rules.
// docs/ui-color.md lists the thresholds.
import { composite, contrast, distance, formatHex, luminance, mix, parseHex } from './color.ts';
import { ANSI_COLORS, SYNTAX_ROLES, type Mode, type ResolvedColors, type Role } from './roles.ts';
/** Text selection keeps at most this alpha, so the background shows through (UI-029). */
export const SELECTION_ALPHA = 166 / 255;
/** The colors that the app applies. Text selection is at most 65% opaque. */
export function appliedColors(colors: ResolvedColors): ResolvedColors {
const [red, green, blue, alpha] = parseHex(colors.selection);
return { ...colors, selection: formatHex([red, green, blue, Math.min(SELECTION_ALPHA, alpha)]) };
}
/** Opaque surfaces as the app draws them. Each takes the applied colors of a theme. */
export const SURFACES = {
bg: colors => opaque(colors.bg),
'bg-elevated': colors => composite(colors['bg-elevated'], opaque(colors.bg)),
'bg-active': colors => composite(colors['bg-active'], opaque(colors.bg)),
selection: colors => composite(colors.selection, opaque(colors.bg)),
'line-highlight': colors => composite(colors['line-highlight'], opaque(colors.bg)),
highlight: colors => composite(mix(colors.highlight, '#0000', 0.3), opaque(colors.bg)),
'item-selection': colors => composite(colors['item-selection-bg'], composite(colors['bg-elevated'], opaque(colors.bg))),
accent: colors => composite(colors.accent, opaque(colors.bg)),
} satisfies Record<string, (colors: ResolvedColors) => string>;
export type Surface = keyof typeof SURFACES;
function opaque(color: string) { return composite(color, '#000000'); }
const SYNTAX = SYNTAX_ROLES.map(role => `syntax-${role}` as const);
// Black and white are exempt: one of them always matches the terminal background.
const ANSI = ANSI_COLORS.filter(color => color !== 'black' && color !== 'white').flatMap(color => [`ansi-${color}`, `ansi-bright-${color}`] as const);
export type ContrastRule = { id: string; kind: 'contrast'; foregrounds: readonly Role[]; surfaces: readonly Surface[]; min: number };
export type DistinctRule = { id: string; kind: 'distinct'; pairs: readonly (readonly [Role, Role])[]; min: number };
export type VarietyRule = { id: string; kind: 'variety'; roles: readonly Role[]; min: number };
export type LightestRule = { id: string; kind: 'lightest'; mode: Mode; role: Role; others: readonly Role[] };
export type Rule = ContrastRule | DistinctRule | VarietyRule | LightestRule;
/** OKLab distance that keeps two status or identity colors apart. */
export const DISTINCT_DISTANCE = 0.1;
export const RULES: readonly Rule[] = [
{ id: 'text', kind: 'contrast', foregrounds: ['text', 'text-dim', 'text-strong'], surfaces: ['bg', 'bg-elevated', 'bg-active', 'selection'], min: 4.5 },
{ id: 'accent-text', kind: 'contrast', foregrounds: ['accent', 'link'], surfaces: ['bg', 'bg-elevated', 'bg-active'], min: 4.5 },
{ id: 'status-text', kind: 'contrast', foregrounds: ['error', 'warn', 'ok'], surfaces: ['bg', 'bg-elevated'], min: 4.5 },
{ id: 'syntax', kind: 'contrast', foregrounds: SYNTAX, surfaces: ['bg', 'bg-active', 'line-highlight'], min: 4.5 },
{ id: 'ansi', kind: 'contrast', foregrounds: ANSI, surfaces: ['bg'], min: 4.5 },
{ id: 'focus', kind: 'contrast', foregrounds: ['focus'], surfaces: ['bg', 'bg-elevated', 'bg-active'], min: 3 },
{ id: 'on-accent', kind: 'contrast', foregrounds: ['on-accent'], surfaces: ['accent'], min: 4.5 },
{ id: 'highlight', kind: 'contrast', foregrounds: ['text'], surfaces: ['highlight'], min: 4.5 },
{ id: 'selection-outline', kind: 'contrast', foregrounds: ['accent'], surfaces: ['item-selection'], min: 3 },
{ id: 'status-distinct', kind: 'distinct', pairs: [['accent', 'error'], ['accent', 'warn'], ['accent', 'ok'], ['error', 'warn'], ['warn', 'ok'], ['error', 'ok']], min: DISTINCT_DISTANCE },
{ id: 'syntax-variety', kind: 'variety', roles: SYNTAX, min: 7 },
{ id: 'light-page', kind: 'lightest', mode: 'light', role: 'bg', others: ['bg-elevated', 'bg-active'] },
];
export type Finding = { rule: string; subject: string; value: number; min: number; pass: boolean };
/** Every check of every rule for one theme. `colors` are the resolved colors, before the selection cap. */
export function checkTheme(resolved: ResolvedColors, mode: Mode, rules: readonly Rule[] = RULES): Finding[] {
const colors = appliedColors(resolved);
const findings: Finding[] = [];
const surfaceColors = Object.fromEntries(Object.entries(SURFACES).map(([name, color]) => [name, color(colors)])) as Record<Surface, string>;
for (const rule of rules) {
if (rule.kind === 'contrast') {
for (const foreground of rule.foregrounds) for (const surface of rule.surfaces) {
const value = contrast(composite(colors[foreground], surfaceColors[surface]), surfaceColors[surface]);
findings.push({ rule: rule.id, subject: `${foreground} on ${surface}`, value, min: rule.min, pass: value >= rule.min });
}
} else if (rule.kind === 'distinct') {
for (const [first, second] of rule.pairs) {
const value = distance(composite(colors[first], surfaceColors.bg), composite(colors[second], surfaceColors.bg));
findings.push({ rule: rule.id, subject: `${first} and ${second}`, value, min: rule.min, pass: value >= rule.min });
}
} else if (rule.kind === 'variety') {
const value = new Set(rule.roles.map(role => colors[role].toLowerCase())).size;
findings.push({ rule: rule.id, subject: 'distinct colors', value, min: rule.min, pass: value >= rule.min });
} else if (rule.mode === mode) {
const page = luminance(surfaceColors.bg);
for (const other of rule.others) {
const value = page - luminance(composite(colors[other], surfaceColors.bg));
findings.push({ rule: rule.id, subject: `${rule.role} lighter than ${other}`, value, min: 0, pass: value > 0 });
}
}
}
return findings;
}
+76 -33
View File
@@ -1,49 +1,92 @@
import { tr } from "../i18n/index.ts";
import { readSection, writeSection } from '../settings/store.ts';
import { isHex, luminance } from './color.ts';
import { ROLES, type Mode, type Role, type ThemeColors } from './roles.ts';
import { builtinTheme } from './themes/index.ts';
export type { ThemeColors } from './roles.ts';
/** The old localStorage key. The customThemes section of the settings file replaces it. */
export const CUSTOM_THEMES_KEY = "runestone.custom-themes";
export const COLOR_TOKENS = ["bg", "bg-elevated", "bg-active", "border", "text", "text-dim", "text-strong", "accent", "accent-2", "selection", "error", "warn", "warn-hot", "ok", "special", "syntax-parameter", "syntax-keyword", "syntax-local", "syntax-static", "syntax-instance", "syntax-global", "syntax-string", "syntax-number", "syntax-comment", "syntax-type", "syntax-function"] as const;
export type ThemeColors = Partial<Record<typeof COLOR_TOKENS[number], string>>;
/** The color keys of schema 1 and 2 files. */
export const LEGACY_COLOR_TOKENS = ["bg", "bg-elevated", "bg-active", "border", "text", "text-dim", "text-strong", "accent", "accent-2", "selection", "error", "warn", "warn-hot", "ok", "special", "syntax-parameter", "syntax-keyword", "syntax-local", "syntax-static", "syntax-instance", "syntax-global", "syntax-string", "syntax-number", "syntax-comment", "syntax-type", "syntax-function"] as const;
// Schema 3 renamed these syntax roles. Source never used the parameter and static colors, so they have no new role.
const LEGACY_SYNTAX: Readonly<Record<string, readonly Role[]>> = {
"syntax-local": ["syntax-variable"], "syntax-instance": ["syntax-property"], "syntax-global": ["syntax-constant", "syntax-punctuation"],
"syntax-parameter": [], "syntax-static": [],
};
export const FONT_ROLES = ['ui', 'prose', 'heading', 'mono'] as const;
export type ThemeFonts = Partial<Record<typeof FONT_ROLES[number], string>>;
export type CustomTheme = { schema: 2; id: string; name: string; colors: ThemeColors; fonts?: ThemeFonts };
/**
* A theme file and a saved custom theme. `base` is a built-in theme with a palette in `mode`.
* Colors that the file does not give come from the base theme, by default RuneStone.
*/
export type CustomTheme = { schema: 3; id: string; name: string; mode: Mode; base?: string; colors: ThemeColors; fonts?: ThemeFonts };
export type LegacyCustomTheme = { schema: 1; id: string; name: string; light: ThemeColors; dark: ThemeColors };
export function parseCustomTheme(input: unknown, legacyMode: "light" | "dark" = "dark"): CustomTheme {
if (!input || typeof input !== "object") throw new Error(tr("Choose a RuneStone theme JSON file."));
const value = input as Record<string, unknown>;
if ((value.schema !== 1 && value.schema !== 2) || typeof value.id !== "string" || !/^[a-z][a-z0-9-]{0,63}$/.test(value.id)
|| typeof value.name !== "string" || !value.name.trim() || value.name.length > 80) throw new Error(tr("The theme needs schema 2, an ID, and a name."));
const colors = (mode: string): ThemeColors => {
const source = value[mode];
if (!source || typeof source !== "object" || Array.isArray(source)) throw new Error(tr("The theme needs {mode} colors.", { mode }));
const result: ThemeColors = {};
for (const [key, color] of Object.entries(source)) {
if (!(COLOR_TOKENS as readonly string[]).includes(key)) throw new Error(tr("Unknown theme color: {key}", { key }));
if (typeof color !== "string" || !/^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(color)) throw new Error(tr("Use a hexadecimal color for {key}.", { key }));
result[key as keyof ThemeColors] = color;
}
if (!result.bg || !result.text || !result.accent) throw new Error(tr("The {mode} palette needs bg, text, and accent.", { mode }));
return result;
};
if (value.schema === 1) { colors("light"); colors("dark"); }
let fonts: ThemeFonts | undefined;
if (value.fonts !== undefined) {
if (!value.fonts || typeof value.fonts !== 'object' || Array.isArray(value.fonts)) throw new Error(tr("Use an object for theme fonts."));
fonts = {};
for (const [role, stack] of Object.entries(value.fonts)) {
if (!(FONT_ROLES as readonly string[]).includes(role)) throw new Error(tr("Unknown theme font: {role}", { role }));
if (typeof stack !== 'string' || stack.length > 512 || !/^[\p{L}\p{N} _,'"-]+$/u.test(stack) || !stack.trim()
|| stack.split(',').some(family => !/^(?:"[^"\n]+"|'[^'\n]+'|[\p{L}\p{N}_ -]+)$/u.test(family.trim()))) throw new Error(tr("Use a font family stack for {role}.", { role }));
fonts[role as keyof ThemeFonts] = stack.trim();
}
/** The mode of a schema 1 or 2 palette, from the lightness of its background. */
function paletteMode(colors: ThemeColors): Mode {
return luminance(colors.bg ?? '#141414') > .179 ? 'light' : 'dark';
}
function parseColors(source: unknown, allowed: readonly string[]): ThemeColors {
if (!source || typeof source !== "object" || Array.isArray(source)) throw new Error(tr("Use an object for theme colors."));
const result: ThemeColors = {};
for (const [key, color] of Object.entries(source)) {
if (!allowed.includes(key)) throw new Error(tr("Unknown theme color: {key}", { key }));
if (!isHex(color)) throw new Error(tr("Use a hexadecimal color for {key}.", { key }));
result[key as Role] = color;
}
return { schema: 2, id: value.id, name: value.name.trim(), colors: colors(value.schema === 1 ? legacyMode : "colors"), ...(fonts ? { fonts } : {}) };
return result;
}
/** A schema 1 or 2 palette with the schema 3 role names. */
function legacyColors(source: unknown, mode: string): ThemeColors {
if (!source || typeof source !== "object" || Array.isArray(source)) throw new Error(tr("The theme needs {mode} colors.", { mode }));
const colors = parseColors(source, LEGACY_COLOR_TOKENS);
if (!colors.bg || !colors.text || !colors.accent) throw new Error(tr("The {mode} palette needs bg, text, and accent.", { mode }));
const result: ThemeColors = {};
for (const [key, color] of Object.entries(colors)) {
for (const role of Object.hasOwn(LEGACY_SYNTAX, key) ? LEGACY_SYNTAX[key] : [key as Role]) result[role] = color;
}
return result;
}
function parseFonts(source: unknown): ThemeFonts | undefined {
if (source === undefined) return undefined;
if (!source || typeof source !== 'object' || Array.isArray(source)) throw new Error(tr("Use an object for theme fonts."));
const fonts: ThemeFonts = {};
for (const [role, stack] of Object.entries(source)) {
if (!(FONT_ROLES as readonly string[]).includes(role)) throw new Error(tr("Unknown theme font: {role}", { role }));
if (typeof stack !== 'string' || stack.length > 512 || !/^[\p{L}\p{N} _,'"-]+$/u.test(stack) || !stack.trim()
|| stack.split(',').some(family => !/^(?:"[^"\n]+"|'[^'\n]+'|[\p{L}\p{N}_ -]+)$/u.test(family.trim()))) throw new Error(tr("Use a font family stack for {role}.", { role }));
fonts[role as keyof ThemeFonts] = stack.trim();
}
return fonts;
}
/** A theme file of schema 1, 2, or 3, as schema 3. A schema 1 file gives the palette of `legacyMode`. */
export function parseCustomTheme(input: unknown, legacyMode: Mode = "dark"): CustomTheme {
if (!input || typeof input !== "object" || Array.isArray(input)) throw new Error(tr("Choose a RuneStone theme JSON file."));
const value = input as Record<string, unknown>;
if ((value.schema !== 1 && value.schema !== 2 && value.schema !== 3) || typeof value.id !== "string" || !/^[a-z][a-z0-9-]{0,63}$/.test(value.id)
|| typeof value.name !== "string" || !value.name.trim() || value.name.length > 80) throw new Error(tr("The theme needs a schema number, an ID, and a name."));
const fonts = parseFonts(value.fonts);
const common = { schema: 3 as const, id: value.id, name: value.name.trim(), ...(fonts ? { fonts } : {}) };
if (value.schema === 3) {
if (value.mode !== 'light' && value.mode !== 'dark') throw new Error(tr("Use light or dark for the theme mode."));
const mode: Mode = value.mode;
const base = value.base === undefined ? undefined : typeof value.base === 'string' ? builtinTheme(value.base) : undefined;
if (value.base !== undefined && !base?.variants[mode]) throw new Error(tr("Use a built-in theme with a {mode} palette as the base.", { mode }));
return { ...common, mode, ...(base ? { base: base.id } : {}), colors: parseColors(value.colors, ROLES) };
}
if (value.schema === 1) { legacyColors(value.light, "light"); legacyColors(value.dark, "dark"); }
const colors = value.schema === 1 ? legacyColors(value[legacyMode], legacyMode) : legacyColors(value.colors, "colors");
return { ...common, mode: paletteMode(colors), colors };
}
/** The saved custom themes. Version 1 themes use the palette of `legacyMode`, by default the saved appearance mode. */
export function customThemes(legacyMode?: "light" | "dark"): CustomTheme[] {
export function customThemes(legacyMode?: Mode): CustomTheme[] {
try {
const stored = readSection('customThemes');
if (!Array.isArray(stored)) return [];
+87
View File
@@ -0,0 +1,87 @@
// Theme roles: the named colors of a theme. Each role is the CSS token `--rs-<role>`.
// A theme gives the base roles. The other roles come from the base roles through one rule for all themes.
// docs/ui-color.md describes each role and its contrast requirement.
import { mix, readableOn } from './color.ts';
export type Mode = 'light' | 'dark';
/** Code colors in Source. src/lib/editor/sourceView.ts maps the syntax tags to these roles. */
export const SYNTAX_ROLES = ['keyword', 'string', 'number', 'comment', 'type', 'function', 'property', 'variable', 'constant', 'punctuation', 'heading'] as const;
/** The eight terminal colors. Each has a bright variant, for example `ansi-bright-red`. */
export const ANSI_COLORS = ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'] as const;
/** Every role, in the order of theme files and of resolution. A derived role comes after the roles that it uses. */
export const ROLES = [
'bg', 'bg-elevated', 'bg-active', 'border', 'text', 'text-dim', 'text-strong',
'accent', 'accent-2', 'accent-dim', 'accent-deep', 'link', 'focus', 'on-accent',
'selection', 'item-selection-bg', 'line-highlight', 'highlight', 'scrim',
'error', 'warn', 'warn-hot', 'ok', 'special',
'syntax-keyword', 'syntax-string', 'syntax-number', 'syntax-comment', 'syntax-type', 'syntax-function',
'syntax-property', 'syntax-variable', 'syntax-constant', 'syntax-punctuation', 'syntax-heading',
'ansi-black', 'ansi-red', 'ansi-green', 'ansi-yellow', 'ansi-blue', 'ansi-magenta', 'ansi-cyan', 'ansi-white',
'ansi-bright-black', 'ansi-bright-red', 'ansi-bright-green', 'ansi-bright-yellow',
'ansi-bright-blue', 'ansi-bright-magenta', 'ansi-bright-cyan', 'ansi-bright-white',
] as const;
export type Role = typeof ROLES[number];
export type ThemeColors = Partial<Record<Role, string>>;
export type ResolvedColors = Record<Role, string>;
/** The roles that every built-in theme gives. Other themes get the missing ones from their base theme. */
export const BASE_ROLES = ['bg', 'bg-elevated', 'bg-active', 'border', 'text', 'text-dim', 'text-strong', 'accent', 'selection', 'error', 'warn', 'warn-hot', 'ok', 'special'] as const satisfies readonly Role[];
type Derive = (colors: ResolvedColors, mode: Mode) => string;
const bright = (role: Role): Derive => colors => colors[role];
// Terminal red, green, and yellow follow the status colors. Blue, magenta, and cyan have their own defaults,
// because the accent and special colors of a theme can have any hue.
const DERIVED: Record<Exclude<Role, typeof BASE_ROLES[number]>, Derive> = {
'accent-2': colors => colors.accent,
'accent-dim': colors => mix(colors.accent, colors.bg, 0.8),
'accent-deep': colors => mix(colors.accent, colors.bg, 0.6),
link: colors => colors.accent,
focus: colors => colors.accent,
'on-accent': colors => readableOn(colors.accent),
'item-selection-bg': colors => mix(colors.accent, '#0000', 0.2),
'line-highlight': (_, mode) => mode === 'light' ? '#0000000d' : '#ffffff0d',
highlight: () => '#edc65b',
scrim: () => '#00000088',
'syntax-keyword': colors => colors.accent,
'syntax-string': colors => colors.ok,
'syntax-number': colors => colors.special,
'syntax-comment': colors => colors['text-dim'],
'syntax-type': colors => colors['accent-2'],
'syntax-function': colors => colors['accent-2'],
'syntax-property': colors => colors['accent-2'],
'syntax-variable': colors => colors.text,
'syntax-constant': colors => colors['text-dim'],
'syntax-punctuation': colors => colors['text-dim'],
'syntax-heading': colors => colors['syntax-keyword'],
'ansi-black': colors => colors['text-dim'],
'ansi-red': colors => colors.error,
'ansi-green': colors => colors.ok,
'ansi-yellow': colors => colors.warn,
'ansi-blue': (_, mode) => mode === 'light' ? '#0451a5' : '#3b8eea',
'ansi-magenta': (_, mode) => mode === 'light' ? '#a626a4' : '#d670d6',
'ansi-cyan': (_, mode) => mode === 'light' ? '#05748a' : '#29b8db',
'ansi-white': colors => colors.text,
'ansi-bright-black': colors => colors['text-dim'],
'ansi-bright-red': bright('ansi-red'),
'ansi-bright-green': bright('ansi-green'),
'ansi-bright-yellow': bright('ansi-yellow'),
'ansi-bright-blue': bright('ansi-blue'),
'ansi-bright-magenta': bright('ansi-magenta'),
'ansi-bright-cyan': bright('ansi-cyan'),
'ansi-bright-white': colors => colors['text-strong'],
};
/** Every role of a theme. `colors` wins over `base`, and the derivation rules fill the rest. */
export function resolveColors(colors: ThemeColors, mode: Mode, base: ThemeColors = {}): ResolvedColors {
const result = { ...base, ...colors } as ResolvedColors;
for (const role of ROLES) {
if (result[role]) continue;
const derive = DERIVED[role as keyof typeof DERIVED];
if (!derive) throw new Error(`The theme has no ${role} color.`);
result[role] = derive(result, mode);
}
return result;
}
+22
View File
@@ -0,0 +1,22 @@
import type { BuiltinTheme } from './index.ts';
// Anthropic brand guidelines: https://github.com/anthropics/skills/blob/main/skills/brand-guidelines/SKILL.md
export const claude = {
id: 'claude' as const,
name: 'Claude',
fonts: { ui: '"Lora", Georgia, serif', prose: '"Lora", Georgia, serif', heading: '"Poppins", Arial, sans-serif' },
variants: {
dark: {
bg: '#141413', 'bg-elevated': '#20201e', 'bg-active': '#32322e', border: '#5a5952',
text: '#faf9f5', 'text-dim': '#b0aea5', 'text-strong': '#faf9f5',
accent: '#d97757', 'accent-2': '#6a9bcc', selection: '#674435',
error: '#f44747', 'warn-hot': '#d68a00', warn: '#cca700', ok: '#788c5d', special: '#6a9bcc',
},
light: {
bg: '#faf9f5', 'bg-elevated': '#faf9f5', 'bg-active': '#e8e6dc', border: '#b0aea5',
text: '#141413', 'text-dim': '#67665f', 'text-strong': '#141413',
accent: '#d97757', 'accent-2': '#6a9bcc', selection: '#e8e6dc',
error: '#b42323', 'warn-hot': '#8a5700', warn: '#806600', ok: '#788c5d', special: '#6a9bcc',
},
},
} satisfies BuiltinTheme;
+19
View File
@@ -0,0 +1,19 @@
import type { BuiltinTheme } from './index.ts';
// Asuka Langley Soryu (Neon Genesis Evangelion).
export const crimsonPilot = {
id: 'crimson-pilot' as const,
name: 'Crimson Pilot',
legacyIds: ['asuka'],
fonts: { ui: 'Bahnschrift, "Trebuchet MS", Arial, sans-serif', prose: '"Segoe UI", "Helvetica Neue", Arial, sans-serif', heading: 'Bahnschrift, "Trebuchet MS", Arial, sans-serif' },
variants: {
dark: {
bg: '#210b10', 'bg-elevated': '#341018', 'bg-active': '#461620', border: '#d93840',
text: '#f4ece1', 'text-dim': '#e0b48e', 'text-strong': '#ffffff',
accent: '#ff5b50', 'accent-2': '#ff9b18', selection: '#122b45', 'item-selection-bg': '#122b45a6',
error: '#f44747', 'warn-hot': '#d68a00', warn: '#cca700', ok: '#89d185', special: '#c792ea',
'syntax-keyword': '#ff5b50', 'syntax-variable': '#f4ece1', 'syntax-property': '#efb278', 'syntax-constant': '#83dc52', 'syntax-punctuation': '#83dc52', 'syntax-string': '#ffe066', 'syntax-number': '#ff8a3d',
'syntax-comment': '#e0b48e', 'syntax-type': '#64c9ff', 'syntax-function': '#559fff',
},
},
} satisfies BuiltinTheme;
+20
View File
@@ -0,0 +1,20 @@
import type { BuiltinTheme } from './index.ts';
// Holo (Spice and Wolf), from the current fan art: copper hair, brown tail, cream fur, and red eyes and apple.
// Amber carries active and selected states. Green scenery is outside this palette.
export const harvestMoon = {
id: 'harvest-moon' as const,
name: 'Harvest Moon',
legacyIds: ['holo'],
fonts: { ui: 'Candara, "Trebuchet MS", "Segoe UI", sans-serif', prose: 'Constantia, Georgia, "Times New Roman", serif', heading: 'Constantia, Georgia, "Times New Roman", serif' },
variants: {
dark: {
bg: '#251b17', 'bg-elevated': '#382820', 'bg-active': '#40291c', border: '#ae744a',
text: '#eee3d1', 'text-dim': '#d3aa8b', 'text-strong': '#fff4df',
accent: '#ffb52e', 'accent-2': '#ff6740', selection: '#482714', 'item-selection-bg': '#482714a6',
error: '#f44747', 'warn-hot': '#d68a00', warn: '#cca700', ok: '#89d185', special: '#c792ea',
'syntax-keyword': '#ff6740', 'syntax-variable': '#eee3d1', 'syntax-property': '#e5ae7e', 'syntax-constant': '#ff8d55', 'syntax-punctuation': '#ff8d55', 'syntax-string': '#ffc45b', 'syntax-number': '#ffffff',
'syntax-comment': '#d3aa8b', 'syntax-type': '#ffe19a', 'syntax-function': '#ffb52e',
},
},
} satisfies BuiltinTheme;
+45
View File
@@ -0,0 +1,45 @@
// The built-in themes. Each theme is data: no code outside this folder may name a theme ID.
import type { Mode, ThemeColors } from '../roles.ts';
import type { ThemeFonts } from '../customThemes.ts';
import { runestone } from './runestone.ts';
import { claude } from './claude.ts';
import { sakura } from './sakura.ts';
import { harvestMoon } from './harvestMoon.ts';
import { crimsonPilot } from './crimsonPilot.ts';
import { silverSerpent } from './silverSerpent.ts';
export type BuiltinTheme = {
id: string;
name: string;
/** Earlier IDs of this theme. A saved choice of an earlier ID selects this theme. */
legacyIds?: readonly string[];
/** A catalog key that the Appearance settings show while the theme is selected. */
notice?: string;
/** Font stacks that differ from the RuneStone stacks. */
fonts?: ThemeFonts;
/** One complete palette for each mode that the theme offers. */
variants: Partial<Record<Mode, ThemeColors>>;
};
export const DEFAULT_FONTS = {
ui: '"Segoe UI Variable Text", "Segoe UI", ui-sans-serif, system-ui, sans-serif',
prose: '"Segoe UI Variable Display", "Segoe UI", "Helvetica Neue", ui-sans-serif, system-ui, sans-serif',
heading: '"Segoe UI Variable Display", "Segoe UI", "Helvetica Neue", ui-sans-serif, system-ui, sans-serif',
mono: '"Cascadia Mono", "Cascadia Code", "JetBrains Mono", "Fira Code", Consolas, ui-monospace, monospace',
} as const satisfies Required<ThemeFonts>;
/** The theme that a removed theme ID returns to, and the base of custom themes. */
export const DEFAULT_THEME = runestone;
export const BUILTIN_THEMES = [runestone, claude, sakura, harvestMoon, crimsonPilot, silverSerpent] as const;
export type BuiltinThemeId = typeof BUILTIN_THEMES[number]['id'];
/** The current ID for each earlier ID of a built-in theme. */
export const LEGACY_THEME_IDS: Readonly<Record<string, BuiltinThemeId>> = Object.fromEntries(
BUILTIN_THEMES.flatMap(theme => ('legacyIds' in theme ? theme.legacyIds : []).map(legacy => [legacy, theme.id])));
/** The built-in theme with this ID or earlier ID. */
export function builtinTheme(id: string): BuiltinTheme | undefined {
const current = Object.hasOwn(LEGACY_THEME_IDS, id) ? LEGACY_THEME_IDS[id] : id;
return BUILTIN_THEMES.find(theme => theme.id === current);
}
+20
View File
@@ -0,0 +1,20 @@
import type { BuiltinTheme } from './index.ts';
export const runestone = {
id: 'default' as const,
name: 'RuneStone',
variants: {
dark: {
bg: '#141414', 'bg-elevated': '#1c1c1c', 'bg-active': '#2a2a2a', border: '#2e2e2e',
text: '#e6e6e6', 'text-dim': '#9a9a9a', 'text-strong': '#f3f3f3',
accent: '#82aaff', selection: '#264f78',
error: '#f44747', 'warn-hot': '#d68a00', warn: '#cca700', ok: '#89d185', special: '#c792ea',
},
light: {
bg: '#f3f3f3', 'bg-elevated': '#ffffff', 'bg-active': '#e8e8e8', border: '#d4d4d4',
text: '#1e1e1e', 'text-dim': '#626262', 'text-strong': '#111111',
accent: '#315fb3', selection: '#add6ff',
error: '#b42323', 'warn-hot': '#8a5700', warn: '#806600', ok: '#287b29', special: '#7740a5',
},
},
} satisfies BuiltinTheme;
+19
View File
@@ -0,0 +1,19 @@
import { message } from '../../i18n/index.ts';
import type { BuiltinTheme } from './index.ts';
// Palette from pm-image:7968b79c-9d80-40a5-9e9a-696c26aacfb9.
export const sakura = {
id: 'sakura' as const,
name: 'Sakura',
notice: message('Sakura uses a light appearance.'),
variants: {
light: {
bg: '#fefcfc', 'bg-elevated': '#fefcfc', 'bg-active': '#dbeacb', border: '#f8dbe6',
text: '#513346', 'text-dim': '#687788', 'text-strong': '#321c2a',
accent: '#98556c', 'accent-2': '#607fa9', selection: '#ffc9dc', 'item-selection-bg': '#ffc9dca6',
error: '#b42323', 'warn-hot': '#8a5700', warn: '#806600', ok: '#618c71', special: '#cb6b91',
'syntax-keyword': '#98556c', 'syntax-variable': '#618c71',
'syntax-property': '#607fa9', 'syntax-constant': '#687788', 'syntax-punctuation': '#687788',
},
},
} satisfies BuiltinTheme;
+19
View File
@@ -0,0 +1,19 @@
import type { BuiltinTheme } from './index.ts';
// "Malfoid", a fan creation: Draco Malfoy written as a female character. The books win over fan art.
export const silverSerpent = {
id: 'silver-serpent' as const,
name: 'Silver Serpent',
legacyIds: ['malfoid'],
fonts: { ui: 'Corbel, "Segoe UI", "Helvetica Neue", Arial, sans-serif', prose: '"Palatino Linotype", "Book Antiqua", Palatino, Georgia, serif', heading: '"Palatino Linotype", "Book Antiqua", Palatino, Georgia, serif' },
variants: {
dark: {
bg: '#151c1b', 'bg-elevated': '#1d3029', 'bg-active': '#223a32', border: '#528f74',
text: '#e3e7eb', 'text-dim': '#bec8ce', 'text-strong': '#fff5d5',
accent: '#36e395', 'accent-2': '#c5d5e2', selection: '#13533a', 'item-selection-bg': '#13533aa6',
error: '#f44747', 'warn-hot': '#d68a00', warn: '#cca700', ok: '#89d185', special: '#c792ea',
'syntax-keyword': '#36e395', 'syntax-variable': '#e3e7eb', 'syntax-property': '#f4c6ae', 'syntax-constant': '#edc45f', 'syntax-punctuation': '#edc45f', 'syntax-string': '#a7e7c4', 'syntax-number': '#ffb79b',
'syntax-comment': '#bec8ce', 'syntax-type': '#ffffff', 'syntax-function': '#61dfbb',
},
},
} satisfies BuiltinTheme;
+9 -40
View File
@@ -1,3 +1,4 @@
/* Defaults until ThemeSync applies the theme. src/lib/theme/roles.ts lists the color roles that each theme sets. */
:root {
--rs-selection-text: var(--rs-text);
--rs-tooltip-padding: 6px 10px;
@@ -57,6 +58,11 @@
--rs-warn: #cca700;
--rs-ok: #89d185;
--rs-special: #c792ea;
--rs-link: var(--rs-accent);
--rs-focus: var(--rs-accent);
--rs-on-accent: #000000;
--rs-highlight: #edc65b;
--rs-scrim: #00000088;
--rs-font-ui: "Segoe UI Variable Text", "Segoe UI", ui-sans-serif, system-ui, sans-serif;
--rs-font-prose: "Segoe UI Variable Display", "Segoe UI", "Helvetica Neue", ui-sans-serif, system-ui, sans-serif;
@@ -86,44 +92,7 @@
--rs-h4: var(--rs-text);
--rs-h5: var(--rs-text-dim);
--rs-h6: var(--rs-text-dim);
}
[data-theme="light"] {
--rs-bg: #f3f3f3;
--rs-bg-elevated: #ffffff;
--rs-bg-active: #e8e8e8;
--rs-border: #d4d4d4;
--rs-text-dim: #6b6b6b;
--rs-text: #1e1e1e;
--rs-text-strong: #111111;
--rs-selection: #add6ff;
--rs-line-highlight: #0000000d;
}
[data-palette="claude"] {
--rs-font-ui: "Lora", Georgia, serif;
--rs-font-prose: "Lora", Georgia, serif;
--rs-font-heading: "Poppins", Arial, sans-serif;
}
[data-palette="sakura"], [data-palette="harvest-moon"], [data-palette="crimson-pilot"], [data-palette="silver-serpent"] {
--rs-item-selection-bg: var(--rs-selection);
}
[data-palette="harvest-moon"] {
--rs-font-ui: Candara, "Trebuchet MS", "Segoe UI", sans-serif;
--rs-font-prose: Constantia, Georgia, "Times New Roman", serif;
--rs-font-heading: var(--rs-font-prose);
}
[data-palette="crimson-pilot"] {
--rs-font-ui: Bahnschrift, "Trebuchet MS", Arial, sans-serif;
--rs-font-prose: "Segoe UI", "Helvetica Neue", Arial, sans-serif;
--rs-font-heading: var(--rs-font-ui);
}
[data-palette="silver-serpent"] {
--rs-font-ui: Corbel, "Segoe UI", "Helvetica Neue", Arial, sans-serif;
--rs-font-prose: "Palatino Linotype", "Book Antiqua", Palatino, Georgia, serif;
--rs-font-heading: var(--rs-font-prose);
/* Fixed colors that do not change with the theme. */
--rs-caption-close-bg: #c42b1c;
--rs-image-viewer-bg: #090a0de8;
}