// Theme documents: a wayBetter theme is a JSON document (like a BetterDiscord theme, but data instead // of a stylesheet) describing colors, type, shape, density, layout, background and motion; the format // is `theme.schema.json` in the `waybetter` package. This module is the document side of the theme // engine: types, the schema's defaults, sanitizing, import, panel overrides, legibility, font roles // and stacks, and page backgrounds. Pure, so it runs in the page runtime, the settings previews and // the tests. What a theme does to one site's page (its selectors, its palette) is the site's // (themeRuntime.ts takes a site adapter). // // Safety: a theme is sanitized field by field before it becomes CSS. Colors are six-digit hex, // numbers are clamped, enums are fixed, font names match a strict pattern, background images are // `data:image/*;base64` only, and CSS is built from those values (never concatenated from raw // strings). The single escape hatch is `css`, which is the same trust level as the owner's own // Custom CSS and is shown as such when a theme is imported. // // Fonts: sites usually block remote and `data:` fonts (CSP `font-src`), so a theme may name installed // system fonts, "Geist" / "Geist Mono" (bundled and registered from bytes: `FontFace(ArrayBuffer)` is // not a fetch), or Google Fonts families the owner downloaded (`source: "google"`, fonts.ts). import { FONT_ROLE_NAMES, MONO_FAMILIES, contrastRatio, hexToRgb, mix, relativeLuminance, type FontRoleName } from './themeApi.ts'; import { deriveColors } from './themeTokens.ts'; export { FONT_ROLE_NAMES } from './themeApi.ts'; export type { FontRoleName } from './themeApi.ts'; export type Role = 'bg' | 'surface' | 'elevated' | 'border' | 'text' | 'muted' | 'accent'; /** The site's filled primary button (X: "Post"/"Follow"): an `inverse` background with an `onInverse` label. */ export type ButtonRole = 'inverse' | 'onInverse'; export type Palette = Record & Partial>; /** `page` is the canvas behind the site's columns (defaults to `bg`); the columns stay on `bg`. */ export type ThemeColors = Palette & { page?: string }; export type Density = 'compact' | 'default' | 'comfortable'; export type AvatarShape = 'circle' | 'rounded' | 'square'; export type Pattern = 'dots' | 'grid' | 'diagonal' | 'scanlines' | 'paper' | 'clouds'; export type Background = | { kind: 'none' } | { kind: 'gradient'; from: string; to: string; angle: number; glow?: string } | { kind: 'pattern'; pattern: Pattern; ink: string; opacity: number; size: number } | { kind: 'image'; url: string; fit: 'cover' | 'tile'; dim: number }; /** * One role's font (roles: themeApi.ts `FONT_ROLE_NAMES`). `family` is a font stack; empty keeps the * inherited family and only changes the rest. `source: "google"` says the first family comes from * Google Fonts (downloaded once, asked first when a theme is imported, loaded from bytes). `weight` * (100-900), `size` (0.75-1.5, relative to the site's size), `tracking` (em) and `tabular` figures * are optional; the interface role takes only `family`/`source` (its size, weights and tracking are * `scale`, `weight`, `bold` and `tracking` of the whole theme). */ export type FontRoleSpec = { family: string[]; source?: 'google'; weight?: number; size?: number; tracking?: number; tabular?: boolean }; export type FontRole = 'inherit' | FontRoleSpec; export type FontRoles = Record; export type FontSpec = { /** * Interface font stack (replaces the site's own font everywhere). Empty keeps the site's. * Shorthand kept for older theme files and older apps: it always equals `roles.interface`'s family. */ family: string[]; /** Post text stack (e.g. a serif reading face); shorthand of `roles.post`'s family. */ tweet: string[]; /** Which font goes where. Every role inherits from `interface` unless it says otherwise. */ roles: FontRoles; /** Multiplies the site's pixel font sizes (0.85-1.2). */ scale: number; /** Regular weight (300-500) and bold weight (500-800) that replace the site's 400/700. */ weight: number; bold: number; /** Letter spacing in em (-0.03-0.06). */ tracking: number; /** Line height multiplier for post text (0 keeps the site's). */ leading: number; }; export type ShapeSpec = { radius: number; button: number; avatar: AvatarShape }; export type LayoutSpec = { column: number; sidebar: number; density: Density; cards: boolean; frame: boolean }; export type EffectsSpec = { motion: number; hover: 'none' | 'tint' | 'lift' | 'glow'; shadow: 'none' | 'soft' | 'deep'; crt: boolean }; export type ThemeSpec = { id: string; name: string; description: string; author: string; version: 1; /** Which way the theme leans; used for scrollbars/form controls and previews. */ mode: 'light' | 'dark' | 'auto'; /** null keeps the site's own colors (X: Default / Dim / Lights out). */ colors: ThemeColors | null; font: FontSpec; shape: ShapeSpec; layout: LayoutSpec; background: Background; effects: EffectsSpec; /** Free-form CSS appended last (owner-trusted, like Custom CSS). */ css: string; }; /** Panel overrides: any group may be partially overridden on top of the selected theme. */ export type ThemeOverrides = { colors?: Partial; /** `roles` is merged role by role (a named role replaces that role only). */ font?: Partial> & { roles?: Partial }; shape?: Partial; layout?: Partial; background?: Background; effects?: Partial; /** The theme's own CSS as edited in the panel (replaces the theme document's `css`). */ css?: { text: string }; }; // --------------------------------------------------------------------------------------------- // The schema's defaults: a theme that sets nothing changes nothing (the site keeps its own geometry; // a site's structure CSS only emits rules where a theme differs from these). export const BASE_SHAPE: ShapeSpec = { radius: 16, button: 9999, avatar: 'circle' }; export const INHERIT_ROLES: FontRoles = { interface: 'inherit', post: 'inherit', heading: 'inherit', numbers: 'inherit', mono: 'inherit', chrome: 'inherit', dialog: 'inherit' }; /** A font spec from the interface/post stacks alone (every other role inherits). */ export const withRoles = (font: Omit): FontSpec => ({ ...font, roles: { ...INHERIT_ROLES, ...(font.family.length ? { interface: { family: font.family } } : {}), ...(font.tweet.length ? { post: { family: font.tweet } } : {}) }, }); export const BASE_FONT: FontSpec = withRoles({ family: [], tweet: [], scale: 1, weight: 400, bold: 700, tracking: 0, leading: 0 }); export const BASE_LAYOUT: LayoutSpec = { column: 600, sidebar: 350, density: 'default', cards: false, frame: false }; export const BASE_EFFECTS: EffectsSpec = { motion: 0, hover: 'none', shadow: 'none', crt: false }; /** The system UI stack themes put after their own sans-serif families. */ export const SYSTEM_SANS = ['Segoe UI', '-apple-system', 'BlinkMacSystemFont', 'system-ui', 'sans-serif']; // --------------------------------------------------------------------------------------------- // Colors and contrast (luminance and ratios: themeApi.ts) export const isHex = (value: unknown): value is string => typeof value === 'string' && /^#[0-9a-f]{6}$/i.test(value); /** `#rrggbb` + alpha as `rgba()`. */ export const rgba = (hex: string, alpha: number) => `rgba(${hexToRgb(hex).join(', ')}, ${+alpha.toFixed(3)})`; /** Moves `color` toward black or white until it reaches `ratio` against every surface. */ function reach(color: string, surfaces: string[], ratio: number): string { const worst = (c: string) => Math.min(...surfaces.map(s => contrastRatio(c, s))); if (worst(color) >= ratio) return color; const lightSurfaces = surfaces.reduce((sum, s) => sum + relativeLuminance(s), 0) / surfaces.length > 0.18; const pole = lightSurfaces ? '#000000' : '#ffffff'; for (let t = 0.04; t <= 1; t += 0.04) { const next = mix(color, pole, t); if (worst(next) >= ratio) return next; } return pole; } /** * Guarantees legibility for any palette (built-in, imported or overridden): text, secondary text * and links reach WCAG AA (4.5:1) on every surface, including the page canvas, and the site's filled * button keeps a readable label and stands out from the page (3:1). */ export function ensureContrast(colors: T): T { const surfaces = [colors.bg, colors.surface, colors.elevated, ...(colors.page ? [colors.page] : [])]; const out = { ...colors }; out.text = reach(colors.text, surfaces, 7); out.muted = reach(colors.muted, surfaces, 4.5); // Links live inside the columns, never on the page canvas. out.accent = reach(colors.accent, [colors.bg, colors.surface, colors.elevated], 4.5); const inverse = colors.inverse ?? out.text; const onInverse = colors.onInverse ?? colors.bg; out.inverse = reach(inverse, [colors.bg], 3); out.onInverse = reach(onInverse, [out.inverse], 4.5); return out; } // --------------------------------------------------------------------------------------------- // Sanitizing const GENERIC_FONTS = new Set(['system-ui', 'sans-serif', 'serif', 'monospace', 'cursive', 'ui-sans-serif', 'ui-serif', 'ui-monospace', 'ui-rounded', '-apple-system', 'BlinkMacSystemFont']); const FONT_NAME = /^[A-Za-z0-9][A-Za-z0-9 .\-]{0,47}$/; const DATA_IMAGE = /^data:image\/(png|jpeg|webp|gif|avif);base64,[A-Za-z0-9+/]+={0,2}$/; export const MAX_IMAGE_CHARS = 1_100_000; export const MAX_CSS_CHARS = 60_000; const PATTERNS: Pattern[] = ['dots', 'grid', 'diagonal', 'scanlines', 'paper', 'clouds']; const obj = (value: unknown): Record => value && typeof value === 'object' && !Array.isArray(value) ? value as Record : {}; const num = (value: unknown, min: number, max: number, fallback: number) => typeof value === 'number' && Number.isFinite(value) ? Math.min(max, Math.max(min, value)) : fallback; const pick = (value: unknown, options: readonly T[], fallback: T): T => options.includes(value as T) ? value as T : fallback; const text = (value: unknown, max: number, fallback = '') => typeof value === 'string' ? value.replace(/[\u0000-\u001f\u007f]/g, '').trim().slice(0, max) : fallback; export function sanitizeFonts(value: unknown): string[] { if (!Array.isArray(value)) return []; return value.filter((name): name is string => typeof name === 'string' && (GENERIC_FONTS.has(name) || FONT_NAME.test(name))).slice(0, 8); } /** A theme needs its background, text and accent; any other role it leaves out is derived from the * base structure (themeTokens.ts `deriveColors`), so every theme has the same proportions. */ function sanitizeColors(value: unknown): ThemeColors | null { const source = obj(value); if (!(['bg', 'text', 'accent'] as const).every(role => isHex(source[role]))) return null; const named = Object.fromEntries((['bg', 'surface', 'elevated', 'border', 'text', 'muted', 'accent'] as Role[]) .filter(role => isHex(source[role])).map(role => [role, (source[role] as string).toLowerCase()])); const colors = deriveColors(named as { bg: string; text: string; accent: string }) as ThemeColors; for (const role of ['inverse', 'onInverse', 'page'] as const) if (isHex(source[role])) colors[role] = (source[role] as string).toLowerCase(); return colors; } export function sanitizeBackground(value: unknown): Background { const source = obj(value); if (source.kind === 'gradient' && isHex(source.from) && isHex(source.to)) { return { kind: 'gradient', from: source.from.toLowerCase(), to: source.to.toLowerCase(), angle: Math.round(num(source.angle, 0, 360, 180)), ...(isHex(source.glow) ? { glow: source.glow.toLowerCase() } : {}) }; } if (source.kind === 'pattern' && isHex(source.ink)) { return { kind: 'pattern', pattern: pick(source.pattern, PATTERNS, 'dots'), ink: source.ink.toLowerCase(), opacity: num(source.opacity, 0, 0.6, 0.1), size: Math.round(num(source.size, 2, 400, 24)) }; } if (source.kind === 'image' && typeof source.url === 'string' && source.url.length <= MAX_IMAGE_CHARS && DATA_IMAGE.test(source.url)) { return { kind: 'image', url: source.url, fit: pick(source.fit, ['cover', 'tile'] as const, 'cover'), dim: num(source.dim, 0.35, 0.95, 0.6) }; } return { kind: 'none' }; } /** Bounds of a role's own settings (the JSON Schema says the same; tested). */ export const ROLE_LIMITS = { weight: [100, 900], size: [0.75, 1.5], tracking: [-0.05, 0.1] } as const; /** One role from JSON: "inherit", or a stack with optional extras (clamped; unknown keys dropped). */ export function sanitizeFontRole(value: unknown, role: FontRoleName): FontRole { if (value === 'inherit' || value === null || value === undefined) return 'inherit'; const source = obj(value); if (!Object.keys(source).length) return 'inherit'; const family = sanitizeFonts(source.family); const out: FontRoleSpec = { family }; if (source.source === 'google' && family.length && !GENERIC_FONTS.has(family[0]!)) out.source = 'google'; if (role !== 'interface') { if (typeof source.weight === 'number' && Number.isFinite(source.weight)) out.weight = Math.round(num(source.weight, ...ROLE_LIMITS.weight, 400)); if (typeof source.size === 'number' && Number.isFinite(source.size)) out.size = +num(source.size, ...ROLE_LIMITS.size, 1).toFixed(3); if (typeof source.tracking === 'number' && Number.isFinite(source.tracking)) out.tracking = +num(source.tracking, ...ROLE_LIMITS.tracking, 0).toFixed(4); if (source.tabular === true) out.tabular = true; } // A role that changes nothing is the same as inheriting. return Object.keys(out).length === 1 && !family.length ? 'inherit' : out; } const roleFamily = (role: FontRole): string[] => role === 'inherit' ? [] : role.family; /** A role with a new family, keeping its other settings (and its Google source only for the same font). */ export function withFamily(role: FontRole, family: string[], source?: 'google'): FontRole { const rest = role === 'inherit' ? {} : { ...role }; delete (rest as Partial).source; delete (rest as Partial).family; const next: FontRoleSpec = { ...rest, family, ...(source && family.length ? { source } : {}) }; return Object.keys(next).length === 1 && !family.length ? 'inherit' : next; } /** * The roles of a font group from JSON over `base`: `roles.` wins; the legacy shorthand * (`family` → interface, `tweet` → post) applies when that role is not named, so theme files and * saved customizations from before font roles keep working. */ function sanitizeRoles(source: Record, base: FontSpec): FontRoles { const named = obj(source.roles); const roles = { ...base.roles }; for (const role of FONT_ROLE_NAMES) if (role in named) roles[role] = sanitizeFontRole(named[role], role); if (!('interface' in named) && 'family' in source) roles.interface = withFamily(base.roles.interface, sanitizeFonts(source.family), sameFirst(source.family, base.roles.interface)); if (!('post' in named) && 'tweet' in source) roles.post = withFamily(base.roles.post, sanitizeFonts(source.tweet), sameFirst(source.tweet, base.roles.post)); return roles; } /** Keeps a role's Google source when the shorthand still names the same first family. */ function sameFirst(stack: unknown, role: FontRole): 'google' | undefined { return role !== 'inherit' && role.source === 'google' && Array.isArray(stack) && stack[0] === role.family[0] ? 'google' : undefined; } function sanitizeFont(value: unknown, base: FontSpec): FontSpec { const source = obj(value); const roles = sanitizeRoles(source, base); return { family: roleFamily(roles.interface), tweet: roleFamily(roles.post), roles, scale: num(source.scale, 0.85, 1.2, base.scale), weight: Math.round(num(source.weight, 300, 500, base.weight)), bold: Math.round(num(source.bold, 500, 800, base.bold)), tracking: num(source.tracking, -0.03, 0.06, base.tracking), leading: source.leading === 0 ? 0 : num(source.leading, 1.2, 1.8, base.leading), }; } const sanitizeShape = (value: unknown, base: ShapeSpec): ShapeSpec => { const source = obj(value); return { radius: Math.round(num(source.radius, 0, 28, base.radius)), button: Math.round(num(source.button, 0, 9999, base.button)), avatar: pick(source.avatar, ['circle', 'rounded', 'square'] as const, base.avatar) }; }; const sanitizeLayout = (value: unknown, base: LayoutSpec): LayoutSpec => { const source = obj(value); return { column: Math.round(num(source.column, 520, 820, base.column)), sidebar: Math.round(num(source.sidebar, 290, 400, base.sidebar)), density: pick(source.density, ['compact', 'default', 'comfortable'] as const, base.density), cards: typeof source.cards === 'boolean' ? source.cards : base.cards, frame: typeof source.frame === 'boolean' ? source.frame : base.frame, }; }; const sanitizeEffects = (value: unknown, base: EffectsSpec): EffectsSpec => { const source = obj(value); return { motion: Math.round(num(source.motion, 0, 400, base.motion)), hover: pick(source.hover, ['none', 'tint', 'lift', 'glow'] as const, base.hover), shadow: pick(source.shadow, ['none', 'soft', 'deep'] as const, base.shadow), crt: typeof source.crt === 'boolean' ? source.crt : base.crt, }; }; export const slug = (value: string) => value.toLowerCase().normalize('NFKD').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40) || 'theme'; /** Any JSON to a complete, safe theme. Missing groups fall back to the schema's defaults. */ export function sanitizeSpec(input: unknown): ThemeSpec { const source = obj(input); const name = text(source.name, 60) || 'Untitled theme'; const id = typeof source.id === 'string' && /^[a-z0-9-]{1,40}$/.test(source.id) ? source.id : slug(name); return { id, name, description: text(source.description, 200), author: text(source.author, 60), version: 1, mode: pick(source.mode, ['light', 'dark', 'auto'] as const, 'auto'), colors: sanitizeColors(source.colors), font: sanitizeFont(source.font, BASE_FONT), shape: sanitizeShape(source.shape, BASE_SHAPE), layout: sanitizeLayout(source.layout, BASE_LAYOUT), background: sanitizeBackground(source.background), effects: sanitizeEffects(source.effects, BASE_EFFECTS), css: typeof source.css === 'string' ? source.css.slice(0, MAX_CSS_CHARS) : '', }; } /** Parses an imported file; errors are human-readable. */ export function parseThemeJson(json: string): { theme: ThemeSpec; warnings: string[] } | { error: string } { let raw: unknown; try { raw = JSON.parse(json); } catch { return { error: 'This file is not valid JSON.' }; } const source = obj(raw); if (typeof source.name !== 'string' || !source.name.trim()) return { error: 'A theme needs a "name".' }; const theme = sanitizeSpec(raw); const warnings: string[] = []; if (source.colors !== undefined && source.colors !== null && !theme.colors) warnings.push('Colors were ignored: bg, text and accent must be #rrggbb (the other roles are derived when missing).'); if (theme.css) warnings.push('Contains custom CSS, which runs inside the site like your own Custom CSS.'); if (source.background && theme.background.kind === 'none' && obj(source.background).kind !== 'none') warnings.push('The background was ignored (images must be data:image/png, jpeg, webp, gif or avif, up to about 800 KB).'); if (theme.colors) { const fixed = ensureContrast(theme.colors); if (fixed.text !== theme.colors.text || fixed.muted !== theme.colors.muted || fixed.accent !== theme.colors.accent) warnings.push('Some text colors were adjusted to stay readable.'); } return { theme, warnings }; } /** Applies panel overrides (and an accent) on top of a theme. Colors are then made legible. */ export function applyOverrides(theme: ThemeSpec, overrides: ThemeOverrides = {}, accent: string | null = null): ThemeSpec { const o = obj(overrides) as ThemeOverrides; let colors = theme.colors ? { ...theme.colors, ...Object.fromEntries(Object.entries(obj(o.colors)).filter(([, v]) => isHex(v))) } as ThemeColors : null; if (colors && accent) colors = { ...colors, accent, ...(theme.colors?.inverse === theme.colors?.accent ? { inverse: accent } : {}) }; return { ...theme, colors: colors ? ensureContrast(colors) : null, // Missing keys fall back to the theme's own; the legacy `family`/`tweet` shorthand still overrides. font: o.font ? sanitizeFont(o.font, theme.font) : theme.font, shape: o.shape ? sanitizeShape({ ...theme.shape, ...o.shape }, theme.shape) : theme.shape, layout: o.layout ? sanitizeLayout({ ...theme.layout, ...o.layout }, theme.layout) : theme.layout, background: o.background ? sanitizeBackground(o.background) : theme.background, effects: o.effects ? sanitizeEffects({ ...theme.effects, ...o.effects }, theme.effects) : theme.effects, css: o.css && typeof o.css.text === 'string' ? o.css.text.slice(0, MAX_CSS_CHARS) : theme.css, }; } /** True when a theme changes nothing about the site (the site's own look without overrides). */ export function isNeutral(theme: ThemeSpec): boolean { return !theme.colors && JSON.stringify([theme.font, theme.shape, theme.layout, theme.effects]) === JSON.stringify([BASE_FONT, BASE_SHAPE, BASE_LAYOUT, BASE_EFFECTS]) && theme.background.kind === 'none' && !theme.css; } // --------------------------------------------------------------------------------------------- // Fonts /** Bundled families and the names they are registered under (shell: @fontsource; site pages: FontFace, fonts.ts). */ export const BUNDLED_FONTS: Record = { 'Geist': 'Geist Variable', 'Geist Mono': 'Geist Mono Variable' }; export function fontStack(names: string[]): string { const out: string[] = []; for (const name of names) { const real = BUNDLED_FONTS[name]; if (real) out.push(`"${real}"`); out.push(GENERIC_FONTS.has(name) ? name : `"${name}"`); } // Emoji and CJK keep working whatever the theme names. return [...new Set(out), '"Segoe UI Emoji"', '"Apple Color Emoji"', 'sans-serif'].join(', '); } /** Roles that are drawn inside the site's page (chrome is wayBetter's own window). */ export const PAGE_ROLES: FontRoleName[] = ['interface', 'post', 'heading', 'numbers', 'mono', 'dialog']; const rolesUsing = (theme: ThemeSpec, roles: readonly FontRoleName[]) => roles.flatMap(role => roleFamily(theme.font.roles[role])); /** Bundled families (Geist, Geist Mono) a theme names in the site's page. */ export const bundledFontsUsed = (theme: ThemeSpec, roles: readonly FontRoleName[] = PAGE_ROLES) => { const names = new Set(rolesUsing(theme, roles)); return Object.keys(BUNDLED_FONTS).filter(name => names.has(name)); }; /** Google Fonts families a theme uses (`source: "google"`), for the given roles. */ export function googleFontsUsed(theme: ThemeSpec, roles: readonly FontRoleName[] = FONT_ROLE_NAMES): string[] { const out = new Set(); for (const role of roles) { const spec = theme.font.roles[role]; if (spec !== 'inherit' && spec.source === 'google' && spec.family[0]) out.add(spec.family[0]); } return [...out]; } /** A role resolved to what is drawn: the stack actually used and its settings. */ export type ResolvedFontRole = { /** CSS `font-family`. */ stack: string; /** The families of that stack (empty when it is the site's or app's own font). */ family: string[]; /** True when the family comes from another role (or the site/app default). */ inherited: boolean; /** A Google Fonts family the stack starts with. */ google: string | null; weight: number | null; size: number; tracking: number | null; tabular: boolean; }; export type ResolvedFontRoles = Record; /** * Every role resolved. `site` is the stack an inheriting interface uses: the site's own font in its * page, wayBetter's own UI font in the shell. Every other role inherits the interface, except that an * inheriting `mono` keeps a monospaced stack (`mono`: themeApi.ts `MONO_FAMILIES`, code rarely suits * an interface font). */ export function resolveFontRoles(font: FontSpec, site: string, mono = fontStack(MONO_FAMILIES)): ResolvedFontRoles { const base = font.roles.interface; const baseFamily = roleFamily(base); const root: ResolvedFontRole = { stack: baseFamily.length ? fontStack(baseFamily) : site, family: baseFamily, inherited: !baseFamily.length, google: base !== 'inherit' && base.source === 'google' ? baseFamily[0] ?? null : null, weight: null, size: 1, tracking: null, tabular: false, }; const out = { interface: root } as ResolvedFontRoles; for (const role of FONT_ROLE_NAMES) { if (role === 'interface') continue; const spec = font.roles[role]; const own = roleFamily(spec); const from = own.length ? { stack: fontStack(own), family: own, inherited: false, google: spec !== 'inherit' && spec.source === 'google' ? own[0]! : null } : role === 'mono' ? { stack: mono, family: [] as string[], inherited: true, google: null } : { stack: root.stack, family: root.family, inherited: true, google: root.google }; out[role] = { ...from, weight: spec === 'inherit' ? null : spec.weight ?? null, size: spec === 'inherit' ? 1 : spec.size ?? 1, tracking: spec === 'inherit' ? null : spec.tracking ?? null, tabular: spec !== 'inherit' && !!spec.tabular, }; } return out; } /** * A named font stack offered by the panel's pickers. `key` names its translated label * (`wb.fonts.choice.*`); `label` is the English one. A site adds its own font first (X: "X's Chirp", * an empty family that keeps the site's type). */ export type FontChoice = { id: string; label: string; key?: string; family: string[] }; /** Font choices offered by the panel; any installed family can also be named in theme JSON. */ export const FONT_CHOICES: FontChoice[] = [ { id: 'geist', label: 'Geist', family: ['Geist', ...SYSTEM_SANS] }, { id: 'geist-mono', label: 'Geist Mono', family: ['Geist Mono', 'Cascadia Mono', 'Consolas', 'Menlo', 'ui-monospace', 'monospace'] }, { id: 'system', label: 'System UI', key: 'wb.fonts.choice.system', family: SYSTEM_SANS }, { id: 'helvetica', label: 'Helvetica / Arial', family: ['Helvetica Neue', 'Helvetica', 'Arial', 'sans-serif'] }, { id: 'humanist', label: 'Humanist (Segoe, Avenir)', key: 'wb.fonts.choice.humanist', family: ['Avenir Next', 'Segoe UI Variable Text', 'Segoe UI', 'sans-serif'] }, { id: 'rounded', label: 'Rounded', key: 'wb.fonts.choice.rounded', family: ['ui-rounded', 'SF Pro Rounded', 'Nunito', 'Bahnschrift', 'Segoe UI', 'sans-serif'] }, { id: 'serif', label: 'Serif (Charter, Georgia)', key: 'wb.fonts.choice.serif', family: ['Charter', 'Iowan Old Style', 'Georgia', 'Cambria', 'serif'] }, { id: 'mono', label: 'System mono', key: 'wb.fonts.choice.mono', family: ['Cascadia Mono', 'SF Mono', 'Consolas', 'Menlo', 'ui-monospace', 'monospace'] }, ]; /** The choice whose stack is exactly `family` in `choices`, or `custom`. */ export const fontChoiceOf = (family: string[], choices: readonly FontChoice[] = FONT_CHOICES) => choices.find(choice => choice.family.join('|') === family.join('|'))?.id ?? 'custom'; // --------------------------------------------------------------------------------------------- // Backgrounds const svgUrl = (svg: string) => `url("data:image/svg+xml,${encodeURIComponent(svg)}")`; /** * The site's page background. A site's `` and `` are often one viewport tall while the * content overflows them (X's timeline), so a background painted on both had `` paint its own * copy over its box, which scrolls away: after a partial scroll the gradient/glow showed only below a hard seam. Now * `` holds the plain page color, `` is transparent (beating, by specificity, the * palette's `html,body{background-color}` and its `[style^="background-color: …"]` remap of the * inline color X puts on ``) and every layer sits on one viewport-sized fixed * layer behind all of the page (`z-index:-1` in the root stacking context), with no `fixed` attachments. */ export function pageBackgroundCss(background: Background, page: string): string[] { const out = [`html:root{background:${page} !important}`, `html:root body{background:transparent !important}`]; if (background.kind !== 'none') { out.push(`html:root::before{content:"";position:fixed;inset:0;z-index:-1;pointer-events:none;contain:strict;background:${backgroundLayers(background, page, false)}}`); } return out; } /** * CSS `background` layers for the page canvas (behind the site's columns). `attach` keeps the `fixed` * attachments for a box that scrolls (the Theme Builder preview); the site's page gets the layers without * them, on one viewport-sized fixed layer (`pageBackgroundCss`). */ export function backgroundLayers(background: Background, page: string, attach = true): string { const fixed = attach ? ' fixed' : ''; switch (background.kind) { case 'gradient': { const glow = background.glow ? `radial-gradient(1200px 600px at 50% -10%, ${rgba(background.glow, 0.55)}, transparent 70%), ` : ''; return `${glow}linear-gradient(${background.angle}deg, ${background.from}, ${background.to})${fixed}, ${page}`; } case 'pattern': { const { ink, opacity: a, size: s } = background; const c = rgba(ink, a); switch (background.pattern) { case 'dots': return `radial-gradient(${c} 1px, transparent 1.6px) 0 0 / ${s}px ${s}px, ${page}`; case 'grid': return `linear-gradient(${c} 1px, transparent 1px) 0 0 / ${s}px ${s}px, linear-gradient(90deg, ${c} 1px, transparent 1px) 0 0 / ${s}px ${s}px, ${page}`; case 'diagonal': return `repeating-linear-gradient(135deg, ${c} 0 1px, transparent 1px ${s}px), ${page}`; case 'scanlines': return `repeating-linear-gradient(0deg, ${c} 0 1px, transparent 1px ${s}px), radial-gradient(ellipse at 50% 40%, ${rgba(ink, a * 1.6)}, transparent 70%)${fixed}, ${page}`; case 'paper': return `${svgUrl(``)} 0 0 / ${s}px ${s}px, ${page}`; case 'clouds': return [ `radial-gradient(${s}px ${Math.round(s * 0.42)}px at 12% 22%, ${c}, transparent 70%)${fixed}`, `radial-gradient(${Math.round(s * 1.3)}px ${Math.round(s * 0.5)}px at 86% 12%, ${c}, transparent 70%)${fixed}`, `radial-gradient(${Math.round(s * 1.1)}px ${Math.round(s * 0.4)}px at 78% 70%, ${c}, transparent 70%)${fixed}`, `radial-gradient(${Math.round(s * 0.9)}px ${Math.round(s * 0.36)}px at 18% 82%, ${c}, transparent 70%)${fixed}`, `linear-gradient(180deg, ${mix(page, '#ffffff', 0.25)}, ${page} 60%)${fixed}`, page, ].join(', '); } return page; } case 'image': { const scrim = `linear-gradient(${rgba(page, background.dim)}, ${rgba(page, background.dim)})${fixed}`; return background.fit === 'tile' ? `${scrim}, url("${background.url}") 0 0 / auto repeat, ${page}` : `${scrim}, url("${background.url}") center / cover no-repeat${fixed}, ${page}`; } default: return page; } }