import { customThemes, FONT_ROLES, type ThemeFonts, type CustomTheme } from './customThemes.ts'; import { readBackgroundImage } from './backgroundImages.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: 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; } /** 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] } }; export const DEFAULT_APPEARANCE: Appearance = { theme: 'default', mode: 'dark' }; /** `themes` is the list of custom themes. By default, it is the saved list. */ export function normalizeAppearance(value: { theme?: unknown; mode?: unknown; newTabBackground?: unknown; transparency?: unknown } | null, themes?: CustomTheme[]): 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:') ? (themes ?? customThemes(value?.mode === 'light' ? 'light' : 'dark')).find(item => `custom:${item.id}` === theme) : undefined; 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 }; } 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 }; } } /** The saved appearance, normalized. */ export function readAppearance(): Appearance { const value = readSection('appearance'); return normalizeAppearance(value && typeof value === 'object' && !Array.isArray(value) ? value : null); } /** * 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 } { 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) }; } /** 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); 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: string): Required { return { ...DEFAULT_FONTS, ...builtinTheme(theme)?.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', 'transparent'); } const backgroundUrls = new WeakMap(); const backgroundRequests = new WeakMap(); 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)'); root.style.setProperty('--rs-menu-bg', hasImage ? 'var(--rs-image-menu-bg)' : 'var(--rs-bg-elevated)'); root.style.setProperty('--rs-menu-active-bg', hasImage ? 'var(--rs-image-menu-active-bg)' : 'var(--rs-bg-active)'); root.style.setProperty('--rs-menu-backdrop', hasImage ? 'var(--rs-image-menu-backdrop)' : 'none'); } 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 { 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; 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; 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]); 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. */ export function saveAppearance(value: Appearance): Promise { const appearance = normalizeAppearance(value); const saved = writeSection('appearance', appearance); applyAppearance(appearance); return saved; }