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:
parent
5305e60053
commit
a232cf15e4
8 changed files with 1627 additions and 25 deletions
|
|
@ -2,6 +2,14 @@
|
|||
// 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
|
||||
// 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;
|
||||
|
||||
|
|
@ -24,6 +32,10 @@ export type PluginScope = {
|
|||
add<T extends Node>(node: T): T;
|
||||
/** Runs `fn` on dispose (restore attributes, clear timers, ...). */
|
||||
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;
|
||||
};
|
||||
|
||||
|
|
@ -43,10 +55,20 @@ export type CorePluginApi = {
|
|||
*/
|
||||
onKey(callback: (event: KeyboardEvent, item: Element | null) => void): Dispose;
|
||||
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;
|
||||
/** 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;
|
||||
};
|
||||
|
||||
/** What the site adapter adds to the core: its theme engine, when it has one. */
|
||||
export type CorePluginExtras = {
|
||||
theme?: ThemeSource;
|
||||
};
|
||||
|
||||
export type PluginApiSite = {
|
||||
/** The runtime global, for error messages (`<name>.waitFor timed out`). */
|
||||
name: string;
|
||||
|
|
@ -56,7 +78,9 @@ export type PluginApiSite = {
|
|||
storagePrefix: string;
|
||||
/** `data-*` key (camelCase) marking plugin `<style>` elements with their id. */
|
||||
styleDataKey: string;
|
||||
/** Id of the kit's shadow host element (`<wb-ui id=…>`), kept from the old single toast. */
|
||||
toastId: string;
|
||||
/** Accent used when the site has no theme source (and the page shows none). */
|
||||
toastBackground: string;
|
||||
/** The item a single-key shortcut acts on: the focused element's closest match (a post, a message). */
|
||||
itemSelector: string;
|
||||
|
|
@ -70,13 +94,28 @@ const CHORD_MS = 1500;
|
|||
|
||||
/** True when a key event belongs to text entry, not to page shortcuts. */
|
||||
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;
|
||||
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 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 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) {
|
||||
let node = doc.getElementById(site.toastId) as (HTMLElement & { _wbTimer?: number }) | null;
|
||||
if (!node) {
|
||||
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);
|
||||
// The old toast vanished after `ms`; 0 or less meant "at once", so it never means "stay".
|
||||
ui.toast(String(message), { duration: Number.isFinite(ms) && ms > 0 ? ms : 1 });
|
||||
},
|
||||
ui,
|
||||
theme,
|
||||
scope() {
|
||||
let disposers: Dispose[] = [];
|
||||
let scopedUi: UiKit | null = null;
|
||||
return {
|
||||
css(id, css) {
|
||||
api.injectCSS(id, css);
|
||||
|
|
@ -271,6 +299,17 @@ export function createCorePluginApi(win: Window & typeof globalThis, site: Plugi
|
|||
defer(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() {
|
||||
const pending = disposers.reverse();
|
||||
disposers = [];
|
||||
|
|
|
|||
226
packages/runtime/src/themeApi.ts
Normal file
226
packages/runtime/src/themeApi.ts
Normal 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
908
packages/runtime/src/ui.ts
Normal 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,
|
||||
});
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue