waybetter/packages/runtime/src/ui.ts
CRT 929abd3278 i18n: dependency-free message runtime, catalog checks, plugin strings, native strings
- runtime/i18n.ts: ICU-lite messages (placeholders as text, Intl.PluralRules plurals with exact
  forms, selectordinal, select, number/date/time), fallback chains (pt-BR -> pt -> en, ar-x-fm ->
  ar), X and legacy code aliases, RTL by locale, lazy catalogs, live onChange. Apostrophes are
  literal except right before { } # or another apostrophe.
- runtime/i18nCheck.ts: rules for contributed catalogs (shape, keys, syntax, placeholder parity,
  select options, markup/control characters, lengths). An argument English only uses to choose a
  plural form may be dropped; missing plural forms are warnings; meta "allowEmpty" fragments.
- runtime/pluginI18n.ts: api.i18n bound per plugin (register/t/locale/dir/onChange/number/date/
  relative/list); the UI kit's own words follow the app's language. pageLang.ts reports the
  site's <html lang>. shell/messages.ts: shell-model words.
- waybetter-host i18n.rs: NativeStrings (validated plain text, caps, one-pass {name} fill, page
  payload by prefix), system_locales via sys-locale; TabState.lang.
- JSON Schemas for catalogs and translator notes; npm exports waybetter/i18n, /i18n/check,
  /i18n/plugin.
2026-09-29 02:53:48 +00:00

947 lines
48 KiB
TypeScript

// `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 { adoptStyles, type RootStyles } from './styles.ts';
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;
/**
* The kit's own words (buttons, accessible names, default errors) in the app's language:
* called with a `kit.*` key and returns the translation, or undefined for English.
*/
text?: (key: KitKey) => string | undefined;
};
/** The kit's default words (English source; `kit.*` keys in the framework catalogs). */
export const KIT_MESSAGES = {
'kit.ok': 'OK',
'kit.cancel': 'Cancel',
'kit.delete': 'Delete',
'kit.close': 'Close',
'kit.dismiss': 'Dismiss',
'kit.dialog': 'Dialog',
'kit.value': 'Value',
'kit.checkValue': 'Please check this value.',
'kit.failed': 'Something went wrong.',
} as const;
export type KitKey = keyof typeof KIT_MESSAGES;
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, fallback: string = KIT_MESSAGES['kit.checkValue']): string | null {
if (typeof result === 'string') return result.trim() ? result : null;
if (result === false) return fallback;
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-dialog, 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-dialog, 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-dialog, 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-dialog, 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-dialog, 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 var(--wb-font-mono, 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-dialog, 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-dialog, 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 word = (key: KitKey): string => {
try {
const value = options.text?.(key);
if (typeof value === 'string' && value) return value;
} catch { /* a broken translator must not break a dialog */ }
return KIT_MESSAGES[key];
};
const isShadowRoot = (node: unknown): node is ShadowRoot => typeof win.ShadowRoot === 'function' && node instanceof win.ShadowRoot;
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 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(wrap);
// An adopted sheet (see styles.ts): the site's CSP cannot refuse it, and it stays with the root
// wherever the host is moved. A host without a shadow root keeps a <style> child.
if (isShadowRoot(root)) adoptStyles(root, UI_CSS);
else {
const style = doc.createElement('style');
style.textContent = UI_CSS;
root.prepend(style);
}
// 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', word('kit.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 || word('kit.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);
}
// The dialog's own CSS, on the kit's root while the dialog is open (adopted where possible).
let ownStyles: RootStyles | null = null;
if (opts.css) {
if (root && isShadowRoot(root)) ownStyles = adoptStyles(root, opts.css);
else {
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 : word('kit.failed'));
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(); ownStyles?.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', word('kit.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 || word('kit.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 ? word('kit.delete') : word('kit.ok')), tone: danger ? 'danger' : 'primary', value: true, default: !danger, autoFocus: !danger },
{ label: opts.cancelLabel || word('kit.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), word('kit.checkValue')); } catch (err) { message = err instanceof Error ? err.message : word('kit.checkValue'); }
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) || word('kit.value'));
wrap.appendChild(field);
body.appendChild(wrap);
},
actions: [
{ label: opts.cancelLabel || word('kit.cancel'), tone: 'secondary', value: null },
{ label: opts.confirmLabel || word('kit.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,
});
}