runtime: plugin UI kit (api.ui: toast, alert, confirm, prompt, dialog, modal) and theme API (api.theme, --wb-* vars); theme JSON Schema; waybetter 0.2.0

The kit draws in one shadow DOM host in the active theme's colors, corners and font and repaints
live; accessible dialogs (focus trap and return, Esc/Enter rules, alertdialog for alerts and
confirms), stacking with inert, toasts with actions, reduced motion, text-only content (ui.h),
and scope.ui closes a plugin's dialogs on dispose. api.toast routes to it.
This commit is contained in:
CRTkafa 2026-09-28 21:47:09 +07:00
parent b676cca861
commit 965a85f359
8 changed files with 1627 additions and 25 deletions

View file

@ -55,7 +55,9 @@ crates/waybetter-host/ Rust: security policy, profiles, plugin store, hotfi
packages/runtime/src/ page runtime core (TypeScript, no dependencies) packages/runtime/src/ page runtime core (TypeScript, no dependencies)
site.ts SiteAdapter (the page half of the adapter) + configureRuntime site.ts SiteAdapter (the page half of the adapter) + configureRuntime
domHub.ts netHub.ts one MutationObserver/frame, one fetch/XHR hook per page domHub.ts netHub.ts one MutationObserver/frame, one fetch/XHR hook per page
pluginApi.ts core of window.<Runtime>.api for plugins pluginApi.ts core of window.<Runtime>.api for plugins (incl. ui and theme)
ui.ts plugin UI kit: toasts, alert/confirm/prompt, dialogs (shadow DOM, themed)
themeApi.ts the active theme as values + --wb-* CSS variables (api.theme)
themeTokens.ts OKLab color model: maps the site's palette onto a theme's axis themeTokens.ts OKLab color model: maps the site's palette onto a theme's axis
paneNav.ts split view: park the site's navigation rail in redundant panes paneNav.ts split view: park the site's navigation rail in redundant panes
linkRouting.ts divert in-page clicks to a pane/tab/browser per setting linkRouting.ts divert in-page clicks to a pane/tab/browser per setting

View file

