runtime + host: the theme engine (theme documents, choice catalog, page runtime, fonts; native theme state)
The site-independent theme engine moves from wayBetter for X into the framework: - runtime/themeSpec.ts: theme document types, the schema's defaults (BASE_*), sanitizing, import, overrides, ensureContrast, font roles/stacks, font choices, backgrounds. - runtime/themeChoice.ts: ThemeChoice and createThemeCatalog(builtins) (normalize, base, resolve, palette, all), choiceForId, serializeChoice. - runtime/themeRuntime.ts: installThemeRuntime(win, site) (live CSS over the site's rules, --wb-* vars, site color mode, first-frame snapshot), collectRules, resolvedFonts. - runtime/fonts.ts: bundled fonts and owner-downloaded Google Fonts from bytes. - themeApi exports hexToRgb, mix and MONO_FAMILIES (one copy: themeTokens and themeSpec use them). - host theme.rs: ThemeChoice/ThemeScopes over a site's ThemeSite (envelope checks against theme.schema.json, which theme a tab shows, page color, delivery script).
This commit is contained in:
parent
1a49cf58d4
commit
7568126f2b
9 changed files with 1542 additions and 14 deletions
73
packages/runtime/src/fonts.ts
Normal file
73
packages/runtime/src/fonts.ts
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
// Theme fonts in a site's page. Sites usually block remote and `data:` font URLs (CSP `font-src`),
|
||||
// but a FontFace built from bytes performs no fetch, so bundled families (Geist and Geist Mono: the
|
||||
// app embeds their woff2 files in its page runtime) are registered only when a theme uses them, and
|
||||
// Google Fonts the owner downloaded arrive as bytes from native code (`provideFonts`).
|
||||
|
||||
import { BUNDLED_FONTS } from './themeSpec.ts';
|
||||
|
||||
/** Unicode ranges of the Latin and Latin Extended subsets (@fontsource file names `latin`, `latin-ext`). */
|
||||
export const LATIN_RANGE = 'U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD';
|
||||
export const LATIN_EXT_RANGE = 'U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF';
|
||||
|
||||
/** A bundled family's files: base64 woff2 (variable, weights 100-900) with the unicode range each covers. */
|
||||
export type BundledFontFiles = Record<string, Array<[base64: string, unicodeRange: string]>>;
|
||||
|
||||
const loaded = new WeakMap<Document, Set<string>>();
|
||||
const log = (family: string, error: unknown) => console.error(`[wayBetter] font ${family} failed`, error);
|
||||
|
||||
/** Registers the bundled families `names` (BUNDLED_FONTS) from `files`, once per document. */
|
||||
export function loadBundledFonts(doc: Document, names: string[], files: BundledFontFiles): void {
|
||||
let done = loaded.get(doc);
|
||||
if (!done) loaded.set(doc, done = new Set());
|
||||
for (const name of names) {
|
||||
const faces = files[name];
|
||||
const family = BUNDLED_FONTS[name];
|
||||
if (!faces || !family || done.has(name)) continue;
|
||||
done.add(name);
|
||||
for (const [base64, unicodeRange] of faces) {
|
||||
const bytes = Uint8Array.from(atob(base64), char => char.charCodeAt(0));
|
||||
const face = new FontFace(family, bytes.buffer, { weight: '100 900', style: 'normal', unicodeRange, display: 'swap' });
|
||||
doc.fonts.add(face);
|
||||
face.load().catch(error => log(name, error));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Google Fonts the owner downloaded: native code validates and caches the woff2 files and hands
|
||||
* their bytes to site tabs whose theme uses them. The page never requests a font; each family is
|
||||
* registered once per document (again only when its bytes change, e.g. after picking other weights).
|
||||
*/
|
||||
export type ProvidedFont = { family: string; faces: Array<{ weight: [number, number]; unicodeRange: string | null; data: string }> };
|
||||
const provided = new WeakMap<Document, Map<string, string>>();
|
||||
const FAMILY = /^[A-Za-z0-9][A-Za-z0-9 ]{0,47}$/;
|
||||
|
||||
/** Registers the provided families (validated again; at most 8 families of 24 faces); returns the families added. */
|
||||
export function provideFonts(doc: Document, fonts: unknown): string[] {
|
||||
const added: string[] = [];
|
||||
if (!Array.isArray(fonts)) return added;
|
||||
let known = provided.get(doc);
|
||||
if (!known) provided.set(doc, known = new Map());
|
||||
for (const font of fonts.slice(0, 8) as ProvidedFont[]) {
|
||||
if (!font || typeof font.family !== 'string' || !FAMILY.test(font.family) || !Array.isArray(font.faces)) continue;
|
||||
const key = font.faces.map(face => `${face?.weight}|${typeof face?.data === 'string' ? face.data.length : 0}`).join(',');
|
||||
if (known.get(font.family) === key) continue;
|
||||
// Other weights of a family replace its earlier faces.
|
||||
for (const face of [...doc.fonts]) if ((face as FontFace).family.replace(/"/g, '') === font.family && (face as FontFace & { wbGoogle?: boolean }).wbGoogle) doc.fonts.delete(face as FontFace);
|
||||
known.set(font.family, key);
|
||||
for (const face of font.faces.slice(0, 24)) {
|
||||
if (!face || typeof face.data !== 'string' || !Array.isArray(face.weight)) continue;
|
||||
try {
|
||||
const bytes = Uint8Array.from(atob(face.data), char => char.charCodeAt(0));
|
||||
const [min, max] = face.weight.map(Number) as [number, number];
|
||||
const descriptors: FontFaceDescriptors = { weight: min === max ? String(min) : `${min} ${max}`, style: 'normal', display: 'swap' };
|
||||
if (typeof face.unicodeRange === 'string' && /^[U+0-9A-Fa-f?, -]{1,4000}$/.test(face.unicodeRange)) descriptors.unicodeRange = face.unicodeRange;
|
||||
const fontFace = Object.assign(new FontFace(font.family, bytes.buffer, descriptors), { wbGoogle: true });
|
||||
doc.fonts.add(fontFace);
|
||||
fontFace.load().catch(error => log(font.family, error));
|
||||
} catch (error) { log(font.family, error); }
|
||||
}
|
||||
added.push(font.family);
|
||||
}
|
||||
return added;
|
||||
}
|
||||
|
|
@ -73,7 +73,9 @@ export type ResolvedFont = {
|
|||
inherited: boolean;
|
||||
};
|
||||
export type ResolvedFonts = Record<FontRoleName, ResolvedFont>;
|
||||
export const MONO_FONT = 'ui-monospace, "Cascadia Mono", "SF Mono", Consolas, Menlo, monospace';
|
||||
/** Monospaced families, in order: what a `mono` role that inherits (or a source without fonts) gets. */
|
||||
export const MONO_FAMILIES = ['Cascadia Mono', 'SF Mono', 'Consolas', 'Menlo', 'ui-monospace', 'monospace'];
|
||||
export const MONO_FONT = MONO_FAMILIES.map(name => (/^(ui-monospace|monospace)$/.test(name) ? name : `"${name}"`)).join(', ');
|
||||
|
||||
/** What a site adapter provides: the current resolved theme and change notifications. */
|
||||
export type ThemeSource = {
|
||||
|
|
@ -95,14 +97,15 @@ export const FALLBACK_FONT = 'system-ui, -apple-system, "Segoe UI", Roboto, Helv
|
|||
|
||||
const HEX = /^#[0-9a-f]{6}$/i;
|
||||
|
||||
function channels(hex: string): [number, number, number] {
|
||||
/** `#rrggbb` → [r, g, b]. */
|
||||
export function hexToRgb(hex: string): [number, number, number] {
|
||||
const n = parseInt(hex.slice(1, 7), 16);
|
||||
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
|
||||
}
|
||||
|
||||
/** WCAG relative luminance of `#rrggbb`. */
|
||||
export function relativeLuminance(hex: string): number {
|
||||
const [r, g, b] = channels(hex).map(v => { const c = v / 255; return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; }) as [number, number, number];
|
||||
const [r, g, b] = hexToRgb(hex).map(v => { const c = v / 255; return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; }) as [number, number, number];
|
||||
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
|
||||
}
|
||||
|
||||
|
|
@ -130,8 +133,9 @@ export function toHex(value: string | null | undefined): string | null {
|
|||
return `#${[match[1], match[2], match[3]].map(v => Math.min(255, Number(v)).toString(16).padStart(2, '0')).join('')}`;
|
||||
}
|
||||
|
||||
function mixHex(a: string, b: string, t: number): string {
|
||||
const [x, y] = [channels(a), channels(b)];
|
||||
/** `a` moved toward `b` by `t` (0–1), per channel. */
|
||||
export function mix(a: string, b: string, t: number): string {
|
||||
const [x, y] = [hexToRgb(a), hexToRgb(b)];
|
||||
return `#${x.map((v, i) => Math.round(v + (y[i]! - v) * t).toString(16).padStart(2, '0')).join('')}`;
|
||||
}
|
||||
|
||||
|
|
@ -143,10 +147,10 @@ export function themeFromColors(bg: string, text: string, accent: string, extra:
|
|||
const dark = relativeLuminance(bg) < relativeLuminance(text);
|
||||
const colors: ResolvedColors = {
|
||||
bg, text, accent,
|
||||
surface: mixHex(bg, text, dark ? 0.05 : 0.03),
|
||||
elevated: mixHex(bg, text, dark ? 0.1 : 0.07),
|
||||
border: mixHex(bg, text, dark ? 0.2 : 0.15),
|
||||
muted: mixHex(bg, text, 0.62),
|
||||
surface: mix(bg, text, dark ? 0.05 : 0.03),
|
||||
elevated: mix(bg, text, dark ? 0.1 : 0.07),
|
||||
border: mix(bg, text, dark ? 0.2 : 0.15),
|
||||
muted: mix(bg, text, 0.62),
|
||||
onAccent: readableOn(accent),
|
||||
inverse: text,
|
||||
onInverse: bg,
|
||||
|
|
|
|||
79
packages/runtime/src/themeChoice.ts
Normal file
79
packages/runtime/src/themeChoice.ts
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
// The owner's theme choice: which theme document is on (a built-in one or an imported one), the
|
||||
// panel's customizations on top of it and an accent override. Native code persists it and hands it
|
||||
// to every site tab; the shell's theme store and the panel edit it. A site brings its built-in
|
||||
// themes (`createThemeCatalog(builtins)`; the first one is the site's own look, the default). Pure.
|
||||
|
||||
import { applyOverrides, isHex, sanitizeSpec, type Palette, type ThemeOverrides, type ThemeSpec } from './themeSpec.ts';
|
||||
|
||||
/** What is persisted natively and handed to the page runtime. */
|
||||
export type ThemeChoice = { preset: string; accent: string | null; overrides: ThemeOverrides; themes: ThemeSpec[] };
|
||||
|
||||
/** Imported themes kept in a choice (the JSON Schema of the native side says the same). */
|
||||
export const MAX_USER_THEMES = 24;
|
||||
const OVERRIDE_GROUPS = ['colors', 'font', 'shape', 'layout', 'background', 'effects', 'css'] as const;
|
||||
|
||||
export type ThemeCatalog = {
|
||||
/** The site's built-in themes; the first is its own look (and the default choice). */
|
||||
builtins: readonly ThemeSpec[];
|
||||
/** Nothing chosen: the first built-in theme, no customizations. */
|
||||
defaultChoice: ThemeChoice;
|
||||
/** Any JSON to a valid choice (imported themes sanitized, bounded and deduplicated; unknown ids fall back). */
|
||||
normalize(input: unknown): ThemeChoice;
|
||||
/** The theme document a choice refers to (built-in or imported), before overrides. */
|
||||
base(choice: ThemeChoice): ThemeSpec;
|
||||
/** The effective theme: the selected document with the panel's overrides and accent, legible. */
|
||||
resolve(choice: ThemeChoice): ThemeSpec;
|
||||
/** The effective palette: the theme's colors (or none for the site's own) with the accent override applied. */
|
||||
palette(choice: ThemeChoice): Partial<Palette> | null;
|
||||
/** Every theme that can be picked: the built-in ones, then the choice's imported ones. */
|
||||
all(choice: ThemeChoice): ThemeSpec[];
|
||||
};
|
||||
|
||||
export function createThemeCatalog(builtins: readonly ThemeSpec[]): ThemeCatalog {
|
||||
if (!builtins.length) throw new Error('wayBetter themes: a site needs at least one built-in theme (its own look)');
|
||||
const first = builtins[0]!;
|
||||
const defaultChoice: ThemeChoice = { preset: first.id, accent: null, overrides: {}, themes: [] };
|
||||
const isBuiltin = (id: unknown) => builtins.some(item => item.id === id);
|
||||
|
||||
function normalize(input: unknown): ThemeChoice {
|
||||
const source = input && typeof input === 'object' ? input as Record<string, unknown> : {};
|
||||
const themes: ThemeSpec[] = [];
|
||||
if (Array.isArray(source.themes)) {
|
||||
for (const raw of source.themes.slice(0, MAX_USER_THEMES)) {
|
||||
const theme = sanitizeSpec(raw);
|
||||
if (!isBuiltin(theme.id) && !themes.some(item => item.id === theme.id)) themes.push(theme);
|
||||
}
|
||||
}
|
||||
const known = (id: unknown) => typeof id === 'string' && (isBuiltin(id) || themes.some(item => item.id === id));
|
||||
const preset = known(source.preset) ? source.preset as string : first.id;
|
||||
const accent = isHex(source.accent) ? source.accent.toLowerCase() : null;
|
||||
const overrides: ThemeOverrides = {};
|
||||
const rawOverrides = source.overrides && typeof source.overrides === 'object' ? source.overrides as Record<string, unknown> : {};
|
||||
for (const key of OVERRIDE_GROUPS) {
|
||||
const value = rawOverrides[key];
|
||||
if (value && typeof value === 'object' && !Array.isArray(value)) (overrides as Record<string, unknown>)[key] = value;
|
||||
}
|
||||
return { preset, accent, overrides, themes };
|
||||
}
|
||||
|
||||
const base = (choice: ThemeChoice) => choice.themes.find(item => item.id === choice.preset) ?? builtins.find(item => item.id === choice.preset) ?? first;
|
||||
const resolve = (choice: ThemeChoice) => applyOverrides(base(choice), choice.overrides, choice.accent);
|
||||
function palette(choice: ThemeChoice): Partial<Palette> | null {
|
||||
const theme = resolve(choice);
|
||||
if (theme.colors) return theme.colors;
|
||||
return choice.accent ? { accent: choice.accent } : null;
|
||||
}
|
||||
const all = (choice: ThemeChoice) => [...builtins, ...choice.themes];
|
||||
return { builtins, defaultChoice, normalize, base, resolve, palette, all };
|
||||
}
|
||||
|
||||
/** The choice a tab's theme id stands for (themeScopes: account and pane themes): the global choice itself, or that theme without customizations. */
|
||||
export function choiceForId(global: ThemeChoice, id: string): ThemeChoice {
|
||||
return id === global.preset ? global : { preset: id, accent: null, overrides: {}, themes: global.themes };
|
||||
}
|
||||
|
||||
/** The shape persisted natively: empty groups are dropped so "no override" stays unambiguous. */
|
||||
export function serializeChoice(choice: ThemeChoice) {
|
||||
const overrides = Object.fromEntries(Object.entries(choice.overrides).filter(([, value]) => value && Object.keys(value).length));
|
||||
return { preset: choice.preset, accent: choice.accent, ...(Object.keys(overrides).length ? { overrides } : {}), ...(choice.themes.length ? { themes: choice.themes } : {}) };
|
||||
}
|
||||
243
packages/runtime/src/themeRuntime.ts
Normal file
243
packages/runtime/src/themeRuntime.ts
Normal file
|
|
@ -0,0 +1,243 @@
|
|||
// The theme engine in a site's page: keeps one `<style>` with the theme's CSS in sync while the site
|
||||
// adds its own rules (React apps insert them lazily), exposes the resolved theme as `--wb-*` custom
|
||||
// properties for plugins and the UI kit, follows the site's own color mode, and paints the last
|
||||
// theme from the page's first frame (a snapshot in the page's storage). What the CSS is comes from
|
||||
// the site adapter (`ThemeRuntimeSite`): X re-declares its own stylesheet rules with the theme's
|
||||
// colors (`buildThemeCss`) and adds type/shape/layout rules over its selectors.
|
||||
|
||||
import { FONT_ROLE_NAMES, themeKey, themeVarsCss, type ResolvedFonts, type ResolvedTheme } from './themeApi.ts';
|
||||
import type { ThemeCatalog, ThemeChoice } from './themeChoice.ts';
|
||||
import { bundledFontsUsed, isNeutral, resolveFontRoles, type FontSpec, type ThemeSpec } from './themeSpec.ts';
|
||||
|
||||
/** A style rule as the engine reads it (CSSStyleRule, or a plain object in tests). */
|
||||
export type RuleLike = { selectorText: string; style: { getPropertyValue(name: string): string; length?: number } };
|
||||
|
||||
/** The font roles as the plugin API reports them in a site's page; an inheriting interface uses `siteStack` (the site's own font). */
|
||||
export function resolvedFonts(font: FontSpec, siteStack: string): ResolvedFonts {
|
||||
const roles = resolveFontRoles(font, siteStack);
|
||||
return Object.fromEntries(FONT_ROLE_NAMES.map(role => {
|
||||
const { stack, weight, size, tracking, tabular, inherited } = roles[role];
|
||||
return [role, { stack, weight, size, tracking, tabular, inherited }];
|
||||
})) as ResolvedFonts;
|
||||
}
|
||||
|
||||
/** Every style rule of `doc`'s stylesheets (inside media/supports groups too), except `own`'s. */
|
||||
export function collectRules(doc: Document, own: HTMLStyleElement | null): RuleLike[] {
|
||||
const rules: RuleLike[] = [];
|
||||
const walk = (list: CSSRuleList) => {
|
||||
for (const rule of Array.from(list)) {
|
||||
if ('selectorText' in rule && 'style' in rule) rules.push(rule as unknown as RuleLike);
|
||||
else if ('cssRules' in rule && !('selectorText' in rule)) walk((rule as CSSGroupingRule).cssRules);
|
||||
}
|
||||
};
|
||||
for (const sheet of Array.from(doc.styleSheets)) {
|
||||
if (own && sheet.ownerNode === own) continue;
|
||||
try { walk(sheet.cssRules); } catch { /* Cross-origin sheet. */ }
|
||||
}
|
||||
return rules;
|
||||
}
|
||||
|
||||
function ruleCount(doc: Document): number {
|
||||
let count = 0;
|
||||
for (const sheet of Array.from(doc.styleSheets)) { try { count += sheet.cssRules.length; } catch { /* Cross-origin. */ } }
|
||||
return count;
|
||||
}
|
||||
|
||||
/**
|
||||
* The last theme CSS a tab showed, kept in the page's own storage so the next document paints it
|
||||
* from its first frame: native code only hands the theme over once the page has finished loading,
|
||||
* and the live CSS needs the site's rules, which it inserts while it renders. sessionStorage is per
|
||||
* tab and survives reloads and navigations; localStorage (smaller cap: the site uses it too) is per
|
||||
* account and covers a tab's first document.
|
||||
*/
|
||||
export type ThemeSnapshot = { key: string; choice: unknown; css: string };
|
||||
const SNAPSHOT_KEY = 'wb:theme-snapshot';
|
||||
export const SNAPSHOT_SESSION_MAX = 1_000_000;
|
||||
export const SNAPSHOT_LOCAL_MAX = 200_000;
|
||||
export type SnapshotStores = { session?: Storage | null; local?: Storage | null };
|
||||
|
||||
function stores(win: Window): SnapshotStores {
|
||||
const get = (name: 'sessionStorage' | 'localStorage') => { try { return win[name]; } catch { return null; } };
|
||||
return { session: get('sessionStorage'), local: get('localStorage') };
|
||||
}
|
||||
|
||||
export function readSnapshot({ session, local }: SnapshotStores): ThemeSnapshot | null {
|
||||
for (const store of [session, local]) {
|
||||
try {
|
||||
const value = JSON.parse(store?.getItem(SNAPSHOT_KEY) || 'null') as Partial<ThemeSnapshot> | null;
|
||||
if (value && typeof value.key === 'string' && typeof value.css === 'string' && value.css && value.choice) return value as ThemeSnapshot;
|
||||
} catch { /* Missing, blocked or foreign data: no snapshot. */ }
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Stores `snapshot` (null clears it: the site's own look needs none), each store within its cap. */
|
||||
export function writeSnapshot({ session, local }: SnapshotStores, snapshot: ThemeSnapshot | null) {
|
||||
const json = snapshot ? JSON.stringify(snapshot) : '';
|
||||
for (const [store, max] of [[session, SNAPSHOT_SESSION_MAX], [local, SNAPSHOT_LOCAL_MAX]] as const) {
|
||||
try {
|
||||
if (json && json.length <= max) store?.setItem(SNAPSHOT_KEY, json);
|
||||
else store?.removeItem(SNAPSHOT_KEY);
|
||||
} catch { /* Quota or blocked storage: the next document just starts unthemed. */ }
|
||||
}
|
||||
}
|
||||
|
||||
/** What the engine needs to know about a site. `Mode` is the site's own color mode (X: light, dim, dark). */
|
||||
export type ThemeRuntimeSite<Mode extends string = string> = {
|
||||
/** The site's built-in themes (themeChoice.ts). */
|
||||
catalog: ThemeCatalog;
|
||||
/** The mode before the page has a body. */
|
||||
initialMode: Mode;
|
||||
/** The site's color mode as the page paints it now (read before the theme's own override: e.g. the body's inline style). */
|
||||
readMode(win: Window): Mode;
|
||||
/** The theme's CSS for the site's current `rules` (the engine's own sheet excluded) in `mode`; `vars` are `siteVars` as the site sets them. */
|
||||
css(rules: RuleLike[], choice: ThemeChoice, mode: Mode, vars: Record<string, string>): string;
|
||||
/** The active theme resolved for plugins and the UI kit (the site's own palette when the theme keeps its colors). */
|
||||
resolved(choice: ThemeChoice, mode: Mode): ResolvedTheme;
|
||||
/** Custom properties of the site's root read with the theme's sheet disabled (their unthemed values). */
|
||||
siteVars?: readonly string[];
|
||||
/** Id of the theme's `<style>` (default `wb-theme-css`). */
|
||||
styleId?: string;
|
||||
/** Name in console errors. */
|
||||
name?: string;
|
||||
};
|
||||
|
||||
export type ThemeHandle<Mode extends string = string> = {
|
||||
apply(choice: unknown): void;
|
||||
current(): ThemeChoice;
|
||||
theme(): ThemeSpec;
|
||||
/** The site's color mode the theme was last rendered for. */
|
||||
mode(): Mode;
|
||||
/** The active theme as values for plugins (`api.theme.current()`). */
|
||||
resolved(): ResolvedTheme;
|
||||
/** Calls `listener` after the theme or the site's color mode changes. */
|
||||
onChange(listener: () => void): () => void;
|
||||
};
|
||||
export type ThemeRuntimeOptions = { /** Registers bundled families (e.g. "Geist") in the page before they are used. */ loadFonts?(names: string[]): void };
|
||||
|
||||
const VARS_ID = 'wb-theme-vars';
|
||||
|
||||
/** Keeps the site's page in the owner's theme (see the top of this file). */
|
||||
export function installThemeRuntime<Mode extends string>(win: Window, site: ThemeRuntimeSite<Mode>, options: ThemeRuntimeOptions = {}): ThemeHandle<Mode> {
|
||||
const doc = win.document;
|
||||
const name = site.name ?? 'wayBetter';
|
||||
const styleId = site.styleId ?? 'wb-theme-css';
|
||||
const { catalog } = site;
|
||||
// Document start (no <html> yet): the snapshot as an adopted sheet paints with the site's first
|
||||
// frame. It stays while the live CSS is for the same theme and site mode, and goes when they differ.
|
||||
const storage = stores(win);
|
||||
const snapshot = readSnapshot(storage);
|
||||
let early: CSSStyleSheet | null = null;
|
||||
if (snapshot) {
|
||||
try {
|
||||
const Sheet = (win as Window & typeof globalThis).CSSStyleSheet;
|
||||
early = new Sheet();
|
||||
early.replaceSync(snapshot.css);
|
||||
doc.adoptedStyleSheets = [...doc.adoptedStyleSheets, early];
|
||||
} catch { early = null; }
|
||||
}
|
||||
const dropEarly = () => {
|
||||
if (!early) return;
|
||||
const sheet = early;
|
||||
early = null;
|
||||
try { doc.adoptedStyleSheets = doc.adoptedStyleSheets.filter(item => item !== sheet); } catch { /* Never break the site. */ }
|
||||
};
|
||||
let savedCss = snapshot?.css ?? '';
|
||||
let choice = catalog.defaultChoice;
|
||||
let theme = catalog.resolve(choice);
|
||||
let lastKey = '';
|
||||
let timer: ReturnType<typeof setInterval> | null = null;
|
||||
const active = () => !isNeutral(theme) || !!choice.accent;
|
||||
let mode: Mode = site.initialMode;
|
||||
let resolved: ResolvedTheme = site.resolved(choice, mode);
|
||||
let resolvedKey = themeKey(resolved);
|
||||
const listeners = new Set<() => void>();
|
||||
const readMode = () => (doc.body ? site.readMode(win) : mode);
|
||||
/** `--wb-*` on :root for plugin CSS, and a change notice when anything visible changed. */
|
||||
const syncResolved = () => {
|
||||
if (doc.body) mode = readMode();
|
||||
resolved = site.resolved(choice, mode);
|
||||
const key = themeKey(resolved);
|
||||
let vars = doc.getElementById(VARS_ID) as HTMLStyleElement | null;
|
||||
if (!vars?.isConnected) {
|
||||
vars = doc.createElement('style');
|
||||
vars.id = VARS_ID;
|
||||
(doc.head || doc.documentElement).appendChild(vars);
|
||||
}
|
||||
const css = themeVarsCss(resolved);
|
||||
if (vars.textContent !== css) vars.textContent = css;
|
||||
if (key === resolvedKey) return;
|
||||
resolvedKey = key;
|
||||
for (const listener of [...listeners]) {
|
||||
try { listener(); } catch (error) { console.error(`[${name}] theme listener failed`, error); }
|
||||
}
|
||||
};
|
||||
let modeObserver: MutationObserver | null = null;
|
||||
const watchMode = () => {
|
||||
if (modeObserver || !doc.body) return;
|
||||
// Sites repaint the body when their own display setting changes (X: Default / Dim / Lights out).
|
||||
const Observer = (win as Window & typeof globalThis).MutationObserver ?? globalThis.MutationObserver;
|
||||
if (!Observer) return;
|
||||
modeObserver = new Observer(() => { try { if (readMode() !== mode) syncResolved(); } catch { /* Never break the site. */ } });
|
||||
modeObserver.observe(doc.body, { attributes: true, attributeFilter: ['style'] });
|
||||
};
|
||||
|
||||
const render = (force = false) => {
|
||||
let style = doc.getElementById(styleId) as HTMLStyleElement | null;
|
||||
if (doc.body) { watchMode(); syncResolved(); }
|
||||
if (!active()) { style?.remove(); lastKey = ''; dropEarly(); if (savedCss) { savedCss = ''; writeSnapshot(storage, null); } return; }
|
||||
if (!doc.body) return;
|
||||
const snapshotKey = `${JSON.stringify(choice)}|${mode}`;
|
||||
if (early && snapshot?.key !== snapshotKey) dropEarly();
|
||||
const key = `${JSON.stringify(choice)}|${mode}|${ruleCount(doc) - (style?.sheet?.cssRules.length ?? 0)}`;
|
||||
if (!force && key === lastKey) return;
|
||||
lastKey = key;
|
||||
if (!style) { style = doc.createElement('style'); style.id = styleId; }
|
||||
// The site's own values, not the ones our previous render overrode (switching themes re-reads them).
|
||||
if (style.sheet) style.sheet.disabled = true;
|
||||
const vars: Record<string, string> = {};
|
||||
if (site.siteVars?.length) {
|
||||
const rootStyle = win.getComputedStyle(doc.documentElement);
|
||||
for (const name of site.siteVars) vars[name] = rootStyle.getPropertyValue(name).trim();
|
||||
}
|
||||
if (style.sheet) style.sheet.disabled = false;
|
||||
const css = site.css(collectRules(doc, style), choice, mode, vars);
|
||||
if (style.textContent !== css) style.textContent = css;
|
||||
// Last in <head> so equal-specificity `!important` rules win over the site's.
|
||||
if (style.parentNode !== doc.head || doc.head.lastElementChild !== style) (doc.head || doc.documentElement).appendChild(style);
|
||||
const full = `${themeVarsCss(resolved)}\n${css}`;
|
||||
if (full !== savedCss) { savedCss = full; writeSnapshot(storage, { key: snapshotKey, choice, css: full }); }
|
||||
};
|
||||
|
||||
const handle: ThemeHandle<Mode> = {
|
||||
apply(input) {
|
||||
choice = catalog.normalize(input);
|
||||
theme = catalog.resolve(choice);
|
||||
const fonts = bundledFontsUsed(theme);
|
||||
if (fonts.length) { try { options.loadFonts?.(fonts); } catch (error) { console.error(`[${name}] theme fonts failed`, error); } }
|
||||
if (active()) {
|
||||
if (!timer) timer = setInterval(() => { try { render(); } catch { /* Never break the site. */ } }, 1200);
|
||||
} else if (timer) { clearInterval(timer); timer = null; }
|
||||
try { render(true); } catch (error) { console.error(`[${name}] theme failed`, error); }
|
||||
win.dispatchEvent(new CustomEvent('wb-theme'));
|
||||
},
|
||||
current: () => choice,
|
||||
theme: () => theme,
|
||||
mode: () => mode,
|
||||
resolved: () => {
|
||||
if (doc.body && readMode() !== mode) syncResolved();
|
||||
return resolved;
|
||||
},
|
||||
onChange(listener) {
|
||||
listeners.add(listener);
|
||||
return () => { listeners.delete(listener); };
|
||||
},
|
||||
};
|
||||
// The snapshot's theme until native code hands over the current one (usually the same): the
|
||||
// live CSS then already renders at DOMContentLoaded instead of after the page finished loading.
|
||||
if (snapshot) { try { handle.apply(snapshot.choice); } catch { /* Never break the site. */ } }
|
||||
if (doc.readyState === 'loading') doc.addEventListener('DOMContentLoaded', () => render(true), { once: true });
|
||||
// `--wb-*` exist from the start (the site's own palette until a theme is applied), for plugins and the UI kit.
|
||||
else if (doc.body) { try { watchMode(); syncResolved(); } catch { /* Never break the site. */ } }
|
||||
return handle;
|
||||
}
|
||||
521
packages/runtime/src/themeSpec.ts
Normal file
521
packages/runtime/src/themeSpec.ts
Normal file
|
|
@ -0,0 +1,521 @@
|
|||
// 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<Role, string> & Partial<Record<ButtonRole, string>>;
|
||||
/** `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<FontRoleName, FontRole>;
|
||||
|
||||
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<ThemeColors>;
|
||||
/** `roles` is merged role by role (a named role replaces that role only). */
|
||||
font?: Partial<Omit<FontSpec, 'roles'>> & { roles?: Partial<FontRoles> };
|
||||
shape?: Partial<ShapeSpec>;
|
||||
layout?: Partial<LayoutSpec>;
|
||||
background?: Background;
|
||||
effects?: Partial<EffectsSpec>;
|
||||
/** 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, 'roles'>): 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<T extends Palette & { page?: string }>(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<string, unknown> => value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
||||
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 = <T extends string>(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<FontRoleSpec>).source;
|
||||
delete (rest as Partial<FontRoleSpec>).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.<name>` 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<string, unknown>, 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<string, string> = { '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<string>();
|
||||
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<FontRoleName, ResolvedFontRole>;
|
||||
|
||||
/**
|
||||
* 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 `<html>` and `<body>` are often one viewport tall while the
|
||||
* content overflows them (X's timeline), so a background painted on both had `<body>` paint its own
|
||||
* copy over its box, which scrolls away: after a partial scroll the gradient/glow showed only below a hard seam. Now
|
||||
* `<html>` holds the plain page color, `<body>` 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 `<body>`) 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(`<svg xmlns="http://www.w3.org/2000/svg" width="${s}" height="${s}"><filter id="n"><feTurbulence type="fractalNoise" baseFrequency=".85" numOctaves="3" stitchTiles="stitch"/><feColorMatrix values="0 0 0 0 ${hexToRgb(ink).map(v => (v / 255).toFixed(3)).join(' 0 0 0 0 ')} 0 0 0 ${(a * 2.2).toFixed(3)} 0"/></filter><rect width="100%" height="100%" filter="url(#n)"/></svg>`)} 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;
|
||||
}
|
||||
}
|
||||
|
|
@ -9,11 +9,7 @@
|
|||
// Pure: runs in the page runtime, the settings previews and the tests. The site adapter supplies the
|
||||
// source palettes (`SourceAxis`, one per site mode); e.g. X's Default/Dim/Lights out.
|
||||
|
||||
/** `#rrggbb` → [r, g, b] (local, so themeSpec.ts can import this module without a cycle). */
|
||||
function hexToRgb(hex: string): Rgb {
|
||||
const n = parseInt(hex.slice(1, 7), 16);
|
||||
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
|
||||
}
|
||||
import { hexToRgb } from './themeApi.ts';
|
||||
|
||||
export type Oklab = [number, number, number];
|
||||
type Rgb = [number, number, number];
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue