Files
RuneStone/src/lib/theme/appearance.ts
T

205 lines
16 KiB
TypeScript

import { customThemes, FONT_ROLES, type ThemeFonts, type ThemeColors, type CustomTheme } from './customThemes.ts';
import { readBackgroundImage } from './backgroundImages.ts';
import { characterTheme, characterSyntax, SYNTAX_ROLES } from './characterThemes.ts';
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 type ThemeName = typeof THEMES[number] | `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] } };
export const DEFAULT_APPEARANCE: Appearance = { theme: 'default', mode: 'dark' };
export function normalizeAppearance(value: { theme?: unknown; mode?: unknown; newTabBackground?: unknown; transparency?: unknown } | null): Appearance {
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:') ? 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') };
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 };
}
const background = value?.newTabBackground;
if (background && typeof background === 'object') {
const source = background as { image?: unknown; imageId?: unknown; overlay?: unknown; position?: unknown; size?: unknown };
const image = typeof source.image === 'string' && source.image.length <= 3_000_000 && /^data:image\/(?:png|jpeg|webp|gif);base64,[a-z0-9+/=]+$/i.test(source.image) ? source.image : undefined;
const imageId = typeof source.imageId === 'string' && /^[0-9a-f-]{36}$/i.test(source.imageId) ? source.imageId : undefined;
const overlay = typeof source.overlay === 'number' && Number.isFinite(source.overlay) ? Math.max(-1, Math.min(1, source.overlay)) : 0;
const position = BACKGROUND_POSITIONS.includes(source.position as typeof BACKGROUND_POSITIONS[number]) ? source.position as typeof BACKGROUND_POSITIONS[number] : 'center';
const size = BACKGROUND_SIZES.includes(source.size as typeof BACKGROUND_SIZES[number]) ? source.size as typeof BACKGROUND_SIZES[number] : 'cover';
if (image || imageId) result.newTabBackground = { ...(image ? { image } : {}), ...(imageId ? { imageId } : {}), overlay, position, size };
}
return result;
}
export function parseAppearance(raw: string | null): Appearance {
try { return normalizeAppearance(JSON.parse(raw || 'null')); }
catch { return { ...DEFAULT_APPEARANCE }; }
}
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'];
}
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 {
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 } };
}
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 applyTransparency(value: Appearance['transparency'], root: HTMLElement) {
const supplied = value?.amount ?? 18;
const amount = value?.enabled === false ? 0 : Number.isFinite(supplied) ? Math.max(0, Math.min(100, supplied)) : 18;
root.dataset.transparency = amount ? 'on' : 'off';
root.style.setProperty('--rs-surface-opacity', `${100 - amount}%`);
root.style.setProperty('--rs-editor-surface-opacity', `${100 - amount * 10 / 18}%`);
root.style.setProperty('--rs-hover-surface-opacity', `${100 - amount * 8 / 18}%`);
root.style.setProperty('--rs-transparent-plugin-bg', amount ? 'transparent' : 'var(--rs-bg)');
}
const backgroundUrls = new WeakMap<HTMLElement, { image: string; url: string }>();
const backgroundRequests = new WeakMap<HTMLElement, string | undefined>();
function applyBackgroundSurfaces(root: HTMLElement, hasImage: boolean) {
root.style.setProperty('--rs-workarea-sidebar-bg', hasImage ? 'var(--rs-image-sidebar-bg)' : 'var(--rs-bg-elevated)');
root.style.setProperty('--rs-workarea-editor-bg', hasImage ? 'var(--rs-image-editor-bg)' : 'var(--rs-bg)');
root.style.setProperty('--rs-workarea-surface-opacity', hasImage ? 'var(--rs-surface-opacity)' : '100%');
root.style.setProperty('--rs-workarea-plugin-bg', hasImage ? 'var(--rs-transparent-plugin-bg)' : 'var(--rs-bg)');
}
async function applySavedBackground(root: HTMLElement, background?: Appearance['newTabBackground']) {
const id = background?.imageId;
backgroundRequests.set(root, id);
if (!id) { applyBackgroundImage(root, background?.image); return; }
const previous = backgroundUrls.get(root);
if (previous?.image === id) { root.style.setProperty('--rs-new-tab-image', `url("${previous.url}")`); applyBackgroundSurfaces(root, true); return; }
applyBackgroundImage(root);
try {
const file = await readBackgroundImage(id);
if (!file || backgroundRequests.get(root) !== id) return;
const url = URL.createObjectURL(file);
const old = backgroundUrls.get(root);
backgroundUrls.set(root, { image: id, url });
root.style.setProperty('--rs-new-tab-image', `url("${url}")`);
applyBackgroundSurfaces(root, true);
if (old) URL.revokeObjectURL(old.url);
} catch { /* Keep the theme usable if image storage is unavailable. */ }
}
function applyBackgroundImage(root: HTMLElement, image?: string) {
const previous = backgroundUrls.get(root);
if (image && previous?.image === image) {
root.style.setProperty('--rs-new-tab-image', `url("${previous.url}")`);
applyBackgroundSurfaces(root, true);
return;
}
let url: string | undefined;
if (image) {
try {
const [header, data] = image.split(',');
const bytes = Uint8Array.from(atob(data), character => character.charCodeAt(0));
url = URL.createObjectURL(new Blob([bytes], { type: header.slice(5, header.indexOf(';')) }));
} catch { /* Invalid saved image data must not stop the theme update. */ }
}
// Large data URLs exceed Chromium's CSS variable limit. Keep only a short blob URL in CSS.
root.style.setProperty('--rs-new-tab-image', url ? `url("${url}")` : 'none');
applyBackgroundSurfaces(root, !!url);
if (image && url) backgroundUrls.set(root, { image, url });
else backgroundUrls.delete(root);
if (previous) URL.revokeObjectURL(previous.url);
}
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;
applyTransparency(normalized.transparency, root);
root.style.setProperty('--rs-new-tab-bg', 'var(--rs-bg)');
const overlay = newTabBackground?.overlay ?? 0;
const shade = overlay < 0 ? '255,255,255' : '0,0,0';
root.style.setProperty('--rs-background-overlay', `linear-gradient(rgba(${shade},${Math.abs(overlay)}),rgba(${shade},${Math.abs(overlay)}))`);
root.style.setProperty('--rs-background-image', newTabBackground ? 'var(--rs-background-overlay), var(--rs-new-tab-image, none)' : 'none');
root.style.setProperty('--rs-background-position', newTabBackground?.position ?? 'center');
root.style.setProperty('--rs-background-size', newTabBackground?.size ?? 'cover');
void applySavedBackground(root, newTabBackground);
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);
window.dispatchEvent(new CustomEvent('runestone-theme-changed'));
}
export function saveAppearance(value: Appearance) {
const appearance = normalizeAppearance(value);
localStorage.setItem(APPEARANCE_KEY, JSON.stringify(appearance));
applyAppearance(appearance);
}