@ -2,6 +2,14 @@
// re-implement DOM watching, route tracking, local storage and cleanup. Everything here is local to // re-implement DOM watching, route tracking, local storage and cleanup. Everything here is local to
// the page: no network requests, no account actions. A site adapter adds its own readers (e.g. a // the page: no network requests, no account actions. A site adapter adds its own readers (e.g. a
// post/message parser) on top of this core. // post/message parser) on top of this core.
//
// `ui` (toasts, alerts, confirmations, prompts, dialogs; ui.ts) and `theme` (the active theme as
// values; themeApi.ts) are part of the core: the site adapter only supplies its theme source.
import { createThemeApi, type ThemeApi, type ThemeSource } from './themeApi.ts';
import { createUiKit, type UiKit } from './ui.ts';
export type { ThemeApi, ThemeSource, UiKit };
export type Dispose = () => void; export type Dispose = () => void;
@ -24,6 +32,10 @@ export type PluginScope = {
add<T extends Node>(node: T): T; add<T extends Node>(node: T): T;
/** Runs `fn` on dispose (restore attributes, clear timers, ...). */ /** Runs `fn` on dispose (restore attributes, clear timers, ...). */
defer(fn: Dispose): void; defer(fn: Dispose): void;
/** Calls `callback(theme)` after the theme changes, until dispose. */
onThemeChange(callback: Parameters<ThemeApi['onChange']>[0]): void;
/** The UI kit, scoped: dialogs and toasts it opened are closed on dispose. */
readonly ui: UiKit;
dispose(): void; dispose(): void;
}; };
@ -43,10 +55,20 @@ export type CorePluginApi = {
*/ */
onKey(callback: (event: KeyboardEvent, item: Element | null) => void): Dispose; onKey(callback: (event: KeyboardEvent, item: Element | null) => void): Dispose;
copyText(text: string): Promise<boolean>; copyText(text: string): Promise<boolean>;
/** A short status message (the UI kit's toast; `ms` is how long it stays). */
toast(message: string, ms?: number): void; toast(message: string, ms?: number): void;
/** Toasts, alerts, confirmations, prompts and dialogs in the active theme (see ui.ts). */
ui: UiKit;
/** The active theme as values: `current()` and `onChange(fn)` (see themeApi.ts). */
theme: ThemeApi;
scope(): PluginScope; scope(): PluginScope;
}; };
/** What the site adapter adds to the core: its theme engine, when it has one. */
export type CorePluginExtras = {
theme?: ThemeSource;
};
export type PluginApiSite = { export type PluginApiSite = {
/** The runtime global, for error messages (`<name>.waitFor timed out`). */ /** The runtime global, for error messages (`<name>.waitFor timed out`). */
name: string; name: string;
@ -56,7 +78,9 @@ export type PluginApiSite = {
storagePrefix: string; storagePrefix: string;
/** `data-*` key (camelCase) marking plugin `<style>` elements with their id. */ /** `data-*` key (camelCase) marking plugin `<style>` elements with their id. */
styleDataKey: string; styleDataKey: string;
/** Id of the kit's shadow host element (`<wb-ui id=…>`), kept from the old single toast. */
toastId: string; toastId: string;
/** Accent used when the site has no theme source (and the page shows none). */
toastBackground: string; toastBackground: string;
/** The item a single-key shortcut acts on: the focused element's closest match (a post, a message). */ /** The item a single-key shortcut acts on: the focused element's closest match (a post, a message). */
itemSelector: string; itemSelector: string;
@ -70,13 +94,28 @@ const CHORD_MS = 1500;
/** True when a key event belongs to text entry, not to page shortcuts. */ /** True when a key event belongs to text entry, not to page shortcuts. */
export function isTypingTarget(target: EventTarget | null): boolean { export function isTypingTarget(target: EventTarget | null): boolean {
const element = target as (Element & { isContentEditable?: boolean }) | null; let element = target as (Element & { isContentEditable?: boolean }) | null;
// Focus inside a shadow root (the UI kit's dialogs) reports its host; look at what is focused in it.
while (element && (element as Element).shadowRoot?.activeElement) element = (element as Element).shadowRoot!.activeElement as Element;
if (!element || typeof element.closest !== 'function') return false; if (!element || typeof element.closest !== 'function') return false;
return Boolean(element.isContentEditable) || /^(INPUT|TEXTAREA|SELECT)$/i.test(element.nodeName) || Boolean(element.closest('[contenteditable="true"]')); return Boolean(element.isContentEditable) || /^(INPUT|TEXTAREA|SELECT)$/i.test(element.nodeName) || Boolean(element.closest('[contenteditable="true"]'));
} }
export function createCorePluginApi(win: Window & typeof globalThis, site: PluginApiSite): CorePluginApi { export function createCorePluginApi(win: Window & typeof globalThis, site: PluginApiSite, extras: CorePluginExtras = {}): CorePluginApi {
const doc = win.document; const doc = win.document;
const theme = createThemeApi(win, extras.theme, /^#[0-9a-f]{6}$/i.test(site.toastBackground) ? site.toastBackground : undefined);
// Created on first use: the kit touches the DOM only when something is shown.
let kit: ReturnType<typeof createUiKit> | null = null;
const uiKit = () => kit ??= createUiKit(win, { theme, product: site.product, hostId: site.toastId });
const ui: UiKit = Object.freeze({
toast: (...args: Parameters<UiKit['toast']>) => uiKit().toast(...args),
alert: (...args: Parameters<UiKit['alert']>) => uiKit().alert(...args),
confirm: (...args: Parameters<UiKit['confirm']>) => uiKit().confirm(...args),
prompt: (...args: Parameters<UiKit['prompt']>) => uiKit().prompt(...args),
dialog: (...args: Parameters<UiKit['dialog']>) => uiKit().dialog(...args),
modal: (...args: Parameters<UiKit['modal']>) => uiKit().modal(...args),
h: (...args: Parameters<UiKit['h']>) => uiKit().h(...args),
});
const styleNodes = new Map<string, HTMLStyleElement>(); const styleNodes = new Map<string, HTMLStyleElement>();
const report = (error: unknown) => console.error(`[${site.product}] plugin callback failed`, error); const report = (error: unknown) => console.error(`[${site.product}] plugin callback failed`, error);
@ -227,25 +266,14 @@ export function createCorePluginApi(win: Window & typeof globalThis, site: Plugi
} }
}, },
toast(message, ms = 2200) { toast(message, ms = 2200) {
let node = doc.getElementById(site.toastId) as (HTMLElement & { _wbTimer?: number }) | null; // The old toast vanished after `ms`; 0 or less meant "at once", so it never means "stay".
if (!node) { ui.toast(String(message), { duration: Number.isFinite(ms) && ms > 0 ? ms : 1 });
node = doc.createElement('div');
node.id = site.toastId;
node.setAttribute('role', 'status');
Object.assign(node.style, {
position: 'fixed', left: '50%', bottom: '28px', transform: 'translateX(-50%)', zIndex: '2147483646',
padding: '10px 16px', borderRadius: '10px', background: site.toastBackground, color: '#fff',
font: '600 14px/1.3 system-ui, sans-serif', boxShadow: '0 6px 24px rgba(0,0,0,.35)', maxWidth: '80vw',
});
doc.body.appendChild(node);
}
node.textContent = message;
if (node._wbTimer) clearTimeout(node._wbTimer);
const current = node;
node._wbTimer = win.setTimeout(() => current.remove(), ms);
}, },
ui,
theme,
scope() { scope() {
let disposers: Dispose[] = []; let disposers: Dispose[] = [];
let scopedUi: UiKit | null = null;
return { return {
css(id, css) { css(id, css) {
api.injectCSS(id, css); api.injectCSS(id, css);
@ -271,6 +299,17 @@ export function createCorePluginApi(win: Window & typeof globalThis, site: Plugi
defer(fn) { defer(fn) {
disposers.push(fn); disposers.push(fn);
}, },
onThemeChange(callback) {
disposers.push(theme.onChange(callback));
},
get ui() {
if (!scopedUi) {
const scoped = uiKit().scoped();
scopedUi = scoped.kit;
disposers.push(() => { scoped.dispose(); scopedUi = null; });
}
return scopedUi;
},
dispose() { dispose() {
const pending = disposers.reverse(); const pending = disposers.reverse();
disposers = []; disposers = [];

View file

@ -0,0 +1,226 @@
// `api.theme`: the active theme as plain values, so plugins (and the UI kit) can match it. The site
// adapter resolves its own theme document into a `ResolvedTheme` (colors by role, radius, font,
// mode) and says when it changes; this module turns that into `--wb-*` CSS custom properties and
// a small `current()` / `onChange()` API. When the site keeps its own colors (no theme, e.g. X
// default), the adapter still resolves the site's palette, so plugins always see real colors.
//
// Pure except `createThemeApi` / `readPageTheme`, which read the page.
export type ThemeMode = 'light' | 'dark';
/** Every color role a theme has, resolved (derived roles filled in, legibility enforced). */
export type ResolvedColors = {
/** The main surface behind content (the site's column background). */
bg: string;
/** A raised surface (cards, inputs). */
surface: string;
/** Hover / selected surface, one step above `surface`. */
elevated: string;
border: string;
text: string;
/** Secondary text. */
muted: string;
accent: string;
/** Readable text on `accent`. */
onAccent: string;
/** The site's filled primary button and its label. */
inverse: string;
onInverse: string;
/** The canvas behind the columns (equals `bg` unless the theme paints a page). */
page: string;
};
export type ResolvedTheme = {
/** Theme id (`x` for the site's own look). */
id: string;
name: string;
mode: ThemeMode;
/** True when the site's own colors are shown (no theme colors). */
siteDefault: boolean;
colors: ResolvedColors;
/** Card / dialog corner radius in px. */
radius: number;
/** Button corner radius in px (9999 = pill). */
buttonRadius: number;
/** CSS `font-family` stack of the interface. */
font: string;
};
/** What a site adapter provides: the current resolved theme and change notifications. */
export type ThemeSource = {
current(): ResolvedTheme | null;
onChange(listener: () => void): () => void;
};
export type ThemeApi = {
/** The active theme, resolved. A frozen snapshot: call again after `onChange`. */
current(): ResolvedTheme;
/** Calls `listener(theme)` after the theme (or the site's light/dark mode) changes. Returns a dispose. */
onChange(listener: (theme: ResolvedTheme) => void): () => void;
};
/** Where the theme file JSON Schema is published with the `waybetter` npm package (`"$schema"` in theme files). */
export const THEME_SCHEMA_URL = 'https://unpkg.com/waybetter/theme.schema.json';
export const FALLBACK_FONT = 'system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif';
const HEX = /^#[0-9a-f]{6}$/i;
function channels(hex: string): [number, number, number] {
const n = parseInt(hex.slice(1, 7), 16);
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
}
/** WCAG relative luminance of `#rrggbb`. */
export function relativeLuminance(hex: string): number {
const [r, g, b] = channels(hex).map(v => { const c = v / 255; return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; }) as [number, number, number];
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}
/** WCAG contrast ratio of two `#rrggbb` colors (1–21). */
export function contrastRatio(a: string, b: string): number {
const [x, y] = [relativeLuminance(a), relativeLuminance(b)].sort((m, n) => n - m) as [number, number];
return (x + 0.05) / (y + 0.05);
}
/** White when it reaches 4.5:1 on `hex`, otherwise whichever of black and white reads better. */
export function readableOn(hex: string): string {
const white = contrastRatio(hex, '#ffffff');
return white >= 4.5 || white >= contrastRatio(hex, '#000000') ? '#ffffff' : '#000000';
}
/** `rgb(…)` / `rgba(…)` / `#rgb` / `#rrggbb` to `#rrggbb`; null when it is transparent or unparsable. */
export function toHex(value: string | null | undefined): string | null {
const text = (value ?? '').trim();
if (HEX.test(text)) return text.toLowerCase();
const short = /^#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec(text);
if (short) return `#${short[1]}${short[1]}${short[2]}${short[2]}${short[3]}${short[3]}`.toLowerCase();
const match = /^rgba?\(\s*(\d+)[,\s]+(\d+)[,\s]+(\d+)(?:\s*[,/]\s*([\d.]+%?))?\s*\)$/.exec(text);
if (!match) return null;
if (match[4] !== undefined && parseFloat(match[4]) === 0) return null;
return `#${[match[1], match[2], match[3]].map(v => Math.min(255, Number(v)).toString(16).padStart(2, '0')).join('')}`;
}
function mixHex(a: string, b: string, t: number): string {
const [x, y] = [channels(a), channels(b)];
return `#${x.map((v, i) => Math.round(v + (y[i]! - v) * t).toString(16).padStart(2, '0')).join('')}`;
}
/**
* A complete resolved theme from a few page colors (background, text, accent), for sites or moments
* without a theme engine. Surfaces, border and muted text sit between background and text.
*/
export function themeFromColors(bg: string, text: string, accent: string, extra: Partial<Omit<ResolvedTheme, 'colors'>> = {}): ResolvedTheme {
const dark = relativeLuminance(bg) < relativeLuminance(text);
const colors: ResolvedColors = {
bg, text, accent,
surface: mixHex(bg, text, dark ? 0.05 : 0.03),
elevated: mixHex(bg, text, dark ? 0.1 : 0.07),
border: mixHex(bg, text, dark ? 0.2 : 0.15),
muted: mixHex(bg, text, 0.62),
onAccent: readableOn(accent),
inverse: text,
onInverse: bg,
page: bg,
};
return { id: 'page', name: 'Page colors', mode: dark ? 'dark' : 'light', siteDefault: true, radius: 16, buttonRadius: 9999, font: FALLBACK_FONT, ...extra, colors };
}
/** The page's own colors (computed body background and text), used when no theme source exists. */
export function readPageTheme(win: Window, accent = '#1d9bf0'): ResolvedTheme {
let bg: string | null = null;
let text: string | null = null;
let font = '';
try {
const body = win.document.body;
if (body) {
const style = win.getComputedStyle(body);
bg = toHex(style.backgroundColor) ?? toHex(win.getComputedStyle(win.document.documentElement).backgroundColor);
text = toHex(style.color);
font = style.fontFamily;
}
} catch { /* No layout yet. */ }
const dark = !!win.matchMedia?.('(prefers-color-scheme: dark)').matches;
bg ??= dark ? '#000000' : '#ffffff';
text ??= relativeLuminance(bg) < 0.2 ? '#e7e9ea' : '#0f1419';
if (contrastRatio(bg, text) < 3) text = readableOn(bg);
return themeFromColors(bg, text, accent, font ? { font } : {});
}
/** Fills in any role a source left out and freezes the result. */
export function normalizeResolved(theme: ResolvedTheme): ResolvedTheme {
const bg = toHex(theme.colors?.bg) ?? '#ffffff';
let text = toHex(theme.colors?.text) ?? readableOn(bg);
if (contrastRatio(bg, text) < 3) text = readableOn(bg);
const base = themeFromColors(bg, text, toHex(theme.colors?.accent) ?? '#1d9bf0');
const colors = { ...base.colors };
for (const key of Object.keys(colors) as Array<keyof ResolvedColors>) {
const value = theme.colors?.[key];
if (key !== 'bg' && key !== 'text' && typeof value === 'string' && HEX.test(value)) colors[key] = value.toLowerCase();
}
if (!HEX.test(theme.colors.onAccent ?? '')) colors.onAccent = readableOn(colors.accent);
const radius = Number.isFinite(theme.radius) ? Math.max(0, Math.min(28, theme.radius)) : 16;
const buttonRadius = Number.isFinite(theme.buttonRadius) ? Math.max(0, theme.buttonRadius) : 9999;
return Object.freeze({
id: String(theme.id || 'theme'), name: String(theme.name || ''), mode: theme.mode === 'light' ? 'light' : 'dark',
siteDefault: !!theme.siteDefault, radius, buttonRadius, font: theme.font || FALLBACK_FONT,
colors: Object.freeze(colors),
});
}
const VAR_NAMES: Record<keyof ResolvedColors, string> = {
bg: '--wb-bg', surface: '--wb-surface', elevated: '--wb-elevated', border: '--wb-border', text: '--wb-text', muted: '--wb-muted',
accent: '--wb-accent', onAccent: '--wb-on-accent', inverse: '--wb-inverse', onInverse: '--wb-on-inverse', page: '--wb-page',
};
/**
* The theme as CSS custom properties: `--wb-bg`, `--wb-surface`, `--wb-elevated`, `--wb-border`,
* `--wb-text`, `--wb-muted`, `--wb-accent`, `--wb-on-accent`, `--wb-inverse`, `--wb-on-inverse`,
* `--wb-page`, `--wb-radius`, `--wb-button-radius`, `--wb-font`, `--wb-mode` (`light`/`dark`).
*/
export function themeVars(theme: ResolvedTheme): Record<string, string> {
const vars: Record<string, string> = {};
for (const [key, name] of Object.entries(VAR_NAMES)) vars[name] = theme.colors[key as keyof ResolvedColors];
vars['--wb-radius'] = `${theme.radius}px`;
vars['--wb-button-radius'] = `${theme.buttonRadius}px`;
vars['--wb-font'] = theme.font;
vars['--wb-mode'] = theme.mode;
return vars;
}
/** `:root{--wb-…}` for a `<style>` element (values come from a resolved theme, never raw input). */
export function themeVarsCss(theme: ResolvedTheme, selector = ':root'): string {
const safe = (value: string) => value.replace(/[;{}<>\\]/g, '');
return `${selector}{${Object.entries(themeVars(theme)).map(([name, value]) => `${name}:${safe(value)}`).join(';')}}`;
}
/** A stable key: equal keys mean nothing visible changed. */
export const themeKey = (theme: ResolvedTheme) => JSON.stringify(theme);
/**
* `api.theme`. With a site `source` it reports the site's resolved theme (falling back to the page's
* computed colors while the source has none); without one, only the page's colors.
*/
export function createThemeApi(win: Window, source?: ThemeSource, fallbackAccent?: string): ThemeApi {
const report = (error: unknown) => console.error('[wayBetter] theme listener failed', error);
const current = (): ResolvedTheme => {
let resolved: ResolvedTheme | null = null;
try { resolved = source?.current() ?? null; } catch (error) { report(error); }
return normalizeResolved(resolved ?? readPageTheme(win, fallbackAccent));
};
return Object.freeze({
current,
onChange(listener: (theme: ResolvedTheme) => void) {
if (!source) return () => {};
let last = '';
try { last = themeKey(current()); } catch { /* Reported by current(). */ }
return source.onChange(() => {
const next = current();
const key = themeKey(next);
if (key === last) return;
last = key;
try { listener(next); } catch (error) { report(error); }
});
},
});
}

908
packages/runtime/src/ui.ts Normal file
View file

@ -0,0 +1,908 @@
// `api.ui`: toasts, alerts, confirmations, prompts and dialogs for plugins, drawn in the active
// theme's colors, corners and font. Everything lives in one Shadow DOM host (`<wb-ui>`), so the
// site's CSS cannot reach it and it cannot reach the site; the host exists only while something is
// on screen, and a plugin's `scope.ui` closes whatever that plugin opened when it stops.
//
// Accessibility: dialogs are `role="dialog"` (alerts and confirmations `role="alertdialog"`),
// `aria-modal`, labelled by their title and described by their message; focus moves in, is trapped
// (Tab / Shift+Tab wrap), and returns to where it was. Esc dismisses, Enter in a single-line field
// runs the default action. Stacked dialogs make the ones below inert. Toasts are a polite live
// region (danger toasts `role="alert"`), pause while hovered or focused, and stack (four at most).
// Motion is skipped with `prefers-reduced-motion`. Text is always set as text (never parsed as HTML).
import { themeVars, type ResolvedTheme, type ThemeApi } from './themeApi.ts';
export type Tone = 'neutral' | 'info' | 'success' | 'warning' | 'danger';
/** Dialog content: text, a node, or a function that fills the dialog's body element. */
export type Content = string | Node | ((body: HTMLElement) => void) | null | undefined;
export type ModalAction = {
label: string;
/** `primary` (filled, the theme's button colors), `secondary` (outlined, default), `danger`, `plain` (text). */
tone?: 'primary' | 'secondary' | 'danger' | 'plain';
/** Runs on click. Return `false` (or a promise of `false`) to keep the dialog open. */
onClick?: (handle: ModalHandle) => unknown;
/** What `closed` resolves with when this action closes the dialog (default: the label). */
value?: unknown;
/** Enter in a single-line field (or on the dialog itself) runs this action. */
default?: boolean;
/** Focused when the dialog opens. */
autoFocus?: boolean;
disabled?: boolean;
};
export type ModalOptions = {
role?: 'dialog' | 'alertdialog';
title?: string;
/** Text under the title (also the dialog's accessible description). */
message?: string;
/** Accessible name when there is no visible title. */
label?: string;
content?: Content;
actions?: ModalAction[];
/** px, or `sm` (380), `md` (480, default), `lg` (640). Always fits the window. */
width?: number | 'sm' | 'md' | 'lg';
/** Adds a tone icon before the title. */
tone?: Tone;
/** Esc and the close button dismiss it (default true). */
dismissible?: boolean;
/** A click on the backdrop dismisses it (default false; alerts and confirmations say true). */
closeOnBackdrop?: boolean;
/** Shows a close button in the header (default: dismissible and titled). */
closeButton?: boolean;
/** Element or selector (inside the dialog) to focus first. */
initialFocus?: HTMLElement | string;
/** Extra CSS for this dialog's content (scoped to the kit's shadow root). */
css?: string;
/** `closed` resolves with this when dismissed (Esc, backdrop, close button, owner stopped). */
dismissValue?: unknown;
/** Buttons stacked full width (the site's confirmation sheet look) instead of a right-aligned row. */
stackActions?: boolean;
onClose?: (result: unknown) => void;
};
export type ModalHandle = {
/** The dialog element (`role="dialog"`). */
readonly element: HTMLElement;
/** Where `content` went; add or replace your own nodes here. */
readonly body: HTMLElement;
readonly open: boolean;
/** Resolves with the close result once the dialog is gone. */
readonly closed: Promise<unknown>;
close(result?: unknown): void;
/** Shows (or clears with null) an error line above the actions, announced to screen readers. */
setError(message: string | null): void;
/** Disables the actions while something runs. */
setBusy(busy: boolean): void;
};
export type DialogOptions = Omit<ModalOptions, 'role'>;
export type AlertOptions = { title?: string; message?: string; tone?: Tone; okLabel?: string };
export type ConfirmOptions = { title?: string; message?: string; confirmLabel?: string; cancelLabel?: string; danger?: boolean };
export type PromptOptions = {
title?: string;
message?: string;
label?: string;
value?: string;
placeholder?: string;
/** Return an error message (or false) to refuse the value; anything else accepts it. */
validate?: (value: string) => string | boolean | null | undefined;
/** A textarea instead of a single line (Ctrl/Cmd+Enter submits). */
multiline?: boolean;
maxLength?: number;
confirmLabel?: string;
cancelLabel?: string;
width?: ModalOptions['width'];
};
export type ToastAction = { label: string; onClick: () => void };
export type ToastOptions = {
tone?: Tone;
/** ms on screen (default 3200, 6000 with an action); 0 keeps it until closed. */
duration?: number;
action?: ToastAction;
};
export type ToastHandle = { readonly element: HTMLElement; close(): void; readonly closed: Promise<void> };
type Child = Node | string | number | null | undefined | false | Child[];
export type ElementProps = Record<string, unknown>;
export type UiKit = {
toast(message: string, options?: ToastOptions | number): ToastHandle;
alert(options: AlertOptions | string): Promise<void>;
confirm(options: ConfirmOptions | string): Promise<boolean>;
prompt(options: PromptOptions | string): Promise<string | null>;
dialog(options: DialogOptions): ModalHandle;
modal(options: ModalOptions): ModalHandle;
/**
* A safe element builder for dialog content: `h('label', { class: 'wb-check' }, input, 'Text')`.
* Strings become text nodes; `on<event>` functions become listeners; `value`/`checked`/`disabled`
* are set as properties; everything else as attributes (no `innerHTML`, no string handlers, no
* `javascript:` URLs).
*/
h(tag: string, props?: ElementProps | null, ...children: Child[]): HTMLElement;
};
export type UiKitOptions = {
theme: ThemeApi;
/** Custom element name of the shadow host (default `wb-ui`). */
hostTag?: string;
/** Id of the shadow host element. */
hostId?: string;
zIndex?: number;
/** Console prefix. */
product?: string;
};
export type RootUiKit = UiKit & {
/** A kit whose dialogs and toasts are closed by `dispose()` (a plugin's `scope.ui`). */
scoped(): { kit: UiKit; dispose(): void };
/** Open dialogs, bottom first (for tests and the shell). */
openModals(): number;
};
// ---------------------------------------------------------------------------------------------
// Pure helpers (tested without a DOM)
export const WIDTHS = { sm: 380, md: 480, lg: 640 } as const;
export const MAX_TOASTS = 4;
/** Dialog width in px for an option value. */
export function dialogWidth(width: ModalOptions['width']): number {
if (typeof width === 'number' && Number.isFinite(width)) return Math.max(260, Math.min(960, Math.round(width)));
return WIDTHS[width as keyof typeof WIDTHS] ?? WIDTHS.md;
}
/** How long a toast stays: explicit ms, 0 = until closed; defaults 3200 / 6000 with an action. */
export function toastDuration(options: ToastOptions): number {
const value = options.duration;
if (typeof value === 'number' && Number.isFinite(value)) return value <= 0 ? 0 : Math.max(800, Math.min(60_000, value));
if (value === Infinity) return 0;
return options.action ? 6000 : 3200;
}
/** Tab / Shift+Tab inside a trap: the index to focus next, or -1 to let the browser move focus. */
export function trapIndex(count: number, current: number, backwards: boolean): number {
if (count === 0) return -1;
if (current < 0) return backwards ? count - 1 : 0;
if (backwards && current === 0) return count - 1;
if (!backwards && current === count - 1) return 0;
return -1;
}
/** A validator's answer as an error message (null = valid). */
export function validationMessage(result: unknown): string | null {
if (typeof result === 'string') return result.trim() ? result : null;
if (result === false) return 'Please check this value.';
return null;
}
const BLOCKED_PROPS = new Set(['innerhtml', 'outerhtml', 'srcdoc', 'insertadjacenthtml']);
const PROPERTY_PROPS = new Set(['value', 'checked', 'disabled', 'selected', 'indeterminate', 'multiple', 'readOnly', 'required', 'rows', 'maxLength', 'spellcheck', 'tabIndex']);
const URL_ATTRS = /^(href|src|srcset|action|formaction|xlink:href|poster|ping|cite|background)$/i;
const SAFE_SCHEMES = new Set(['http', 'https', 'mailto']);
/**
* Whether a URL attribute value is safe: relative, or http(s)/mailto. Checked the way browsers read
* a URL (tabs and newlines anywhere and leading control characters/spaces are ignored), so
* `java\tscript:` or `\x01javascript:` do not slip through.
*/
export function isSafeUrl(value: string): boolean {
const normalized = String(value).replace(/[\t\n\r]/g, '').replace(/^[\u0000-\u0020]+/, '');
const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(normalized);
return !scheme || SAFE_SCHEMES.has(scheme[1]!.toLowerCase());
}
/** The builder behind `ui.h`, for any document. */
export function buildElement(doc: Document, tag: string, props?: ElementProps | null, ...children: Child[]): HTMLElement {
if (!/^[a-z][a-z0-9-]*$/i.test(tag) || /^(script|style|iframe|object|embed)$/i.test(tag)) throw new Error(`ui.h: unsupported tag ${JSON.stringify(tag)}`);
const element = doc.createElement(tag);
for (const [key, value] of Object.entries(props ?? {})) {
if (value === undefined || value === null || value === false && !PROPERTY_PROPS.has(key)) continue;
if (BLOCKED_PROPS.has(key.toLowerCase())) continue;
if (key === 'class' || key === 'className') element.className = String(value);
else if (key === 'text') element.textContent = String(value);
else if (key === 'style' && typeof value === 'object') Object.assign(element.style, value);
else if (key === 'dataset' && typeof value === 'object') Object.assign(element.dataset, value);
else if (/^on[a-z]/i.test(key)) { if (typeof value === 'function') element.addEventListener(key.slice(2).toLowerCase(), value as EventListener); }
else if (PROPERTY_PROPS.has(key)) (element as unknown as Record<string, unknown>)[key] = value;
else if (URL_ATTRS.test(key) && !isSafeUrl(String(value))) continue;
else element.setAttribute(key, value === true ? '' : String(value));
}
const append = (child: Child) => {
if (child === null || child === undefined || child === false) return;
if (Array.isArray(child)) { for (const item of child) append(item); return; }
element.appendChild(typeof child === 'object' ? child : doc.createTextNode(String(child)));
};
for (const child of children) append(child);
return element;
}
// ---------------------------------------------------------------------------------------------
// Styles (inside the shadow root; every value comes from `--wb-*` set on the host)
const DANGER = '#f4212e';
const TONES: Record<Tone, string> = { neutral: 'var(--wb-accent)', info: 'var(--wb-accent)', success: '#00ba7c', warning: '#ffad1f', danger: DANGER };
// Toast colors keep their label at 4.5:1 or more (neutral toasts use the theme's inverse pair,
// which the theme engine keeps legible).
const TOAST_TONES: Record<Exclude<Tone, 'neutral' | 'info'>, [string, string]> = { success: ['#00805a', '#ffffff'], warning: ['#ffd400', '#0f1419'], danger: ['#d0121f', '#ffffff'] };
export const UI_CSS = `
:host { all: initial; }
.wb-root { font-family: var(--wb-font); color: var(--wb-text); -webkit-font-smoothing: antialiased; }
.wb-root *, .wb-root *::before, .wb-root *::after { box-sizing: border-box; }
.wb-layer { position: fixed; inset: 0; display: grid; place-items: center; padding: 16px; pointer-events: auto; overscroll-behavior: contain; }
.wb-backdrop { position: absolute; inset: 0; background: var(--wb-scrim); animation: wb-fade .16s ease-out; }
.wb-dialog { position: relative; width: min(var(--wb-dialog-width, 480px), 100%); max-height: calc(100vh - 32px); overflow: auto; overscroll-behavior: contain;
display: flex; flex-direction: column; gap: 0; padding: 20px 24px 22px; background: var(--wb-bg); color: var(--wb-text);
border: 1px solid var(--wb-border); border-radius: var(--wb-radius); box-shadow: 0 24px 64px -12px rgba(0,0,0,.45), 0 2px 8px rgba(0,0,0,.12);
font: 400 15px/1.45 var(--wb-font); outline: none; animation: wb-in .18s cubic-bezier(.2,.9,.3,1.2); }
.wb-layer.wb-closing .wb-dialog { animation: wb-out .12s ease-in forwards; }
.wb-layer.wb-closing .wb-backdrop { animation: wb-fade-out .12s ease-in forwards; }
.wb-layer[inert] .wb-dialog { filter: saturate(.9); }
.wb-head { display: flex; align-items: flex-start; gap: 10px; margin: 0 0 4px; }
.wb-title { flex: 1; margin: 0; font: 800 20px/1.25 var(--wb-font); letter-spacing: -.01em; color: var(--wb-text); overflow-wrap: anywhere; }
.wb-icon { flex: none; width: 24px; height: 24px; margin-top: 1px; color: var(--wb-tone); }
.wb-icon svg { display: block; width: 24px; height: 24px; }
.wb-close { flex: none; display: grid; place-items: center; width: 32px; height: 32px; margin: -6px -10px 0 0; padding: 0; border: 0; border-radius: 999px;
background: transparent; color: var(--wb-text); cursor: pointer; }
.wb-close:hover { background: var(--wb-hover); }
.wb-close svg { width: 18px; height: 18px; }
.wb-message { margin: 4px 0 0; color: var(--wb-muted); white-space: pre-line; overflow-wrap: anywhere; }
.wb-body { margin-top: 14px; min-width: 0; }
.wb-body:empty { display: none; }
.wb-error { margin: 12px 0 0; color: var(--wb-danger); font-size: 13px; font-weight: 600; }
.wb-error[hidden] { display: none; }
.wb-actions { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 10px; margin-top: 22px; }
.wb-actions:empty { display: none; }
.wb-actions.wb-stack { flex-direction: column; align-items: stretch; gap: 12px; margin-top: 24px; }
.wb-actions.wb-stack .wb-btn { height: 44px; font-size: 16px; }
.wb-btn { display: inline-flex; align-items: center; justify-content: center; gap: 6px; min-width: 72px; height: 36px; padding: 0 18px;
border: 1px solid transparent; border-radius: var(--wb-button-radius); font: 700 15px/1 var(--wb-font); cursor: pointer; white-space: nowrap;
transition: background-color .12s, filter .12s, opacity .12s; }
.wb-btn:disabled, .wb-btn[aria-disabled="true"] { opacity: .5; cursor: default; }
.wb-btn:focus-visible, .wb-close:focus-visible, .wb-toast button:focus-visible { outline: 2px solid var(--wb-accent); outline-offset: 2px; }
.wb-primary { background: var(--wb-inverse); color: var(--wb-on-inverse); }
.wb-primary:not(:disabled):not([aria-disabled="true"]):hover { filter: brightness(.92) contrast(1.05); }
.wb-danger { background: var(--wb-danger); color: #fff; }
.wb-danger:not(:disabled):hover { filter: brightness(.92); }
.wb-secondary { background: transparent; color: var(--wb-text); border-color: var(--wb-border-strong); }
.wb-secondary:not(:disabled):hover { background: var(--wb-hover); }
.wb-plain { background: transparent; color: var(--wb-accent); min-width: 0; padding: 0 10px; }
.wb-plain:not(:disabled):hover { background: var(--wb-hover); }
.wb-btn[aria-busy="true"] { cursor: progress; }
/* Form parts for dialog content. */
.wb-field { display: flex; flex-direction: column; gap: 6px; margin: 0 0 12px; }
.wb-field:last-child { margin-bottom: 0; }
.wb-label { font-size: 13px; font-weight: 600; color: var(--wb-muted); }
.wb-hint { margin: 0; font-size: 13px; color: var(--wb-muted); }
.wb-input, .wb-dialog input[type="text"], .wb-dialog input[type="search"], .wb-dialog input[type="url"], .wb-dialog input[type="number"], .wb-dialog textarea, .wb-dialog select {
width: 100%; min-height: 40px; padding: 9px 12px; border: 1px solid var(--wb-border-strong); border-radius: var(--wb-field-radius);
background: var(--wb-bg); color: var(--wb-text); font: 400 15px/1.4 var(--wb-font); outline: none; transition: border-color .12s, box-shadow .12s; }
.wb-dialog textarea { min-height: 96px; resize: vertical; }
.wb-dialog textarea.wb-mono { font: 400 13px/1.5 ui-monospace, "Cascadia Mono", Consolas, Menlo, monospace; }
.wb-input::placeholder, .wb-dialog input::placeholder, .wb-dialog textarea::placeholder { color: var(--wb-muted); opacity: .8; }
.wb-input:focus, .wb-dialog input:focus, .wb-dialog textarea:focus, .wb-dialog select:focus { border-color: var(--wb-accent); box-shadow: 0 0 0 1px var(--wb-accent); }
.wb-dialog [aria-invalid="true"] { border-color: var(--wb-danger) !important; box-shadow: 0 0 0 1px var(--wb-danger) !important; }
.wb-check { display: flex; align-items: flex-start; gap: 10px; padding: 7px 0; cursor: pointer; line-height: 1.35; }
.wb-check input { flex: none; width: 18px; height: 18px; margin: 1px 0 0; accent-color: var(--wb-accent); cursor: pointer; }
.wb-check small { display: block; color: var(--wb-muted); font-size: 13px; }
.wb-divider { height: 1px; margin: 12px 0; background: var(--wb-border); border: 0; }
.wb-row { display: flex; align-items: center; gap: 10px; }
.wb-muted { color: var(--wb-muted); }
.wb-dialog a { color: var(--wb-accent); }
/* Toasts */
.wb-toasts { position: fixed; left: 50%; bottom: 24px; transform: translateX(-50%); display: flex; flex-direction: column; align-items: center; gap: 8px;
width: max-content; max-width: min(560px, calc(100vw - 32px)); pointer-events: none; }
.wb-toast { display: flex; align-items: center; gap: 12px; min-height: 44px; max-width: 100%; padding: 10px 10px 10px 16px; border-radius: min(var(--wb-radius), 12px);
background: var(--wb-toast-bg); color: var(--wb-toast-fg); box-shadow: 0 10px 30px -6px rgba(0,0,0,.4); pointer-events: auto;
font: 500 15px/1.35 var(--wb-font); animation: wb-toast-in .2s cubic-bezier(.2,.9,.3,1.2); }
.wb-toast.wb-closing { animation: wb-toast-out .14s ease-in forwards; }
${Object.entries(TOAST_TONES).map(([tone, [bg, fg]]) => `.wb-toast[data-tone="${tone}"] { --wb-toast-bg: ${bg}; --wb-toast-fg: ${fg}; }`).join(' ')}
.wb-toast-icon { flex: none; display: grid; margin-left: -4px; }
.wb-toast-icon svg { width: 20px; height: 20px; }
.wb-toast[data-tone="info"] .wb-toast-icon { color: var(--wb-accent); }
.wb-toast-text { flex: 1; min-width: 0; overflow-wrap: anywhere; white-space: pre-line; padding-right: 4px; }
.wb-toast button { flex: none; border: 0; cursor: pointer; color: inherit; font: 700 14px/1 var(--wb-font); }
.wb-toast-action { height: 30px; padding: 0 12px; border-radius: var(--wb-button-radius); background: color-mix(in srgb, currentColor 16%, transparent); }
.wb-toast-action:hover { background: color-mix(in srgb, currentColor 26%, transparent); }
.wb-toast-close { display: grid; place-items: center; width: 28px; height: 28px; padding: 0; border-radius: 999px; background: transparent; opacity: .8; }
.wb-toast-close:hover { opacity: 1; background: color-mix(in srgb, currentColor 16%, transparent); }
.wb-toast-close svg { width: 16px; height: 16px; }
@keyframes wb-fade { from { opacity: 0; } }
@keyframes wb-fade-out { to { opacity: 0; } }
@keyframes wb-in { from { opacity: 0; transform: translateY(6px) scale(.97); } }
@keyframes wb-out { to { opacity: 0; transform: scale(.98); } }
@keyframes wb-toast-in { from { opacity: 0; transform: translateY(10px) scale(.98); } }
@keyframes wb-toast-out { to { opacity: 0; transform: translateY(6px); } }
@media (prefers-reduced-motion: reduce) {
.wb-root *, .wb-root *::before, .wb-root *::after { animation: none !important; transition: none !important; }
}
`;
const SVG_NS = 'http://www.w3.org/2000/svg';
const ICONS: Record<Exclude<Tone, 'neutral'> | 'close', string> = {
info: 'M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20Zm1 15h-2v-6h2v6Zm0-8h-2V7h2v2Z',
success: 'M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20Zm-1.2 14.2-4-4 1.4-1.4 2.6 2.6 5-5 1.4 1.4-6.4 6.4Z',
warning: 'M12 2 1 21h22L12 2Zm1 16h-2v-2h2v2Zm0-4h-2v-5h2v5Z',
danger: 'M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20Zm1 15h-2v-2h2v2Zm0-4h-2V7h2v6Z',
close: 'M10.59 12 4.54 5.96l1.42-1.42L12 10.59l6.04-6.05 1.42 1.42L13.41 12l6.05 6.04-1.42 1.42L12 13.41l-6.04 6.05-1.42-1.42L10.59 12Z',
};
const FOCUSABLE = 'a[href],button:not([disabled]),input:not([disabled]):not([type="hidden"]),select:not([disabled]),textarea:not([disabled]),[contenteditable]:not([contenteditable="false"]),[tabindex]:not([tabindex="-1"])';
// ---------------------------------------------------------------------------------------------
type Entry = { close(result?: unknown): void };
type Owner = Set<Entry>;
type OpenModal = {
layer: HTMLElement;
panel: HTMLElement;
handle: ModalHandle;
dismiss(): void;
returnTo: HTMLElement | null;
lastFocus: HTMLElement | null;
};
/** The deepest focused element, through open shadow roots. */
export function deepActiveElement(doc: Document): HTMLElement | null {
let active = doc.activeElement as HTMLElement | null;
while (active?.shadowRoot?.activeElement) active = active.shadowRoot.activeElement as HTMLElement;
return active;
}
export function createUiKit(win: Window & typeof globalThis, options: UiKitOptions): RootUiKit {
const doc = win.document;
const hostTag = options.hostTag ?? 'wb-ui';
const product = options.product ?? 'wayBetter';
const report = (error: unknown) => console.error(`[${product}] ui callback failed`, error);
const reducedMotion = () => { try { return !!win.matchMedia?.('(prefers-reduced-motion: reduce)').matches; } catch { return false; } };
let host: HTMLElement | null = null;
let root: ShadowRoot | HTMLElement | null = null;
let layers: HTMLElement | null = null;
let toastRegion: HTMLElement | null = null;
let offTheme: (() => void) | null = null;
const stack: OpenModal[] = [];
const toasts: Array<{ element: HTMLElement; key: string; restart(): void; close(): void; closed: Promise<void> }> = [];
let seq = 0;
let pendingExits = 0;
const ownerIds = new WeakMap<Owner, number>();
const paint = (theme: ResolvedTheme) => {
if (!host) return;
const vars = themeVars(theme);
const dark = theme.mode === 'dark';
vars['--wb-scrim'] = dark ? 'rgba(91, 112, 131, 0.4)' : 'rgba(15, 20, 25, 0.4)';
vars['--wb-hover'] = `color-mix(in srgb, ${theme.colors.text} ${dark ? 12 : 8}%, transparent)`;
vars['--wb-border-strong'] = `color-mix(in srgb, ${theme.colors.border} 70%, ${theme.colors.muted})`;
vars['--wb-field-radius'] = `${Math.min(10, Math.max(2, Math.round(theme.radius / 2)))}px`;
vars['--wb-danger'] = DANGER;
vars['--wb-toast-bg'] = theme.colors.inverse;
vars['--wb-toast-fg'] = theme.colors.onInverse;
for (const [name, value] of Object.entries(vars)) host.style.setProperty(name, value);
host.style.setProperty('color-scheme', theme.mode);
};
const ensureRoot = () => {
if (host?.isConnected && root && layers && toastRegion) return;
if (host) {
// Someone removed the host while things were open: close them (their promises resolve).
offTheme?.();
offTheme = null;
for (const entry of [...stack]) entry.dismiss();
for (const item of [...toasts]) item.close();
}
host?.remove();
host = doc.createElement(hostTag);
host.setAttribute('data-wb-ui', '');
if (options.hostId) host.id = options.hostId;
// The host sits above the site; it takes no clicks itself (its layers and toasts do).
host.style.cssText = `all:initial;position:fixed;inset:0;z-index:${options.zIndex ?? 2147483600};pointer-events:none;display:block;`;
root = typeof host.attachShadow === 'function' ? host.attachShadow({ mode: 'open' }) : host;
const style = doc.createElement('style');
style.textContent = UI_CSS;
const wrap = doc.createElement('div');
wrap.className = 'wb-root';
layers = doc.createElement('div');
toastRegion = doc.createElement('div');
toastRegion.className = 'wb-toasts';
toastRegion.setAttribute('aria-live', 'polite');
toastRegion.setAttribute('aria-relevant', 'additions');
wrap.append(layers, toastRegion);
root.append(style, wrap);
// Keys typed in a dialog are ours: the site's (and plugins') page shortcuts never see them.
for (const type of ['keydown', 'keyup', 'keypress']) root.addEventListener(type, event => event.stopPropagation());
(doc.body ?? doc.documentElement).appendChild(host);
paint(options.theme.current());
offTheme = options.theme.onChange(paint);
};
/** Removes the host once nothing is on screen, so a stopped plugin leaves the page as it was. */
const maybeTeardown = () => {
if (stack.length || toasts.length || pendingExits) return;
offTheme?.();
offTheme = null;
host?.remove();
host = root = layers = toastRegion = null;
};
const later = (fn: () => void, ms: number) => {
if (ms <= 0) { fn(); return; }
pendingExits += 1;
win.setTimeout(() => { pendingExits -= 1; fn(); maybeTeardown(); }, ms);
};
const svg = (path: string) => {
const icon = doc.createElementNS(SVG_NS, 'svg');
icon.setAttribute('viewBox', '0 0 24 24');
icon.setAttribute('aria-hidden', 'true');
const shape = doc.createElementNS(SVG_NS, 'path');
shape.setAttribute('d', path);
shape.setAttribute('fill', 'currentColor');
icon.appendChild(shape);
return icon;
};
const tabbables = (panel: HTMLElement) => Array.from(panel.querySelectorAll<HTMLElement>(FOCUSABLE))
.filter(el => el.tabIndex >= 0 && !el.closest('[hidden],[inert]') && el.getClientRects().length > 0);
const focus = (el: HTMLElement | null | undefined) => { try { el?.focus({ preventScroll: true }); } catch { /* Detached. */ } };
// One focus guard for all dialogs: focus that lands outside the kit goes back to the top dialog.
let guardWindow = 0;
let guardCount = 0;
const onFocusIn = (event: FocusEvent) => {
const top = stack[stack.length - 1];
if (!top || event.target === host) return;
// Another focus trap (the site's own modal) fighting ours must not loop forever: give up after 20 tries a second.
const now = Date.now();
if (now - guardWindow > 1000) { guardWindow = now; guardCount = 0; }
if (++guardCount > 20) return;
focus(top.lastFocus?.isConnected && top.panel.contains(top.lastFocus) ? top.lastFocus : tabbables(top.panel)[0] ?? top.panel);
};
const syncStack = () => {
stack.forEach((entry, index) => {
const top = index === stack.length - 1;
entry.layer.toggleAttribute('inert', !top);
if (top) entry.layer.removeAttribute('aria-hidden');
else entry.layer.setAttribute('aria-hidden', 'true');
});
if (stack.length) doc.addEventListener('focusin', onFocusIn, true);
else doc.removeEventListener('focusin', onFocusIn, true);
};
function modal(input: ModalOptions, owner?: Owner): ModalHandle {
ensureRoot();
const opts = input ?? {};
const id = `wb-${++seq}`;
const dismissible = opts.dismissible !== false;
const layer = doc.createElement('div');
layer.className = 'wb-layer';
const backdrop = doc.createElement('div');
backdrop.className = 'wb-backdrop';
const panel = doc.createElement('div');
panel.className = 'wb-dialog';
panel.setAttribute('role', opts.role === 'alertdialog' ? 'alertdialog' : 'dialog');
panel.setAttribute('aria-modal', 'true');
panel.tabIndex = -1;
panel.style.setProperty('--wb-dialog-width', `${dialogWidth(opts.width)}px`);
if (opts.tone) panel.style.setProperty('--wb-tone', TONES[opts.tone]);
if (opts.title || (dismissible && opts.closeButton)) {
const head = doc.createElement('div');
head.className = 'wb-head';
if (opts.tone && opts.tone !== 'neutral') {
const icon = doc.createElement('span');
icon.className = 'wb-icon';
icon.appendChild(svg(ICONS[opts.tone]));
head.appendChild(icon);
}
const title = doc.createElement('h2');
title.className = 'wb-title';
title.id = `${id}-title`;
title.textContent = opts.title ?? '';
head.appendChild(title);
if (dismissible && (opts.closeButton ?? !!opts.title)) {
const x = doc.createElement('button');
x.type = 'button';
x.className = 'wb-close';
x.setAttribute('aria-label', 'Close');
x.appendChild(svg(ICONS.close));
x.addEventListener('click', () => dismiss());
head.appendChild(x);
}
panel.appendChild(head);
if (opts.title) panel.setAttribute('aria-labelledby', title.id);
}
if (!opts.title) panel.setAttribute('aria-label', opts.label || opts.message || 'Dialog');
if (opts.message) {
const message = doc.createElement('p');
message.className = 'wb-message';
message.id = `${id}-message`;
message.textContent = opts.message;
panel.appendChild(message);
panel.setAttribute('aria-describedby', message.id);
}
if (opts.css) {
const style = doc.createElement('style');
style.textContent = opts.css;
panel.appendChild(style);
}
const body = doc.createElement('div');
body.className = 'wb-body';
panel.appendChild(body);
const error = doc.createElement('p');
error.className = 'wb-error';
error.id = `${id}-error`;
error.setAttribute('role', 'alert');
error.hidden = true;
panel.appendChild(error);
const actionRow = doc.createElement('div');
actionRow.className = opts.stackActions ? 'wb-actions wb-stack' : 'wb-actions';
panel.appendChild(actionRow);
let isOpen = true;
let resolveClosed!: (value: unknown) => void;
const closed = new Promise<unknown>(resolve => { resolveClosed = resolve; });
const buttons: HTMLButtonElement[] = [];
let defaultAction: { action: ModalAction; button: HTMLButtonElement } | null = null;
let autoFocus: HTMLElement | null = null;
// Busy buttons are aria-disabled, not disabled: a disabled button would drop keyboard focus.
let busy = false;
const setBusy = (value: boolean) => {
busy = value;
for (const button of buttons) {
if (value) { button.setAttribute('aria-disabled', 'true'); button.setAttribute('aria-busy', 'true'); }
else { button.removeAttribute('aria-busy'); if (!button.dataset.disabled) button.removeAttribute('aria-disabled'); }
}
};
const handle: ModalHandle = {
element: panel,
body,
get open() { return isOpen; },
closed,
close: result => close(result),
setError(message) {
error.textContent = message ?? '';
error.hidden = !message;
},
setBusy,
};
const run = async (action: ModalAction) => {
if (!isOpen || busy) return;
let keep = false;
if (action.onClick) {
let result: unknown;
try {
result = action.onClick(handle);
if (result && typeof (result as Promise<unknown>).then === 'function') {
setBusy(true);
try { result = await result; } finally { if (isOpen) setBusy(false); }
}
} catch (err) {
report(err);
handle.setError(err instanceof Error && err.message ? err.message : 'Something went wrong.');
return;
}
keep = result === false;
}
if (!keep && isOpen) close('value' in action ? action.value : action.label);
};
for (const action of opts.actions ?? []) {
const button = doc.createElement('button');
button.type = 'button';
button.className = `wb-btn wb-${action.tone ?? 'secondary'}`;
button.textContent = action.label;
if (action.disabled) { button.disabled = true; button.dataset.disabled = '1'; }
button.addEventListener('click', () => { void run(action); });
buttons.push(button);
actionRow.appendChild(button);
if (action.default && !defaultAction) defaultAction = { action, button };
if (action.autoFocus && !autoFocus) autoFocus = button;
}
const fill = (content: Content) => {
if (content === null || content === undefined) return;
if (typeof content === 'string') { const p = doc.createElement('p'); p.className = 'wb-message'; p.textContent = content; body.appendChild(p); }
else if (typeof content === 'function') content(body);
else body.appendChild(content);
};
try { fill(opts.content); } catch (err) { report(err); }
const dismiss = () => { if (isOpen) close(opts.dismissValue); };
const entry: OpenModal = { layer, panel, handle, dismiss, returnTo: deepActiveElement(doc), lastFocus: null };
const ownerEntry: Entry = { close: () => dismiss() };
owner?.add(ownerEntry);
function close(result?: unknown) {
if (!isOpen) return;
isOpen = false;
owner?.delete(ownerEntry);
const index = stack.indexOf(entry);
const wasTop = index === stack.length - 1;
if (index >= 0) stack.splice(index, 1);
syncStack();
layer.setAttribute('inert', '');
layer.classList.add('wb-closing');
later(() => layer.remove(), reducedMotion() ? 0 : 130);
// Dialogs opened from this one return focus where this one would have.
for (const other of stack) if (other.returnTo && layer.contains(other.returnTo)) other.returnTo = entry.returnTo;
// Focus never lingers in a dialog that is animating out (keys would still go to its fields).
const active = deepActiveElement(doc);
if (active && layer.contains(active)) active.blur();
if (wasTop) {
const next = stack[stack.length - 1];
const back = entry.returnTo;
if (back?.isConnected && (!next || next.panel.contains(back))) focus(back);
if (next && deepActiveElement(doc) !== back) focus(next.lastFocus?.isConnected && next.panel.contains(next.lastFocus) ? next.lastFocus : next.panel);
}
try { opts.onClose?.(result); } catch (err) { report(err); }
resolveClosed(result);
maybeTeardown();
}
// Keyboard: Tab stays inside; Esc dismisses; Enter runs the default action from a single-line field.
layer.addEventListener('keydown', event => {
if (stack[stack.length - 1] !== entry) return;
// Keys that belong to an input method (composing CJK text) are not ours.
if (event.isComposing || event.keyCode === 229) return;
if (event.key === 'Tab') {
const list = tabbables(panel);
const active = deepActiveElement(doc);
const next = trapIndex(list.length, active ? list.indexOf(active) : -1, event.shiftKey);
if (list.length === 0) { event.preventDefault(); focus(panel); }
else if (next >= 0) { event.preventDefault(); focus(list[next]); }
} else if (event.key === 'Escape') {
event.preventDefault();
if (dismissible) dismiss();
} else if (event.key === 'Enter' && defaultAction && !defaultAction.button.disabled && !busy) {
const target = event.composedPath()[0] as HTMLElement;
const tag = target?.nodeName;
const singleLine = tag === 'INPUT' && !/^(checkbox|radio|button|submit|reset|file)$/i.test((target as HTMLInputElement).type);
const multilineSubmit = tag === 'TEXTAREA' && (event.ctrlKey || event.metaKey);
if (singleLine || multilineSubmit || target === panel) {
event.preventDefault();
void run(defaultAction.action);
}
}
});
layer.addEventListener('focusin', event => { entry.lastFocus = event.composedPath()[0] as HTMLElement; });
// A backdrop click counts only when the press also started on it (a text selection dragged out
// of a field must not close the dialog).
let pressedBackdrop = false;
backdrop.addEventListener('pointerdown', () => { pressedBackdrop = true; });
// Pressing the backdrop must not move focus out of the dialog (to <body>, where keys reach the page).
backdrop.addEventListener('mousedown', event => event.preventDefault());
// Focus that drops to nothing (a click on a non-focusable spot, a removed element) comes back.
layer.addEventListener('focusout', event => {
if (event.relatedTarget) return;
win.setTimeout(() => {
if (!isOpen || stack[stack.length - 1] !== entry) return;
const active = deepActiveElement(doc);
if (!active || active === doc.body || active === doc.documentElement) focus(entry.lastFocus?.isConnected ? entry.lastFocus : panel);
}, 0);
});
layer.addEventListener('pointerup', event => {
const onBackdrop = pressedBackdrop && event.target === backdrop;
pressedBackdrop = false;
if (onBackdrop && opts.closeOnBackdrop && dismissible) dismiss();
});
// The page behind never scrolls while a dialog is open.
layer.addEventListener('wheel', event => {
let node = event.target as HTMLElement | null;
while (node && node !== layer) {
if (node.scrollHeight > node.clientHeight + 1 && /auto|scroll/.test(win.getComputedStyle(node).overflowY)) {
const down = event.deltaY > 0;
if (down ? node.scrollTop + node.clientHeight < node.scrollHeight - 1 : node.scrollTop > 0) return;
}
node = node.parentElement;
}
event.preventDefault();
}, { passive: false });
layer.append(backdrop, panel);
layers!.appendChild(layer);
stack.push(entry);
syncStack();
let initial: HTMLElement | null = null;
try { initial = typeof opts.initialFocus === 'string' ? panel.querySelector<HTMLElement>(opts.initialFocus) : opts.initialFocus ?? null; } catch (err) { report(err); }
const firstField = panel.querySelector<HTMLElement>('.wb-body input:not([type="hidden"]):not([disabled]), .wb-body textarea:not([disabled]), .wb-body select:not([disabled])');
focus(initial ?? autoFocus ?? firstField ?? defaultAction?.button ?? buttons[0] ?? panel);
return handle;
}
function toast(message: string, input?: ToastOptions | number, owner?: Owner): ToastHandle {
ensureRoot();
const opts: ToastOptions = typeof input === 'number' ? { duration: input } : input ?? {};
const tone = opts.tone ?? 'neutral';
const text = String(message ?? '');
let ownerId = 0;
if (owner) { ownerId = ownerIds.get(owner) ?? ++seq; ownerIds.set(owner, ownerId); }
const key = `${ownerId}|${tone}|${text}|${opts.action?.label ?? ''}`;
// The same message again restarts the visible one instead of stacking a copy.
const same = toasts.find(item => item.key === key);
if (same) {
same.restart();
return { element: same.element, close: same.close, closed: same.closed };
}
const element = doc.createElement('div');
element.className = 'wb-toast';
element.dataset.tone = tone;
element.setAttribute('role', tone === 'danger' ? 'alert' : 'status');
if (tone !== 'neutral') {
const icon = doc.createElement('span');
icon.className = 'wb-toast-icon';
icon.appendChild(svg(ICONS[tone]));
element.appendChild(icon);
}
const label = doc.createElement('span');
label.className = 'wb-toast-text';
label.textContent = text;
element.appendChild(label);
let resolveClosed!: () => void;
const closed = new Promise<void>(resolve => { resolveClosed = resolve; });
let timer = 0;
let open = true;
const duration = toastDuration(opts);
const ownerEntry: Entry = { close: () => close() };
let held = false;
const start = () => { win.clearTimeout(timer); if (duration > 0 && !held) timer = win.setTimeout(close, duration); };
const hold = (value: boolean) => { held = value; if (value) win.clearTimeout(timer); else start(); };
function close() {
if (!open) return;
open = false;
win.clearTimeout(timer);
// A focused toast going away hands focus back to the open dialog (or lets go of it).
const active = deepActiveElement(doc);
if (active && element.contains(active)) {
const top = stack[stack.length - 1];
if (top) focus(top.lastFocus?.isConnected && top.panel.contains(top.lastFocus) ? top.lastFocus : top.panel);
else active.blur();
}
owner?.delete(ownerEntry);
const index = toasts.indexOf(item);
if (index >= 0) toasts.splice(index, 1);
element.classList.add('wb-closing');
later(() => element.remove(), reducedMotion() ? 0 : 150);
resolveClosed();
maybeTeardown();
}
if (opts.action) {
const action = opts.action;
const button = doc.createElement('button');
button.type = 'button';
button.className = 'wb-toast-action';
button.textContent = action.label;
button.addEventListener('click', () => {
try { action.onClick(); } catch (err) { report(err); }
close();
});
element.appendChild(button);
}
const dismissButton = doc.createElement('button');
dismissButton.type = 'button';
dismissButton.className = 'wb-toast-close';
dismissButton.setAttribute('aria-label', 'Dismiss');
dismissButton.appendChild(svg(ICONS.close));
dismissButton.addEventListener('click', () => close());
element.appendChild(dismissButton);
// Hovering or focusing a toast holds it on screen.
element.addEventListener('pointerenter', () => hold(true));
element.addEventListener('pointerleave', () => hold(false));
element.addEventListener('focusin', () => hold(true));
element.addEventListener('focusout', () => hold(false));
element.addEventListener('keydown', event => { if (event.key === 'Escape') close(); });
const item = { element, key, restart: start, close, closed };
toasts.push(item);
owner?.add(ownerEntry);
toastRegion!.appendChild(element);
while (toasts.length > MAX_TOASTS) toasts[0]!.close();
start();
return { element, close, closed };
}
const text = (value: unknown) => (typeof value === 'string' ? value : value == null ? '' : String(value));
function alert(input: AlertOptions | string, owner?: Owner): Promise<void> {
const opts: AlertOptions = typeof input === 'string' ? { message: input } : input ?? {};
const handle = modal({
role: 'alertdialog', title: text(opts.title) || undefined, message: text(opts.message) || undefined, tone: opts.tone,
width: 'sm', closeOnBackdrop: true, closeButton: false, stackActions: true,
actions: [{ label: opts.okLabel || 'OK', tone: 'primary', default: true, autoFocus: true, value: undefined }],
}, owner);
return handle.closed.then(() => undefined);
}
function confirm(input: ConfirmOptions | string, owner?: Owner): Promise<boolean> {
const opts: ConfirmOptions = typeof input === 'string' ? { message: input } : input ?? {};
const danger = !!opts.danger;
const handle = modal({
role: 'alertdialog', title: text(opts.title) || undefined, message: text(opts.message) || undefined,
width: 'sm', closeOnBackdrop: true, closeButton: false, stackActions: true, dismissValue: false,
actions: [
// A destructive confirmation starts on Cancel, so Enter never destroys by accident.
{ label: opts.confirmLabel || (danger ? 'Delete' : 'OK'), tone: danger ? 'danger' : 'primary', value: true, default: !danger, autoFocus: !danger },
{ label: opts.cancelLabel || 'Cancel', tone: 'secondary', value: false, autoFocus: danger },
],
}, owner);
return handle.closed.then(result => result === true);
}
function prompt(input: PromptOptions | string, owner?: Owner): Promise<string | null> {
const opts: PromptOptions = typeof input === 'string' ? { title: input } : input ?? {};
const field = doc.createElement(opts.multiline ? 'textarea' : 'input') as HTMLInputElement | HTMLTextAreaElement;
if (field instanceof win.HTMLInputElement) field.type = 'text';
field.className = opts.multiline ? '' : 'wb-input';
field.value = text(opts.value);
if (opts.placeholder) field.placeholder = opts.placeholder;
if (opts.maxLength && opts.maxLength > 0) field.maxLength = Math.floor(opts.maxLength);
field.spellcheck = true;
let tried = false;
let handle!: ModalHandle;
const check = () => {
let message: string | null = null;
try { message = validationMessage(opts.validate?.(field.value)); } catch (err) { message = err instanceof Error ? err.message : 'Please check this value.'; }
field.setAttribute('aria-invalid', message ? 'true' : 'false');
handle.setError(message);
return !message;
};
field.addEventListener('input', () => { if (tried) check(); });
handle = modal({
role: 'dialog', title: text(opts.title) || undefined, message: text(opts.message) || undefined, width: opts.width ?? 'sm', dismissValue: null,
content: body => {
const wrap = doc.createElement('label');
wrap.className = 'wb-field';
if (opts.label) {
const caption = doc.createElement('span');
caption.className = 'wb-label';
caption.textContent = opts.label;
wrap.appendChild(caption);
} else field.setAttribute('aria-label', text(opts.title) || 'Value');
wrap.appendChild(field);
body.appendChild(wrap);
},
actions: [
{ label: opts.cancelLabel || 'Cancel', tone: 'secondary', value: null },
{ label: opts.confirmLabel || 'OK', tone: 'primary', default: true, onClick: () => { tried = true; return check() ? undefined : false; }, value: undefined },
],
initialFocus: field,
}, owner);
field.setAttribute('aria-describedby', `${handle.element.querySelector('.wb-error')?.id ?? ''}`);
// The OK action's result is the field's value at the moment it closed.
return handle.closed.then(result => (result === null || !tried ? null : field.value));
}
const make = (owner?: Owner): UiKit => Object.freeze({
toast: (message: string, options?: ToastOptions | number) => toast(message, options, owner),
alert: (options: AlertOptions | string) => alert(options, owner),
confirm: (options: ConfirmOptions | string) => confirm(options, owner),
prompt: (options: PromptOptions | string) => prompt(options, owner),
dialog: (options: DialogOptions) => modal({ closeOnBackdrop: false, ...options, role: 'dialog' }, owner),
modal: (options: ModalOptions) => modal(options, owner),
h: (tag: string, props?: ElementProps | null, ...children: Child[]) => buildElement(doc, tag, props, ...children),
});
const base = make();
return Object.freeze({
...base,
scoped() {
const owner: Owner = new Set();
return {
kit: make(owner),
dispose() {
for (const entry of [...owner]) {
try { entry.close(); } catch (err) { report(err); }
}
owner.clear();
},
};
},
openModals: () => stack.length,
});
}

View file

@ -0,0 +1,200 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { buildElement, dialogWidth, toastDuration, trapIndex, validationMessage, UI_CSS, WIDTHS } from '../src/ui.ts';
import {
contrastRatio, createThemeApi, normalizeResolved, readableOn, themeFromColors, themeVars, themeVarsCss, toHex,
type ResolvedTheme, type ThemeSource,
} from '../src/themeApi.ts';
import { createCorePluginApi, isTypingTarget, type PluginApiSite } from '../src/pluginApi.ts';
test('dialog widths: presets, clamped numbers, md by default', () => {
assert.equal(dialogWidth(undefined), WIDTHS.md);
assert.equal(dialogWidth('sm'), 380);
assert.equal(dialogWidth('lg'), 640);
assert.equal(dialogWidth(100), 260);
assert.equal(dialogWidth(5000), 960);
assert.equal(dialogWidth(520.4), 520);
assert.equal(dialogWidth(Number.NaN), WIDTHS.md);
});
test('toast duration: defaults, action default, sticky and clamping', () => {
assert.equal(toastDuration({}), 3200);
assert.equal(toastDuration({ action: { label: 'Undo', onClick() {} } }), 6000);
assert.equal(toastDuration({ duration: 0 }), 0, '0 keeps it until closed');
assert.equal(toastDuration({ duration: Infinity }), 0);
assert.equal(toastDuration({ duration: 10 }), 800);
assert.equal(toastDuration({ duration: 9000 }), 9000);
assert.equal(toastDuration({ duration: 10 ** 9 }), 60_000);
});
test('focus trap wraps at both ends and lets the browser move focus in between', () => {
assert.equal(trapIndex(0, -1, false), -1, 'nothing to focus');
assert.equal(trapIndex(3, -1, false), 0, 'focus outside the list enters at the start');
assert.equal(trapIndex(3, -1, true), 2, 'Shift+Tab from outside enters at the end');
assert.equal(trapIndex(3, 2, false), 0, 'Tab on the last wraps to the first');
assert.equal(trapIndex(3, 0, true), 2, 'Shift+Tab on the first wraps to the last');
assert.equal(trapIndex(3, 1, false), -1);
assert.equal(trapIndex(3, 1, true), -1);
assert.equal(trapIndex(1, 0, false), 0, 'a single element keeps focus');
});
test('validation answers become error messages', () => {
assert.equal(validationMessage('Too long'), 'Too long');
assert.equal(validationMessage(' '), null);
assert.equal(validationMessage(false), 'Please check this value.');
for (const ok of [true, null, undefined, 0, '']) assert.equal(validationMessage(ok), null);
});
test('the kit stylesheet is scoped and honours reduced motion', () => {
assert.match(UI_CSS, /prefers-reduced-motion: reduce/);
assert.match(UI_CSS, /:host \{ all: initial; \}/);
// Every rule targets the kit's own classes (no bare element selectors that could leak by accident).
for (const selector of UI_CSS.replace(/\/\*[\s\S]*?\*\//g, '').replace(/@keyframes[^{]+\{(?:[^{}]*\{[^}]*\})*\s*\}/g, '').match(/(^|\})\s*([^{}@]+)\{/g) ?? []) {
const text = selector.replace(/^\}?\s*/, '').replace(/\{$/, '').trim();
if (!text || text.startsWith('from') || text.startsWith('to')) continue;
for (const part of text.split(',')) assert.match(part.trim(), /^(:host|\.wb-)/, part);
}
});
type FakeNode = {
tag: string; attrs: Record<string, string>; props: Record<string, unknown>; children: unknown[]; listeners: Record<string, unknown>;
className: string; textContent: string; style: Record<string, string>; dataset: Record<string, string>;
setAttribute(k: string, v: string): void; addEventListener(t: string, f: unknown): void; appendChild(c: unknown): unknown;
};
function fakeDoc() {
return {
createElement(tag: string) {
const node: FakeNode = {
tag, attrs: {}, props: {}, children: [], listeners: {}, className: '', textContent: '', style: {}, dataset: {},
setAttribute(k, v) { node.attrs[k] = v; },
addEventListener(t, f) { node.listeners[t] = f; },
appendChild(c) { node.children.push(c); return c; },
};
return node;
},
createTextNode(text: string) { return { text }; },
} as unknown as Document;
}
test('ui.h builds from text only: no innerHTML, string handlers or javascript: URLs', () => {
const doc = fakeDoc();
const click = () => {};
const el = buildElement(doc, 'a', {
class: 'wb-check', href: 'javascript:alert(1)', onclick: 'alert(1)', onClick: click, innerHTML: '<img onerror=x>',
title: 'hi', hidden: true, skip: false, checked: false, dataset: { id: '7' },
}, '<b>not html</b>', 3, null, ['a', false]) as unknown as FakeNode;
assert.equal(el.className, 'wb-check');
assert.equal(el.attrs.href, undefined, 'javascript: URL dropped');
assert.equal(el.attrs.onclick, undefined, 'string handler dropped');
assert.equal(el.listeners.click, click, 'function handler becomes a listener');
assert.equal((el as unknown as Record<string, unknown>).innerHTML, undefined);
assert.equal(el.attrs.innerHTML, undefined);
assert.equal(el.attrs.title, 'hi');
assert.equal(el.attrs.hidden, '');
assert.equal(el.attrs.skip, undefined, 'false attributes are left out');
assert.equal((el as unknown as Record<string, unknown>).checked, false, 'false properties are still set');
assert.equal(el.dataset.id, '7');
assert.deepEqual(el.children, [{ text: '<b>not html</b>' }, { text: '3' }, { text: 'a' }]);
assert.throws(() => buildElement(doc, 'script'), /unsupported tag/);
assert.throws(() => buildElement(doc, 'img onerror=x'), /unsupported tag/);
});
test('colors: hex parsing, contrast, readable label color', () => {
assert.equal(toHex('rgb(0, 0, 0)'), '#000000');
assert.equal(toHex('rgba(21, 32, 43, 1)'), '#15202b');
assert.equal(toHex('rgba(0, 0, 0, 0)'), null, 'transparent is no color');
assert.equal(toHex('#FFF'), '#ffffff');
assert.equal(toHex('red'), null);
assert.ok(Math.abs(contrastRatio('#000000', '#ffffff') - 21) < 0.01);
assert.equal(readableOn('#0b5ed7'), '#ffffff', 'white when it reaches AA');
assert.equal(readableOn('#1d9bf0'), '#000000', "X's blue reads better with black (7:1 vs 3:1)");
assert.equal(readableOn('#ffd400'), '#000000');
});
test('a resolved theme fills missing roles, clamps geometry and becomes --wb-* variables', () => {
const partial = { id: 'demo', name: 'Demo', mode: 'dark', siteDefault: false, radius: 99, buttonRadius: 9999, font: '',
colors: { bg: '#000000', text: '#E7E9EA', accent: '#1d9bf0' } } as unknown as ResolvedTheme;
const theme = normalizeResolved(partial);
assert.equal(theme.colors.text, '#e7e9ea');
assert.ok(theme.colors.surface && theme.colors.border && theme.colors.muted, 'derived roles');
assert.equal(theme.colors.onAccent, readableOn('#1d9bf0'));
assert.equal(theme.radius, 28, 'radius clamped');
assert.ok(theme.font.includes('sans-serif'), 'font falls back to a system stack');
assert.ok(Object.isFrozen(theme) && Object.isFrozen(theme.colors));
const vars = themeVars(theme);
assert.equal(vars['--wb-bg'], '#000000');
assert.equal(vars['--wb-on-inverse'], theme.colors.onInverse);
assert.equal(vars['--wb-radius'], '28px');
assert.equal(vars['--wb-mode'], 'dark');
const css = themeVarsCss({ ...theme, font: 'Evil;}</style><script>' });
assert.ok(css.startsWith(':root{') && css.endsWith('}'));
assert.doesNotMatch(css.slice(6, -1), /[{}<>]/, 'values cannot break out of the rule');
const light = themeFromColors('#ffffff', '#0f1419', '#1d9bf0');
assert.equal(light.mode, 'light');
assert.equal(light.colors.inverse, '#0f1419');
});
test('theme api: reports the source, falls back to page colors, notifies only on real changes', () => {
let current: ResolvedTheme | null = null;
const listeners = new Set<() => void>();
const source: ThemeSource = { current: () => current, onChange: fn => { listeners.add(fn); return () => listeners.delete(fn); } };
const win = {
document: { body: null, documentElement: {} },
getComputedStyle: () => ({ backgroundColor: 'rgb(0, 0, 0)', color: 'rgb(231, 233, 234)', fontFamily: 'Chirp' }),
matchMedia: () => ({ matches: true }),
} as unknown as Window;
const api = createThemeApi(win, source);
assert.equal(api.current().siteDefault, true, 'no source theme yet: page fallback');
const seen: string[] = [];
const off = api.onChange(theme => seen.push(theme.id));
current = themeFromColors('#101820', '#f0f0f0', '#ff7a00', { id: 'mine', siteDefault: false });
for (const fn of listeners) fn();
for (const fn of listeners) fn();
assert.deepEqual(seen, ['mine'], 'one notification per visible change');
assert.equal(api.current().colors.accent, '#ff7a00');
off();
assert.equal(listeners.size, 0, 'dispose unsubscribes');
});
test('core api exposes ui and theme without touching the DOM until something is shown', () => {
const site: PluginApiSite = {
name: 'Demo', product: 'wayBetter for Test', storagePrefix: 'demo:', styleDataKey: 'demo', toastId: 'demo-ui',
toastBackground: '#123456', itemSelector: 'article', chordKeys: [],
};
let created = 0;
const win = {
document: { createElement: () => { created += 1; return {}; }, body: null, documentElement: {} },
location: { href: 'https://example.com/' },
getComputedStyle: () => ({ backgroundColor: 'rgb(255, 255, 255)', color: 'rgb(15, 20, 25)', fontFamily: '' }),
} as unknown as Window & typeof globalThis;
const api = createCorePluginApi(win, site);
assert.equal(typeof api.ui.confirm, 'function');
assert.equal(typeof api.ui.dialog, 'function');
assert.equal(api.theme.current().colors.accent, '#123456', 'site accent is the fallback');
const scope = api.scope();
assert.equal(typeof scope.ui.prompt, 'function');
assert.equal(scope.ui, scope.ui, 'one scoped kit per scope');
scope.onThemeChange(() => {});
scope.dispose();
assert.equal(created, 0);
});
test('typing detection looks into focused shadow roots (dialog fields)', () => {
const input = { nodeName: 'INPUT', closest: () => null };
const host = { nodeName: 'WB-UI', closest: () => null, shadowRoot: { activeElement: input } };
assert.equal(isTypingTarget(host as unknown as EventTarget), true);
const button = { nodeName: 'BUTTON', closest: () => null };
assert.equal(isTypingTarget({ nodeName: 'WB-UI', closest: () => null, shadowRoot: { activeElement: button } } as unknown as EventTarget), false);
});
test('URL attributes are judged the way browsers read them', async () => {
const { isSafeUrl } = await import('../src/ui.ts');
for (const bad of ['javascript:alert(1)', 'java\tscript:alert(1)', 'java\nscript:x', '\x01javascript:x', ' JavaScript:x', 'data:text/html,x', 'vbscript:x']) {
assert.equal(isSafeUrl(bad), false, JSON.stringify(bad));
}
for (const ok of ['https://x.com/jack', 'http://example.com', 'mailto:a@b.c', '/jack/status/1', '#top', 'relative/path', '?q=1']) {
assert.equal(isSafeUrl(ok), true, ok);
}
const el = buildElement(fakeDoc(), 'a', { href: 'java\tscript:alert(1)', src: '\x01javascript:x', srcset: 'javascript:x 1x' }) as unknown as FakeNode;
assert.deepEqual(el.attrs, {}, 'no unsafe URL attribute is set');
});

View file

@ -5,8 +5,10 @@ window, extended in place the way BetterDiscord extends Discord. Websites and se
heavy Electron client alike: every wayBetter app is the same shell, runtime and one small adapter. heavy Electron client alike: every wayBetter app is the same shell, runtime and one small adapter.
- **`waybetter/runtime/*`**: the page runtime. One DOM-mutation/animation-frame hub, one - **`waybetter/runtime/*`**: the page runtime. One DOM-mutation/animation-frame hub, one
fetch/XHR hub, a plugin API core, an OKLab theme color model, split-pane rail hiding, link fetch/XHR hub, a plugin API core with a themed UI kit (toasts, alerts, confirmations, prompts,
routing and account change reporting. dialogs), a theme API, an OKLab theme color model, split-pane rail hiding, link routing and
account change reporting.
- **`waybetter/theme.schema.json`**: the JSON Schema of wayBetter theme files.
- **`waybetter/shell/*`**: pure models for the app chrome around the pages: address bar chips, - **`waybetter/shell/*`**: pure models for the app chrome around the pages: address bar chips,
dock/split-pane rules, dragged links, account profiles, the update chip, command palette dock/split-pane rules, dragged links, account profiles, the update chip, command palette
ranking and window controls. The Tauri window API is passed in by the caller, never imported. ranking and window controls. The Tauri window API is passed in by the caller, never imported.
@ -43,9 +45,11 @@ pieces. The source comments document each module's contract.
- `linkRouting`: routes clicks on the app's own links per the "links to app pages" setting. - `linkRouting`: routes clicks on the app's own links per the "links to app pages" setting.
- `netHub`: one shared fetch/XHR hook for URL rewrites, gates and passive JSON taps. - `netHub`: one shared fetch/XHR hook for URL rewrites, gates and passive JSON taps.
- `paneNav`: hides a redundant navigation rail when two panes show the same account. - `paneNav`: hides a redundant navigation rail when two panes show the same account.
- `pluginApi`: small helpers shared by user JS plugins. - `pluginApi`: small helpers shared by user JS plugins, including `ui` and `theme`.
- `site`: the page-side composition root for an adapter. - `site`: the page-side composition root for an adapter.
- `themeApi`: the active theme as values (`ResolvedTheme`), `--wb-*` CSS variables, contrast helpers.
- `themeTokens`: the OKLab color model themes are built on. - `themeTokens`: the OKLab color model themes are built on.
- `ui`: the plugin UI kit (see below).
**Shell** **Shell**
@ -58,6 +62,62 @@ pieces. The source comments document each module's contract.
- `updateModel`: the titlebar update chip model. - `updateModel`: the titlebar update chip model.
- `windowControls`: native window calls for the titlebar, resize grips and caption buttons. - `windowControls`: native window calls for the titlebar, resize grips and caption buttons.
## Plugin UI kit (`runtime/ui`)
Plugins get it as `api.ui` (and `scope.ui`, which closes whatever it opened on `scope.dispose()`).
Everything is drawn in one Shadow DOM host, so the site's CSS cannot restyle it, and it takes its
colors, corners and font from the active theme (`api.theme`), live.
```js
const ui = this.scope.ui;
ui.toast('Link copied'); // tones: neutral, info, success, warning, danger
ui.toast('Post hidden', { action: { label: 'Undo', onClick: undo } });
await ui.alert({ title: 'Saved', message: 'Kept on this device only.', tone: 'success' });
if (await ui.confirm({ title: 'Delete this note?', confirmLabel: 'Delete', danger: true })) remove();
const name = await ui.prompt({ title: 'Rename', value: 'Reading', validate: v => v.trim() ? null : 'Required' });
const dialog = ui.dialog({
title: 'Settings',
content: body => body.append(ui.h('label', { class: 'wb-check' }, ui.h('input', { type: 'checkbox' }), 'Hide trends')),
actions: [{ label: 'Cancel' }, { label: 'Save', tone: 'primary', default: true, onClick: save }],
});
```
- `modal(options)` is the primitive under all of them; `dialog` is a `role="dialog"`, `alert` /
`confirm` are `role="alertdialog"`. All are `aria-modal`, labelled by their title and described
by their message.
- Focus moves in, Tab/Shift+Tab wrap inside, and focus returns to where it was. Esc dismisses;
Enter in a single-line field (Ctrl/Cmd+Enter in a textarea) runs the `default` action. A
destructive `confirm` starts on Cancel.
- Backdrop clicks dismiss alerts and confirmations only (a press that started in a field and ended
on the backdrop does not count). Keys typed in a dialog never reach the page's own shortcuts.
- Dialogs stack (lower ones become `inert`); toasts stack (four at most), pause while hovered or
focused and are a polite live region (`role="alert"` for danger).
- `prefers-reduced-motion` turns off the animations. Text is always set as text; `ui.h(tag,
props, ...children)` builds content without `innerHTML`, string handlers or `javascript:` URLs.
- Classes for content: `wb-field`, `wb-label`, `wb-hint`, `wb-check`, `wb-input`, `wb-mono`,
`wb-divider`, `wb-row`, `wb-muted`; per-dialog CSS goes in `css`.
`createUiKit(window, { theme })` builds a kit outside the plugin API; `theme` is a `ThemeApi` from
`createThemeApi(window, source)`, where `source` is the site's `{ current(), onChange() }`.
## Themes
`api.theme.current()` returns the active theme resolved: `colors` (`bg`, `surface`, `elevated`,
`border`, `text`, `muted`, `accent`, `onAccent`, `inverse`, `onInverse`, `page`), `radius`,
`buttonRadius`, `font`, `mode` and `siteDefault` (true when the site's own colors show).
`api.theme.onChange(fn)` fires after it changes. The same values are CSS custom properties on
`:root` (`--wb-bg`, `--wb-text`, `--wb-accent`, `--wb-radius`, `--wb-font`, …), so plugin CSS can
use `var(--wb-accent)`.
Theme files are JSON; `theme.schema.json` describes every field and its limits (the app clamps
out-of-range values when it imports a file). Point a theme at it for editor completion and checks:
```json
{ "$schema": "https://unpkg.com/waybetter/theme.schema.json", "name": "Midnight Mint", "colors": { "bg": "#0b1110", "text": "#e8f3ef", "accent": "#3ddc97" } }
```
or, in a project that installs the package, `"$schema": "./node_modules/waybetter/theme.schema.json"`.
## Projects using wayBetter ## Projects using wayBetter
| Project | Target | What it is | | Project | Target | What it is |

View file

@ -1,9 +1,9 @@
{ {
"name": "waybetter", "name": "waybetter",
"version": "0.1.1", "version": "0.2.0",
"license": "GPL-3.0-or-later", "license": "GPL-3.0-or-later",
"type": "module", "type": "module",
"description": "wayBetter: the framework for apps that run the apps you already use in a light native (Tauri) window and extend them in place. Page runtime (DOM/request hubs, plugins, theme color model, link routing, account reporting) and shell models (address bar, panes, profiles, palette, updates). No dependencies.", "description": "wayBetter: the framework for apps that run the apps you already use in a light native (Tauri) window and extend them in place. Page runtime (DOM/request hubs, plugins, plugin UI kit with themed dialogs and toasts, theme API and theme JSON Schema, theme color model, link routing, account reporting) and shell models (address bar, panes, profiles, palette, updates). No dependencies.",
"keywords": [ "keywords": [
"waybetter", "waybetter",
"tauri", "tauri",
@ -52,10 +52,18 @@
"types": "./dist/runtime/site.d.ts", "types": "./dist/runtime/site.d.ts",
"import": "./dist/runtime/site.js" "import": "./dist/runtime/site.js"
}, },
"./runtime/themeApi": {
"types": "./dist/runtime/themeApi.d.ts",
"import": "./dist/runtime/themeApi.js"
},
"./runtime/themeTokens": { "./runtime/themeTokens": {
"types": "./dist/runtime/themeTokens.d.ts", "types": "./dist/runtime/themeTokens.d.ts",
"import": "./dist/runtime/themeTokens.js" "import": "./dist/runtime/themeTokens.js"
}, },
"./runtime/ui": {
"types": "./dist/runtime/ui.d.ts",
"import": "./dist/runtime/ui.js"
},
"./runtime/*": { "./runtime/*": {
"types": "./dist/runtime/*.d.ts", "types": "./dist/runtime/*.d.ts",
"import": "./dist/runtime/*.js" "import": "./dist/runtime/*.js"
@ -95,10 +103,13 @@
"./shell/*": { "./shell/*": {
"types": "./dist/shell/*.d.ts", "types": "./dist/shell/*.d.ts",
"import": "./dist/shell/*.js" "import": "./dist/shell/*.js"
} },
"./theme.schema.json": "./theme.schema.json",
"./package.json": "./package.json"
}, },
"files": [ "files": [
"dist", "dist",
"theme.schema.json",
"README.md", "README.md",
"LICENSE" "LICENSE"
], ],

View file

@ -0,0 +1,156 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://unpkg.com/waybetter/theme.schema.json",
"title": "wayBetter theme",
"description": "A wayBetter theme document (data, not a stylesheet). Only `name` is required. Apps sanitize every field before use: values out of range are clamped and unknown values fall back to the default, so this schema describes what is kept unchanged.",
"type": "object",
"required": ["name"],
"additionalProperties": false,
"properties": {
"$schema": { "type": "string" },
"id": { "type": "string", "pattern": "^[a-z0-9-]{1,40}$", "description": "Derived from the name when missing." },
"name": { "type": "string", "minLength": 1, "maxLength": 60, "pattern": "\\S" },
"description": { "type": "string", "maxLength": 200 },
"author": { "type": "string", "maxLength": 60 },
"version": { "const": 1 },
"mode": { "enum": ["light", "dark", "auto"], "default": "auto", "description": "Which way scrollbars and form controls lean." },
"colors": {
"description": "bg, text and accent are required; every other role is derived from them when missing. null keeps the site's own colors.",
"oneOf": [
{ "type": "null" },
{
"type": "object",
"required": ["bg", "text", "accent"],
"additionalProperties": false,
"properties": {
"bg": { "$ref": "#/$defs/hex", "description": "Column background." },
"surface": { "$ref": "#/$defs/hex", "description": "Raised surface (cards, inputs)." },
"elevated": { "$ref": "#/$defs/hex", "description": "Hover / selected surface." },
"border": { "$ref": "#/$defs/hex" },
"text": { "$ref": "#/$defs/hex" },
"muted": { "$ref": "#/$defs/hex", "description": "Secondary text." },
"accent": { "$ref": "#/$defs/hex", "description": "Links, focus, selected tabs." },
"inverse": { "$ref": "#/$defs/hex", "description": "The filled primary button." },
"onInverse": { "$ref": "#/$defs/hex", "description": "The filled primary button's label." },
"page": { "$ref": "#/$defs/hex", "description": "The canvas behind the columns (defaults to bg)." }
}
}
]
},
"font": {
"type": "object",
"additionalProperties": false,
"properties": {
"family": { "$ref": "#/$defs/fontStack", "description": "Interface font stack; empty keeps the site's font." },
"tweet": { "$ref": "#/$defs/fontStack", "description": "Optional stack for post text only." },
"scale": { "type": "number", "minimum": 0.85, "maximum": 1.2, "default": 1 },
"weight": { "type": "integer", "minimum": 300, "maximum": 500, "default": 400 },
"bold": { "type": "integer", "minimum": 500, "maximum": 800, "default": 700 },
"tracking": { "type": "number", "minimum": -0.03, "maximum": 0.06, "default": 0, "description": "Letter spacing in em." },
"leading": {
"description": "Post line height; 0 keeps the site's.",
"anyOf": [{ "const": 0 }, { "type": "number", "minimum": 1.2, "maximum": 1.8 }],
"default": 0
}
}
},
"shape": {
"type": "object",
"additionalProperties": false,
"properties": {
"radius": { "type": "integer", "minimum": 0, "maximum": 28, "default": 16, "description": "Card radius in px." },
"button": { "type": "integer", "minimum": 0, "maximum": 9999, "default": 9999, "description": "Button radius in px (9999 = pill)." },
"avatar": { "enum": ["circle", "rounded", "square"], "default": "circle" }
}
},
"layout": {
"type": "object",
"additionalProperties": false,
"properties": {
"column": { "type": "integer", "minimum": 520, "maximum": 820, "default": 600 },
"sidebar": { "type": "integer", "minimum": 290, "maximum": 400, "default": 350 },
"density": { "enum": ["compact", "default", "comfortable"], "default": "default" },
"cards": { "type": "boolean", "default": false },
"frame": { "type": "boolean", "default": false }
}
},
"background": {
"oneOf": [
{
"type": "object",
"required": ["kind"],
"additionalProperties": false,
"properties": { "kind": { "const": "none" } }
},
{
"type": "object",
"required": ["kind", "from", "to"],
"additionalProperties": false,
"properties": {
"kind": { "const": "gradient" },
"from": { "$ref": "#/$defs/hex" },
"to": { "$ref": "#/$defs/hex" },
"angle": { "type": "integer", "minimum": 0, "maximum": 360, "default": 180 },
"glow": { "$ref": "#/$defs/hex" }
}
},
{
"type": "object",
"required": ["kind", "ink"],
"additionalProperties": false,
"properties": {
"kind": { "const": "pattern" },
"pattern": { "enum": ["dots", "grid", "diagonal", "scanlines", "paper", "clouds"], "default": "dots" },
"ink": { "$ref": "#/$defs/hex" },
"opacity": { "type": "number", "minimum": 0, "maximum": 0.6, "default": 0.1 },
"size": { "type": "integer", "minimum": 2, "maximum": 400, "default": 24 }
}
},
{
"type": "object",
"required": ["kind", "url"],
"additionalProperties": false,
"properties": {
"kind": { "const": "image" },
"url": {
"type": "string",
"maxLength": 1100000,
"pattern": "^data:image/(png|jpeg|webp|gif|avif);base64,[A-Za-z0-9+/]+={0,2}$",
"description": "An embedded image (about 800 KB at most). Remote URLs are never loaded."
},
"fit": { "enum": ["cover", "tile"], "default": "cover" },
"dim": { "type": "number", "minimum": 0.35, "maximum": 0.95, "default": 0.6 }
}
}
]
},
"effects": {
"type": "object",
"additionalProperties": false,
"properties": {
"motion": { "type": "integer", "minimum": 0, "maximum": 400, "default": 0, "description": "Transition length in ms." },
"hover": { "enum": ["none", "tint", "lift", "glow"], "default": "none" },
"shadow": { "enum": ["none", "soft", "deep"], "default": "none" },
"crt": { "type": "boolean", "default": false }
}
},
"css": {
"type": "string",
"maxLength": 60000,
"description": "Free-form CSS appended last. Same trust level as the owner's own Custom CSS; import dialogs say so."
}
},
"$defs": {
"hex": { "type": "string", "pattern": "^#[0-9a-fA-F]{6}$" },
"fontStack": {
"type": "array",
"maxItems": 8,
"items": {
"anyOf": [
{ "enum": ["system-ui", "sans-serif", "serif", "monospace", "cursive", "ui-sans-serif", "ui-serif", "ui-monospace", "ui-rounded", "-apple-system", "BlinkMacSystemFont"] },
{ "type": "string", "pattern": "^[A-Za-z0-9][A-Za-z0-9 .\\-]{0,47}$" }
]
}
}
}
}