runtime: styles for created roots are constructed sheets (CSP-proof)

- styles.ts: adoptStyles(root, css) adopts a constructed stylesheet into a shadow root or document
  (not governed by a page's CSP, parsed once, stays with the root when its host is moved);
  <style> fallback where constructable sheets are missing or refused.
- UI kit: the kit's shadow root and each dialog's `css` use it (dialog CSS goes with the dialog).
- Plugin API: api.adoptCSS(root, css) and scope.adoptCSS (removed on dispose); injectCSS keeps its
  <style> and, when a CSP leaves it without a sheet, applies the same rules as an adopted sheet.
- tests/styles.test.ts.
This commit is contained in:
CRTkafa 2026-09-28 21:09:14 +00:00
parent 0746aaccda
commit 4a294b993a
4 changed files with 310 additions and 8 deletions

View file

@ -10,6 +10,7 @@
// 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';
@ -357,6 +358,7 @@ export function createUiKit(win: Window & typeof globalThis, options: UiKitOptio
const hostTag = options.hostTag ?? 'wb-ui';
const product = options.product ?? 'wayBetter';
const report = (error: unknown) => console.error(`[${product}] ui callback failed`, error);
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;
@ -401,8 +403,6 @@ export function createUiKit(win: Window & typeof globalThis, options: UiKitOptio
// 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');
@ -411,7 +411,15 @@ export function createUiKit(win: Window & typeof globalThis, options: UiKitOptio
toastRegion.setAttribute('aria-live', 'polite');
toastRegion.setAttribute('aria-relevant', 'additions');
wrap.append(layers, toastRegion);
root.append(style, wrap);
root.append(wrap);
// An adopted sheet (see styles.ts): the site's CSP cannot refuse it, and it stays with the root
// wherever the host is moved. A host without a shadow root keeps a <style> child.
if (isShadowRoot(root)) adoptStyles(root, UI_CSS);
else {
const style = doc.createElement('style');
style.textContent = UI_CSS;
root.prepend(style);
}
// Keys typed in a dialog are ours: the site's (and plugins') page shortcuts never see them.
for (const type of ['keydown', 'keyup', 'keypress']) root.addEventListener(type, event => event.stopPropagation());
(doc.body ?? doc.documentElement).appendChild(host);
@ -525,10 +533,15 @@ export function createUiKit(win: Window & typeof globalThis, options: UiKitOptio
panel.appendChild(message);
panel.setAttribute('aria-describedby', message.id);
}
// The dialog's own CSS, on the kit's root while the dialog is open (adopted where possible).
let ownStyles: RootStyles | null = null;
if (opts.css) {
const style = doc.createElement('style');
style.textContent = opts.css;
panel.appendChild(style);
if (root && isShadowRoot(root)) ownStyles = adoptStyles(root, opts.css);
else {
const style = doc.createElement('style');
style.textContent = opts.css;
panel.appendChild(style);
}
}
const body = doc.createElement('div');
body.className = 'wb-body';
@ -629,7 +642,7 @@ export function createUiKit(win: Window & typeof globalThis, options: UiKitOptio
syncStack();
layer.setAttribute('inert', '');
layer.classList.add('wb-closing');
later(() => layer.remove(), reducedMotion() ? 0 : 130);
later(() => { layer.remove(); ownStyles?.remove(); }, reducedMotion() ? 0 : 130);
// Dialogs opened from this one return focus where this one would have.
for (const other of stack) if (other.returnTo && layer.contains(other.returnTo)) other.returnTo = entry.returnTo;
// Focus never lingers in a dialog that is animating out (keys would still go to its fields).