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

@ -8,9 +8,10 @@
import { createThemeApi, type ThemeApi, type ThemeSource } from './themeApi.ts';
import { createUiKit, type UiKit } from './ui.ts';
import { adoptStyles, type RootStyles } from './styles.ts';
import { createCommandRegistry, type CommandDefinition, type CommandInfo, type CommandRegistry } from './commands.ts';
export type { ThemeApi, ThemeSource, UiKit, CommandDefinition, CommandInfo, CommandRegistry };
export type { ThemeApi, ThemeSource, UiKit, CommandDefinition, CommandInfo, CommandRegistry, RootStyles };
export type Dispose = () => void;
@ -25,6 +26,8 @@ export type PluginStorage = {
/** Collects disposers so a plugin's `stop()` is a single `scope.dispose()`. */
export type PluginScope = {
css(id: string, css: string): void;
/** `api.adoptCSS`, taken off the root on dispose. */
adoptCSS(root: ShadowRoot | Document, css: string): RootStyles;
on(target: EventTarget, type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
observe(selector: string, callback: (element: Element) => void): void;
onRouteChange(callback: (href: string, previous: string) => void): void;
@ -45,6 +48,12 @@ export type PluginScope = {
export type CorePluginApi = {
injectCSS(id: string, css: string): void;
clearCSS(id: string): void;
/**
* Styles a shadow root the plugin created (or the document) with a constructable stylesheet:
* the page's Content-Security-Policy cannot refuse it, it is parsed once, and it stays with the
* root wherever its host is moved. Falls back to a `<style>` element where unsupported.
*/
adoptCSS(root: ShadowRoot | Document, css: string): RootStyles;
waitFor(selector: string, timeoutMs?: number): Promise<Element>;
/** Namespaced JSON storage in this tab's localStorage (`<storagePrefix><namespace>:<key>`). */
storage(namespace: string): PluginStorage;
@ -125,6 +134,7 @@ export function createCorePluginApi(win: Window & typeof globalThis, site: Plugi
h: (...args: Parameters<UiKit['h']>) => uiKit().h(...args),
});
const styleNodes = new Map<string, HTMLStyleElement>();
const adoptedFallbacks = new Map<string, RootStyles>();
const report = (error: unknown) => console.error(`[${site.product}] plugin callback failed`, error);
const registry = createCommandRegistry({ target: doc, isTyping: event => isTypingTarget(event.target) || isTypingTarget(doc.activeElement), report });
const commands: CommandRegistry = Object.freeze({
@ -159,10 +169,26 @@ export function createCorePluginApi(win: Window & typeof globalThis, site: Plugi
styleNodes.set(id, node);
}
node.textContent = css;
// A CSP that refuses inline styles leaves the element without a sheet: the same rules as an
// adopted sheet instead (CSP does not govern constructed sheets).
const blocked = 'sheet' in node && node.sheet === null && css.trim() !== '';
const fallback = adoptedFallbacks.get(id);
if (blocked) {
if (fallback) fallback.update(css);
else adoptedFallbacks.set(id, adoptStyles(doc, css));
} else if (fallback) {
fallback.remove();
adoptedFallbacks.delete(id);
}
},
clearCSS(id) {
styleNodes.get(id)?.remove();
styleNodes.delete(id);
adoptedFallbacks.get(id)?.remove();
adoptedFallbacks.delete(id);
},
adoptCSS(root, css) {
return adoptStyles(root, css);
},
waitFor(selector, timeoutMs = 15000) {
return new Promise((resolve, reject) => {
@ -299,6 +325,11 @@ export function createCorePluginApi(win: Window & typeof globalThis, site: Plugi
api.injectCSS(id, css);
disposers.push(() => api.clearCSS(id));
},
adoptCSS(root, css) {
const styles = api.adoptCSS(root, css);
disposers.push(() => styles.remove());
return styles;
},
on(target, type, listener, options) {
target.addEventListener(type, listener, options);
disposers.push(() => target.removeEventListener(type, listener, options));