// `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 (``), 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; 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; 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 }; type Child = Node | string | number | null | undefined | false | Child[]; export type ElementProps = Record; export type UiKit = { toast(message: string, options?: ToastOptions | number): ToastHandle; alert(options: AlertOptions | string): Promise; confirm(options: ConfirmOptions | string): Promise; prompt(options: PromptOptions | string): Promise; 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` 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)[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 = { 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, [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 | '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; 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 }> = []; let seq = 0; let pendingExits = 0; const ownerIds = new WeakMap(); 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