Theme engine v2, the document side: component tokens, layout variants, decoration, icon packs
A theme may now say how each piece of a site is built, not only one radius and one density: - components (themeComponents.ts): 36 generic parts with clamped tokens (radius, border incl. 98.css-style bevels, fill by color role / glass / gradient, padding, sizes, type, shadow, shape, hover/active/focus), presets and parents; compiled over a site's part map as soft values (--wb-part-*) and rigid rules; text on a chosen fill keeps its contrast. - variants (themeVariants.ts): fixed words on six axes; the owner holds an axis or switches layout changes off; the look of a variant is the site's skin. - decoration (themeDecor.ts): dividers, chrome (title bar, masthead, prompt), a focus ring that is always visible, selection, scrollbars, links, motion under reduced-motion. - icon packs (themeIcons.ts): a standalone document of glyphs by semantic name (path data, colored layers or a small PNG, never an SVG document), with license, source and credits; a theme only names a pack; the owner's icon choice is separate; drawn as CSS masks of the current color over the site's own svg boxes, behind forced-colors and mask-support guards, per group. - a theme document gains the optional groups components, variants, decor, icons and colors.actions; a theme without them is sanitized to exactly what it was. - theme.schema.json and the new icons.schema.json are generated from the same tables (scripts/theme-schema.mjs; a test fails when they are stale).
This commit is contained in:
parent
a172d79d4a
commit
a8d4fc9d55
12 changed files with 6689 additions and 88 deletions
|
|
@ -10,7 +10,7 @@ export type ThemeChoice = { preset: string; accent: string | null; overrides: Th
|
||||||
|
|
||||||
/** Imported themes kept in a choice (the JSON Schema of the native side says the same). */
|
/** Imported themes kept in a choice (the JSON Schema of the native side says the same). */
|
||||||
export const MAX_USER_THEMES = 24;
|
export const MAX_USER_THEMES = 24;
|
||||||
const OVERRIDE_GROUPS = ['colors', 'font', 'shape', 'layout', 'background', 'effects', 'css'] as const;
|
const OVERRIDE_GROUPS = ['colors', 'font', 'shape', 'layout', 'background', 'effects', 'css', 'variants'] as const;
|
||||||
|
|
||||||
export type ThemeCatalog = {
|
export type ThemeCatalog = {
|
||||||
/** The site's built-in themes; the first is its own look (and the default choice). */
|
/** The site's built-in themes; the first is its own look (and the default choice). */
|
||||||
|
|
|
||||||
472
packages/runtime/src/themeComponents.ts
Normal file
472
packages/runtime/src/themeComponents.ts
Normal file
|
|
@ -0,0 +1,472 @@
|
||||||
|
// Component tokens: the part of a theme that says how each piece of the site is built (a button's
|
||||||
|
// radius and border, a post's padding and fill, the size and case of a handle), instead of one radius
|
||||||
|
// and one density for everything. A theme names generic components (`post`, `buttonPrimary`,
|
||||||
|
// `navItem`); the site adapter says which selectors they are (its part map). Pure.
|
||||||
|
//
|
||||||
|
// Safety is the same as the rest of a theme document: every token is a clamped number, a fixed word
|
||||||
|
// or a color role name. No token carries CSS text, a selector or a color literal, so one contrast
|
||||||
|
// pass over the palette covers every component, and the CSS is built from the vocabulary below.
|
||||||
|
//
|
||||||
|
// How it lands in the page: values are custom properties at zero specificity
|
||||||
|
// (`:where(:root){--wb-part-post-radius:0px}`), rules are rigid (`:root:root <part>{border-radius:
|
||||||
|
// var(--wb-part-post-radius) !important}`). An owner's Custom CSS or a plugin overrides a value by
|
||||||
|
// setting the variable, for the whole page or for one subtree, without fighting `!important`.
|
||||||
|
//
|
||||||
|
// The bevel borders (`bevel-out`, `bevel-in`) follow 98.css's raised and sunken edges (MIT, Jordan
|
||||||
|
// Scales, https://github.com/jdan/98.css): four inset shadows, here computed from the theme's roles.
|
||||||
|
|
||||||
|
import { contrastRatio, hexToRgb, mix, relativeLuminance, type FontRoleName } from './themeApi.ts';
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Vocabulary
|
||||||
|
|
||||||
|
/** Color roles a component may name. `onAccent` is the readable label on the accent. */
|
||||||
|
export const COLOR_ROLES = ['bg', 'surface', 'elevated', 'page', 'border', 'text', 'muted', 'accent', 'onAccent', 'inverse', 'onInverse'] as const;
|
||||||
|
export type ColorRole = typeof COLOR_ROLES[number];
|
||||||
|
export type RoleColors = Record<ColorRole, string>;
|
||||||
|
|
||||||
|
export const BORDER_STYLES = ['none', 'solid', 'dashed', 'dotted', 'double', 'bevel-out', 'bevel-in'] as const;
|
||||||
|
export const SHADOWS = ['none', 'soft', 'deep', 'hard', 'inset', 'glow'] as const;
|
||||||
|
export const CASES = ['none', 'upper', 'lower', 'capitalize', 'small-caps'] as const;
|
||||||
|
export const AVATAR_SHAPES = ['circle', 'rounded', 'square', 'squircle', 'hexagon', 'octagon', 'diamond'] as const;
|
||||||
|
export const CORNERS = ['round', 'cut'] as const;
|
||||||
|
const FONT_ROLES: readonly FontRoleName[] = ['interface', 'post', 'heading', 'numbers', 'mono', 'chrome', 'dialog'];
|
||||||
|
|
||||||
|
export type Gradient = { from: ColorRole; to: ColorRole; angle: number };
|
||||||
|
export type Fill = ColorRole | 'transparent' | 'glass' | Gradient;
|
||||||
|
export type StateTokens = { fill?: Fill; text?: ColorRole; borderColor?: ColorRole; shadow?: typeof SHADOWS[number]; lift?: number; scale?: number; underline?: boolean };
|
||||||
|
export type ComponentTokens = {
|
||||||
|
preset?: string;
|
||||||
|
radius?: number | 'pill';
|
||||||
|
borderWidth?: number;
|
||||||
|
borderStyle?: typeof BORDER_STYLES[number];
|
||||||
|
borderColor?: ColorRole;
|
||||||
|
fill?: Fill;
|
||||||
|
text?: ColorRole;
|
||||||
|
padX?: number;
|
||||||
|
padY?: number;
|
||||||
|
gap?: number;
|
||||||
|
height?: number;
|
||||||
|
width?: number;
|
||||||
|
size?: number;
|
||||||
|
maxHeight?: number;
|
||||||
|
font?: FontRoleName;
|
||||||
|
fontSize?: number;
|
||||||
|
weight?: number;
|
||||||
|
case?: typeof CASES[number];
|
||||||
|
tracking?: number;
|
||||||
|
leading?: number;
|
||||||
|
shadow?: typeof SHADOWS[number];
|
||||||
|
shape?: typeof AVATAR_SHAPES[number];
|
||||||
|
corner?: typeof CORNERS[number];
|
||||||
|
visible?: boolean;
|
||||||
|
hover?: StateTokens;
|
||||||
|
active?: StateTokens;
|
||||||
|
focus?: StateTokens;
|
||||||
|
};
|
||||||
|
|
||||||
|
type ComponentDef = {
|
||||||
|
/** Tokens set on the parent apply to this component too. */
|
||||||
|
parent?: string;
|
||||||
|
/** A text part: type tokens land on its leaves. */
|
||||||
|
text?: boolean;
|
||||||
|
/** Size ranges in px (absent: the token is not accepted on this component). */
|
||||||
|
height?: [number, number]; width?: [number, number]; size?: [number, number]; maxHeight?: [number, number]; fontSize?: [number, number];
|
||||||
|
/** Tokens only some components take. */
|
||||||
|
shape?: boolean; corner?: boolean; visible?: boolean;
|
||||||
|
/** Glass fills (a blur) are allowed here; never on parts that repeat down a timeline. */
|
||||||
|
glass?: boolean;
|
||||||
|
/** Gradient fills are allowed here (bars and buttons). */
|
||||||
|
gradient?: boolean;
|
||||||
|
/** Presets of this component's family. */
|
||||||
|
presets?: keyof typeof PRESETS;
|
||||||
|
/** Contrast its text must reach on its own fill. */
|
||||||
|
contrast?: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
const LABEL: [number, number] = [12, 20];
|
||||||
|
const SMALL: [number, number] = [11, 18];
|
||||||
|
/** Every component a theme can name. Sites map them to selectors; a component a site does not have is ignored. */
|
||||||
|
export const COMPONENTS = {
|
||||||
|
nav: { width: [56, 320], glass: true, gradient: true },
|
||||||
|
navItem: { height: [36, 64], fontSize: LABEL, text: true },
|
||||||
|
topBar: { height: [40, 64], glass: true, gradient: true, fontSize: LABEL },
|
||||||
|
tabs: { presets: 'tabs', gradient: true },
|
||||||
|
tab: { height: [32, 56], fontSize: LABEL, text: true, presets: 'tabs' },
|
||||||
|
post: { corner: true, presets: 'post', contrast: 7 },
|
||||||
|
avatar: { size: [20, 64], shape: true, visible: true },
|
||||||
|
displayName: { text: true, fontSize: LABEL, visible: true },
|
||||||
|
handle: { text: true, fontSize: SMALL, visible: true },
|
||||||
|
postText: { text: true, fontSize: [13, 24], contrast: 7 },
|
||||||
|
meta: { text: true, fontSize: SMALL },
|
||||||
|
actionBar: {},
|
||||||
|
action: { size: [28, 44] },
|
||||||
|
count: { text: true, fontSize: SMALL, visible: true },
|
||||||
|
media: { corner: true, maxHeight: [200, 700] },
|
||||||
|
linkCard: { corner: true },
|
||||||
|
quote: {},
|
||||||
|
button: { height: [24, 56], fontSize: LABEL, text: true, gradient: true, presets: 'button' },
|
||||||
|
buttonPrimary: { parent: 'button', height: [24, 56], fontSize: LABEL, text: true, gradient: true, presets: 'button' },
|
||||||
|
buttonSecondary: { parent: 'button', height: [24, 56], fontSize: LABEL, text: true, gradient: true, presets: 'button' },
|
||||||
|
buttonGhost: { parent: 'button', height: [24, 56], fontSize: LABEL, text: true, gradient: true, presets: 'button' },
|
||||||
|
input: { height: [32, 56], fontSize: LABEL, text: true, presets: 'input' },
|
||||||
|
search: { height: [32, 56], fontSize: LABEL, text: true, presets: 'input' },
|
||||||
|
composer: { fontSize: [13, 24], text: true },
|
||||||
|
/** The tool icons under a composer (media, poll, emoji); `text` is their color. */
|
||||||
|
composerTool: { size: [28, 44] },
|
||||||
|
panel: { glass: true, presets: 'panel' },
|
||||||
|
menu: { parent: 'panel', glass: true, presets: 'panel' },
|
||||||
|
dialog: { parent: 'panel', glass: true, presets: 'panel' },
|
||||||
|
toast: { parent: 'panel', glass: true, presets: 'panel' },
|
||||||
|
hoverCard: { parent: 'panel', glass: true, presets: 'panel' },
|
||||||
|
sidebarCard: { parent: 'panel', glass: true, corner: true, presets: 'panel' },
|
||||||
|
badge: { size: [14, 24], corner: true, fontSize: SMALL, text: true },
|
||||||
|
pill: { fontSize: SMALL, text: true },
|
||||||
|
divider: {},
|
||||||
|
scrollbar: {},
|
||||||
|
profileHeader: {},
|
||||||
|
} as const satisfies Record<string, ComponentDef>;
|
||||||
|
export type ComponentId = keyof typeof COMPONENTS;
|
||||||
|
export const COMPONENT_IDS = Object.keys(COMPONENTS) as ComponentId[];
|
||||||
|
export type ThemeComponents = Partial<Record<ComponentId, ComponentTokens>>;
|
||||||
|
|
||||||
|
/** Clamp ranges of the tokens every component shares (the JSON Schema says the same; tested). */
|
||||||
|
export const TOKEN_LIMITS = {
|
||||||
|
radius: [0, 32], borderWidth: [0, 4], padX: [0, 32], padY: [0, 32], gap: [0, 24], weight: [100, 900],
|
||||||
|
tracking: [-0.05, 0.2], leading: [1.1, 2], angle: [0, 360], lift: [0, 4], scale: [0.96, 1.04],
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
/** Named token bundles per family; a theme's own tokens win over its preset's. Frozen once shipped. */
|
||||||
|
export const PRESETS = {
|
||||||
|
button: {
|
||||||
|
pill: { radius: 'pill', borderWidth: 0 },
|
||||||
|
soft: { radius: 8, borderWidth: 0 },
|
||||||
|
square: { radius: 0, borderWidth: 1, borderStyle: 'solid' },
|
||||||
|
outline: { radius: 6, borderWidth: 1, borderStyle: 'solid', fill: 'transparent', text: 'text', borderColor: 'border' },
|
||||||
|
bevel: { radius: 0, borderStyle: 'bevel-out', fill: 'surface', text: 'text', active: { shadow: 'inset' } },
|
||||||
|
gloss: { radius: 'pill', borderWidth: 1, borderStyle: 'solid', shadow: 'soft' },
|
||||||
|
'flat-link': { radius: 0, borderWidth: 0, fill: 'transparent', text: 'accent', hover: { underline: true } },
|
||||||
|
},
|
||||||
|
post: {
|
||||||
|
flat: { radius: 0, borderWidth: 0, fill: 'transparent', shadow: 'none' },
|
||||||
|
card: { radius: 14, borderWidth: 1, borderStyle: 'solid', borderColor: 'border', fill: 'surface' },
|
||||||
|
bubble: { radius: 20, borderWidth: 0, fill: 'surface' },
|
||||||
|
window: { radius: 0, borderStyle: 'bevel-out', fill: 'surface' },
|
||||||
|
ruled: { radius: 0, borderWidth: 0, fill: 'transparent' },
|
||||||
|
},
|
||||||
|
input: {
|
||||||
|
pill: { radius: 'pill', borderWidth: 1, borderStyle: 'solid', borderColor: 'border' },
|
||||||
|
underline: { radius: 0, borderWidth: 0, fill: 'transparent' },
|
||||||
|
sunken: { radius: 0, borderStyle: 'bevel-in', fill: 'bg', text: 'text' },
|
||||||
|
boxed: { radius: 4, borderWidth: 1, borderStyle: 'solid', borderColor: 'border', fill: 'bg' },
|
||||||
|
},
|
||||||
|
panel: {
|
||||||
|
sheet: { radius: 12, borderWidth: 1, borderStyle: 'solid', borderColor: 'border', fill: 'surface', shadow: 'soft' },
|
||||||
|
window: { radius: 0, borderStyle: 'bevel-out', fill: 'surface', shadow: 'none' },
|
||||||
|
glass: { radius: 16, borderWidth: 1, borderStyle: 'solid', borderColor: 'border', fill: 'glass', shadow: 'soft' },
|
||||||
|
},
|
||||||
|
tabs: {
|
||||||
|
underline: { radius: 0 },
|
||||||
|
pills: { radius: 'pill' },
|
||||||
|
folder: { radius: 6, borderWidth: 1, borderStyle: 'solid', borderColor: 'border' },
|
||||||
|
blocks: { radius: 0, borderWidth: 1, borderStyle: 'solid', borderColor: 'border' },
|
||||||
|
},
|
||||||
|
} as const satisfies Record<string, Record<string, ComponentTokens>>;
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Sanitizing
|
||||||
|
|
||||||
|
const obj = (value: unknown): Record<string, unknown> => value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
||||||
|
const finite = (value: unknown): value is number => typeof value === 'number' && Number.isFinite(value);
|
||||||
|
const clamp = (value: number, [min, max]: readonly [number, number]) => Math.min(max, Math.max(min, value));
|
||||||
|
const oneOf = <T extends string>(value: unknown, options: readonly T[]): T | undefined => options.includes(value as T) ? value as T : undefined;
|
||||||
|
const role = (value: unknown) => oneOf(value, COLOR_ROLES);
|
||||||
|
|
||||||
|
function sanitizeFill(value: unknown, def: ComponentDef): Fill | undefined {
|
||||||
|
if (value === 'transparent') return 'transparent';
|
||||||
|
if (value === 'glass') return def.glass ? 'glass' : undefined;
|
||||||
|
const named = role(value);
|
||||||
|
if (named) return named;
|
||||||
|
const source = obj(value);
|
||||||
|
const from = role(source.from), to = role(source.to);
|
||||||
|
if (def.gradient && from && to) return { from, to, angle: Math.round(clamp(finite(source.angle) ? source.angle : 180, TOKEN_LIMITS.angle)) };
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function sanitizeState(value: unknown, def: ComponentDef): StateTokens | undefined {
|
||||||
|
const source = obj(value);
|
||||||
|
const out: StateTokens = {};
|
||||||
|
const fill = sanitizeFill(source.fill, def); if (fill !== undefined) out.fill = fill;
|
||||||
|
const text = role(source.text); if (text) out.text = text;
|
||||||
|
const borderColor = role(source.borderColor); if (borderColor) out.borderColor = borderColor;
|
||||||
|
const shadow = oneOf(source.shadow, SHADOWS); if (shadow) out.shadow = shadow;
|
||||||
|
if (finite(source.lift)) out.lift = +clamp(source.lift, TOKEN_LIMITS.lift).toFixed(1);
|
||||||
|
if (finite(source.scale)) out.scale = +clamp(source.scale, TOKEN_LIMITS.scale).toFixed(3);
|
||||||
|
if (typeof source.underline === 'boolean') out.underline = source.underline;
|
||||||
|
return Object.keys(out).length ? out : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One component's tokens from JSON: clamped, unknown names and tokens the component does not take dropped. */
|
||||||
|
export function sanitizeComponentTokens(id: ComponentId, value: unknown): ComponentTokens | undefined {
|
||||||
|
const def: ComponentDef = COMPONENTS[id];
|
||||||
|
const source = obj(value);
|
||||||
|
const out: ComponentTokens = {};
|
||||||
|
if (def.presets && typeof source.preset === 'string' && Object.hasOwn(PRESETS[def.presets], source.preset)) out.preset = source.preset;
|
||||||
|
if (source.radius === 'pill') out.radius = 'pill';
|
||||||
|
else if (finite(source.radius)) out.radius = Math.round(clamp(source.radius, TOKEN_LIMITS.radius));
|
||||||
|
if (finite(source.borderWidth)) out.borderWidth = +clamp(source.borderWidth, TOKEN_LIMITS.borderWidth).toFixed(1);
|
||||||
|
const borderStyle = oneOf(source.borderStyle, BORDER_STYLES); if (borderStyle) out.borderStyle = borderStyle;
|
||||||
|
const borderColor = role(source.borderColor); if (borderColor) out.borderColor = borderColor;
|
||||||
|
const fill = sanitizeFill(source.fill, def); if (fill !== undefined) out.fill = fill;
|
||||||
|
const text = role(source.text); if (text) out.text = text;
|
||||||
|
for (const key of ['padX', 'padY', 'gap'] as const) if (finite(source[key])) out[key] = Math.round(clamp(source[key] as number, TOKEN_LIMITS[key]));
|
||||||
|
for (const key of ['height', 'width', 'size', 'maxHeight', 'fontSize'] as const) {
|
||||||
|
const range = def[key];
|
||||||
|
if (range && finite(source[key])) out[key] = Math.round(clamp(source[key] as number, range));
|
||||||
|
}
|
||||||
|
if (def.text || def.fontSize) {
|
||||||
|
const font = oneOf(source.font, FONT_ROLES); if (font) out.font = font;
|
||||||
|
if (finite(source.weight)) out.weight = Math.round(clamp(source.weight, TOKEN_LIMITS.weight) / 50) * 50;
|
||||||
|
const textCase = oneOf(source.case, CASES); if (textCase && id !== 'postText') out.case = textCase;
|
||||||
|
if (finite(source.tracking)) out.tracking = +clamp(source.tracking, TOKEN_LIMITS.tracking).toFixed(3);
|
||||||
|
if (finite(source.leading)) out.leading = +clamp(source.leading, TOKEN_LIMITS.leading).toFixed(2);
|
||||||
|
}
|
||||||
|
const shadow = oneOf(source.shadow, SHADOWS); if (shadow) out.shadow = shadow;
|
||||||
|
if (def.shape) { const shape = oneOf(source.shape, AVATAR_SHAPES); if (shape) out.shape = shape; }
|
||||||
|
if (def.corner) { const corner = oneOf(source.corner, CORNERS); if (corner) out.corner = corner; }
|
||||||
|
if (def.visible && typeof source.visible === 'boolean') out.visible = source.visible;
|
||||||
|
for (const state of ['hover', 'active', 'focus'] as const) { const tokens = sanitizeState(source[state], def); if (tokens) out[state] = tokens; }
|
||||||
|
return Object.keys(out).length ? out : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The `components` group from JSON. Null when nothing valid is left (the theme sets no component). */
|
||||||
|
export function sanitizeComponents(value: unknown): ThemeComponents | null {
|
||||||
|
const source = obj(value);
|
||||||
|
const out: ThemeComponents = {};
|
||||||
|
for (const id of COMPONENT_IDS) {
|
||||||
|
if (!Object.hasOwn(source, id)) continue;
|
||||||
|
const tokens = sanitizeComponentTokens(id, source[id]);
|
||||||
|
if (tokens) out[id] = tokens;
|
||||||
|
}
|
||||||
|
return Object.keys(out).length ? out : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Every component with its preset and its parent's tokens folded in (own tokens win, then the preset, then the parent). */
|
||||||
|
export function resolveComponents(components: ThemeComponents): ThemeComponents {
|
||||||
|
const expand = (id: ComponentId, tokens: ComponentTokens | undefined): ComponentTokens => {
|
||||||
|
if (!tokens) return {};
|
||||||
|
const def: ComponentDef = COMPONENTS[id];
|
||||||
|
const preset = tokens.preset && def.presets ? (PRESETS[def.presets] as Record<string, ComponentTokens>)[tokens.preset] : undefined;
|
||||||
|
const { preset: _name, ...own } = tokens;
|
||||||
|
return { ...preset, ...own };
|
||||||
|
};
|
||||||
|
const out: ThemeComponents = {};
|
||||||
|
for (const id of COMPONENT_IDS) {
|
||||||
|
const def: ComponentDef = COMPONENTS[id];
|
||||||
|
const parent = def.parent as ComponentId | undefined;
|
||||||
|
const inherited = parent ? expand(parent, components[parent]) : {};
|
||||||
|
const merged = { ...inherited, ...expand(id, components[id]) };
|
||||||
|
if (Object.keys(merged).length) out[id] = merged;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Compiling
|
||||||
|
|
||||||
|
/** A site's selectors for one component. */
|
||||||
|
export type PartDef = {
|
||||||
|
/** The component's box. */
|
||||||
|
sel: string;
|
||||||
|
/** Its text leaves (sites often put type on leaf spans); defaults to the box. */
|
||||||
|
text?: string;
|
||||||
|
/** Where a fill is painted when it is not the box itself. */
|
||||||
|
fill?: string;
|
||||||
|
/** Tokens the site cannot honor on this part (left out of the CSS). */
|
||||||
|
skip?: ReadonlyArray<keyof ComponentTokens>;
|
||||||
|
};
|
||||||
|
export type PartMap = Partial<Record<ComponentId, PartDef>>;
|
||||||
|
|
||||||
|
export type ComponentContext = {
|
||||||
|
/** Every role as `#rrggbb` (the theme's palette, legible). */
|
||||||
|
colors: RoleColors;
|
||||||
|
/** `font-family` per font role. */
|
||||||
|
fonts: Record<FontRoleName, string>;
|
||||||
|
};
|
||||||
|
|
||||||
|
const rgba = (hex: string, alpha: number) => `rgba(${hexToRgb(hex).join(', ')}, ${alpha})`;
|
||||||
|
const dark = (hex: string) => relativeLuminance(hex) < 0.18;
|
||||||
|
|
||||||
|
/** The most readable of the theme's text-capable roles on `fill`. */
|
||||||
|
export function readableRole(fill: string, colors: RoleColors, preferred?: ColorRole): ColorRole {
|
||||||
|
const candidates: ColorRole[] = ['text', 'onAccent', 'onInverse', 'bg', 'inverse'];
|
||||||
|
if (preferred && !candidates.includes(preferred)) candidates.unshift(preferred);
|
||||||
|
return candidates.reduce((best, candidate) => contrastRatio(colors[candidate], fill) > contrastRatio(colors[best], fill) ? candidate : best, preferred ?? 'text');
|
||||||
|
}
|
||||||
|
|
||||||
|
function fillCss(fill: Fill, colors: RoleColors): { decl: Array<[string, string]>; solid: string | null } {
|
||||||
|
if (fill === 'transparent') return { decl: [['background-color', 'transparent'], ['background-image', 'none']], solid: null };
|
||||||
|
if (fill === 'glass') return { decl: [['background-color', rgba(colors.surface, 0.72)], ['backdrop-filter', 'blur(14px) saturate(1.4)'], ['-webkit-backdrop-filter', 'blur(14px) saturate(1.4)']], solid: colors.surface };
|
||||||
|
if (typeof fill === 'string') return { decl: [['background-color', colors[fill]], ['background-image', 'none']], solid: colors[fill] };
|
||||||
|
// A gradient is judged at its less readable end: the midpoint stands in for both when choosing a label.
|
||||||
|
return { decl: [['background-color', colors[fill.to]], ['background-image', `linear-gradient(${fill.angle}deg, ${colors[fill.from]}, ${colors[fill.to]})`]], solid: mix(colors[fill.from], colors[fill.to], 0.5) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Raised and sunken edges after 98.css: two light and two dark inset lines, from the part's own fill. */
|
||||||
|
function bevel(out: boolean, face: string): string {
|
||||||
|
const light = mix(face, '#ffffff', 0.85), soft = mix(face, '#ffffff', 0.35), shade = mix(face, '#000000', 0.35), deep = mix(face, '#000000', 0.9);
|
||||||
|
return out
|
||||||
|
? `inset -1px -1px ${deep}, inset 1px 1px ${light}, inset -2px -2px ${shade}, inset 2px 2px ${soft}`
|
||||||
|
: `inset -1px -1px ${light}, inset 1px 1px ${shade}, inset -2px -2px ${soft}, inset 2px 2px ${deep}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function shadowCss(name: typeof SHADOWS[number], colors: RoleColors): string {
|
||||||
|
const base = dark(colors.bg);
|
||||||
|
switch (name) {
|
||||||
|
case 'soft': return base ? `0 1px 2px ${rgba('#000000', 0.4)}, 0 8px 24px ${rgba('#000000', 0.35)}` : `0 1px 2px ${rgba('#000000', 0.06)}, 0 8px 24px ${rgba('#000000', 0.1)}`;
|
||||||
|
case 'deep': return `0 0 0 1px ${rgba(colors.border, 0.6)}, 0 24px 64px ${rgba('#000000', base ? 0.6 : 0.28)}`;
|
||||||
|
case 'hard': return `4px 4px 0 ${colors.accent}`;
|
||||||
|
case 'inset': return `inset 1px 1px 3px ${rgba('#000000', base ? 0.6 : 0.25)}`;
|
||||||
|
case 'glow': return `0 0 0 1px ${rgba(colors.accent, 0.5)}, 0 0 18px ${rgba(colors.accent, 0.35)}`;
|
||||||
|
default: return 'none';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const SHAPES: Record<typeof AVATAR_SHAPES[number], Array<[string, string]>> = {
|
||||||
|
circle: [['border-radius', '50%']],
|
||||||
|
rounded: [['border-radius', '26%']],
|
||||||
|
square: [['border-radius', '2px']],
|
||||||
|
squircle: [['border-radius', '34%']],
|
||||||
|
hexagon: [['border-radius', '0'], ['clip-path', 'polygon(25% 4%, 75% 4%, 100% 50%, 75% 96%, 25% 96%, 0 50%)']],
|
||||||
|
octagon: [['border-radius', '0'], ['clip-path', 'polygon(30% 0, 70% 0, 100% 30%, 100% 70%, 70% 100%, 30% 100%, 0 70%, 0 30%)']],
|
||||||
|
diamond: [['border-radius', '0'], ['clip-path', 'polygon(50% 0, 100% 50%, 50% 100%, 0 50%)']],
|
||||||
|
};
|
||||||
|
const CASE_CSS: Record<typeof CASES[number], Array<[string, string]>> = {
|
||||||
|
none: [['text-transform', 'none'], ['font-variant-caps', 'normal']],
|
||||||
|
upper: [['text-transform', 'uppercase']],
|
||||||
|
lower: [['text-transform', 'lowercase']],
|
||||||
|
capitalize: [['text-transform', 'capitalize']],
|
||||||
|
'small-caps': [['text-transform', 'none'], ['font-variant-caps', 'all-small-caps']],
|
||||||
|
};
|
||||||
|
|
||||||
|
/** A part rule's selector: two `:root`s lift it over the site's atomic classes and inline styles' non-important values. */
|
||||||
|
export const partRule = (selector: string) => selector.split(/,(?![^(]*\))/).map(one => `:root:root ${one.trim()}`).join(',');
|
||||||
|
|
||||||
|
export type CompiledComponents = {
|
||||||
|
/** `--wb-part-*` declarations (for `:where(:root)`). */
|
||||||
|
values: string[];
|
||||||
|
/** Rules that read them. */
|
||||||
|
rules: string[];
|
||||||
|
/** What the contrast pass changed, for import notes and the builder's report. */
|
||||||
|
notes: string[];
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* CSS for a theme's components over a site's part map. A component without a part, and a token the
|
||||||
|
* part skips, emits nothing. Text on a fill the theme chose is held to the component's contrast
|
||||||
|
* (the text role is swapped for the most readable one); sizes stay at or above a 24px target.
|
||||||
|
*/
|
||||||
|
export function compileComponents(components: ThemeComponents, parts: PartMap, ctx: ComponentContext): CompiledComponents {
|
||||||
|
const values: string[] = [], rules: string[] = [], notes: string[] = [];
|
||||||
|
const resolved = resolveComponents(components);
|
||||||
|
for (const id of COMPONENT_IDS) {
|
||||||
|
const tokens = resolved[id], part = parts[id];
|
||||||
|
if (!tokens || !part) continue;
|
||||||
|
const def: ComponentDef = COMPONENTS[id];
|
||||||
|
const skip = new Set<string>(part.skip ?? []);
|
||||||
|
const has = <K extends keyof ComponentTokens>(key: K): boolean => tokens[key] !== undefined && !skip.has(key);
|
||||||
|
const box: string[] = [], type: string[] = [], fillRule: string[] = [];
|
||||||
|
const put = (list: string[], token: string, property: string, value: string) => {
|
||||||
|
const name = `--wb-part-${id}-${token}`;
|
||||||
|
if (!values.some(item => item.startsWith(`${name}:`))) values.push(`${name}:${value}`);
|
||||||
|
list.push(`${property}:var(${name}) !important`);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Fill first: the text role depends on it.
|
||||||
|
let face: string | null = null;
|
||||||
|
if (has('fill')) {
|
||||||
|
const { decl, solid } = fillCss(tokens.fill!, ctx.colors);
|
||||||
|
face = solid;
|
||||||
|
decl.forEach(([property, value], index) => put(part.fill ? fillRule : box, `fill${index ? `-${index}` : ''}`, property, value));
|
||||||
|
}
|
||||||
|
let textRole = has('text') ? tokens.text! : undefined;
|
||||||
|
if (face && (def.text || textRole)) {
|
||||||
|
const need = def.contrast ?? 4.5;
|
||||||
|
if (!textRole || contrastRatio(ctx.colors[textRole], face) < need) {
|
||||||
|
const readable = readableRole(face, ctx.colors, textRole);
|
||||||
|
if (textRole && readable !== textRole) notes.push(`${id}: text "${textRole}" on its fill is under ${need}:1, using "${readable}"`);
|
||||||
|
textRole = readable;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (textRole) put(type, 'text', 'color', ctx.colors[textRole]);
|
||||||
|
|
||||||
|
if (has('radius')) put(box, 'radius', 'border-radius', tokens.radius === 'pill' ? '9999px' : `${tokens.radius}px`);
|
||||||
|
const style = has('borderStyle') ? tokens.borderStyle! : undefined;
|
||||||
|
if (style === 'bevel-out' || style === 'bevel-in') {
|
||||||
|
const base = face ?? ctx.colors.surface;
|
||||||
|
put(box, 'border-style', 'border-style', 'none');
|
||||||
|
put(box, 'bevel', 'box-shadow', bevel(style === 'bevel-out', base));
|
||||||
|
} else {
|
||||||
|
if (style) put(box, 'border-style', 'border-style', style);
|
||||||
|
if (has('borderWidth')) put(box, 'border-width', 'border-width', `${tokens.borderWidth}px`);
|
||||||
|
// A width without a style would draw nothing: X's boxes are `border: 0 solid`.
|
||||||
|
if (has('borderWidth') && !style && tokens.borderWidth! > 0) put(box, 'border-style', 'border-style', 'solid');
|
||||||
|
if (has('shadow')) put(box, 'shadow', 'box-shadow', shadowCss(tokens.shadow!, ctx.colors));
|
||||||
|
}
|
||||||
|
if (has('borderColor')) put(box, 'border-color', 'border-color', ctx.colors[tokens.borderColor!]);
|
||||||
|
if (has('padX')) put(box, 'pad-x', 'padding-inline', `${tokens.padX}px`);
|
||||||
|
if (has('padY')) put(box, 'pad-y', 'padding-block', `${tokens.padY}px`);
|
||||||
|
if (has('gap')) put(box, 'gap', 'gap', `${tokens.gap}px`);
|
||||||
|
if (has('height')) put(box, 'height', 'min-height', `${Math.max(24, tokens.height!)}px`);
|
||||||
|
if (has('width')) put(box, 'width', 'width', `${tokens.width}px`);
|
||||||
|
if (has('size')) { put(box, 'size', 'width', `${tokens.size}px`); box.push(`height:var(--wb-part-${id}-size) !important`); }
|
||||||
|
if (has('maxHeight')) put(box, 'max-height', 'max-height', `${tokens.maxHeight}px`);
|
||||||
|
if (has('shape')) SHAPES[tokens.shape!].forEach(([property, value], index) => put(box, `shape${index ? `-${index}` : ''}`, property, value));
|
||||||
|
if (has('corner') && tokens.corner === 'cut') put(box, 'corner', 'clip-path', 'polygon(0 0, calc(100% - 12px) 0, 100% 12px, 100% 100%, 12px 100%, 0 calc(100% - 12px))');
|
||||||
|
if (has('visible') && tokens.visible === false) put(box, 'display', 'display', 'none');
|
||||||
|
|
||||||
|
if (has('font')) put(type, 'font', 'font-family', ctx.fonts[tokens.font!]);
|
||||||
|
if (has('fontSize')) {
|
||||||
|
put(type, 'font-size', 'font-size', `${tokens.fontSize}px`);
|
||||||
|
put(type, 'line-height', 'line-height', String(tokens.leading ?? 1.3));
|
||||||
|
} else if (has('leading')) put(type, 'line-height', 'line-height', String(tokens.leading));
|
||||||
|
if (has('weight')) put(type, 'weight', 'font-weight', String(tokens.weight));
|
||||||
|
if (has('case')) CASE_CSS[tokens.case!].forEach(([property, value], index) => put(type, `case${index ? `-${index}` : ''}`, property, value));
|
||||||
|
if (has('tracking')) put(type, 'tracking', 'letter-spacing', `${tokens.tracking}em`);
|
||||||
|
|
||||||
|
const textSel = part.text ?? part.sel;
|
||||||
|
if (box.length) rules.push(`${partRule(part.sel)}{${box.join(';')}}`);
|
||||||
|
if (fillRule.length) rules.push(`${partRule(part.fill!)}{${fillRule.join(';')}}`);
|
||||||
|
if (type.length) rules.push(`${partRule(textSel)}{${type.join(';')}}`);
|
||||||
|
|
||||||
|
for (const state of ['hover', 'active', 'focus'] as const) {
|
||||||
|
const tokensOf = tokens[state];
|
||||||
|
if (!tokensOf || skip.has(state)) continue;
|
||||||
|
const pseudo = state === 'focus' ? ':focus-visible' : `:${state}`;
|
||||||
|
const still: string[] = [], moving: string[] = [], label: string[] = [];
|
||||||
|
let stateFace = face;
|
||||||
|
if (tokensOf.fill !== undefined) { const { decl, solid } = fillCss(tokensOf.fill, ctx.colors); stateFace = solid ?? face; for (const [property, value] of decl) still.push(`${property}:${value} !important`); }
|
||||||
|
let stateText = tokensOf.text;
|
||||||
|
if (stateFace && (stateText || tokensOf.fill !== undefined) && (def.text || stateText)) {
|
||||||
|
if (!stateText || contrastRatio(ctx.colors[stateText], stateFace) < (def.contrast ?? 4.5)) stateText = readableRole(stateFace, ctx.colors, stateText);
|
||||||
|
}
|
||||||
|
if (stateText) label.push(`color:${ctx.colors[stateText]} !important`);
|
||||||
|
if (tokensOf.underline !== undefined) label.push(`text-decoration:${tokensOf.underline ? 'underline' : 'none'} !important`);
|
||||||
|
if (tokensOf.borderColor) still.push(`border-color:${ctx.colors[tokensOf.borderColor]} !important`);
|
||||||
|
if (tokensOf.shadow) still.push(`box-shadow:${tokensOf.shadow === 'inset' && (style === 'bevel-out' || style === 'bevel-in') ? bevel(false, face ?? ctx.colors.surface) : shadowCss(tokensOf.shadow, ctx.colors)} !important`);
|
||||||
|
const transforms = [tokensOf.lift ? `translateY(-${tokensOf.lift}px)` : '', tokensOf.scale && tokensOf.scale !== 1 ? `scale(${tokensOf.scale})` : ''].filter(Boolean);
|
||||||
|
if (transforms.length) moving.push(`transform:${transforms.join(' ')} !important`);
|
||||||
|
const stateSel = (selector: string) => selector.split(/,(?![^(]*\))/).map(one => `${one.trim()}${pseudo}`).join(',');
|
||||||
|
if (still.length) rules.push(`${partRule(stateSel(part.sel))}{${still.join(';')}}`);
|
||||||
|
// The label of a hovered or pressed part: the box and the text leaves under it.
|
||||||
|
if (label.length) rules.push(`${partRule(`${stateSel(part.sel)},${part.sel.split(/,(?![^(]*\))/).map(one => `${one.trim()}${pseudo} :is(span,div,a)`).join(',')}`)}{${label.join(';')}}`);
|
||||||
|
// Movement only for people who have not asked for less of it.
|
||||||
|
if (moving.length) rules.push(`@media (prefers-reduced-motion:no-preference){${partRule(stateSel(part.sel))}{${moving.join(';')}}}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { values, rules, notes };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The `colors.actions` group: the colors of an on state (liked, reposted, bookmarked) and of the reply hover. */
|
||||||
|
export const ACTION_NAMES = ['reply', 'repost', 'like', 'bookmark'] as const;
|
||||||
|
export type ActionColors = Partial<Record<typeof ACTION_NAMES[number], string>>;
|
||||||
154
packages/runtime/src/themeDecor.ts
Normal file
154
packages/runtime/src/themeDecor.ts
Normal file
|
|
@ -0,0 +1,154 @@
|
||||||
|
// Decoration: what a theme draws between and around the components: divider lines, a title bar or a
|
||||||
|
// masthead, the focus ring, selection, scrollbars, link underlines, the feel of motion. Fixed words
|
||||||
|
// and clamped numbers, colors by role. Where the lines and bars go is the site's (its decor targets).
|
||||||
|
// Pure.
|
||||||
|
|
||||||
|
import { contrastRatio } from './themeApi.ts';
|
||||||
|
import { COLOR_ROLES, type ColorRole, type RoleColors } from './themeComponents.ts';
|
||||||
|
|
||||||
|
export const DIVIDER_STYLES = ['none', 'hairline', 'solid', 'dashed', 'dotted', 'double'] as const;
|
||||||
|
export const CHROME_KINDS = ['none', 'titlebar', 'masthead', 'prompt'] as const;
|
||||||
|
export const RING_STYLES = ['solid', 'dashed', 'dotted', 'double'] as const;
|
||||||
|
export const MOTION_CURVES = ['standard', 'snappy', 'spring', 'linear', 'steps'] as const;
|
||||||
|
export const LINK_UNDERLINES = ['always', 'hover', 'never'] as const;
|
||||||
|
|
||||||
|
export type ThemeDecor = {
|
||||||
|
dividers?: { style: typeof DIVIDER_STYLES[number]; color?: ColorRole; width?: number };
|
||||||
|
/** A drawn frame around the main column: a window title bar, a newspaper masthead, a terminal prompt. `title` is plain text. */
|
||||||
|
chrome?: { kind: typeof CHROME_KINDS[number]; title?: string };
|
||||||
|
focusRing?: { width?: number; style?: typeof RING_STYLES[number]; color?: ColorRole; offset?: number };
|
||||||
|
selection?: { fill: ColorRole; text: ColorRole };
|
||||||
|
scrollbar?: { width?: 'auto' | 'thin'; thumb?: ColorRole; track?: ColorRole; style?: 'flat' | 'classic' };
|
||||||
|
links?: { underline: typeof LINK_UNDERLINES[number] };
|
||||||
|
motion?: { duration?: number; curve?: typeof MOTION_CURVES[number]; press?: number };
|
||||||
|
};
|
||||||
|
|
||||||
|
const obj = (value: unknown): Record<string, unknown> => value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
||||||
|
const oneOf = <T extends string>(value: unknown, options: readonly T[]): T | undefined => options.includes(value as T) ? value as T : undefined;
|
||||||
|
const num = (value: unknown, min: number, max: number): number | undefined => typeof value === 'number' && Number.isFinite(value) ? Math.min(max, Math.max(min, value)) : undefined;
|
||||||
|
const role = (value: unknown) => oneOf(value, COLOR_ROLES);
|
||||||
|
/** Text a theme may put into a drawn bar: letters, digits, spaces and a little punctuation; it is written into a CSS string. */
|
||||||
|
export const chromeTitle = (value: unknown) => typeof value === 'string' ? value.replace(/[^\p{L}\p{N} .,:!?&+\-_/#@*~()[\]|>$]/gu, '').replace(/&/g, '+').trim().slice(0, 24) : '';
|
||||||
|
|
||||||
|
/** The `decor` group from JSON. Null when nothing valid is left. */
|
||||||
|
export function sanitizeDecor(value: unknown): ThemeDecor | null {
|
||||||
|
const source = obj(value);
|
||||||
|
const out: ThemeDecor = {};
|
||||||
|
const dividers = obj(source.dividers), dividerStyle = oneOf(dividers.style, DIVIDER_STYLES);
|
||||||
|
if (dividerStyle) {
|
||||||
|
const color = role(dividers.color), width = num(dividers.width, 0, 3);
|
||||||
|
out.dividers = { style: dividerStyle, ...(color ? { color } : {}), ...(width !== undefined ? { width: +width.toFixed(1) } : {}) };
|
||||||
|
}
|
||||||
|
const chrome = obj(source.chrome), kind = oneOf(chrome.kind, CHROME_KINDS);
|
||||||
|
if (kind && kind !== 'none') { const title = chromeTitle(chrome.title); out.chrome = { kind, ...(title ? { title } : {}) }; }
|
||||||
|
const ring = obj(source.focusRing);
|
||||||
|
if (Object.keys(ring).length) {
|
||||||
|
const width = num(ring.width, 2, 4), style = oneOf(ring.style, RING_STYLES), color = role(ring.color), offset = num(ring.offset, 0, 4);
|
||||||
|
const focusRing = { ...(width !== undefined ? { width: Math.round(width) } : {}), ...(style ? { style } : {}), ...(color ? { color } : {}), ...(offset !== undefined ? { offset: Math.round(offset) } : {}) };
|
||||||
|
if (Object.keys(focusRing).length) out.focusRing = focusRing;
|
||||||
|
}
|
||||||
|
const selection = obj(source.selection), fill = role(selection.fill), text = role(selection.text);
|
||||||
|
if (fill && text) out.selection = { fill, text };
|
||||||
|
const bar = obj(source.scrollbar);
|
||||||
|
if (Object.keys(bar).length) {
|
||||||
|
const width = oneOf(bar.width, ['auto', 'thin'] as const), thumb = role(bar.thumb), track = role(bar.track), style = oneOf(bar.style, ['flat', 'classic'] as const);
|
||||||
|
const scrollbar = { ...(width ? { width } : {}), ...(thumb ? { thumb } : {}), ...(track ? { track } : {}), ...(style ? { style } : {}) };
|
||||||
|
if (Object.keys(scrollbar).length) out.scrollbar = scrollbar;
|
||||||
|
}
|
||||||
|
const underline = oneOf(obj(source.links).underline, LINK_UNDERLINES);
|
||||||
|
if (underline) out.links = { underline };
|
||||||
|
const motion = obj(source.motion);
|
||||||
|
if (Object.keys(motion).length) {
|
||||||
|
const duration = num(motion.duration, 0, 400), curve = oneOf(motion.curve, MOTION_CURVES), press = num(motion.press, 0.96, 1);
|
||||||
|
const value = { ...(duration !== undefined ? { duration: Math.round(duration) } : {}), ...(curve ? { curve } : {}), ...(press !== undefined ? { press: +press.toFixed(3) } : {}) };
|
||||||
|
if (Object.keys(value).length) out.motion = value;
|
||||||
|
}
|
||||||
|
return Object.keys(out).length ? out : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Where a site's decoration goes. Every entry is optional: a site without it draws nothing for that key. */
|
||||||
|
export type DecorTargets<Context> = {
|
||||||
|
/** Rows whose bottom edge is the divider between items (a site's list cells). */
|
||||||
|
divider?: string;
|
||||||
|
/** Links inside running text. */
|
||||||
|
link?: string;
|
||||||
|
/** What takes keyboard focus. */
|
||||||
|
focusable?: string;
|
||||||
|
/** What moves with `motion` (buttons, links, rows). */
|
||||||
|
moving?: string;
|
||||||
|
/** What a press shrinks. */
|
||||||
|
pressable?: string;
|
||||||
|
/** The scrollable roots. */
|
||||||
|
scroller?: string;
|
||||||
|
/** The site's drawing of each chrome kind. */
|
||||||
|
chrome?: Partial<Record<Exclude<typeof CHROME_KINDS[number], 'none'>, (title: string, ctx: Context) => string>>;
|
||||||
|
};
|
||||||
|
|
||||||
|
const CURVES: Record<typeof MOTION_CURVES[number], string> = {
|
||||||
|
standard: 'cubic-bezier(.2,.7,.2,1)', snappy: 'cubic-bezier(.3,1.4,.5,1)', spring: 'cubic-bezier(.2,1.6,.4,1)', linear: 'linear', steps: 'steps(3,end)',
|
||||||
|
};
|
||||||
|
|
||||||
|
/** The role among `candidates` that reaches `ratio` on every surface, else the most visible one. */
|
||||||
|
function visibleOn(colors: RoleColors, wanted: ColorRole, surfaces: string[], ratio: number): string {
|
||||||
|
const worst = (hex: string) => Math.min(...surfaces.map(surface => contrastRatio(hex, surface)));
|
||||||
|
if (worst(colors[wanted]) >= ratio) return colors[wanted];
|
||||||
|
return (['accent', 'text', 'inverse'] as ColorRole[]).map(name => colors[name]).reduce((best, hex) => worst(hex) > worst(best) ? hex : best, colors[wanted]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* CSS for a theme's decoration. A focus ring is always drawn when the theme names one (at least 2px
|
||||||
|
* and 3:1 on the page's surfaces: the color is swapped for a visible one otherwise); motion only
|
||||||
|
* for people who have not asked for less of it.
|
||||||
|
*/
|
||||||
|
export function compileDecor<Context extends { colors: RoleColors }>(decor: ThemeDecor, targets: DecorTargets<Context>, ctx: Context): string[] {
|
||||||
|
const out: string[] = [];
|
||||||
|
const { colors } = ctx;
|
||||||
|
const surfaces = [colors.bg, colors.surface, colors.page];
|
||||||
|
if (decor.dividers && targets.divider) {
|
||||||
|
const { style, color = 'border', width } = decor.dividers;
|
||||||
|
const line = style === 'none' ? '0 none' : `${style === 'hairline' ? 1 : width ?? (style === 'double' ? 3 : 1)}px ${style === 'hairline' ? 'solid' : style} ${colors[color]}`;
|
||||||
|
out.push(`:root:root :is(${targets.divider}){border-bottom:${line} !important}`);
|
||||||
|
}
|
||||||
|
if (decor.focusRing && targets.focusable) {
|
||||||
|
const { width = 2, style = 'solid', color = 'accent', offset = 2 } = decor.focusRing;
|
||||||
|
out.push(`:root:root :is(${targets.focusable}):focus-visible{outline:${Math.max(2, width)}px ${style} ${visibleOn(colors, color, surfaces, 3)} !important;outline-offset:${offset}px !important}`);
|
||||||
|
}
|
||||||
|
if (decor.selection) {
|
||||||
|
const fill = colors[decor.selection.fill];
|
||||||
|
const text = contrastRatio(colors[decor.selection.text], fill) >= 4.5 ? colors[decor.selection.text] : (contrastRatio('#ffffff', fill) >= contrastRatio('#000000', fill) ? '#ffffff' : '#000000');
|
||||||
|
out.push(`:root:root ::selection{background-color:${fill} !important;color:${text} !important}`);
|
||||||
|
}
|
||||||
|
if (decor.scrollbar) {
|
||||||
|
const { width, thumb = 'border', track, style } = decor.scrollbar;
|
||||||
|
const scroller = targets.scroller ?? 'html,body';
|
||||||
|
const thumbColor = visibleOn(colors, thumb, [track ? colors[track] : colors.page], 1.5);
|
||||||
|
out.push(`:root:root :is(${scroller}){scrollbar-color:${thumbColor} ${track ? colors[track] : 'transparent'} !important${width ? `;scrollbar-width:${width} !important` : ''}}`);
|
||||||
|
// The classic look needs the engine's own scrollbar parts; `scrollbar-color` would switch them off where both are set.
|
||||||
|
if (style === 'classic') {
|
||||||
|
const face = track ? colors[track] : colors.surface;
|
||||||
|
out.push(`@supports selector(::-webkit-scrollbar){:root:root :is(${scroller}){scrollbar-color:auto !important;scrollbar-width:auto !important}:root:root ::-webkit-scrollbar{width:16px;height:16px;background:${face}}:root:root ::-webkit-scrollbar-thumb{background:${colors.surface};box-shadow:inset -1px -1px ${colors.text},inset 1px 1px ${colors.bg},inset -2px -2px ${colors.muted},inset 2px 2px ${colors.elevated}}:root:root ::-webkit-scrollbar-corner{background:${face}}}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (decor.links && targets.link) {
|
||||||
|
const { underline } = decor.links;
|
||||||
|
out.push(`:root:root :is(${targets.link}){text-decoration:${underline === 'always' ? 'underline' : 'none'} !important;text-underline-offset:2px}`);
|
||||||
|
if (underline === 'hover') out.push(`:root:root :is(${targets.link}):hover{text-decoration:underline !important}`);
|
||||||
|
}
|
||||||
|
if (decor.motion && (targets.moving || targets.pressable)) {
|
||||||
|
const { duration, curve = 'standard', press } = decor.motion;
|
||||||
|
const rules: string[] = [];
|
||||||
|
if (duration !== undefined && targets.moving) {
|
||||||
|
rules.push(`:root:root :is(${targets.moving}){transition:background-color ${duration}ms ${CURVES[curve]},color ${duration}ms ${CURVES[curve]},border-color ${duration}ms ${CURVES[curve]},box-shadow ${duration}ms ${CURVES[curve]},transform ${duration}ms ${CURVES[curve]} !important}`);
|
||||||
|
}
|
||||||
|
if (press !== undefined && press < 1 && targets.pressable) rules.push(`:root:root :is(${targets.pressable}):active{transform:scale(${press}) !important}`);
|
||||||
|
if (rules.length) out.push(`@media (prefers-reduced-motion:no-preference){${rules.join('')}}`);
|
||||||
|
}
|
||||||
|
if (decor.chrome) {
|
||||||
|
const css = targets.chrome?.[decor.chrome.kind as Exclude<typeof CHROME_KINDS[number], 'none'>]?.(decor.chrome.title ?? '', ctx);
|
||||||
|
if (css) out.push(css);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A theme's text as a CSS string literal (for `content`): the allow-list of `chromeTitle` plus escaping of what could end the string. */
|
||||||
|
export const cssString = (value: string) => `"${value.replace(/[\\"\n\r\f]/g, match => `\\${match.charCodeAt(0).toString(16)} `)}"`;
|
||||||
296
packages/runtime/src/themeIcons.ts
Normal file
296
packages/runtime/src/themeIcons.ts
Normal file
|
|
@ -0,0 +1,296 @@
|
||||||
|
// Icon packs: a standalone document (`*.icons.json`) of glyphs by semantic name (`home`, `like`,
|
||||||
|
// `reply`), drawn over a site's own icons. A theme only names a pack (a suggestion); the owner's icon
|
||||||
|
// choice is separate ("Follow the theme", a pack, or the site's own icons). Pure.
|
||||||
|
//
|
||||||
|
// A pack is data, never an SVG document: a glyph is path data (checked against a path grammar), a few
|
||||||
|
// colored layers of path data, or a small PNG. The engine builds the SVG itself, so no element,
|
||||||
|
// attribute, script or reference can arrive with a pack.
|
||||||
|
//
|
||||||
|
// Drawing: nothing in the site's DOM is rewritten. The site's own `<svg>` box gets the glyph as a CSS
|
||||||
|
// mask filled with `currentColor` (so the site's color states keep working: a liked heart stays the
|
||||||
|
// like color) and its own paths are made transparent. Colored glyphs (layers, PNG) are a background
|
||||||
|
// image instead. Which `<svg>` is which icon is the site's table (container first, path signature
|
||||||
|
// second). No glyph, no match or no pack: no rule, the site's icon stays.
|
||||||
|
|
||||||
|
import { COLOR_ROLES, type ColorRole, type RoleColors } from './themeComponents.ts';
|
||||||
|
|
||||||
|
/** Semantic names a pack may draw. `.active` is a selected navigation item, `.on` an action that is set. */
|
||||||
|
export const ICON_NAMES = [
|
||||||
|
'home', 'home.active', 'explore', 'explore.active', 'notifications', 'notifications.active', 'messages', 'messages.active',
|
||||||
|
'grok', 'bookmarks', 'bookmarks.active', 'lists', 'communities', 'premium', 'profile', 'profile.active', 'more', 'compose',
|
||||||
|
'reply', 'repost', 'repost.on', 'like', 'like.on', 'views', 'bookmark', 'bookmark.on', 'share',
|
||||||
|
'verified', 'logo', 'caret', 'back', 'close', 'search', 'settings',
|
||||||
|
'media', 'gif', 'poll', 'emoji', 'schedule', 'location', 'pinned', 'repostContext', 'lock',
|
||||||
|
] as const;
|
||||||
|
export type IconName = typeof ICON_NAMES[number];
|
||||||
|
export const ICON_GROUPS = ['nav', 'actions', 'composer', 'misc'] as const;
|
||||||
|
export type IconGroup = typeof ICON_GROUPS[number];
|
||||||
|
|
||||||
|
/** Limits of a pack (the JSON Schema and the Store check say the same). */
|
||||||
|
export const ICON_LIMITS = { names: 64, pathChars: 4000, layers: 6, pngChars: 6000, packBytes: 120_000, labelChars: 12, overrides: 8 } as const;
|
||||||
|
/** Path data only: commands, numbers, separators. */
|
||||||
|
export const PATH_GRAMMAR = /^[MmLlHhVvCcSsQqTtAaZz0-9eE\s,.+-]{1,4000}$/;
|
||||||
|
const PNG_DATA = /^data:image\/png;base64,[A-Za-z0-9+/]+={0,2}$/;
|
||||||
|
const HEX = /^#[0-9a-f]{6}$/i;
|
||||||
|
/** Words a theme or pack may put next to an action: written into CSS strings. */
|
||||||
|
const LABEL_TEXT = /^[\p{L}\p{N} [\]().:+\-_/#@*~!?]{1,12}$/u;
|
||||||
|
|
||||||
|
export type IconFill = ColorRole | string | { from: string; to: string };
|
||||||
|
export type IconGlyph =
|
||||||
|
| { d: string; rule?: 'evenodd'; stroke?: boolean }
|
||||||
|
| { layers: Array<{ d: string; fill: IconFill; opacity?: number; rule?: 'evenodd' }> }
|
||||||
|
| { png: string; pixel?: boolean };
|
||||||
|
export type IconStyle = { stroke: number; cap: 'round' | 'square' | 'butt'; join: 'round' | 'miter' | 'bevel'; scale: number };
|
||||||
|
export const BASE_ICON_STYLE: IconStyle = { stroke: 1.75, cap: 'round', join: 'round', scale: 1 };
|
||||||
|
export const ICON_LABEL_NAMES = ['reply', 'repost', 'like', 'views', 'bookmark', 'share'] as const;
|
||||||
|
export type IconLabels = Partial<Record<typeof ICON_LABEL_NAMES[number], string>>;
|
||||||
|
export type IconSymbols = { like?: 'heart' | 'star' | 'custom'; separator?: 'dot' | 'bullet' | 'slash' | 'dash' | 'pipe' | 'none' };
|
||||||
|
|
||||||
|
export type IconPack = {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
description: string;
|
||||||
|
author: string;
|
||||||
|
/** SPDX id, or `own` for the author's own drawings, or a plain name for artwork under other terms. */
|
||||||
|
license: string;
|
||||||
|
/** Where the drawings come from (a project name or URL as text) and whom to credit. */
|
||||||
|
source: string;
|
||||||
|
credits: string;
|
||||||
|
version: 1;
|
||||||
|
style: IconStyle;
|
||||||
|
glyphs: Partial<Record<IconName, IconGlyph>>;
|
||||||
|
symbols?: IconSymbols;
|
||||||
|
labels?: IconLabels;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** What a theme says about icons: a pack by id, plus small adjustments. Never a whole pack. */
|
||||||
|
export type ThemeIcons = { pack?: string; style?: Partial<IconStyle>; overrides?: Partial<Record<IconName, IconGlyph>>; symbols?: IconSymbols; labels?: IconLabels };
|
||||||
|
|
||||||
|
const obj = (value: unknown): Record<string, unknown> => value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
||||||
|
const plain = (value: unknown, max: number) => typeof value === 'string' ? value.replace(/[\u0000-\u001f\u007f<>]/g, '').trim().slice(0, max) : '';
|
||||||
|
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 path = (value: unknown): value is string => typeof value === 'string' && PATH_GRAMMAR.test(value);
|
||||||
|
|
||||||
|
function sanitizeFill(value: unknown): IconFill | null {
|
||||||
|
if (typeof value === 'string') return (COLOR_ROLES as readonly string[]).includes(value) ? value : HEX.test(value) ? value.toLowerCase() : null;
|
||||||
|
const source = obj(value);
|
||||||
|
return typeof source.from === 'string' && typeof source.to === 'string' && HEX.test(source.from) && HEX.test(source.to) ? { from: source.from.toLowerCase(), to: source.to.toLowerCase() } : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One glyph from JSON, or null when it is not valid path data, layers or a small PNG. */
|
||||||
|
export function sanitizeGlyph(value: unknown): IconGlyph | null {
|
||||||
|
const source = obj(value);
|
||||||
|
if (path(source.d)) return { d: source.d.trim(), ...(source.rule === 'evenodd' ? { rule: 'evenodd' as const } : {}), ...(source.stroke === true ? { stroke: true } : {}) };
|
||||||
|
if (Array.isArray(source.layers)) {
|
||||||
|
const layers = source.layers.slice(0, ICON_LIMITS.layers).flatMap(raw => {
|
||||||
|
const layer = obj(raw), fill = sanitizeFill(layer.fill);
|
||||||
|
if (!path(layer.d) || !fill) return [];
|
||||||
|
return [{ d: layer.d.trim(), fill, ...(typeof layer.opacity === 'number' ? { opacity: +num(layer.opacity, 0, 1, 1).toFixed(2) } : {}), ...(layer.rule === 'evenodd' ? { rule: 'evenodd' as const } : {}) }];
|
||||||
|
});
|
||||||
|
return layers.length ? { layers } : null;
|
||||||
|
}
|
||||||
|
if (typeof source.png === 'string' && source.png.length <= ICON_LIMITS.pngChars + 22 && PNG_DATA.test(source.png)) return { png: source.png, ...(source.pixel === true ? { pixel: true } : {}) };
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const sanitizeIconStyle = (value: unknown, base: IconStyle = BASE_ICON_STYLE): IconStyle => {
|
||||||
|
const source = obj(value);
|
||||||
|
const pick = <T extends string>(item: unknown, options: readonly T[], fallback: T) => options.includes(item as T) ? item as T : fallback;
|
||||||
|
return {
|
||||||
|
stroke: +num(source.stroke, 1, 2.5, base.stroke).toFixed(2), cap: pick(source.cap, ['round', 'square', 'butt'] as const, base.cap),
|
||||||
|
join: pick(source.join, ['round', 'miter', 'bevel'] as const, base.join), scale: +num(source.scale, 0.8, 1.25, base.scale).toFixed(2),
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
function sanitizeGlyphs(value: unknown, max: number): Partial<Record<IconName, IconGlyph>> {
|
||||||
|
const source = obj(value);
|
||||||
|
const out: Partial<Record<IconName, IconGlyph>> = {};
|
||||||
|
let count = 0;
|
||||||
|
for (const name of ICON_NAMES) {
|
||||||
|
if (count >= max || !Object.hasOwn(source, name)) continue;
|
||||||
|
const glyph = sanitizeGlyph(source[name]);
|
||||||
|
if (glyph) { out[name] = glyph; count++; }
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
function sanitizeSymbols(value: unknown): IconSymbols | undefined {
|
||||||
|
const source = obj(value);
|
||||||
|
const out: IconSymbols = {};
|
||||||
|
if (source.like === 'heart' || source.like === 'star' || source.like === 'custom') out.like = source.like;
|
||||||
|
if (['dot', 'bullet', 'slash', 'dash', 'pipe', 'none'].includes(source.separator as string)) out.separator = source.separator as IconSymbols['separator'];
|
||||||
|
return Object.keys(out).length ? out : undefined;
|
||||||
|
}
|
||||||
|
function sanitizeLabels(value: unknown): IconLabels | undefined {
|
||||||
|
const source = obj(value);
|
||||||
|
const out: IconLabels = {};
|
||||||
|
for (const name of ICON_LABEL_NAMES) if (typeof source[name] === 'string' && LABEL_TEXT.test(source[name] as string)) out[name] = (source[name] as string).trim();
|
||||||
|
return Object.keys(out).length ? out : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Any JSON to a valid pack, or null when it has no id, no name or no valid glyph. */
|
||||||
|
export function sanitizeIconPack(input: unknown): IconPack | null {
|
||||||
|
const source = obj(input);
|
||||||
|
const name = plain(source.name, 60);
|
||||||
|
const id = typeof source.id === 'string' && /^[a-z0-9-]{1,40}$/.test(source.id) ? source.id : '';
|
||||||
|
const glyphs = sanitizeGlyphs(source.glyphs, ICON_LIMITS.names);
|
||||||
|
if (!id || !name || !Object.keys(glyphs).length) return null;
|
||||||
|
const symbols = sanitizeSymbols(source.symbols), labels = sanitizeLabels(source.labels);
|
||||||
|
return {
|
||||||
|
id, name, description: plain(source.description, 200), author: plain(source.author, 60), license: plain(source.license, 60) || 'unknown',
|
||||||
|
source: plain(source.source, 200), credits: plain(source.credits, 400), version: 1, style: sanitizeIconStyle(source.style), glyphs,
|
||||||
|
...(symbols ? { symbols } : {}), ...(labels ? { labels } : {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Parses an imported `*.icons.json`; errors are human-readable. */
|
||||||
|
export function parseIconPackJson(json: string): { pack: IconPack; warnings: string[] } | { error: string } {
|
||||||
|
if (json.length > ICON_LIMITS.packBytes) return { error: 'This icon pack is larger than 120 KB.' };
|
||||||
|
let raw: unknown;
|
||||||
|
try { raw = JSON.parse(json); } catch { return { error: 'This file is not valid JSON.' }; }
|
||||||
|
const pack = sanitizeIconPack(raw);
|
||||||
|
if (!pack) return { error: 'An icon pack needs an "id", a "name" and at least one valid glyph.' };
|
||||||
|
const dropped = Object.keys(obj(obj(raw).glyphs)).length - Object.keys(pack.glyphs).length;
|
||||||
|
const warnings: string[] = [];
|
||||||
|
if (dropped > 0) warnings.push(`${dropped} glyph(s) were ignored: unknown names, or drawings that are not plain path data.`);
|
||||||
|
if (pack.license === 'unknown') warnings.push('This pack does not say under which license its drawings are.');
|
||||||
|
return { pack, warnings };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The `icons` group of a theme from JSON. Null when it says nothing valid. */
|
||||||
|
export function sanitizeThemeIcons(value: unknown): ThemeIcons | null {
|
||||||
|
const source = obj(value);
|
||||||
|
const out: ThemeIcons = {};
|
||||||
|
if (typeof source.pack === 'string' && /^[a-z0-9-]{1,40}$/.test(source.pack)) out.pack = source.pack;
|
||||||
|
if (Object.keys(obj(source.style)).length) {
|
||||||
|
const style = obj(source.style), full = sanitizeIconStyle(style);
|
||||||
|
out.style = Object.fromEntries((['stroke', 'cap', 'join', 'scale'] as const).filter(key => key in style).map(key => [key, full[key]])) as Partial<IconStyle>;
|
||||||
|
}
|
||||||
|
const overrides = sanitizeGlyphs(source.overrides, ICON_LIMITS.overrides);
|
||||||
|
if (Object.keys(overrides).length) out.overrides = overrides;
|
||||||
|
const symbols = sanitizeSymbols(source.symbols); if (symbols) out.symbols = symbols;
|
||||||
|
const labels = sanitizeLabels(source.labels); if (labels) out.labels = labels;
|
||||||
|
return Object.keys(out).length ? out : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// The owner's choice and the catalog
|
||||||
|
|
||||||
|
/** `theme`: follow the theme's suggestion; `site`: the site's own icons; otherwise a pack id. */
|
||||||
|
export type IconChoice = 'theme' | 'site' | string;
|
||||||
|
export const normalizeIconChoice = (value: unknown): IconChoice => typeof value === 'string' && /^[a-z0-9-]{1,40}$/.test(value) ? value : 'theme';
|
||||||
|
|
||||||
|
export type IconCatalog = {
|
||||||
|
packs: readonly IconPack[];
|
||||||
|
get(id: string | undefined): IconPack | null;
|
||||||
|
/** The pack that is drawn: the owner's pick, else the theme's suggestion; null for the site's own icons or an unknown pack. */
|
||||||
|
resolve(choice: IconChoice, theme: ThemeIcons | null | undefined): IconPack | null;
|
||||||
|
};
|
||||||
|
export function createIconCatalog(builtins: readonly IconPack[], installed: readonly IconPack[] = []): IconCatalog {
|
||||||
|
const packs = [...builtins, ...installed.filter(pack => !builtins.some(item => item.id === pack.id))];
|
||||||
|
const get = (id: string | undefined) => packs.find(pack => pack.id === id) ?? null;
|
||||||
|
return { packs, get, resolve: (choice, theme) => choice === 'site' ? null : choice === 'theme' ? get(theme?.pack) : get(choice) };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Drawing
|
||||||
|
|
||||||
|
const esc = (value: string) => value.replace(/[<>&"']/g, '');
|
||||||
|
const paint = (fill: IconFill, colors: RoleColors | null, id: string): { attr: string; def: string } => {
|
||||||
|
if (typeof fill === 'string') return { attr: HEX.test(fill) ? fill : colors?.[fill as ColorRole] ?? '#000000', def: '' };
|
||||||
|
return { attr: `url(#${id})`, def: `<linearGradient id="${id}" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="${esc(fill.from)}"/><stop offset="1" stop-color="${esc(fill.to)}"/></linearGradient>` };
|
||||||
|
};
|
||||||
|
|
||||||
|
/** The SVG document of a glyph, built from validated data. `colors` resolves role fills of layers; a single path is black (it is used as a mask). */
|
||||||
|
export function glyphSvg(glyph: IconGlyph, style: IconStyle, colors: RoleColors | null = null): string | null {
|
||||||
|
const open = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">';
|
||||||
|
if ('d' in glyph) {
|
||||||
|
const attrs = glyph.stroke
|
||||||
|
? `fill="none" stroke="#000" stroke-width="${style.stroke}" stroke-linecap="${style.cap}" stroke-linejoin="${style.join}"`
|
||||||
|
: `fill="#000"${glyph.rule ? ' fill-rule="evenodd"' : ''}`;
|
||||||
|
return `${open}<path d="${esc(glyph.d)}" ${attrs}/></svg>`;
|
||||||
|
}
|
||||||
|
if ('layers' in glyph) {
|
||||||
|
const defs: string[] = [];
|
||||||
|
const paths = glyph.layers.map((layer, index) => {
|
||||||
|
const { attr, def } = paint(layer.fill, colors, `g${index}`);
|
||||||
|
if (def) defs.push(def);
|
||||||
|
return `<path d="${esc(layer.d)}" fill="${attr}"${layer.opacity !== undefined ? ` opacity="${layer.opacity}"` : ''}${layer.rule ? ' fill-rule="evenodd"' : ''}/>`;
|
||||||
|
});
|
||||||
|
return `${open}${defs.length ? `<defs>${defs.join('')}</defs>` : ''}${paths.join('')}</svg>`;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const svgUrl = (svg: string) => `url("data:image/svg+xml,${encodeURIComponent(svg).replace(/'/g, '%27').replace(/"/g, '%22')}")`;
|
||||||
|
/** True for glyphs that carry their own colors (drawn as an image, not as a mask of the current color). */
|
||||||
|
export const isColored = (glyph: IconGlyph) => !('d' in glyph);
|
||||||
|
|
||||||
|
/** How a site finds one of its icons: the container that holds it (stable hooks), else the start of its path data. */
|
||||||
|
export type IconMatcher = {
|
||||||
|
/** Selector of the icon's `<svg>` by its container (`[data-testid="like"] svg`). */
|
||||||
|
ctx?: string;
|
||||||
|
/** Prefixes of the site's own path data for this icon, for icons without a container hook. */
|
||||||
|
sig?: readonly string[];
|
||||||
|
group: IconGroup;
|
||||||
|
/** Needed for its group to be drawn at all (a rail never shows half ours, half the site's). */
|
||||||
|
core?: boolean;
|
||||||
|
};
|
||||||
|
export type IconTable = Partial<Record<IconName, IconMatcher>>;
|
||||||
|
|
||||||
|
/** Selectors of the `<svg>` boxes of one icon. */
|
||||||
|
export function iconSelectors(matcher: IconMatcher): string[] {
|
||||||
|
const out: string[] = [];
|
||||||
|
if (matcher.ctx) out.push(...matcher.ctx.split(/,(?![^(]*\))/).map(one => one.trim()));
|
||||||
|
for (const prefix of matcher.sig ?? []) if (PATH_GRAMMAR.test(prefix)) out.push(`svg:has(> g > path[d^="${prefix}"])`);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type IconContext = {
|
||||||
|
colors: RoleColors | null;
|
||||||
|
/** Attribute on `<html>` that lists the groups that are on (`data-wb-icons="nav actions"`); absent: every group draws. */
|
||||||
|
gate?: string;
|
||||||
|
/** The owner lets themes and packs change icons (default: yes). */
|
||||||
|
allowed?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* CSS that draws `pack` over a site's icons. One rule per glyph the pack has and the site's table
|
||||||
|
* knows, inside guards: forced colors remove backgrounds (a masked icon would vanish) and an engine
|
||||||
|
* without masks would paint solid squares.
|
||||||
|
*/
|
||||||
|
export function compileIcons(pack: IconPack | null, theme: ThemeIcons | null | undefined, table: IconTable, ctx: IconContext): string {
|
||||||
|
if (ctx.allowed === false) return '';
|
||||||
|
const glyphs: Partial<Record<IconName, IconGlyph>> = { ...pack?.glyphs, ...theme?.overrides };
|
||||||
|
const style = { ...(pack?.style ?? BASE_ICON_STYLE), ...theme?.style };
|
||||||
|
const masked: string[] = [], colored: string[] = [], hidden: string[] = [];
|
||||||
|
for (const name of ICON_NAMES) {
|
||||||
|
const glyph = glyphs[name], matcher = table[name];
|
||||||
|
if (!glyph || !matcher) continue;
|
||||||
|
const gate = ctx.gate ? `html[${ctx.gate}~="${matcher.group}"] ` : '';
|
||||||
|
const selectors = iconSelectors(matcher).map(one => `${gate}${one}`);
|
||||||
|
if (!selectors.length) continue;
|
||||||
|
const size = `${Math.round(style.scale * 100)}%`;
|
||||||
|
if ('png' in glyph) {
|
||||||
|
colored.push(`${selectors.join(',')}{background:url("${glyph.png}") center / ${size} no-repeat !important;${glyph.pixel ? 'image-rendering:pixelated;' : ''}}`);
|
||||||
|
} else {
|
||||||
|
const svg = glyphSvg(glyph, style, ctx.colors);
|
||||||
|
if (!svg) continue;
|
||||||
|
if (isColored(glyph)) colored.push(`${selectors.join(',')}{background:${svgUrl(svg)} center / ${size} no-repeat !important}`);
|
||||||
|
else masked.push(`${selectors.join(',')}{background-color:currentColor !important;-webkit-mask:${svgUrl(svg)} center / ${size} no-repeat;mask:${svgUrl(svg)} center / ${size} no-repeat}`);
|
||||||
|
}
|
||||||
|
hidden.push(...selectors.map(one => `${one} > *`));
|
||||||
|
}
|
||||||
|
if (!hidden.length) return '';
|
||||||
|
const hide = `${hidden.join(',')}{opacity:0 !important}`;
|
||||||
|
const images = colored.length ? `${colored.join('\n')}\n` : '';
|
||||||
|
// Colored glyphs need no mask support; masked ones are dropped together with their hiding rule where masks are missing.
|
||||||
|
if (!masked.length) return `@media (forced-colors:none){\n${images}${hide}\n}`;
|
||||||
|
return `@media (forced-colors:none){@supports ((mask-image:url("")) or (-webkit-mask-image:url(""))){\n${images}${masked.join('\n')}\n${hide}\n}}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The groups of `table` whose core icons are all on the page (`has(selector)` says whether one matches). Empty table entries count as present. */
|
||||||
|
export function iconGroupsPresent(table: IconTable, has: (selector: string) => boolean): IconGroup[] {
|
||||||
|
return ICON_GROUPS.filter(group => {
|
||||||
|
const core = ICON_NAMES.map(name => table[name]).filter((matcher): matcher is IconMatcher => !!matcher && matcher.group === group && !!matcher.core);
|
||||||
|
return core.every(matcher => iconSelectors(matcher).some(selector => { try { return has(selector); } catch { return false; } }));
|
||||||
|
});
|
||||||
|
}
|
||||||
154
packages/runtime/src/themeSchema.ts
Normal file
154
packages/runtime/src/themeSchema.ts
Normal file
|
|
@ -0,0 +1,154 @@
|
||||||
|
// The JSON Schema of a theme's structure groups and of an icon pack, generated from the same tables
|
||||||
|
// the sanitizers use (themeComponents.ts, themeVariants.ts, themeDecor.ts, themeIcons.ts), so a range
|
||||||
|
// or a word exists in one place. `theme.schema.json` and `icons.schema.json` in the `waybetter`
|
||||||
|
// package are written from here (`scripts/theme-schema.mjs`); a test fails when they are stale. Pure.
|
||||||
|
|
||||||
|
import {
|
||||||
|
ACTION_NAMES, AVATAR_SHAPES, BORDER_STYLES, CASES, COLOR_ROLES, COMPONENTS, COMPONENT_IDS, CORNERS, PRESETS, SHADOWS, TOKEN_LIMITS,
|
||||||
|
} from './themeComponents.ts';
|
||||||
|
import { CHROME_KINDS, DIVIDER_STYLES, LINK_UNDERLINES, MOTION_CURVES, RING_STYLES } from './themeDecor.ts';
|
||||||
|
import { ICON_LABEL_NAMES, ICON_LIMITS, ICON_NAMES, PATH_GRAMMAR } from './themeIcons.ts';
|
||||||
|
import { VARIANT_AXES, VARIANT_AXIS_NAMES } from './themeVariants.ts';
|
||||||
|
|
||||||
|
type Json = Record<string, unknown>;
|
||||||
|
const range = ([minimum, maximum]: readonly [number, number], type = 'number'): Json => ({ type, minimum, maximum });
|
||||||
|
const words = (values: readonly string[]): Json => ({ enum: [...values] });
|
||||||
|
const closed = (properties: Json, extra: Json = {}): Json => ({ type: 'object', additionalProperties: false, properties, ...extra });
|
||||||
|
/** Schema-side guard for words written into CSS strings (the sanitizer's allow-list is stricter: letters, digits and a little punctuation). */
|
||||||
|
const LABEL_PATTERN = String.raw`^[^\u0000-\u001f"\\<>&{};'` + '`]+$';
|
||||||
|
const role = { $ref: '#/$defs/role' };
|
||||||
|
const hex = { $ref: '#/$defs/hex' };
|
||||||
|
|
||||||
|
type Def = { parent?: string; text?: boolean; height?: readonly [number, number]; width?: readonly [number, number]; size?: readonly [number, number]; maxHeight?: readonly [number, number]; fontSize?: readonly [number, number]; shape?: boolean; corner?: boolean; visible?: boolean; glass?: boolean; gradient?: boolean; presets?: keyof typeof PRESETS };
|
||||||
|
|
||||||
|
// Fills and states come in four kinds (with or without glass, with or without a gradient); each is one shared definition.
|
||||||
|
const kind = (def: Def) => `${def.glass ? 'Glass' : ''}${def.gradient ? 'Gradient' : ''}`;
|
||||||
|
function fillDef(glass: boolean, gradient: boolean): Json {
|
||||||
|
const options: Json[] = [role, { const: 'transparent' }];
|
||||||
|
if (glass) options.push({ const: 'glass' });
|
||||||
|
if (gradient) options.push(closed({ from: role, to: role, angle: range(TOKEN_LIMITS.angle) }, { required: ['from', 'to'] }));
|
||||||
|
return { oneOf: options };
|
||||||
|
}
|
||||||
|
const stateDef = (name: string): Json => closed({
|
||||||
|
fill: { $ref: `#/$defs/fill${name}` }, text: role, borderColor: role, shadow: { $ref: '#/$defs/shadow' }, lift: range(TOKEN_LIMITS.lift), scale: range(TOKEN_LIMITS.scale), underline: { type: 'boolean' },
|
||||||
|
});
|
||||||
|
const fill = (def: Def): Json => ({ $ref: `#/$defs/fill${kind(def)}` });
|
||||||
|
const state = (def: Def): Json => ({ $ref: `#/$defs/state${kind(def)}` });
|
||||||
|
|
||||||
|
function component(def: Def, id: string): Json {
|
||||||
|
const properties: Json = {
|
||||||
|
radius: { oneOf: [range(TOKEN_LIMITS.radius), { const: 'pill' }] },
|
||||||
|
borderWidth: range(TOKEN_LIMITS.borderWidth), borderStyle: words(BORDER_STYLES), borderColor: role,
|
||||||
|
fill: fill(def), text: role,
|
||||||
|
padX: range(TOKEN_LIMITS.padX), padY: range(TOKEN_LIMITS.padY), gap: range(TOKEN_LIMITS.gap),
|
||||||
|
shadow: { $ref: '#/$defs/shadow' }, hover: state(def), active: state(def), focus: state(def),
|
||||||
|
};
|
||||||
|
if (def.presets) properties.preset = words(Object.keys(PRESETS[def.presets]));
|
||||||
|
for (const key of ['height', 'width', 'size', 'maxHeight', 'fontSize'] as const) if (def[key]) properties[key] = range(def[key]!);
|
||||||
|
if (def.text || def.fontSize) {
|
||||||
|
properties.font = { $ref: '#/$defs/fontRoleName' };
|
||||||
|
properties.weight = range(TOKEN_LIMITS.weight);
|
||||||
|
if (id !== 'postText') properties.case = words(CASES);
|
||||||
|
properties.tracking = range(TOKEN_LIMITS.tracking);
|
||||||
|
properties.leading = range(TOKEN_LIMITS.leading);
|
||||||
|
}
|
||||||
|
if (def.shape) properties.shape = words(AVATAR_SHAPES);
|
||||||
|
if (def.corner) properties.corner = words(CORNERS);
|
||||||
|
if (def.visible) properties.visible = { type: 'boolean' };
|
||||||
|
return closed(properties);
|
||||||
|
}
|
||||||
|
|
||||||
|
const glyph: Json = {
|
||||||
|
oneOf: [
|
||||||
|
closed({ d: { $ref: '#/$defs/pathData' }, rule: { const: 'evenodd' }, stroke: { type: 'boolean' } }, { required: ['d'] }),
|
||||||
|
closed({
|
||||||
|
layers: {
|
||||||
|
type: 'array', minItems: 1, maxItems: ICON_LIMITS.layers,
|
||||||
|
items: closed({ d: { $ref: '#/$defs/pathData' }, fill: { oneOf: [role, hex, closed({ from: hex, to: hex }, { required: ['from', 'to'] })] }, opacity: range([0, 1]), rule: { const: 'evenodd' } }, { required: ['d', 'fill'] }),
|
||||||
|
},
|
||||||
|
}, { required: ['layers'] }),
|
||||||
|
closed({ png: { type: 'string', maxLength: ICON_LIMITS.pngChars + 22, pattern: '^data:image/png;base64,[A-Za-z0-9+/]+={0,2}$' }, pixel: { type: 'boolean' } }, { required: ['png'] }),
|
||||||
|
],
|
||||||
|
};
|
||||||
|
const iconStyle = closed({ stroke: range([1, 2.5]), cap: words(['round', 'square', 'butt']), join: words(['round', 'miter', 'bevel']), scale: range([0.8, 1.25]) });
|
||||||
|
const symbols = closed({ like: words(['heart', 'star', 'custom']), separator: words(['dot', 'bullet', 'slash', 'dash', 'pipe', 'none']) });
|
||||||
|
const labels = closed(Object.fromEntries(ICON_LABEL_NAMES.map(name => [name, { type: 'string', minLength: 1, maxLength: ICON_LIMITS.labelChars, pattern: LABEL_PATTERN }])));
|
||||||
|
const glyphs = (maxProperties: number): Json => closed(Object.fromEntries(ICON_NAMES.map(name => [name, { $ref: '#/$defs/glyph' }])), { maxProperties });
|
||||||
|
|
||||||
|
/** `$defs` shared by the structure groups and the pack schema. */
|
||||||
|
export const structureDefs = (): Json => ({
|
||||||
|
role: { description: 'A color role of the theme. Components never carry a color literal.', ...words(COLOR_ROLES) },
|
||||||
|
fontRoleName: words(['interface', 'post', 'heading', 'numbers', 'mono', 'chrome', 'dialog']),
|
||||||
|
shadow: words(SHADOWS),
|
||||||
|
...Object.fromEntries([[false, false], [true, false], [false, true], [true, true]].flatMap(([glass, gradient]) => {
|
||||||
|
const name = `${glass ? 'Glass' : ''}${gradient ? 'Gradient' : ''}`;
|
||||||
|
return [[`fill${name}`, fillDef(glass!, gradient!)], [`state${name}`, stateDef(name)]];
|
||||||
|
})),
|
||||||
|
pathData: { type: 'string', minLength: 1, maxLength: ICON_LIMITS.pathChars, pattern: PATH_GRAMMAR.source.replace(/\{1,4000\}\$$/, '+$') },
|
||||||
|
glyph,
|
||||||
|
});
|
||||||
|
|
||||||
|
/** The properties a theme document gains: `components`, `variants`, `decor`, `icons`. */
|
||||||
|
export function structureProperties(): Json {
|
||||||
|
return {
|
||||||
|
components: {
|
||||||
|
description: 'How each piece of the site is built. Every token is optional; a missing token changes nothing.',
|
||||||
|
...closed(Object.fromEntries(COMPONENT_IDS.map(id => [id, component(COMPONENTS[id] as Def, id)]))),
|
||||||
|
},
|
||||||
|
variants: {
|
||||||
|
description: 'Structural choices. The first option of each axis is the site\'s own layout.',
|
||||||
|
...closed(Object.fromEntries(VARIANT_AXIS_NAMES.map(axis => [axis, words(VARIANT_AXES[axis])]))),
|
||||||
|
},
|
||||||
|
decor: {
|
||||||
|
description: 'Lines, bars, focus ring, selection, scrollbars, link underlines, motion.',
|
||||||
|
...closed({
|
||||||
|
dividers: closed({ style: words(DIVIDER_STYLES), color: role, width: range([0, 3]) }, { required: ['style'] }),
|
||||||
|
chrome: closed({ kind: words(CHROME_KINDS), title: { type: 'string', maxLength: 24 } }, { required: ['kind'] }),
|
||||||
|
focusRing: closed({ width: range([2, 4]), style: words(RING_STYLES), color: role, offset: range([0, 4]) }),
|
||||||
|
selection: closed({ fill: role, text: role }, { required: ['fill', 'text'] }),
|
||||||
|
scrollbar: closed({ width: words(['auto', 'thin']), thumb: role, track: role, style: words(['flat', 'classic']) }),
|
||||||
|
links: closed({ underline: words(LINK_UNDERLINES) }, { required: ['underline'] }),
|
||||||
|
motion: closed({ duration: range([0, 400]), curve: words(MOTION_CURVES), press: range([0.96, 1]) }),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
icons: {
|
||||||
|
description: 'The icon pack this theme suggests (by id), with small adjustments. A whole pack is its own document (icons.schema.json).',
|
||||||
|
...closed({ pack: { type: 'string', pattern: '^[a-z0-9-]{1,40}$' }, style: iconStyle, overrides: glyphs(ICON_LIMITS.overrides), symbols, labels }),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `colors.actions`. */
|
||||||
|
export const actionColorsSchema = (): Json => ({
|
||||||
|
description: 'Colors of a set action (liked, reposted, bookmarked) and of the reply hover. Absent: the site\'s own.',
|
||||||
|
...closed(Object.fromEntries(ACTION_NAMES.map(name => [name, hex]))),
|
||||||
|
});
|
||||||
|
|
||||||
|
/** The JSON Schema of an icon pack document (`*.icons.json`). */
|
||||||
|
export function iconPackSchema(id: string): Json {
|
||||||
|
return {
|
||||||
|
$schema: 'https://json-schema.org/draft/2020-12/schema',
|
||||||
|
$id: id,
|
||||||
|
title: 'wayBetter icon pack',
|
||||||
|
description: 'Glyphs by semantic name, drawn over a site\'s own icons. Path data, colored layers of path data, or small PNGs: never an SVG document.',
|
||||||
|
type: 'object',
|
||||||
|
required: ['id', 'name', 'license', 'glyphs'],
|
||||||
|
additionalProperties: false,
|
||||||
|
properties: {
|
||||||
|
$schema: { type: 'string' },
|
||||||
|
id: { type: 'string', pattern: '^[a-z0-9-]{1,40}$' },
|
||||||
|
name: { type: 'string', minLength: 1, maxLength: 60 },
|
||||||
|
description: { type: 'string', maxLength: 200 },
|
||||||
|
author: { type: 'string', maxLength: 60 },
|
||||||
|
license: { type: 'string', minLength: 1, maxLength: 60, description: 'SPDX id, "own" for the author\'s own drawings, or a plain name for artwork under other terms.' },
|
||||||
|
source: { type: 'string', maxLength: 200 },
|
||||||
|
credits: { type: 'string', maxLength: 400 },
|
||||||
|
version: { const: 1 },
|
||||||
|
style: iconStyle,
|
||||||
|
glyphs: { ...glyphs(ICON_LIMITS.names), minProperties: 1 },
|
||||||
|
symbols,
|
||||||
|
labels,
|
||||||
|
},
|
||||||
|
$defs: { hex: { type: 'string', pattern: '^#[0-9a-fA-F]{6}$' }, ...structureDefs() },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
@ -18,6 +18,10 @@
|
||||||
|
|
||||||
import { FONT_ROLE_NAMES, MONO_FAMILIES, contrastRatio, hexToRgb, mix, relativeLuminance, type FontRoleName } from './themeApi.ts';
|
import { FONT_ROLE_NAMES, MONO_FAMILIES, contrastRatio, hexToRgb, mix, relativeLuminance, type FontRoleName } from './themeApi.ts';
|
||||||
import { deriveColors } from './themeTokens.ts';
|
import { deriveColors } from './themeTokens.ts';
|
||||||
|
import { ACTION_NAMES, sanitizeComponents, type ActionColors, type ThemeComponents } from './themeComponents.ts';
|
||||||
|
import { sanitizeDecor, type ThemeDecor } from './themeDecor.ts';
|
||||||
|
import { sanitizeThemeIcons, type ThemeIcons } from './themeIcons.ts';
|
||||||
|
import { sanitizeVariants, type ThemeVariants } from './themeVariants.ts';
|
||||||
|
|
||||||
export { FONT_ROLE_NAMES } from './themeApi.ts';
|
export { FONT_ROLE_NAMES } from './themeApi.ts';
|
||||||
export type { FontRoleName } from './themeApi.ts';
|
export type { FontRoleName } from './themeApi.ts';
|
||||||
|
|
@ -26,8 +30,12 @@ export type Role = 'bg' | 'surface' | 'elevated' | 'border' | 'text' | 'muted' |
|
||||||
/** The site's filled primary button (X: "Post"/"Follow"): an `inverse` background with an `onInverse` label. */
|
/** The site's filled primary button (X: "Post"/"Follow"): an `inverse` background with an `onInverse` label. */
|
||||||
export type ButtonRole = 'inverse' | 'onInverse';
|
export type ButtonRole = 'inverse' | 'onInverse';
|
||||||
export type Palette = Record<Role, string> & Partial<Record<ButtonRole, string>>;
|
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 };
|
* `page` is the canvas behind the site's columns (defaults to `bg`); the columns stay on `bg`.
|
||||||
|
* `actions` are the colors of a set action (liked, reposted, bookmarked) and of the reply hover;
|
||||||
|
* absent, the site's own action colors stay.
|
||||||
|
*/
|
||||||
|
export type ThemeColors = Palette & { page?: string; actions?: ActionColors };
|
||||||
|
|
||||||
export type Density = 'compact' | 'default' | 'comfortable';
|
export type Density = 'compact' | 'default' | 'comfortable';
|
||||||
export type AvatarShape = 'circle' | 'rounded' | 'square';
|
export type AvatarShape = 'circle' | 'rounded' | 'square';
|
||||||
|
|
@ -91,6 +99,16 @@ export type ThemeSpec = {
|
||||||
effects: EffectsSpec;
|
effects: EffectsSpec;
|
||||||
/** Free-form CSS appended last (owner-trusted, like Custom CSS). */
|
/** Free-form CSS appended last (owner-trusted, like Custom CSS). */
|
||||||
css: string;
|
css: string;
|
||||||
|
// The groups below are optional and additive: a theme without them is drawn exactly as before,
|
||||||
|
// and an app that does not know them drops them and draws the rest.
|
||||||
|
/** How each piece of the site is built (themeComponents.ts). */
|
||||||
|
components?: ThemeComponents;
|
||||||
|
/** Structural choices: where the navigation sits, how a post is laid out (themeVariants.ts). */
|
||||||
|
variants?: ThemeVariants;
|
||||||
|
/** Lines, bars, focus ring, selection, scrollbars, motion (themeDecor.ts). */
|
||||||
|
decor?: ThemeDecor;
|
||||||
|
/** Which icon pack the theme suggests, with small adjustments (themeIcons.ts). */
|
||||||
|
icons?: ThemeIcons;
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Panel overrides: any group may be partially overridden on top of the selected theme. */
|
/** Panel overrides: any group may be partially overridden on top of the selected theme. */
|
||||||
|
|
@ -104,6 +122,8 @@ export type ThemeOverrides = {
|
||||||
effects?: Partial<EffectsSpec>;
|
effects?: Partial<EffectsSpec>;
|
||||||
/** The theme's own CSS as edited in the panel (replaces the theme document's `css`). */
|
/** The theme's own CSS as edited in the panel (replaces the theme document's `css`). */
|
||||||
css?: { text: string };
|
css?: { text: string };
|
||||||
|
/** The owner's say on a theme's layout suggestions, axis by axis (an axis set to the site's own option switches it off). */
|
||||||
|
variants?: Record<string, string>;
|
||||||
};
|
};
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
|
@ -149,7 +169,7 @@ export function reach(color: string, surfaces: string[], ratio: number): string
|
||||||
* and links reach WCAG AA (4.5:1) on every surface, including the page canvas, and the site's filled
|
* 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).
|
* button keeps a readable label and stands out from the page (3:1).
|
||||||
*/
|
*/
|
||||||
export function ensureContrast<T extends Palette & { page?: string }>(colors: T): T {
|
export function ensureContrast<T extends Palette & { page?: string; actions?: ActionColors }>(colors: T): T {
|
||||||
const surfaces = [colors.bg, colors.surface, colors.elevated, ...(colors.page ? [colors.page] : [])];
|
const surfaces = [colors.bg, colors.surface, colors.elevated, ...(colors.page ? [colors.page] : [])];
|
||||||
const out = { ...colors };
|
const out = { ...colors };
|
||||||
out.text = reach(colors.text, surfaces, 7);
|
out.text = reach(colors.text, surfaces, 7);
|
||||||
|
|
@ -160,6 +180,8 @@ export function ensureContrast<T extends Palette & { page?: string }>(colors: T)
|
||||||
const onInverse = colors.onInverse ?? colors.bg;
|
const onInverse = colors.onInverse ?? colors.bg;
|
||||||
out.inverse = reach(inverse, [colors.bg], 3);
|
out.inverse = reach(inverse, [colors.bg], 3);
|
||||||
out.onInverse = reach(onInverse, [out.inverse], 4.5);
|
out.onInverse = reach(onInverse, [out.inverse], 4.5);
|
||||||
|
// Action colors are icons and counts: non-text contrast on the column and on a raised row.
|
||||||
|
if (colors.actions) out.actions = Object.fromEntries(Object.entries(colors.actions).map(([name, color]) => [name, reach(color as string, [colors.bg, colors.surface], 3)]));
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -192,6 +214,9 @@ function sanitizeColors(value: unknown): ThemeColors | null {
|
||||||
.filter(role => isHex(source[role])).map(role => [role, (source[role] as string).toLowerCase()]));
|
.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;
|
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();
|
for (const role of ['inverse', 'onInverse', 'page'] as const) if (isHex(source[role])) colors[role] = (source[role] as string).toLowerCase();
|
||||||
|
const actions = obj(source.actions);
|
||||||
|
const named_actions = Object.fromEntries(ACTION_NAMES.filter(name => isHex(actions[name])).map(name => [name, (actions[name] as string).toLowerCase()]));
|
||||||
|
if (Object.keys(named_actions).length) colors.actions = named_actions;
|
||||||
return colors;
|
return colors;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -309,9 +334,20 @@ export function sanitizeSpec(input: unknown): ThemeSpec {
|
||||||
background: sanitizeBackground(source.background),
|
background: sanitizeBackground(source.background),
|
||||||
effects: sanitizeEffects(source.effects, BASE_EFFECTS),
|
effects: sanitizeEffects(source.effects, BASE_EFFECTS),
|
||||||
css: typeof source.css === 'string' ? source.css.slice(0, MAX_CSS_CHARS) : '',
|
css: typeof source.css === 'string' ? source.css.slice(0, MAX_CSS_CHARS) : '',
|
||||||
|
...structureGroups(source),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The optional structure groups of a theme, each present only when it says something valid. */
|
||||||
|
function structureGroups(source: Record<string, unknown>): Pick<ThemeSpec, 'components' | 'variants' | 'decor' | 'icons'> {
|
||||||
|
const components = sanitizeComponents(source.components), variants = sanitizeVariants(source.variants);
|
||||||
|
const decor = sanitizeDecor(source.decor), icons = sanitizeThemeIcons(source.icons);
|
||||||
|
return { ...(components ? { components } : {}), ...(variants ? { variants } : {}), ...(decor ? { decor } : {}), ...(icons ? { icons } : {}) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** True when a theme carries any of the structure groups (components, variants, decoration, icons). */
|
||||||
|
export const hasStructure = (theme: ThemeSpec) => !!(theme.components || theme.variants || theme.decor || theme.icons);
|
||||||
|
|
||||||
/** Parses an imported file; errors are human-readable. */
|
/** Parses an imported file; errors are human-readable. */
|
||||||
export function parseThemeJson(json: string): { theme: ThemeSpec; warnings: string[] } | { error: string } {
|
export function parseThemeJson(json: string): { theme: ThemeSpec; warnings: string[] } | { error: string } {
|
||||||
let raw: unknown;
|
let raw: unknown;
|
||||||
|
|
@ -345,13 +381,21 @@ export function applyOverrides(theme: ThemeSpec, overrides: ThemeOverrides = {},
|
||||||
background: o.background ? sanitizeBackground(o.background) : theme.background,
|
background: o.background ? sanitizeBackground(o.background) : theme.background,
|
||||||
effects: o.effects ? sanitizeEffects({ ...theme.effects, ...o.effects }, theme.effects) : theme.effects,
|
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,
|
css: o.css && typeof o.css.text === 'string' ? o.css.text.slice(0, MAX_CSS_CHARS) : theme.css,
|
||||||
|
...variantOverrides(theme, o.variants),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A theme's variants with the owner's per-axis say on top (the raw merge goes through the sanitizer, so the site's own option removes the axis). */
|
||||||
|
function variantOverrides(theme: ThemeSpec, overrides: unknown): Pick<ThemeSpec, 'variants'> {
|
||||||
|
if (!overrides || typeof overrides !== 'object') return {};
|
||||||
|
const variants = sanitizeVariants({ ...theme.variants, ...(overrides as Record<string, unknown>) });
|
||||||
|
return { variants: variants ?? undefined };
|
||||||
|
}
|
||||||
|
|
||||||
/** True when a theme changes nothing about the site (the site's own look without overrides). */
|
/** True when a theme changes nothing about the site (the site's own look without overrides). */
|
||||||
export function isNeutral(theme: ThemeSpec): boolean {
|
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])
|
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;
|
&& theme.background.kind === 'none' && !theme.css && !hasStructure(theme);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
|
|
||||||
64
packages/runtime/src/themeVariants.ts
Normal file
64
packages/runtime/src/themeVariants.ts
Normal file
|
|
@ -0,0 +1,64 @@
|
||||||
|
// Layout variants: the structural choices a theme may suggest (navigation on top, compact posts,
|
||||||
|
// worded actions), as fixed words on a few axes. The vocabulary and the precedence are here; what a
|
||||||
|
// variant looks like on a site is that site's CSS (its skins). Pure.
|
||||||
|
//
|
||||||
|
// A theme suggests, the owner decides: an axis an owner's own switch already controls is left to that
|
||||||
|
// switch, and the owner can turn layout changes by themes off altogether.
|
||||||
|
|
||||||
|
/** The axes and their options. The first option of each axis is the site's own layout (no rule). */
|
||||||
|
export const VARIANT_AXES = {
|
||||||
|
nav: ['labels', 'icons', 'top', 'bottom'],
|
||||||
|
post: ['default', 'cards', 'bubbles', 'compact', 'broadsheet'],
|
||||||
|
actions: ['icons', 'labels', 'quiet'],
|
||||||
|
header: ['default', 'solid', 'bar'],
|
||||||
|
sidebar: ['default', 'narrow', 'hidden'],
|
||||||
|
width: ['default', 'full'],
|
||||||
|
} as const;
|
||||||
|
export type VariantAxis = keyof typeof VARIANT_AXES;
|
||||||
|
export const VARIANT_AXIS_NAMES = Object.keys(VARIANT_AXES) as VariantAxis[];
|
||||||
|
export type ThemeVariants = { [A in VariantAxis]?: typeof VARIANT_AXES[A][number] };
|
||||||
|
|
||||||
|
/** The `variants` group from JSON: known axes and options only; an axis left at the site's own layout is dropped. */
|
||||||
|
export function sanitizeVariants(value: unknown): ThemeVariants | null {
|
||||||
|
const source = value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
||||||
|
const out: Record<string, string> = {};
|
||||||
|
for (const axis of VARIANT_AXIS_NAMES) {
|
||||||
|
const options: readonly string[] = VARIANT_AXES[axis];
|
||||||
|
const option = source[axis];
|
||||||
|
if (typeof option === 'string' && options.includes(option) && option !== options[0]) out[axis] = option;
|
||||||
|
}
|
||||||
|
return Object.keys(out).length ? out as ThemeVariants : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type VariantGate = {
|
||||||
|
/** The owner lets themes change the layout (default: yes). */
|
||||||
|
allowed?: boolean;
|
||||||
|
/** Axes an owner's own switch controls right now: the theme's suggestion is not drawn for them. */
|
||||||
|
owned?: readonly VariantAxis[];
|
||||||
|
};
|
||||||
|
|
||||||
|
/** The variants that are drawn: the theme's (with the owner's customization already merged in), minus what the owner holds. */
|
||||||
|
export function resolveVariants(variants: ThemeVariants | null | undefined, gate: VariantGate = {}): ThemeVariants {
|
||||||
|
if (!variants || gate.allowed === false) return {};
|
||||||
|
const out: Record<string, string> = {};
|
||||||
|
for (const axis of VARIANT_AXIS_NAMES) {
|
||||||
|
const option = variants[axis];
|
||||||
|
if (option && !gate.owned?.includes(axis)) out[axis] = option;
|
||||||
|
}
|
||||||
|
return out as ThemeVariants;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A site's CSS for each variant it can draw: `skins.nav.top(ctx)` returns the rules. */
|
||||||
|
export type VariantSkins<Context> = { [A in VariantAxis]?: Partial<Record<typeof VARIANT_AXES[A][number], (ctx: Context) => string>> };
|
||||||
|
|
||||||
|
/** The CSS of the resolved variants, in axis order. A variant the site has no skin for draws nothing. */
|
||||||
|
export function compileVariants<Context>(variants: ThemeVariants, skins: VariantSkins<Context>, ctx: Context): string[] {
|
||||||
|
const out: string[] = [];
|
||||||
|
for (const axis of VARIANT_AXIS_NAMES) {
|
||||||
|
const option = variants[axis];
|
||||||
|
const build = option ? (skins[axis] as Record<string, ((ctx: Context) => string) | undefined> | undefined)?.[option] : undefined;
|
||||||
|
const css = build?.(ctx);
|
||||||
|
if (css) out.push(css);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
278
packages/runtime/tests/themeStructure.test.ts
Normal file
278
packages/runtime/tests/themeStructure.test.ts
Normal file
|
|
@ -0,0 +1,278 @@
|
||||||
|
// A theme's structure groups (components, variants, decoration, icons) and icon packs: what the
|
||||||
|
// sanitizers accept, what the compilers emit, and that the published schemas are generated from the
|
||||||
|
// same tables. Site selectors here are made up; a site's own part map is tested in that site's app.
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { spawnSync } from 'node:child_process';
|
||||||
|
import { readFileSync } from 'node:fs';
|
||||||
|
import test from 'node:test';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
import { contrastRatio } from '../src/themeApi.ts';
|
||||||
|
import {
|
||||||
|
COMPONENTS, COMPONENT_IDS, PRESETS, TOKEN_LIMITS, compileComponents, partRule, readableRole, resolveComponents, sanitizeComponents,
|
||||||
|
type ComponentContext, type PartMap, type RoleColors,
|
||||||
|
} from '../src/themeComponents.ts';
|
||||||
|
import { chromeTitle, compileDecor, cssString, sanitizeDecor } from '../src/themeDecor.ts';
|
||||||
|
import {
|
||||||
|
BASE_ICON_STYLE, ICON_LIMITS, ICON_NAMES, PATH_GRAMMAR, compileIcons, createIconCatalog, glyphSvg, iconGroupsPresent, normalizeIconChoice, parseIconPackJson, sanitizeGlyph,
|
||||||
|
sanitizeIconPack, sanitizeThemeIcons, type IconPack, type IconTable,
|
||||||
|
} from '../src/themeIcons.ts';
|
||||||
|
import { applyOverrides, hasStructure, isNeutral, sanitizeSpec } from '../src/themeSpec.ts';
|
||||||
|
import { VARIANT_AXES, compileVariants, resolveVariants, sanitizeVariants } from '../src/themeVariants.ts';
|
||||||
|
|
||||||
|
const COLORS: RoleColors = {
|
||||||
|
bg: '#ffffff', surface: '#f5f8fa', elevated: '#e8f1f7', page: '#c0deed', border: '#e1e8ed', text: '#292f33', muted: '#5b6b78',
|
||||||
|
accent: '#0077b0', onAccent: '#ffffff', inverse: '#0077b0', onInverse: '#ffffff',
|
||||||
|
};
|
||||||
|
const CTX: ComponentContext = {
|
||||||
|
colors: COLORS,
|
||||||
|
fonts: { interface: 'Helvetica, sans-serif', post: 'Georgia, serif', heading: 'Helvetica, sans-serif', numbers: 'Helvetica, sans-serif', mono: 'monospace', chrome: 'system-ui', dialog: 'system-ui' },
|
||||||
|
};
|
||||||
|
const PARTS: PartMap = {
|
||||||
|
post: { sel: '[data-part="post"]' },
|
||||||
|
postText: { sel: '[data-part="text"]', text: '[data-part="text"],[data-part="text"] :is(span,a)' },
|
||||||
|
buttonPrimary: { sel: '[data-part="primary"]', text: '[data-part="primary"] span' },
|
||||||
|
buttonSecondary: { sel: '[data-part="secondary"]' },
|
||||||
|
avatar: { sel: '[data-part="avatar"]', skip: ['size'] },
|
||||||
|
handle: { sel: '[data-part="handle"]' },
|
||||||
|
search: { sel: '[data-part="search"]' },
|
||||||
|
};
|
||||||
|
const css = (components: unknown) => { const out = compileComponents(sanitizeComponents(components) ?? {}, PARTS, CTX); return { ...out, text: [...out.values, ...out.rules].join('\n') }; };
|
||||||
|
|
||||||
|
test('component tokens are clamped, unknown names and tokens a component does not take are dropped', () => {
|
||||||
|
const clean = sanitizeComponents({
|
||||||
|
post: { radius: 999, borderWidth: -3, borderStyle: 'groove', fill: '#ff0000', padX: 12.6, shadow: 'soft', visible: false, fontSize: 40, corner: 'cut', nonsense: 1 },
|
||||||
|
avatar: { shape: 'hexagon', size: 3, visible: false, corner: 'cut' },
|
||||||
|
postText: { fontSize: 99, case: 'upper', weight: 433, tracking: 9, leading: 0.2, font: 'post' },
|
||||||
|
buttonPrimary: { preset: 'bevel', radius: 'pill', fill: { from: 'accent', to: 'surface', angle: 720 }, hover: { lift: 40, scale: 2, underline: true, fill: 'url(x)' } },
|
||||||
|
topBar: { fill: 'glass', height: 1 },
|
||||||
|
handle: { fill: 'glass', preset: 'bevel' },
|
||||||
|
rocket: { radius: 4 },
|
||||||
|
nav: 'javascript:alert(1)',
|
||||||
|
})!;
|
||||||
|
assert.deepEqual(clean.post, { radius: TOKEN_LIMITS.radius[1], borderWidth: 0, padX: 13, shadow: 'soft', corner: 'cut' }, 'no literal color, no unknown style, no font size or visibility on a post');
|
||||||
|
assert.deepEqual(clean.avatar, { size: 20, shape: 'hexagon', visible: false });
|
||||||
|
assert.deepEqual(clean.postText, { fontSize: 24, font: 'post', weight: 450, tracking: 0.2, leading: 1.1 }, 'post text never changes case');
|
||||||
|
assert.deepEqual(clean.buttonPrimary, { preset: 'bevel', radius: 'pill', fill: { from: 'accent', to: 'surface', angle: 360 }, hover: { lift: 4, scale: 1.04, underline: true } });
|
||||||
|
assert.deepEqual(clean.topBar, { fill: 'glass', height: 40 });
|
||||||
|
assert.equal(clean.handle, undefined, 'glass is for bars and panels; a handle has no presets');
|
||||||
|
assert.ok(!('rocket' in clean) && !('nav' in clean));
|
||||||
|
assert.equal(sanitizeComponents({ post: {} }), null);
|
||||||
|
assert.equal(sanitizeComponents('nope'), null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('presets and parents: own tokens win over the preset, the preset over the parent', () => {
|
||||||
|
const resolved = resolveComponents(sanitizeComponents({ button: { radius: 4, weight: 700 }, buttonPrimary: { preset: 'pill', borderWidth: 2 }, panel: { preset: 'window' }, menu: { radius: 8 } })!);
|
||||||
|
assert.deepEqual(resolved.buttonPrimary, { radius: 'pill', weight: 700, borderWidth: 2 });
|
||||||
|
assert.deepEqual(resolved.buttonSecondary, { radius: 4, weight: 700 });
|
||||||
|
assert.equal(resolved.menu!.radius, 8);
|
||||||
|
assert.equal(resolved.menu!.borderStyle, 'bevel-out');
|
||||||
|
assert.equal(resolved.dialog!.radius, 0);
|
||||||
|
// Every preset is itself valid vocabulary for a component of its family.
|
||||||
|
for (const [family, presets] of Object.entries(PRESETS)) {
|
||||||
|
const id = COMPONENT_IDS.find(item => (COMPONENTS[item] as { presets?: string }).presets === family)!;
|
||||||
|
for (const [name, tokens] of Object.entries(presets)) assert.deepEqual(sanitizeComponents({ [id]: tokens })![id], tokens, `${family}.${name}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('compiled components: soft values, rigid rules, nothing for a part the site does not have', () => {
|
||||||
|
const out = css({ post: { radius: 0, borderWidth: 1, borderColor: 'border', padX: 16, fill: 'surface' }, postText: { fontSize: 17, font: 'post', leading: 1.5 }, nav: { width: 200 }, avatar: { size: 32, shape: 'square' } });
|
||||||
|
assert.ok(out.values.includes('--wb-part-post-radius:0px') && out.values.includes('--wb-part-postText-font-size:17px') && out.values.includes('--wb-part-postText-line-height:1.5'));
|
||||||
|
assert.ok(out.rules.includes(':root:root [data-part="post"]{background-color:var(--wb-part-post-fill) !important;background-image:var(--wb-part-post-fill-1) !important;border-radius:var(--wb-part-post-radius) !important;border-width:var(--wb-part-post-border-width) !important;border-style:var(--wb-part-post-border-style) !important;border-color:var(--wb-part-post-border-color) !important;padding-inline:var(--wb-part-post-pad-x) !important}'), out.rules[0]);
|
||||||
|
assert.ok(out.rules.some(rule => rule.startsWith(':root:root [data-part="text"],:root:root [data-part="text"] :is(span,a){') && rule.includes('font-family:var(--wb-part-postText-font)')), 'type lands on the text leaves');
|
||||||
|
assert.ok(!out.text.includes('nav') && !out.text.includes('--wb-part-avatar-size'), 'no part, or a skipped token: no rule');
|
||||||
|
assert.ok(out.text.includes('--wb-part-avatar-shape:2px'));
|
||||||
|
// Every rule is important and every value it reads was emitted with it.
|
||||||
|
for (const rule of out.rules) for (const name of rule.match(/var\((--[\w-]+)\)/g) ?? []) assert.ok(out.values.some(value => value.startsWith(`${name.slice(4, -1)}:`)), name);
|
||||||
|
assert.equal(partRule('a, b:is(c,d)'), ':root:root a,:root:root b:is(c,d)');
|
||||||
|
assert.equal(compileComponents({}, PARTS, CTX).rules.length, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('text on a fill the theme chose keeps its contrast: the role is swapped for a readable one', () => {
|
||||||
|
// Accent text on an accent button (1:1), and a post filled with the theme's text color.
|
||||||
|
const out = css({ buttonPrimary: { fill: 'accent', text: 'accent' }, post: { fill: 'text' }, postText: { text: 'muted' }, avatar: { fill: 'surface' } });
|
||||||
|
assert.ok(out.values.includes(`--wb-part-buttonPrimary-text:${COLORS.onAccent}`));
|
||||||
|
assert.ok(out.notes.some(note => note.startsWith('buttonPrimary:')));
|
||||||
|
assert.ok(out.values.includes(`--wb-part-postText-text:${COLORS.muted}`), 'no fill of its own: the theme\'s role stands (the palette guarantees it on the theme\'s surfaces)');
|
||||||
|
assert.ok(!out.text.includes('--wb-part-avatar-text'), 'a fill alone colors no text on a part that is not a text part');
|
||||||
|
assert.equal(readableRole('#000000', COLORS), 'onAccent');
|
||||||
|
for (const role of ['accent', 'text', 'surface', 'inverse'] as const) {
|
||||||
|
const label = css({ buttonPrimary: { fill: role } }).values.find(value => value.startsWith('--wb-part-buttonPrimary-text:'))!.split(':')[1]!;
|
||||||
|
assert.ok(contrastRatio(label, COLORS[role]) >= 4.5, `${role}: ${label}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('bevels are four inset lines from the part\'s fill; states move only without reduced motion', () => {
|
||||||
|
const out = css({ buttonPrimary: { preset: 'bevel', hover: { lift: 2, fill: 'elevated' }, active: { shadow: 'inset', scale: 0.98 }, focus: { borderColor: 'accent' } } });
|
||||||
|
const bevel = out.values.find(value => value.startsWith('--wb-part-buttonPrimary-bevel:'))!;
|
||||||
|
assert.equal(bevel.match(/inset/g)!.length, 4);
|
||||||
|
assert.ok(out.values.includes('--wb-part-buttonPrimary-border-style:none'));
|
||||||
|
assert.ok(out.rules.some(rule => rule.startsWith(':root:root [data-part="primary"]:hover{background-color:#e8f1f7 !important')));
|
||||||
|
assert.ok(out.rules.some(rule => rule.startsWith('@media (prefers-reduced-motion:no-preference){:root:root [data-part="primary"]:hover{transform:translateY(-2px) !important}')));
|
||||||
|
assert.ok(out.rules.some(rule => rule.includes('[data-part="primary"]:active{box-shadow:inset') && rule.match(/inset/g)!.length === 4), 'a pressed bevel is the sunken bevel');
|
||||||
|
assert.ok(out.rules.some(rule => rule.startsWith(':root:root [data-part="primary"]:focus-visible{border-color:#0077b0 !important}')));
|
||||||
|
assert.ok(out.rules.filter(rule => rule.includes('transform')).every(rule => rule.startsWith('@media (prefers-reduced-motion:no-preference)')));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('variants: known axes and options only; the owner holds an axis or switches layout changes off', () => {
|
||||||
|
assert.deepEqual(sanitizeVariants({ nav: 'top', post: 'default', actions: 'explode', header: 'bar', zoom: 'in' }), { nav: 'top', header: 'bar' });
|
||||||
|
assert.equal(sanitizeVariants({ nav: 'labels', post: 'default' }), null, 'the site\'s own options are not a variant');
|
||||||
|
assert.deepEqual(resolveVariants({ nav: 'top', post: 'compact', sidebar: 'hidden' }, { owned: ['sidebar'] }), { nav: 'top', post: 'compact' });
|
||||||
|
assert.deepEqual(resolveVariants({ nav: 'top' }, { allowed: false }), {});
|
||||||
|
assert.deepEqual(resolveVariants(null), {});
|
||||||
|
const skins = { nav: { top: (ctx: { bar: string }) => `nav{top:0;background:${ctx.bar}}` }, post: { compact: () => 'article{padding:4px}' } };
|
||||||
|
assert.deepEqual(compileVariants({ post: 'compact', nav: 'top', actions: 'labels' }, skins, { bar: 'red' }), ['nav{top:0;background:red}', 'article{padding:4px}'], 'axis order; no skin, no rule');
|
||||||
|
for (const options of Object.values(VARIANT_AXES)) assert.ok(options.length >= 2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an owner\'s per-axis say rides on the theme: the site\'s own option removes the axis', () => {
|
||||||
|
const theme = sanitizeSpec({ name: 'T', variants: { nav: 'top', post: 'compact' } });
|
||||||
|
assert.deepEqual(applyOverrides(theme, { variants: { nav: 'labels', actions: 'labels' } }).variants, { post: 'compact', actions: 'labels' });
|
||||||
|
assert.deepEqual(applyOverrides(theme).variants, { nav: 'top', post: 'compact' });
|
||||||
|
assert.equal(applyOverrides(theme, { variants: { nav: 'labels', post: 'default' } }).variants, undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('decoration: clamps, plain titles, a focus ring that is always visible', () => {
|
||||||
|
const decor = sanitizeDecor({
|
||||||
|
dividers: { style: 'dashed', color: 'muted', width: 9 }, chrome: { kind: 'titlebar', title: 'Timeline"};body{display:none}<script>' },
|
||||||
|
focusRing: { width: 0, style: 'wavy', color: 'surface', offset: 40 }, selection: { fill: 'accent', text: 'accent' },
|
||||||
|
scrollbar: { style: 'classic', thumb: 'surface', track: 'elevated', width: 'huge' }, links: { underline: 'always' }, motion: { duration: 9999, curve: 'steps', press: 0.5 }, cursor: 'url(x)',
|
||||||
|
})!;
|
||||||
|
assert.deepEqual(decor.dividers, { style: 'dashed', color: 'muted', width: 3 });
|
||||||
|
assert.deepEqual(decor.chrome, { kind: 'titlebar', title: 'Timelinebodydisplay:none' });
|
||||||
|
assert.deepEqual(decor.focusRing, { width: 2, color: 'surface', offset: 4 });
|
||||||
|
assert.deepEqual(decor.motion, { duration: 400, curve: 'steps', press: 0.96 });
|
||||||
|
assert.ok(!('cursor' in decor));
|
||||||
|
assert.equal(sanitizeDecor({ chrome: { kind: 'none' }, selection: { fill: 'accent' } }), null);
|
||||||
|
assert.equal(chromeTitle('C:\\WINDOWS> dir & "x"'), 'C:WINDOWS> dir + x');
|
||||||
|
assert.equal(cssString('a"b\\c'), '"a\\22 b\\5c c"');
|
||||||
|
|
||||||
|
const targets = { divider: '[data-cell]', focusable: 'a,button', link: '[data-text] a', moving: 'a,button', pressable: 'button', chrome: { titlebar: (title: string) => `[data-col]::before{content:${cssString(title)}}` } };
|
||||||
|
const out = compileDecor(decor, targets, { colors: COLORS }).join('\n');
|
||||||
|
assert.ok(out.includes(':root:root :is([data-cell]){border-bottom:3px dashed #5b6b78 !important}'));
|
||||||
|
// The theme asked for a ring in its surface color (1.07:1 on the page): the ring takes a visible role instead.
|
||||||
|
const ring = /outline:2px solid (#[0-9a-f]{6})/.exec(out)![1]!;
|
||||||
|
for (const surface of [COLORS.bg, COLORS.surface, COLORS.page]) assert.ok(contrastRatio(ring, surface) >= 3, `${ring} on ${surface}`);
|
||||||
|
assert.ok(out.includes('::selection{background-color:#0077b0 !important;color:#ffffff !important}'), 'selection text is readable on its fill');
|
||||||
|
assert.ok(out.includes('::-webkit-scrollbar-thumb') && out.includes('[data-col]::before{content:"Timelinebodydisplay:none"}'));
|
||||||
|
assert.ok(out.includes('@media (prefers-reduced-motion:no-preference){') && out.includes('steps(3,end)') && out.includes('button):active{transform:scale(0.96)'));
|
||||||
|
assert.deepEqual(compileDecor(decor, {}, { colors: COLORS }).filter(rule => !rule.includes('::selection') && !rule.includes('scrollbar')), [], 'a site without targets draws only what needs none');
|
||||||
|
});
|
||||||
|
|
||||||
|
const PACK: IconPack = sanitizeIconPack({
|
||||||
|
id: 'test-pack', name: 'Test pack', author: 'Someone', license: 'own', source: 'drawn for the test', credits: 'Someone',
|
||||||
|
style: { stroke: 2, cap: 'square', join: 'miter', scale: 0.9 },
|
||||||
|
glyphs: {
|
||||||
|
home: { d: 'M4 11l8-7 8 7v9H4z', stroke: true }, like: { d: 'M12 20l-8-8a5 5 0 0 1 8-6 5 5 0 0 1 8 6z' }, 'like.on': { d: 'M12 20l-8-8a5 5 0 0 1 8-6 5 5 0 0 1 8 6z' },
|
||||||
|
reply: { layers: [{ d: 'M3 4h18v12H9l-5 4z', fill: { from: '#ffffff', to: '#88ccff' } }, { d: 'M6 7h12v2H6z', fill: 'accent', opacity: 0.8 }] },
|
||||||
|
share: { png: 'data:image/png;base64,iVBORw0KGgo=', pixel: true },
|
||||||
|
},
|
||||||
|
labels: { reply: 'reply', like: 'fav' }, symbols: { like: 'star' },
|
||||||
|
})!;
|
||||||
|
const TABLE: IconTable = {
|
||||||
|
home: { ctx: '[data-nav="home"] svg', group: 'nav', core: true },
|
||||||
|
explore: { ctx: '[data-nav="explore"] svg', group: 'nav', core: true },
|
||||||
|
like: { ctx: '[data-act="like"] svg', group: 'actions', core: true },
|
||||||
|
'like.on': { ctx: '[data-act="unlike"] svg', group: 'actions' },
|
||||||
|
reply: { ctx: '[data-act="reply"] svg', group: 'actions', core: true },
|
||||||
|
share: { sig: ['M12 2.59l5.7 5.7'], group: 'actions' },
|
||||||
|
grok: { sig: ['M2.2 12"><script>'], group: 'nav' },
|
||||||
|
};
|
||||||
|
|
||||||
|
test('a glyph is path data, colored layers or a small PNG; nothing else gets in', () => {
|
||||||
|
for (const hostile of [
|
||||||
|
{ d: 'M0 0<script>alert(1)</script>' }, { d: 'M0 0" onload="x' }, { d: 'url(javascript:1)' }, { d: '<' }, { d: 'M0 0'.padEnd(ICON_LIMITS.pathChars + 1, '0') }, { d: '' },
|
||||||
|
{ layers: [{ d: 'M0 0h1', fill: 'url(#x)' }] }, { layers: [{ d: 'M0 0h1', fill: 'red' }] }, { layers: [] },
|
||||||
|
{ png: 'data:image/svg+xml;base64,AAAA' }, { png: 'https://example.com/a.png' }, { png: `data:image/png;base64,${'A'.repeat(ICON_LIMITS.pngChars + 8)}` },
|
||||||
|
{ svg: '<svg/>' }, '<svg/>', null,
|
||||||
|
]) assert.equal(sanitizeGlyph(hostile), null, JSON.stringify(hostile).slice(0, 60));
|
||||||
|
assert.deepEqual(sanitizeGlyph({ d: ' M4 4L20 20 ', rule: 'evenodd', stroke: true, extra: 1 }), { d: 'M4 4L20 20', rule: 'evenodd', stroke: true });
|
||||||
|
assert.equal((sanitizeGlyph({ layers: Array.from({ length: 9 }, () => ({ d: 'M0 0h1v1z', fill: '#AABBCC' })) }) as { layers: unknown[] }).layers.length, ICON_LIMITS.layers);
|
||||||
|
assert.ok(PATH_GRAMMAR.test('M12 21a9 9 0 1 1 0-18 9 9 0 0 1 0 18zM3 12h18') && !PATH_GRAMMAR.test('M0 0;'));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an icon pack document: id, name and at least one glyph; unknown names dropped; license stated or flagged', () => {
|
||||||
|
assert.equal(PACK.license, 'own');
|
||||||
|
assert.deepEqual(Object.keys(PACK.glyphs), ['home', 'reply', 'like', 'like.on', 'share']);
|
||||||
|
assert.deepEqual(PACK.style, { stroke: 2, cap: 'square', join: 'miter', scale: 0.9 });
|
||||||
|
assert.equal(sanitizeIconPack({ id: 'x', name: 'X', glyphs: { rocket: { d: 'M0 0h1' } } }), null);
|
||||||
|
assert.equal(sanitizeIconPack({ id: 'Bad Id', name: 'X', glyphs: { home: { d: 'M0 0h1' } } }), null);
|
||||||
|
const parsed = parseIconPackJson(JSON.stringify({ id: 'p', name: 'P <b>', glyphs: { home: { d: 'M0 0h1' }, rocket: { d: 'M0 0' }, like: { d: '<' } } }));
|
||||||
|
assert.ok('pack' in parsed && parsed.pack.name === 'P b' && parsed.pack.license === 'unknown' && parsed.warnings.length === 2);
|
||||||
|
assert.ok('error' in parseIconPackJson('{'));
|
||||||
|
assert.ok('error' in parseIconPackJson(JSON.stringify({ id: 'p', name: 'P', glyphs: {} })));
|
||||||
|
assert.ok('error' in parseIconPackJson(' '.repeat(ICON_LIMITS.packBytes + 1)));
|
||||||
|
assert.equal(new Set(ICON_NAMES).size, ICON_NAMES.length);
|
||||||
|
assert.ok(ICON_NAMES.length <= ICON_LIMITS.names);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a theme names a pack and may adjust it a little; the owner\'s icon choice is separate', () => {
|
||||||
|
const icons = sanitizeThemeIcons({ pack: 'test-pack', style: { stroke: 9 }, overrides: { home: { d: 'M1 1h2' }, rocket: { d: 'M0 0' } }, symbols: { like: 'star', verified: 'nope' }, labels: { reply: 'reply', like: 'a"b', share: 'way too long a label' }, glyphs: { home: { d: 'M0 0' } } })!;
|
||||||
|
assert.deepEqual(icons, { pack: 'test-pack', style: { stroke: 2.5 }, overrides: { home: { d: 'M1 1h2' } }, symbols: { like: 'star' }, labels: { reply: 'reply' } });
|
||||||
|
assert.equal(sanitizeThemeIcons({ pack: 'NOPE!' }), null);
|
||||||
|
const catalog = createIconCatalog([PACK]);
|
||||||
|
assert.equal(catalog.resolve('theme', icons), PACK);
|
||||||
|
assert.equal(catalog.resolve('theme', null), null);
|
||||||
|
assert.equal(catalog.resolve('site', icons), null, 'the owner asked for the site\'s own icons');
|
||||||
|
assert.equal(catalog.resolve('missing-pack', icons), null, 'a pack that is not installed falls back to the site\'s icons');
|
||||||
|
assert.equal(catalog.resolve('test-pack', null), PACK, 'an explicit pick needs no theme');
|
||||||
|
assert.equal(normalizeIconChoice('test-pack'), 'test-pack');
|
||||||
|
assert.equal(normalizeIconChoice({}), 'theme');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('icons are drawn as masks of the current color (colored glyphs as images), behind guards, per group', () => {
|
||||||
|
const out = compileIcons(PACK, null, TABLE, { colors: COLORS, gate: 'data-wb-icons' });
|
||||||
|
assert.ok(out.startsWith('@media (forced-colors:none){@supports ((mask-image:url("")) or (-webkit-mask-image:url(""))){'));
|
||||||
|
const home = out.split('\n').find(line => line.startsWith('html[data-wb-icons~="nav"] [data-nav="home"] svg{'))!;
|
||||||
|
assert.ok(home.includes('background-color:currentColor !important') && home.includes('-webkit-mask:url("data:image/svg+xml,') && home.includes('mask:url("data:image/svg+xml,') && home.includes('/ 90% no-repeat'));
|
||||||
|
const svgOf = (line: string) => decodeURIComponent(/url\("data:image\/svg\+xml,([^"]*)"\)/.exec(line)![1]!);
|
||||||
|
assert.ok(svgOf(home).includes('stroke-width="2" stroke-linecap="square" stroke-linejoin="miter"'), 'the pack\'s stroke style');
|
||||||
|
const reply = out.split('\n').find(line => line.startsWith('html[data-wb-icons~="actions"] [data-act="reply"] svg{'))!;
|
||||||
|
assert.ok(reply.includes('background:url("data:image/svg+xml,') && !reply.includes('mask'), 'layers carry their own colors');
|
||||||
|
assert.ok(svgOf(reply).includes(`fill="${COLORS.accent}" opacity="0.8"`) && svgOf(reply).includes('<linearGradient id="g0"'));
|
||||||
|
assert.ok(out.includes('svg:has(> g > path[d^="M12 2.59l5.7 5.7"]){background:url("data:image/png;base64,iVBORw0KGgo=") center / 90% no-repeat !important;image-rendering:pixelated;}'));
|
||||||
|
assert.ok(out.includes('[data-act="unlike"] svg > *') && out.includes('{opacity:0 !important}'), 'the site\'s own paths are hidden, not removed');
|
||||||
|
assert.ok(!out.includes('explore') && !out.includes('script'), 'no glyph: the site\'s icon stays; a signature that is not path data is never written');
|
||||||
|
// No encoded quote can end the url("…") early.
|
||||||
|
for (const url of out.match(/url\("data:image\/svg\+xml,[^)]*\)/g)!) assert.ok(!url.slice(5, -2).includes('"'));
|
||||||
|
assert.equal(compileIcons(PACK, null, TABLE, { colors: COLORS, allowed: false }), '');
|
||||||
|
assert.equal(compileIcons(null, null, TABLE, { colors: COLORS }), '');
|
||||||
|
assert.ok(compileIcons(null, { overrides: { explore: { d: 'M2 2h20v20H2z' } } }, TABLE, { colors: null }).includes('[data-nav="explore"] svg{'), 'a theme\'s own override needs no pack');
|
||||||
|
assert.equal(glyphSvg({ png: 'data:image/png;base64,AAAA' }, BASE_ICON_STYLE), null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a group is drawn only when all of its core icons are on the page', () => {
|
||||||
|
const present = (selectors: string[]) => iconGroupsPresent(TABLE, selector => selectors.includes(selector));
|
||||||
|
assert.deepEqual(present(['[data-nav="home"] svg', '[data-nav="explore"] svg', '[data-act="like"] svg', '[data-act="reply"] svg']), ['nav', 'actions', 'composer', 'misc']);
|
||||||
|
assert.deepEqual(present(['[data-nav="home"] svg', '[data-act="like"] svg', '[data-act="reply"] svg']), ['actions', 'composer', 'misc'], 'a rail never shows half ours, half the site\'s');
|
||||||
|
assert.deepEqual(iconGroupsPresent(TABLE, () => { throw new Error('bad selector'); }), ['composer', 'misc']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a theme document: structure groups are optional, additive and dropped when empty', () => {
|
||||||
|
const v1 = sanitizeSpec({ name: 'Plain', colors: { bg: '#ffffff', text: '#111111', accent: '#0066cc' } });
|
||||||
|
for (const key of ['components', 'variants', 'decor', 'icons']) assert.ok(!(key in v1), `${key} absent from a theme that does not set it`);
|
||||||
|
assert.ok(!hasStructure(v1));
|
||||||
|
const v2 = sanitizeSpec({
|
||||||
|
name: 'Built', colors: { bg: '#ffffff', text: '#111111', accent: '#0066cc', actions: { like: '#F5A623', reply: 'red' } },
|
||||||
|
components: { post: { preset: 'card' }, nope: {} }, variants: { nav: 'top' }, decor: { links: { underline: 'always' } }, icons: { pack: 'wb-classic' },
|
||||||
|
});
|
||||||
|
assert.deepEqual(v2.colors!.actions, { like: '#f5a623' });
|
||||||
|
assert.deepEqual([v2.components, v2.variants, v2.decor, v2.icons], [{ post: { preset: 'card' } }, { nav: 'top' }, { links: { underline: 'always' } }, { pack: 'wb-classic' }]);
|
||||||
|
assert.ok(hasStructure(v2));
|
||||||
|
assert.ok(!isNeutral(sanitizeSpec({ name: 'Only structure', variants: { nav: 'top' } })), 'a theme that only moves the navigation is not the site\'s own look');
|
||||||
|
assert.ok(!hasStructure(sanitizeSpec({ name: 'Nothing', components: { post: {} }, variants: { nav: 'labels' } })), 'empty groups and the site\'s own options are no structure');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the published schemas are generated from these tables and current', () => {
|
||||||
|
const script = fileURLToPath(new URL('../../waybetter/scripts/theme-schema.mjs', import.meta.url));
|
||||||
|
const run = spawnSync(process.execPath, [script, '--check'], { encoding: 'utf8' });
|
||||||
|
assert.equal(run.status, 0, run.stderr);
|
||||||
|
const schema = JSON.parse(readFileSync(new URL('../../waybetter/theme.schema.json', import.meta.url), 'utf8'));
|
||||||
|
assert.deepEqual(Object.keys(schema.properties.components.properties), COMPONENT_IDS);
|
||||||
|
assert.deepEqual([schema.properties.components.properties.post.properties.radius.oneOf[0].minimum, schema.properties.components.properties.post.properties.radius.oneOf[0].maximum], [...TOKEN_LIMITS.radius]);
|
||||||
|
assert.deepEqual(schema.properties.variants.properties.nav.enum, [...VARIANT_AXES.nav]);
|
||||||
|
assert.equal(schema.properties.components.properties.postText.properties.case, undefined);
|
||||||
|
assert.ok(new RegExp(schema.$defs.pathData.pattern).test('M4 4L20 20') && !new RegExp(schema.$defs.pathData.pattern).test('<svg>'));
|
||||||
|
const icons = JSON.parse(readFileSync(new URL('../../waybetter/icons.schema.json', import.meta.url), 'utf8'));
|
||||||
|
assert.deepEqual(Object.keys(icons.properties.glyphs.properties), [...ICON_NAMES]);
|
||||||
|
assert.deepEqual(icons.required, ['id', 'name', 'license', 'glyphs']);
|
||||||
|
});
|
||||||
646
packages/waybetter/icons.schema.json
Normal file
646
packages/waybetter/icons.schema.json
Normal file
|
|
@ -0,0 +1,646 @@
|
||||||
|
{
|
||||||
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
|
"$id": "https://unpkg.com/waybetter/icons.schema.json",
|
||||||
|
"title": "wayBetter icon pack",
|
||||||
|
"description": "Glyphs by semantic name, drawn over a site's own icons. Path data, colored layers of path data, or small PNGs: never an SVG document.",
|
||||||
|
"type": "object",
|
||||||
|
"required": [
|
||||||
|
"id",
|
||||||
|
"name",
|
||||||
|
"license",
|
||||||
|
"glyphs"
|
||||||
|
],
|
||||||
|
"additionalProperties": false,
|
||||||
|
"properties": {
|
||||||
|
"$schema": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"id": {
|
||||||
|
"type": "string",
|
||||||
|
"pattern": "^[a-z0-9-]{1,40}$"
|
||||||
|
},
|
||||||
|
"name": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"maxLength": 60
|
||||||
|
},
|
||||||
|
"description": {
|
||||||
|
"type": "string",
|
||||||
|
"maxLength": 200
|
||||||
|
},
|
||||||
|
"author": {
|
||||||
|
"type": "string",
|
||||||
|
"maxLength": 60
|
||||||
|
},
|
||||||
|
"license": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"maxLength": 60,
|
||||||
|
"description": "SPDX id, \"own\" for the author's own drawings, or a plain name for artwork under other terms."
|
||||||
|
},
|
||||||
|
"source": {
|
||||||
|
"type": "string",
|
||||||
|
"maxLength": 200
|
||||||
|
},
|
||||||
|
"credits": {
|
||||||
|
"type": "string",
|
||||||
|
"maxLength": 400
|
||||||
|
},
|
||||||
|
"version": {
|
||||||
|
"const": 1
|
||||||
|
},
|
||||||
|
"style": {
|
||||||
|
"type": "object",
|
||||||
|
"additionalProperties": false,
|
||||||
|
"properties": {
|
||||||
|
"stroke": {
|
||||||
|
"type": "number",
|
||||||
|
"minimum": 1,
|
||||||
|
"maximum": 2.5
|
||||||
|
},
|
||||||
|
"cap": {
|
||||||
|
"enum": [
|
||||||
|
"round",
|
||||||
|
"square",
|
||||||
|
"butt"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"join": {
|
||||||
|
"enum": [
|
||||||
|
"round",
|
||||||
|
"miter",
|
||||||
|
"bevel"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"scale": {
|
||||||
|
"type": "number",
|
||||||
|
"minimum": 0.8,
|
||||||
|
"maximum": 1.25
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"glyphs": {
|
||||||
|
"type": "object",
|
||||||
|
"additionalProperties": false,
|
||||||
|
"properties": {
|
||||||
|
"home": {
|
||||||
|
"$ref": "#/$defs/glyph"
|
||||||
|
},
|
||||||
|
"home.active": {
|
||||||
|
"$ref": "#/$defs/glyph"
|
||||||
|
},
|
||||||
|
"explore": {
|
||||||
|
"$ref": "#/$defs/glyph"
|
||||||
|
},
|
||||||
|
"explore.active": {
|
||||||
|
"$ref": "#/$defs/glyph"
|
||||||
|
},
|
||||||
|
"notifications": {
|
||||||
|
"$ref": "#/$defs/glyph"
|
||||||
|
},
|
||||||
|
"notifications.active": {
|
||||||
|
"$ref": "#/$defs/glyph"
|
||||||
|
},
|
||||||
|
"messages": {
|
||||||
|
"$ref": "#/$defs/glyph"
|
||||||
|
},
|
||||||
|
"messages.active": {
|
||||||
|
"$ref": "#/$defs/glyph"
|
||||||
|
},
|
||||||
|
"grok": {
|
||||||
|
"$ref": "#/$defs/glyph"
|
||||||
|
},
|
||||||
|
"bookmarks": {
|
||||||
|
"$ref": "#/$defs/glyph"
|
||||||
|
},
|
||||||
|
"bookmarks.active": {
|
||||||
|
"$ref": "#/$defs/glyph"
|
||||||
|
},
|
||||||
|
"lists": {
|
||||||
|
"$ref": "#/$defs/glyph"
|
||||||
|
},
|
||||||
|
"communities": {
|
||||||
|
"$ref": "#/$defs/glyph"
|
||||||
|
},
|
||||||
|
"premium": {
|
||||||
|
"$ref": "#/$defs/glyph"
|
||||||
|
},
|
||||||
|
"profile": {
|
||||||
|
"$ref": "#/$defs/glyph"
|
||||||
|
},
|
||||||
|
"profile.active": {
|
||||||
|
"$ref": "#/$defs/glyph"
|
||||||
|
},
|
||||||
|
"more": {
|
||||||
|
"$ref": "#/$defs/glyph"
|
||||||
|
},
|
||||||
|
"compose": {
|
||||||
|
"$ref": "#/$defs/glyph"
|
||||||
|
},
|
||||||
|
"reply": {
|
||||||
|
"$ref": "#/$defs/glyph"
|
||||||
|
},
|
||||||
|
"repost": {
|
||||||
|
"$ref": "#/$defs/glyph"
|
||||||
|
},
|
||||||
|
"repost.on": {
|
||||||
|
"$ref": "#/$defs/glyph"
|
||||||
|
},
|
||||||
|
"like": {
|
||||||
|
"$ref": "#/$defs/glyph"
|
||||||
|
},
|
||||||
|
"like.on": {
|
||||||
|
"$ref": "#/$defs/glyph"
|
||||||
|
},
|
||||||
|
"views": {
|
||||||
|
"$ref": "#/$defs/glyph"
|
||||||
|
},
|
||||||
|
"bookmark": {
|
||||||
|
"$ref": "#/$defs/glyph"
|
||||||
|
},
|
||||||
|
"bookmark.on": {
|
||||||
|
"$ref": "#/$defs/glyph"
|
||||||
|
},
|
||||||
|
"share": {
|
||||||
|
"$ref": "#/$defs/glyph"
|
||||||
|
},
|
||||||
|
"verified": {
|
||||||
|
"$ref": "#/$defs/glyph"
|
||||||
|
},
|
||||||
|
"logo": {
|
||||||
|
"$ref": "#/$defs/glyph"
|
||||||
|
},
|
||||||
|
"caret": {
|
||||||
|
"$ref": "#/$defs/glyph"
|
||||||
|
},
|
||||||
|
"back": {
|
||||||
|
"$ref": "#/$defs/glyph"
|
||||||
|
},
|
||||||
|
"close": {
|
||||||
|
"$ref": "#/$defs/glyph"
|
||||||
|
},
|
||||||
|
"search": {
|
||||||
|
"$ref": "#/$defs/glyph"
|
||||||
|
},
|
||||||
|
"settings": {
|
||||||
|
"$ref": "#/$defs/glyph"
|
||||||
|
},
|
||||||
|
"media": {
|
||||||
|
"$ref": "#/$defs/glyph"
|
||||||
|
},
|
||||||
|
"gif": {
|
||||||
|
"$ref": "#/$defs/glyph"
|
||||||
|
},
|
||||||
|
"poll": {
|
||||||
|
"$ref": "#/$defs/glyph"
|
||||||
|
},
|
||||||
|
"emoji": {
|
||||||
|
"$ref": "#/$defs/glyph"
|
||||||
|
},
|
||||||
|
"schedule": {
|
||||||
|
"$ref": "#/$defs/glyph"
|
||||||
|
},
|
||||||
|
"location": {
|
||||||
|
"$ref": "#/$defs/glyph"
|
||||||
|
},
|
||||||
|
"pinned": {
|
||||||
|
"$ref": "#/$defs/glyph"
|
||||||
|
},
|
||||||
|
"repostContext": {
|
||||||
|
"$ref": "#/$defs/glyph"
|
||||||
|
},
|
||||||
|
"lock": {
|
||||||
|
"$ref": "#/$defs/glyph"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"maxProperties": 64,
|
||||||
|
"minProperties": 1
|
||||||
|
},
|
||||||
|
"symbols": {
|
||||||
|
"type": "object",
|
||||||
|
"additionalProperties": false,
|
||||||
|
"properties": {
|
||||||
|
"like": {
|
||||||
|
"enum": [
|
||||||
|
"heart",
|
||||||
|
"star",
|
||||||
|
"custom"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"separator": {
|
||||||
|
"enum": [
|
||||||
|
"dot",
|
||||||
|
"bullet",
|
||||||
|
"slash",
|
||||||
|
"dash",
|
||||||
|
"pipe",
|
||||||
|
"none"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"labels": {
|
||||||
|
"type": "object",
|
||||||
|
"additionalProperties": false,
|
||||||
|
"properties": {
|
||||||
|
"reply": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"maxLength": 12,
|
||||||
|
"pattern": "^[^\\u0000-\\u001f\"\\\\<>&{};'`]+$"
|
||||||
|
},
|
||||||
|
"repost": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"maxLength": 12,
|
||||||
|
"pattern": "^[^\\u0000-\\u001f\"\\\\<>&{};'`]+$"
|
||||||
|
},
|
||||||
|
"like": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"maxLength": 12,
|
||||||
|
"pattern": "^[^\\u0000-\\u001f\"\\\\<>&{};'`]+$"
|
||||||
|
},
|
||||||
|
"views": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"maxLength": 12,
|
||||||
|
"pattern": "^[^\\u0000-\\u001f\"\\\\<>&{};'`]+$"
|
||||||
|
},
|
||||||
|
"bookmark": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"maxLength": 12,
|
||||||
|
"pattern": "^[^\\u0000-\\u001f\"\\\\<>&{};'`]+$"
|
||||||
|
},
|
||||||
|
"share": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"maxLength": 12,
|
||||||
|
"pattern": "^[^\\u0000-\\u001f\"\\\\<>&{};'`]+$"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"$defs": {
|
||||||
|
"hex": {
|
||||||
|
"type": "string",
|
||||||
|
"pattern": "^#[0-9a-fA-F]{6}$"
|
||||||
|
},
|
||||||
|
"role": {
|
||||||
|
"description": "A color role of the theme. Components never carry a color literal.",
|
||||||
|
"enum": [
|
||||||
|
"bg",
|
||||||
|
"surface",
|
||||||
|
"elevated",
|
||||||
|
"page",
|
||||||
|
"border",
|
||||||
|
"text",
|
||||||
|
"muted",
|
||||||
|
"accent",
|
||||||
|
"onAccent",
|
||||||
|
"inverse",
|
||||||
|
"onInverse"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"fontRoleName": {
|
||||||
|
"enum": [
|
||||||
|
"interface",
|
||||||
|
"post",
|
||||||
|
"heading",
|
||||||
|
"numbers",
|
||||||
|
"mono",
|
||||||
|
"chrome",
|
||||||
|
"dialog"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"shadow": {
|
||||||
|
"enum": [
|
||||||
|
"none",
|
||||||
|
"soft",
|
||||||
|
"deep",
|
||||||
|
"hard",
|
||||||
|
"inset",
|
||||||
|
"glow"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"fill": {
|
||||||
|
"oneOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/$defs/role"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"const": "transparent"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"state": {
|
||||||
|
"type": "object",
|
||||||
|
"additionalProperties": false,
|
||||||
|
"properties": {
|
||||||
|
"fill": {
|
||||||
|
"$ref": "#/$defs/fill"
|
||||||
|
},
|
||||||
|
"text": {
|
||||||
|
"$ref": "#/$defs/role"
|
||||||
|
},
|
||||||
|
"borderColor": {
|
||||||
|
"$ref": "#/$defs/role"
|
||||||
|
},
|
||||||
|
"shadow": {
|
||||||
|
"$ref": "#/$defs/shadow"
|
||||||
|
},
|
||||||
|
"lift": {
|
||||||
|
"type": "number",
|
||||||
|
"minimum": 0,
|
||||||
|
"maximum": 4
|
||||||
|
},
|
||||||
|
"scale": {
|
||||||
|
"type": "number",
|
||||||
|
"minimum": 0.96,
|
||||||
|
"maximum": 1.04
|
||||||
|
},
|
||||||
|
"underline": {
|
||||||
|
"type": "boolean"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"fillGlass": {
|
||||||
|
"oneOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/$defs/role"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"const": "transparent"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"const": "glass"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"stateGlass": {
|
||||||
|
"type": "object",
|
||||||
|
"additionalProperties": false,
|
||||||
|
"properties": {
|
||||||
|
"fill": {
|
||||||
|
"$ref": "#/$defs/fillGlass"
|
||||||
|
},
|
||||||
|
"text": {
|
||||||
|
"$ref": "#/$defs/role"
|
||||||
|
},
|
||||||
|
"borderColor": {
|
||||||
|
"$ref": "#/$defs/role"
|
||||||
|
},
|
||||||
|
"shadow": {
|
||||||
|
"$ref": "#/$defs/shadow"
|
||||||
|
},
|
||||||
|
"lift": {
|
||||||
|
"type": "number",
|
||||||
|
"minimum": 0,
|
||||||
|
"maximum": 4
|
||||||
|
},
|
||||||
|
"scale": {
|
||||||
|
"type": "number",
|
||||||
|
"minimum": 0.96,
|
||||||
|
"maximum": 1.04
|
||||||
|
},
|
||||||
|
"underline": {
|
||||||
|
"type": "boolean"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"fillGradient": {
|
||||||
|
"oneOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/$defs/role"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"const": "transparent"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "object",
|
||||||
|
"additionalProperties": false,
|
||||||
|
"properties": {
|
||||||
|
"from": {
|
||||||
|
"$ref": "#/$defs/role"
|
||||||
|
},
|
||||||
|
"to": {
|
||||||
|
"$ref": "#/$defs/role"
|
||||||
|
},
|
||||||
|
"angle": {
|
||||||
|
"type": "number",
|
||||||
|
"minimum": 0,
|
||||||
|
"maximum": 360
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"from",
|
||||||
|
"to"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"stateGradient": {
|
||||||
|
"type": "object",
|
||||||
|
"additionalProperties": false,
|
||||||
|
"properties": {
|
||||||
|
"fill": {
|
||||||
|
"$ref": "#/$defs/fillGradient"
|
||||||
|
},
|
||||||
|
"text": {
|
||||||
|
"$ref": "#/$defs/role"
|
||||||
|
},
|
||||||
|
"borderColor": {
|
||||||
|
"$ref": "#/$defs/role"
|
||||||
|
},
|
||||||
|
"shadow": {
|
||||||
|
"$ref": "#/$defs/shadow"
|
||||||
|
},
|
||||||
|
"lift": {
|
||||||
|
"type": "number",
|
||||||
|
"minimum": 0,
|
||||||
|
"maximum": 4
|
||||||
|
},
|
||||||
|
"scale": {
|
||||||
|
"type": "number",
|
||||||
|
"minimum": 0.96,
|
||||||
|
"maximum": 1.04
|
||||||
|
},
|
||||||
|
"underline": {
|
||||||
|
"type": "boolean"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"fillGlassGradient": {
|
||||||
|
"oneOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/$defs/role"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"const": "transparent"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"const": "glass"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "object",
|
||||||
|
"additionalProperties": false,
|
||||||
|
"properties": {
|
||||||
|
"from": {
|
||||||
|
"$ref": "#/$defs/role"
|
||||||
|
},
|
||||||
|
"to": {
|
||||||
|
"$ref": "#/$defs/role"
|
||||||
|
},
|
||||||
|
"angle": {
|
||||||
|
"type": "number",
|
||||||
|
"minimum": 0,
|
||||||
|
"maximum": 360
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"from",
|
||||||
|
"to"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"stateGlassGradient": {
|
||||||
|
"type": "object",
|
||||||
|
"additionalProperties": false,
|
||||||
|
"properties": {
|
||||||
|
"fill": {
|
||||||
|
"$ref": "#/$defs/fillGlassGradient"
|
||||||
|
},
|
||||||
|
"text": {
|
||||||
|
"$ref": "#/$defs/role"
|
||||||
|
},
|
||||||
|
"borderColor": {
|
||||||
|
"$ref": "#/$defs/role"
|
||||||
|
},
|
||||||
|
"shadow": {
|
||||||
|
"$ref": "#/$defs/shadow"
|
||||||
|
},
|
||||||
|
"lift": {
|
||||||
|
"type": "number",
|
||||||
|
"minimum": 0,
|
||||||
|
"maximum": 4
|
||||||
|
},
|
||||||
|
"scale": {
|
||||||
|
"type": "number",
|
||||||
|
"minimum": 0.96,
|
||||||
|
"maximum": 1.04
|
||||||
|
},
|
||||||
|
"underline": {
|
||||||
|
"type": "boolean"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"pathData": {
|
||||||
|
"type": "string",
|
||||||
|
"minLength": 1,
|
||||||
|
"maxLength": 4000,
|
||||||
|
"pattern": "^[MmLlHhVvCcSsQqTtAaZz0-9eE\\s,.+-]+$"
|
||||||
|
},
|
||||||
|
"glyph": {
|
||||||
|
"oneOf": [
|
||||||
|
{
|
||||||
|
"type": "object",
|
||||||
|
"additionalProperties": false,
|
||||||
|
"properties": {
|
||||||
|
"d": {
|
||||||
|
"$ref": "#/$defs/pathData"
|
||||||
|
},
|
||||||
|
"rule": {
|
||||||
|
"const": "evenodd"
|
||||||
|
},
|
||||||
|
"stroke": {
|
||||||
|
"type": "boolean"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"d"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "object",
|
||||||
|
"additionalProperties": false,
|
||||||
|
"properties": {
|
||||||
|
"layers": {
|
||||||
|
"type": "array",
|
||||||
|
"minItems": 1,
|
||||||
|
"maxItems": 6,
|
||||||
|
"items": {
|
||||||
|
"type": "object",
|
||||||
|
"additionalProperties": false,
|
||||||
|
"properties": {
|
||||||
|
"d": {
|
||||||
|
"$ref": "#/$defs/pathData"
|
||||||
|
},
|
||||||
|
"fill": {
|
||||||
|
"oneOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/$defs/role"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"$ref": "#/$defs/hex"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "object",
|
||||||
|
"additionalProperties": false,
|
||||||
|
"properties": {
|
||||||
|
"from": {
|
||||||
|
"$ref": "#/$defs/hex"
|
||||||
|
},
|
||||||
|
"to": {
|
||||||
|
"$ref": "#/$defs/hex"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"from",
|
||||||
|
"to"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"opacity": {
|
||||||
|
"type": "number",
|
||||||
|
"minimum": 0,
|
||||||
|
"maximum": 1
|
||||||
|
},
|
||||||
|
"rule": {
|
||||||
|
"const": "evenodd"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"d",
|
||||||
|
"fill"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"layers"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "object",
|
||||||
|
"additionalProperties": false,
|
||||||
|
"properties": {
|
||||||
|
"png": {
|
||||||
|
"type": "string",
|
||||||
|
"maxLength": 6022,
|
||||||
|
"pattern": "^data:image/png;base64,[A-Za-z0-9+/]+={0,2}$"
|
||||||
|
},
|
||||||
|
"pixel": {
|
||||||
|
"type": "boolean"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"png"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -185,6 +185,7 @@
|
||||||
"import": "./dist/shell/*.js"
|
"import": "./dist/shell/*.js"
|
||||||
},
|
},
|
||||||
"./theme.schema.json": "./theme.schema.json",
|
"./theme.schema.json": "./theme.schema.json",
|
||||||
|
"./icons.schema.json": "./icons.schema.json",
|
||||||
"./store-catalog.schema.json": "./store-catalog.schema.json",
|
"./store-catalog.schema.json": "./store-catalog.schema.json",
|
||||||
"./cli/store": "./cli/store.mjs",
|
"./cli/store": "./cli/store.mjs",
|
||||||
"./cli/release": "./cli/release.mjs",
|
"./cli/release": "./cli/release.mjs",
|
||||||
|
|
@ -200,6 +201,7 @@
|
||||||
"build",
|
"build",
|
||||||
"cli",
|
"cli",
|
||||||
"theme.schema.json",
|
"theme.schema.json",
|
||||||
|
"icons.schema.json",
|
||||||
"store-catalog.schema.json",
|
"store-catalog.schema.json",
|
||||||
"i18n.schema.json",
|
"i18n.schema.json",
|
||||||
"i18n-meta.schema.json",
|
"i18n-meta.schema.json",
|
||||||
|
|
|
||||||
32
packages/waybetter/scripts/theme-schema.mjs
Normal file
32
packages/waybetter/scripts/theme-schema.mjs
Normal file
|
|
@ -0,0 +1,32 @@
|
||||||
|
// Writes the generated parts of `theme.schema.json` (a theme's structure groups: components,
|
||||||
|
// variants, decoration, icons, action colors) and the whole `icons.schema.json` (icon packs) from
|
||||||
|
// the runtime's vocabulary tables, so a range or a word is defined once.
|
||||||
|
//
|
||||||
|
// node scripts/theme-schema.mjs rewrite both files
|
||||||
|
// node scripts/theme-schema.mjs --check exit 1 when a file is stale (the test runs this)
|
||||||
|
import { readFileSync, writeFileSync } from 'node:fs';
|
||||||
|
import { actionColorsSchema, iconPackSchema, structureDefs, structureProperties } from '../../runtime/src/themeSchema.ts';
|
||||||
|
|
||||||
|
const check = process.argv.includes('--check');
|
||||||
|
const file = name => new URL(`../${name}`, import.meta.url);
|
||||||
|
|
||||||
|
/** The theme schema with its generated parts replaced. */
|
||||||
|
export function themeSchema(current) {
|
||||||
|
const schema = structuredClone(current);
|
||||||
|
Object.assign(schema.properties, structureProperties());
|
||||||
|
const colors = schema.properties.colors.oneOf.find(option => option.type === 'object');
|
||||||
|
colors.properties.actions = actionColorsSchema();
|
||||||
|
Object.assign(schema.$defs, structureDefs());
|
||||||
|
return schema;
|
||||||
|
}
|
||||||
|
export const iconsSchema = () => iconPackSchema('https://unpkg.com/waybetter/icons.schema.json');
|
||||||
|
|
||||||
|
const stale = [];
|
||||||
|
for (const [name, build] of [['theme.schema.json', () => themeSchema(JSON.parse(readFileSync(file('theme.schema.json'), 'utf8')))], ['icons.schema.json', iconsSchema]]) {
|
||||||
|
const next = `${JSON.stringify(build(), null, 2)}\n`;
|
||||||
|
let current = '';
|
||||||
|
try { current = readFileSync(file(name), 'utf8').replace(/\r\n/g, '\n'); } catch { /* Not written yet. */ }
|
||||||
|
if (current === next) continue;
|
||||||
|
if (check) stale.push(name); else { writeFileSync(file(name), next); console.log(`wrote ${name}`); }
|
||||||
|
}
|
||||||
|
if (stale.length) { console.error(`stale: ${stale.join(', ')} (run node scripts/theme-schema.mjs)`); process.exit(1); }
|
||||||
File diff suppressed because it is too large
Load diff
Loading…
Add table
Add a link
Reference in a new issue