@silkui/core 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,4 +1,215 @@
1
1
  # @silkui/core
2
2
 
3
- The nodes and events of a Silk UI tree for JavaScript applications that run on the embedded
4
- SilkJS engine. See [ui-js](../../README.md) for the API and the host.
3
+ The node and event API of a [Silk UI](https://github.com/silk-lang/SilkUI) tree, for
4
+ JavaScript apps that run on the SilkJS engine embedded in a Silk UI program. Its nodes are
5
+ the tree's own (box, text, input, rich input, image, icon, canvas). Its methods and its
6
+ event flow are the DOM's: `appendChild`, `addEventListener`, capture and bubble,
7
+ `preventDefault`.
8
+
9
+ `@silkui/react` and `@silkui/foldkit` are built on it. Use it directly for a plain
10
+ JavaScript or TypeScript app, or to draw on nodes from inside a framework app.
11
+
12
+ ## Install
13
+
14
+ The quickest start is a template, which sets up the Silk host, Vite and this package:
15
+
16
+ ```sh
17
+ silk init my-app -t ui-js # plain TypeScript; ui-react and ui-foldkit use this package too
18
+ cd my-app
19
+ silk task dev
20
+ ```
21
+
22
+ See [Get started](https://silk-ui-docs.juliaortiz-js.workers.dev/start/). To add it to an
23
+ existing Silk UI web project:
24
+
25
+ ```sh
26
+ npm install @silkui/core
27
+ ```
28
+
29
+ The package runs inside a Silk UI host (the native window, or the web canvas), which provides
30
+ the native functions it calls. It does not run in Node or in a plain browser page by itself.
31
+
32
+ ## Usage
33
+
34
+ ```ts
35
+ import { createBox, createText, mount } from "@silkui/core";
36
+
37
+ const label = createText("Clicked 0 times");
38
+ const button = createBox(
39
+ { paddingTop: 12, paddingBottom: 12, paddingLeft: 20, paddingRight: 20, borderRadius: 10, backgroundColor: "rgb(37, 99, 235)", color: "white" },
40
+ label,
41
+ );
42
+ button.tabIndex = 0;
43
+ button.look("hover").set({ backgroundColor: "rgb(59, 130, 246)" });
44
+
45
+ let clicks = 0;
46
+ button.addEventListener("click", () => {
47
+ clicks += 1;
48
+ label.data = `Clicked ${clicks} times`;
49
+ });
50
+
51
+ mount(createBox({ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center" }, button));
52
+ ```
53
+
54
+ ## API
55
+
56
+ ### Nodes
57
+
58
+ | Export | What it does |
59
+ | --- | --- |
60
+ | `createBox(style?, ...children)` | A box with `style` as its base look. Strings among the children become text nodes |
61
+ | `createText(data?)` | A text node. It takes its look from its parent |
62
+ | `createInput(style?)` | An editable text field. `value`, `selectionStart`, `selectionEnd` and `setSelectionRange` work as on an `<input>` |
63
+ | `createRichInput(style?)` | A text field with marks and inline atoms (see below) |
64
+ | `createIcon(svg, style?)` | SVG markup drawn at the node's size, with its `color` as `currentColor` |
65
+ | `createNode(kind)` | A node of any kind: `"box"`, `"text"`, `"input"`, `"richinput"`, `"image"`, `"icon"`, `"canvas"` |
66
+ | `mount(node)` / `root()` | Makes a node the root of the window's tree, or returns it |
67
+ | `nodeById(id)` | The node with a tree id, for hosts and tools |
68
+
69
+ A node has `append`, `appendChild`, `insertBefore`, `removeChild`, `remove`, `contains`,
70
+ `parentNode`, `childNodes`, `firstChild`, `lastChild` and the sibling getters, as in the DOM.
71
+ A removed node keeps its state and can be inserted again. `destroy()` frees a node and its
72
+ subtree for good. `focus()` and `scrollTo(x, y)` do what their names say.
73
+
74
+ ### Style and looks
75
+
76
+ ```ts
77
+ node.style.set({ width: 120, flexGrow: 1, fontFamily: "Noto Sans, sans-serif" });
78
+ node.style = { height: 40 }; // replaces the base look
79
+ node.look("hover").set({ opacity: 0.8 }); // also "active", "focus", "focusVisible"
80
+ node.look("starting").set({ opacity: 0 }); // what transitions start from, as @starting-style
81
+ ```
82
+
83
+ - Properties use their camel case names, typed from `csstype`. Numbers are CSS pixels,
84
+ except for unitless properties such as `opacity`, `flexGrow`, `zIndex` and `lineHeight`.
85
+ `null` takes a property out.
86
+ - Layout is CSS: flex, grid (`gridTemplateColumns: "auto 1fr"`, `repeat()`, `minmax()`,
87
+ named lines, `gridTemplateAreas`, `gridArea`, `gridColumn: "span 2"`) and positioning.
88
+ Grid properties apply from the base look only.
89
+ - `fontFamily` takes CSS `font-family` text, resolved in the host's fonts.
90
+ - `transition` and `animation` work as in CSS. `defineKeyframes(name, { from: {...}, "50%": {...}, to: {...} })`
91
+ defines `@keyframes` for them.
92
+
93
+ ### Events
94
+
95
+ ```ts
96
+ node.addEventListener("pointerdown", (event) => event.preventDefault(), { capture: true });
97
+ ```
98
+
99
+ An event runs the capture phase from the root down, the target, then bubbles, with
100
+ `stopPropagation`, `stopImmediatePropagation`, `preventDefault` and `composedPath`, as on the
101
+ web. Listeners run before the tree's default action, so `preventDefault()` on a
102
+ `pointerdown` keeps the focus where it is. `dispatchEvent(event)` runs an `Event` you made
103
+ through the tree.
104
+
105
+ | Events | Members |
106
+ | --- | --- |
107
+ | `pointerdown`, `pointerup`, `click` | `clientX`, `clientY`, `button`, `detail` (2 for a double click), modifier keys |
108
+ | `pointermove`, `pointerenter`, `pointerleave`, `pointercancel` | `clientX`, `clientY`, modifier keys |
109
+ | `wheel` | `deltaX`, `deltaY` |
110
+ | `keydown`, `keyup` | `key`, `code`, `repeat`, modifier keys |
111
+ | `focus`, `blur`, `load`, `error`, `gotpointercapture`, `lostpointercapture` | |
112
+ | `input` | `value`, `inputType`, and `document` on a rich input |
113
+ | `selectionchange` | `selectionStart`, `selectionEnd` |
114
+ | `scroll` | `scrollLeft`, `scrollTop` |
115
+ | `layout` | `bounds`: where layout put the node, in window pixels |
116
+ | `transitionrun`, `transitionstart`, `transitionend`, `transitioncancel` | `propertyName`, `elapsedTime` |
117
+ | `animationstart`, `animationiteration`, `animationend`, `animationcancel` | `animationName`, `elapsedTime` |
118
+
119
+ A listener that throws does not stop the dispatch. `setErrorHandler(handler)` receives the
120
+ exception; without one the host reports it.
121
+
122
+ ### Attributes and accessibility
123
+
124
+ `setAttribute(name, value)` sets the tree's attributes: `tabIndex`, `disabled`, `label`,
125
+ `testId`, `placeholder`, `multiline`, `readOnly`, `checked`, `selected`, `expanded`,
126
+ `focusTrap`, `inert`, `href`, `cursor` and `transition`, plus `id`. A name the tree does not
127
+ have throws a `TypeError`. `tabIndex` and `disabled` are also properties.
128
+
129
+ - `role` and the ARIA attributes work as in the DOM, spelled `aria-label` or `ariaLabel`.
130
+ `aria-labelledby`, `aria-describedby`, `aria-controls` and `aria-activedescendant` name
131
+ other nodes by their `id`.
132
+ - `announce(message, { politeness })` has screen readers say a message nothing on screen shows.
133
+ - `inert` puts a subtree out of reach of focus, pointers and screen readers, as in HTML.
134
+ - A node with an `href` is a link: a click on it that no listener prevented opens the address.
135
+
136
+ ### Rich inputs
137
+
138
+ A rich input edits a document of styled text and inline atoms (mentions, chips):
139
+
140
+ ```ts
141
+ import { createRichInput, OBJECT } from "@silkui/core";
142
+
143
+ const field = createRichInput({ width: 400 });
144
+ field.defineMark("bold", { fontWeight: 700 });
145
+ field.defineAtom("mention", { backgroundColor: "rgb(219, 234, 254)", borderRadius: 4 });
146
+ field.document = { text: `Hi ${OBJECT}`, marks: [], atoms: [{ kind: "mention", label: "@ada", data: "user-1" }] };
147
+ field.addEventListener("input", (event) => save(event.document));
148
+ ```
149
+
150
+ - An atom sits in `text` as one `OBJECT` character (U+FFFC), so the caret steps over it and
151
+ Backspace deletes it whole. Offsets are string indices.
152
+ - `format(name, on)` and `toggleMark(name)` mark the selection, or the text typed next at a
153
+ caret. `activeMarks` holds the marks typed text gets.
154
+ - `insertAtom(start, end, atom)` replaces a range with an atom, such as a `@` trigger
155
+ turning into a mention. Listen for `selectionchange` to open a picker.
156
+ - Undo, IME and copy work as in a plain input.
157
+
158
+ ### Markdown
159
+
160
+ `parseMarkdown(text, options?)` returns the syntax tree of Markdown text in the shape of
161
+ [mdast](https://github.com/syntax-tree/mdast), the tree remark gives, so renderers written
162
+ for remark work on it and the app needs no Markdown parser in its bundle. It is CommonMark
163
+ with GitHub's tables, strikethrough, task lists and autolinks (`gfm: false` turns them off,
164
+ or set `tables`, `strikethrough`, `taskLists` and `autolinkLiterals` one by one).
165
+ `footnotes`, `frontmatter` and `alerts` (`> [!NOTE]`) turn on more. Nodes have no
166
+ `position`.
167
+
168
+ ## TypeScript
169
+
170
+ The package ships its types. Every node class, event and style property is typed, and
171
+ `addEventListener` gives each listener the event of its type. `parseMarkdown` returns the
172
+ `mdast` `Root` type.
173
+
174
+ ## More
175
+
176
+ - [The ui-js reference](https://github.com/silk-lang/SilkUI/blob/main/modules/js/README.md):
177
+ every package, the host, and the web globals a realm has.
178
+ - [Templates](https://github.com/silk-lang/examples) and
179
+ [Get started](https://silk-ui-docs.juliaortiz-js.workers.dev/start/).
180
+ - [Source](https://github.com/silk-lang/SilkUI/tree/main/modules/js/packages/core). MIT license.
181
+
182
+
183
+ ## Stylesheets
184
+
185
+ CSS imports built with `@silkui/vite` are adopted before the first frame and replaced in
186
+ place during development. For application-managed themes, adopt constructed sheets on the
187
+ node passed to `mount`:
188
+
189
+ ```js
190
+ import { CSSStyleSheet, createBox, mount } from "@silkui/core";
191
+
192
+ const theme = new CSSStyleSheet();
193
+ theme.replaceSync(".card { padding: 12px; color: rebeccapurple }");
194
+ const app = createBox();
195
+ app.className = "card";
196
+ app.adoptedStyleSheets = [theme];
197
+ mount(app);
198
+ await theme.replace(".card { padding: 18px; color: teal }");
199
+ ```
200
+
201
+ JavaScript development hosts include the text compiler. Release hosts require
202
+ `App.runtimeStylesheets()` in their Silk task pipeline. Without that option they accept
203
+ compiled sheets and reject text compilation. The compiler is linked only when enabled.
204
+
205
+ `adoptedStyleSheets` is an ordered mutable array. Assignment, `push`, `splice`, reordering,
206
+ and shrinking `length` update the active root. Entries must be constructed `CSSStyleSheet`
207
+ objects; deleting an indexed property or creating holes is invalid. The same sheet can
208
+ appear multiple times, and replacing it updates each adoption. Invalid compiled bytes leave
209
+ the current sheet intact. Replacing the mounted root switches to that node's adopted list.
210
+
211
+ `CSSStyleSheet.fromCompiled(bytes)` creates a sheet from `Uint8Array`, `ArrayBuffer`, or
212
+ Base64-encoded compiled bytes; `sheet.replaceCompiled(bytes)` updates it. The format is
213
+ versioned and must match the host. Build-time sheets come first, followed by imported CSS
214
+ and the root's constructed sheets. There is no `document`, `<style>`, or `<link>` node;
215
+ `cssRules`, `insertRule`, and `deleteRule` are not part of this API.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@silkui/core",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "The node and event API of a Silk UI tree for JavaScript applications that run on the embedded SilkJS engine",
5
5
  "repository": {
6
6
  "type": "git",
package/src/index.d.ts CHANGED
@@ -1,3 +1,13 @@
1
+ /** A constructed stylesheet. Text loading requires runtime stylesheet compilation in the host. */
2
+ export class CSSStyleSheet {
3
+ static fromCompiled(bytes: Uint8Array | ArrayBuffer | string): CSSStyleSheet;
4
+ replaceCompiled(bytes: Uint8Array | ArrayBuffer | string): void;
5
+ replaceSync(text: string): void;
6
+ replace(text: string): Promise<CSSStyleSheet>;
7
+ }
8
+ /** Used by build tools to replace or remove a compiled CSS import without restarting the app. */
9
+ export function updateStyleSheet(id: string, compiled: Uint8Array | ArrayBuffer | string | null): void;
10
+
1
11
  import type * as CSS from "csstype";
2
12
 
3
13
  /** The node kinds of the tree. `richinput` is an `input` with marks and atoms. */
@@ -29,11 +39,34 @@ export interface Look {
29
39
  export type Listener<E extends Event = Event> = ((this: Node, event: E) => void) | { handleEvent(event: E): void };
30
40
  export type ListenerOptions = boolean | { capture?: boolean; once?: boolean };
31
41
 
42
+ /** Live tokens in a node's class attribute. */
43
+ export class ClassList implements Iterable<string> {
44
+ constructor(node: Node);
45
+ value: string;
46
+ readonly length: number;
47
+ item(index: number): string | null;
48
+ contains(token: string): boolean;
49
+ add(...tokens: string[]): void;
50
+ remove(...tokens: string[]): void;
51
+ toggle(token: string, force?: boolean): boolean;
52
+ replace(oldToken: string, newToken: string): boolean;
53
+ values(): IterableIterator<string>;
54
+ keys(): IterableIterator<number>;
55
+ entries(): IterableIterator<[number, string]>;
56
+ forEach(callback: (value: string, index: number, list: ClassList) => void, thisArg?: unknown): void;
57
+ [Symbol.iterator](): IterableIterator<string>;
58
+ toString(): string;
59
+ }
60
+
32
61
  /** A node of the tree. Make one with `createBox`, `createText`, `createInput` or `createNode`. */
33
62
  export class Node {
34
63
  constructor(kind: NodeKind);
35
- /** The tree's number for the node (not the DOM `id`: that is `setAttribute("id", ...)`). */
36
- readonly id: number;
64
+ /** Stable protocol identifier, independent of the CSS id attribute. */
65
+ readonly nodeId: number;
66
+ id: string;
67
+ className: string;
68
+ adoptedStyleSheets: CSSStyleSheet[];
69
+ readonly classList: ClassList;
37
70
  readonly kind: NodeKind;
38
71
  readonly parentNode: Node | null;
39
72
  readonly childNodes: readonly Node[];
@@ -61,9 +94,13 @@ export class Node {
61
94
  /**
62
95
  * Sets a tree attribute (`tabIndex`, `disabled`, `label`, `testId`, `placeholder`, `href`,
63
96
  * `cursor`, `multiline`, `readOnly`, `inert`, `focusTrap`, `transition`), `id`, `role`, or
64
- * an ARIA attribute spelled `aria-checked` or `ariaChecked`.
97
+ * an ARIA attribute spelled `aria-checked` or `ariaChecked`, or a `data-*` attribute.
98
+ * `null` and `undefined` remove an attribute.
65
99
  */
66
100
  setAttribute(name: string, value: unknown): void;
101
+ getAttribute(name: string): string | null;
102
+ hasAttribute(name: string): boolean;
103
+ removeAttribute(name: string): void;
67
104
  set tabIndex(value: number);
68
105
  set disabled(value: boolean);
69
106
  focus(): void;
package/src/index.js CHANGED
@@ -43,6 +43,7 @@ let nextId = 0;
43
43
  const CSS_NAMES = new Map();
44
44
 
45
45
  function cssName(name) {
46
+ if (name.startsWith("--")) return name;
46
47
  let css = CSS_NAMES.get(name);
47
48
  if (css === undefined) {
48
49
  css = name.replace(/[A-Z]/g, (letter) => "-" + letter.toLowerCase());
@@ -68,20 +69,11 @@ function familyOf(names) {
68
69
  }
69
70
 
70
71
  function cssValue(name, value) {
72
+ if (name.startsWith("--")) return String(value);
71
73
  if (name === "fontFamily") return familyOf(String(value));
72
74
  return typeof value === "number" && !UNITLESS.has(name) ? value + "px" : String(value);
73
75
  }
74
76
 
75
- // ARIA states with a tree attribute of their own, by the name after `aria-`. The host takes
76
- // the other ARIA names as they are; one it does not know is ignored, with one warning.
77
- const ARIA_STATES = { checked: "checked", selected: "selected", expanded: "expanded" };
78
- const ARIA_RANGE = { valuemin: 0, valuemax: 1, valuenow: 2 };
79
- // ARIA attributes that name other elements by their ids. The tree takes node numbers, so a
80
- // relation is sent again whenever an id it names comes, goes or moves to another node.
81
- const ARIA_RELATIONS = new Set(["labelledby", "describedby", "controls", "activedescendant"]);
82
- // Nodes by their `id`, and the nodes whose relations name each id.
83
- const byId = new Map();
84
- const naming = new Map();
85
77
  const warned = new Set();
86
78
 
87
79
  function warnOnce(message) {
@@ -135,15 +127,15 @@ class Look {
135
127
  if (removed) {
136
128
  // The tree sets declarations over earlier ones, so taking one out means starting the
137
129
  // look again.
138
- native.clearStyle(this.#node.id, this.#state);
130
+ native.clearStyle(this.#node.nodeId, this.#state);
139
131
  css = this.cssText;
140
132
  }
141
- if (css) native.style(this.#node.id, css, this.#state);
133
+ if (css) native.style(this.#node.nodeId, css, this.#state);
142
134
  }
143
135
 
144
136
  /** Replaces the whole look. */
145
137
  replace(properties) {
146
- native.clearStyle(this.#node.id, this.#state);
138
+ native.clearStyle(this.#node.nodeId, this.#state);
147
139
  this.#values = Object.create(null);
148
140
  this.set(properties);
149
141
  }
@@ -159,6 +151,220 @@ class Look {
159
151
  }
160
152
  }
161
153
 
154
+ const CLASS_SPACE = /[\t\n\f\r ]/;
155
+ function classToken(value) {
156
+ const token = String(value);
157
+ if (!token || CLASS_SPACE.test(token)) {
158
+ const error = new Error(!token ? "A class token cannot be empty" : "A class token cannot contain whitespace");
159
+ error.name = !token ? "SyntaxError" : "InvalidCharacterError";
160
+ throw error;
161
+ }
162
+ return token;
163
+ }
164
+
165
+ /** A live token list backed by the node's class attribute. */
166
+ export class ClassList {
167
+ #node;
168
+ constructor(node) { this.#node = node; }
169
+ #tokens() { return [...new Set(this.value.split(/[\t\n\f\r ]+/).filter(Boolean))]; }
170
+ #write(tokens) { this.#node.className = tokens.join(" "); }
171
+ get value() { return this.#node.className; }
172
+ set value(value) { this.#node.className = value; }
173
+ get length() { return this.#tokens().length; }
174
+ item(index) { return this.#tokens()[Number(index) >>> 0] ?? null; }
175
+ contains(token) { return this.#tokens().includes(classToken(token)); }
176
+ add(...values) {
177
+ const tokens = values.map(classToken);
178
+ this.#write([...new Set([...this.#tokens(), ...tokens])]);
179
+ }
180
+ remove(...values) {
181
+ const tokens = values.map(classToken);
182
+ this.#write(this.#tokens().filter((token) => !tokens.includes(token)));
183
+ }
184
+ toggle(value, force) {
185
+ const token = classToken(value);
186
+ const present = this.contains(token);
187
+ const wanted = force === undefined ? !present : !!force;
188
+ if (wanted && !present) this.add(token);
189
+ else if (!wanted && present) this.remove(token);
190
+ return wanted;
191
+ }
192
+ replace(oldValue, newValue) {
193
+ const oldToken = classToken(oldValue), newToken = classToken(newValue);
194
+ const tokens = this.#tokens(), index = tokens.indexOf(oldToken);
195
+ if (index === -1) return false;
196
+ if (oldToken !== newToken) {
197
+ if (tokens.includes(newToken)) tokens.splice(index, 1);
198
+ else tokens[index] = newToken;
199
+ }
200
+ this.#write(tokens);
201
+ return true;
202
+ }
203
+ values() { return this.#tokens().values(); }
204
+ keys() { return this.#tokens().keys(); }
205
+ entries() { return this.#tokens().entries(); }
206
+ forEach(callback, thisArg) { this.#tokens().forEach((value, index) => callback.call(thisArg, value, index, this)); }
207
+ [Symbol.iterator]() { return this.values(); }
208
+ toString() { return this.value; }
209
+ }
210
+
211
+ const sheetData = new WeakMap();
212
+ const adoptedLists = new WeakMap();
213
+ const importedSheets = new Map();
214
+ let installedSheets = [];
215
+ let nextSheet = 1;
216
+
217
+ function sheetError(message) {
218
+ const error = new Error(message);
219
+ error.name = "NotAllowedError";
220
+ return error;
221
+ }
222
+
223
+ function base64Bytes(value) {
224
+ if (typeof value === "string") return value;
225
+ const bytes = value instanceof ArrayBuffer ? new Uint8Array(value) : value;
226
+ if (!(bytes instanceof Uint8Array)) throw new TypeError("Expected compiled stylesheet bytes");
227
+ const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
228
+ let encoded = "";
229
+ for (let i = 0; i < bytes.length; i += 3) {
230
+ const bits = (bytes[i] << 16) | ((bytes[i + 1] ?? 0) << 8) | (bytes[i + 2] ?? 0);
231
+ encoded += alphabet[bits >>> 18] + alphabet[(bits >>> 12) & 63]
232
+ + (i + 1 < bytes.length ? alphabet[(bits >>> 6) & 63] : "=")
233
+ + (i + 2 < bytes.length ? alphabet[bits & 63] : "=");
234
+ }
235
+ return encoded;
236
+ }
237
+
238
+ function replaceSheet(sheet, bytes) {
239
+ native.styleSheet(0, 0, bytes);
240
+ const state = sheetData.get(sheet);
241
+ state.bytes = bytes;
242
+ for (const entry of installedSheets) {
243
+ if (entry.sheet !== sheet) continue;
244
+ native.styleSheet(entry.live ? 2 : 1, entry.id, bytes);
245
+ entry.live = true;
246
+ }
247
+ }
248
+
249
+ /** A constructed stylesheet, adopted on an application's root. */
250
+ export class CSSStyleSheet {
251
+ constructor() { sheetData.set(this, { bytes: null, replacing: false }); }
252
+
253
+ static fromCompiled(bytes) {
254
+ const sheet = new CSSStyleSheet();
255
+ replaceSheet(sheet, base64Bytes(bytes));
256
+ return sheet;
257
+ }
258
+
259
+ replaceCompiled(bytes) {
260
+ if (sheetData.get(this).replacing) throw sheetError("A stylesheet replacement is already pending");
261
+ replaceSheet(this, base64Bytes(bytes));
262
+ }
263
+
264
+ replaceSync(text) {
265
+ if (sheetData.get(this).replacing) throw sheetError("A stylesheet replacement is already pending");
266
+ if (!native.compileStyleSheet) throw sheetError("Runtime CSS compilation is disabled in this host");
267
+ replaceSheet(this, native.compileStyleSheet(String(text)));
268
+ }
269
+
270
+ replace(text) {
271
+ const state = sheetData.get(this);
272
+ if (state.replacing) return Promise.reject(sheetError("A stylesheet replacement is already pending"));
273
+ const source = String(text);
274
+ state.replacing = true;
275
+ return Promise.resolve().then(() => {
276
+ if (!native.compileStyleSheet) throw sheetError("Runtime CSS compilation is disabled in this host");
277
+ replaceSheet(this, native.compileStyleSheet(source));
278
+ return this;
279
+ }).finally(() => { state.replacing = false; });
280
+ }
281
+ }
282
+
283
+ function clearAdoptedSheets() {
284
+ for (const entry of installedSheets) if (entry.live) native.styleSheet(3, entry.id, "");
285
+ installedSheets = [];
286
+ }
287
+
288
+ function syncAdoptedSheets() {
289
+ if (!rootNode) return;
290
+ clearAdoptedSheets();
291
+ const sheets = [...importedSheets.values(), ...(adoptedLists.get(rootNode)?.values ?? [])];
292
+ for (const sheet of sheets) {
293
+ if (nextSheet >= 0x80000000) throw new RangeError("Too many stylesheet adoptions");
294
+ const entry = { sheet, id: nextSheet++, live: false };
295
+ installedSheets.push(entry);
296
+ const bytes = sheetData.get(sheet).bytes;
297
+ if (bytes !== null) { native.styleSheet(1, entry.id, bytes); entry.live = true; }
298
+ }
299
+ }
300
+
301
+ function validateSheets(values) {
302
+ for (const sheet of values) if (!sheetData.has(sheet)) throw new TypeError("adoptedStyleSheets accepts constructed CSSStyleSheet objects");
303
+ return values;
304
+ }
305
+
306
+ const sheetMutators = new Set(["copyWithin", "fill", "pop", "push", "reverse", "shift", "sort", "splice", "unshift"]);
307
+ function adoptedList(node) {
308
+ let list = adoptedLists.get(node);
309
+ if (list) return list;
310
+ const values = [];
311
+ const assign = next => {
312
+ validateSheets(next);
313
+ values.splice(0, values.length, ...next);
314
+ if (rootNode === node) syncAdoptedSheets();
315
+ };
316
+ const numeric = key => typeof key === "string" && /^(0|[1-9][0-9]*)$/.test(key);
317
+ const proxy = new Proxy(values, {
318
+ get(target, key, receiver) {
319
+ if (!sheetMutators.has(key)) return Reflect.get(target, key, receiver);
320
+ return (...args) => {
321
+ const next = values.slice();
322
+ const result = Array.prototype[key].apply(next, args);
323
+ assign(next);
324
+ return result === next ? proxy : result;
325
+ };
326
+ },
327
+ set(target, key, value) {
328
+ if (key !== "length" && !numeric(key)) return Reflect.set(target, key, value);
329
+ const next = values.slice();
330
+ Reflect.set(next, key, value);
331
+ assign(next);
332
+ return true;
333
+ },
334
+ defineProperty(target, key, descriptor) {
335
+ if (key !== "length" && !numeric(key)) return Reflect.defineProperty(target, key, descriptor);
336
+ if (!Object.hasOwn(descriptor, "value") || descriptor.get || descriptor.set || descriptor.configurable === false || descriptor.writable === false) {
337
+ throw new TypeError("adoptedStyleSheets entries must remain mutable values");
338
+ }
339
+ const next = values.slice();
340
+ Reflect.set(next, key, descriptor.value);
341
+ assign(next);
342
+ return true;
343
+ },
344
+ deleteProperty(target, key) {
345
+ if (!numeric(key)) return Reflect.deleteProperty(target, key);
346
+ return Number(key) >= values.length;
347
+ },
348
+ });
349
+ list = { values, proxy, assign };
350
+ adoptedLists.set(node, list);
351
+ return list;
352
+ }
353
+
354
+ /** Installs or replaces a CSS import compiled by the development build tool. */
355
+ export function updateStyleSheet(id, compiled) {
356
+ const key = String(id);
357
+ const previous = importedSheets.get(key);
358
+ if (compiled === null) {
359
+ if (importedSheets.delete(key)) syncAdoptedSheets();
360
+ } else if (previous) {
361
+ previous.replaceCompiled(compiled);
362
+ } else {
363
+ importedSheets.set(key, CSSStyleSheet.fromCompiled(compiled));
364
+ syncAdoptedSheets();
365
+ }
366
+ }
367
+
162
368
  /** A node of the tree. Make one with `createBox`, `createText`, `createInput` or `createNode`. */
163
369
  export class Node {
164
370
  #listeners = null;
@@ -166,19 +372,22 @@ export class Node {
166
372
  #base = null;
167
373
  #looks = null;
168
374
  #flags = 0;
169
- // aria-valuemin, aria-valuemax and aria-valuenow, which the tree takes as one range.
170
- #range = null;
375
+ #attributes = null;
376
+ #classList = null;
171
377
 
172
378
  constructor(kind) {
173
- this.id = ++nextId;
379
+ Object.defineProperty(this, "nodeId", { value: ++nextId, enumerable: true });
174
380
  this.kind = kind;
175
381
  this.parentNode = null;
176
382
  // A text leaf has no children: they all share one empty list.
177
383
  this.childNodes = kind === "text" ? NO_CHILDREN : [];
178
- nodes.set(this.id, this);
179
- native.create(this.id, KINDS[kind]);
384
+ nodes.set(this.nodeId, this);
385
+ native.create(this.nodeId, KINDS[kind]);
180
386
  }
181
387
 
388
+ get adoptedStyleSheets() { return adoptedList(this).proxy; }
389
+ set adoptedStyleSheets(value) { adoptedList(this).assign(Array.from(value)); }
390
+
182
391
  get firstChild() {
183
392
  return this.childNodes[0] ?? null;
184
393
  }
@@ -213,10 +422,10 @@ export class Node {
213
422
  child.parentNode = this;
214
423
  if (before) {
215
424
  this.childNodes.splice(this.childNodes.indexOf(before), 0, child);
216
- native.insertBefore(this.id, child.id, before.id);
425
+ native.insertBefore(this.nodeId, child.nodeId, before.nodeId);
217
426
  } else {
218
427
  this.childNodes.push(child);
219
- native.append(this.id, child.id);
428
+ native.append(this.nodeId, child.nodeId);
220
429
  }
221
430
  return child;
222
431
  }
@@ -235,7 +444,7 @@ export class Node {
235
444
  if (child.parentNode !== this) throw new Error("the node to remove is not a child of this node");
236
445
  this.childNodes.splice(this.childNodes.indexOf(child), 1);
237
446
  child.parentNode = null;
238
- native.remove(child.id);
447
+ native.remove(child.nodeId);
239
448
  return child;
240
449
  }
241
450
 
@@ -245,12 +454,13 @@ export class Node {
245
454
 
246
455
  /** Detaches and frees this node and its subtree. They cannot be used again. */
247
456
  destroy() {
457
+ if (rootNode && this.contains(rootNode)) { clearAdoptedSheets(); rootNode = null; }
248
458
  const parent = this.parentNode;
249
459
  if (parent) {
250
460
  parent.childNodes.splice(parent.childNodes.indexOf(this), 1);
251
461
  this.parentNode = null;
252
462
  }
253
- native.destroy(this.id);
463
+ native.destroy(this.nodeId);
254
464
  forget(this);
255
465
  }
256
466
 
@@ -281,88 +491,54 @@ export class Node {
281
491
  * the address with `open`, as a click on an `<a>` follows it.
282
492
  *
283
493
  * `role` and `aria-*` work as in the DOM, spelled `aria-checked` or `ariaChecked`. A role
284
- * or ARIA name the tree does not know is ignored with a warning.
494
+ * the tree does not know is ignored with a warning. Literal ARIA and data attributes
495
+ * remain available to selectors even when they have no native accessibility mapping.
285
496
  */
497
+ get id() { return this._elementId ?? ""; }
498
+ set id(value) { this.setAttribute("id", String(value)); }
499
+ get className() { return this.getAttribute("class") ?? ""; }
500
+ set className(value) { this.setAttribute("class", String(value)); }
501
+ get classList() { return this.#classList ??= new ClassList(this); }
502
+
503
+ getAttribute(name) {
504
+ name = String(name);
505
+ const aria = ariaName(name);
506
+ name = aria === null ? name === "className" ? "class" : name : "aria-" + aria;
507
+ return this.#attributes?.get(name) ?? null;
508
+ }
509
+
510
+ hasAttribute(name) { return this.getAttribute(name) !== null; }
511
+ removeAttribute(name) { this.setAttribute(name, null); }
512
+
286
513
  setAttribute(name, value) {
287
- if (name === "role") {
288
- const words = value == null ? "" : String(value);
289
- if (!native.attribute(this.id, "role", words)) warnOnce("the tree has no role '" + words + "': it is ignored");
290
- return;
291
- }
292
- if (name === "id") {
293
- this.#identify(value == null ? "" : String(value));
294
- return;
295
- }
514
+ name = String(name);
296
515
  const aria = ariaName(name);
297
- if (aria !== null) {
298
- this.#aria(aria, value);
299
- return;
300
- }
301
- if (name === "href") {
302
- this._href = value ? String(value) : null;
303
- this.#want(KIND_OF.get("click"));
304
- }
305
- native.attribute(this.id, name, value);
306
- }
307
-
308
- #aria(name, value) {
309
- if (name === "label") {
310
- native.attribute(this.id, "label", value == null ? "" : String(value));
311
- } else if (name in ARIA_STATES) {
312
- // ARIA states are the words "true" and "false"; anything else is false.
313
- if (name === "checked") native.attribute(this.id, "indeterminate", value === "mixed");
314
- native.attribute(this.id, ARIA_STATES[name], value === true || value === "true");
315
- } else if (ARIA_RELATIONS.has(name)) {
316
- this.#relate(name, value == null ? [] : String(value).split(/\s+/).filter(Boolean));
317
- } else if (name in ARIA_RANGE) {
318
- const range = (this.#range ??= [undefined, undefined, undefined]);
319
- range[ARIA_RANGE[name]] = value == null || value === "" ? undefined : Number(value);
320
- const [min = 0, max = 100, now] = range;
321
- if (now === undefined || Number.isNaN(now)) native.attribute(this.id, "valueRange");
322
- else native.attribute(this.id, "valueRange", min, max, now);
323
- } else if (!native.attribute(this.id, "aria-" + name, value == null ? "" : String(value))) {
324
- warnOnce("the tree has no 'aria-" + name + "' yet: it is ignored");
516
+ name = aria === null ? name === "className" ? "class" : name : "aria-" + aria;
517
+ const text = value == null ? null : String(value);
518
+ if (name === "role") {
519
+ if (!native.attribute(this.nodeId, "role", text ?? "")) warnOnce("the tree has no role '" + text + "': it is ignored");
520
+ } else if (name === "id") {
521
+ this.#identify(text);
522
+ } else if (aria !== null) {
523
+ native.attribute(this.nodeId, name, text);
524
+ } else {
525
+ if (name === "href") {
526
+ this._href = text || null;
527
+ this.#want(KIND_OF.get("click"));
528
+ }
529
+ native.attribute(this.nodeId, name,
530
+ name === "class" || name === "lang" || name === "dir" || name.startsWith("data-") ? text : value);
325
531
  }
532
+ if (text === null) this.#attributes?.delete(name);
533
+ else (this.#attributes ??= new Map()).set(name, text);
326
534
  }
327
535
 
328
536
  // The `id` other nodes' relations name this node by.
329
537
  #identify(id) {
330
538
  const old = this._elementId ?? "";
331
- if (old === id) return;
332
- if (old && byId.get(old) === this) {
333
- byId.delete(old);
334
- resolveNaming(old);
335
- }
539
+ if (old === (id ?? "") && this.getAttribute("id") === id) return;
336
540
  this._elementId = id || undefined;
337
- native.attribute(this.id, "id", id);
338
- if (id) {
339
- byId.set(id, this);
340
- resolveNaming(id);
341
- }
342
- }
343
-
344
- // Sets relation `name` (`labelledby`) to the nodes with ids `refs`, as they are now and
345
- // as they change.
346
- #relate(name, refs) {
347
- const relations = (this._relations ??= new Map());
348
- for (const ref of relations.get(name) ?? []) naming.get(ref)?.delete(this);
349
- if (refs.length) relations.set(name, refs);
350
- else relations.delete(name);
351
- for (const ref of refs) {
352
- let sources = naming.get(ref);
353
- if (!sources) naming.set(ref, (sources = new Set()));
354
- sources.add(this);
355
- }
356
- this._sendRelation(name);
357
- }
358
-
359
- _sendRelation(name) {
360
- const numbers = [];
361
- for (const ref of this._relations?.get(name) ?? []) {
362
- const target = byId.get(ref);
363
- if (target) numbers.push(target.id);
364
- }
365
- native.attribute(this.id, "aria-" + name, numbers.join(" "));
541
+ native.attribute(this.nodeId, "id", id);
366
542
  }
367
543
 
368
544
  // Tells the tree which events this node wants: its listeners', and clicks on a link.
@@ -370,23 +546,23 @@ export class Node {
370
546
  const list = this.#listeners?.get(TYPES[kind]);
371
547
  const wanted = (list && list.length > 0) || (kind === CLICK && this._href);
372
548
  const flags = wanted ? this.#flags | (1 << kind) : this.#flags & ~(1 << kind);
373
- if (flags !== this.#flags) native.listen(this.id, (this.#flags = flags));
549
+ if (flags !== this.#flags) native.listen(this.nodeId, (this.#flags = flags));
374
550
  }
375
551
 
376
552
  set tabIndex(value) {
377
- native.attribute(this.id, "tabIndex", value);
553
+ native.attribute(this.nodeId, "tabIndex", value);
378
554
  }
379
555
 
380
556
  set disabled(value) {
381
- native.attribute(this.id, "disabled", value);
557
+ native.attribute(this.nodeId, "disabled", value);
382
558
  }
383
559
 
384
560
  focus() {
385
- native.focus(this.id);
561
+ native.focus(this.nodeId);
386
562
  }
387
563
 
388
564
  scrollTo(x, y) {
389
- native.scrollTo(this.id, x, y);
565
+ native.scrollTo(this.nodeId, x, y);
390
566
  }
391
567
 
392
568
  /**
@@ -450,7 +626,7 @@ export class Text extends Node {
450
626
  value = String(value);
451
627
  if (value === this.#data && value !== "") return;
452
628
  this.#data = value;
453
- native.setText(this.id, value);
629
+ native.setText(this.nodeId, value);
454
630
  }
455
631
 
456
632
  get textContent() {
@@ -478,12 +654,12 @@ export class Input extends Node {
478
654
 
479
655
  set value(value) {
480
656
  this.#value = String(value);
481
- native.setText(this.id, this.#value);
657
+ native.setText(this.nodeId, this.#value);
482
658
  }
483
659
 
484
660
  /** Selects from `anchor` to `focus`, as UTF-8 byte offsets in the value. */
485
661
  setSelectionRange(anchor, focus) {
486
- native.select(this.id, anchor, focus);
662
+ native.select(this.nodeId, anchor, focus);
487
663
  }
488
664
 
489
665
  _changed(value, anchor, focus) {
@@ -545,7 +721,7 @@ export class Icon extends Node {
545
721
  if (markup === this.#svg) return;
546
722
  if (this.#svg) dropIcon(this.#svg);
547
723
  this.#svg = markup;
548
- native.source(this.id, markup ? holdIcon(markup) : 0);
724
+ native.source(this.nodeId, markup ? holdIcon(markup) : 0);
549
725
  }
550
726
 
551
727
  _forget() {
@@ -653,12 +829,12 @@ export class RichInput extends Input {
653
829
 
654
830
  /** What text with mark `name` looks like: properties as `style.set` takes them. */
655
831
  defineMark(name, style) {
656
- native.mark(this.id, this.#bit(name), cssTextOf(style));
832
+ native.mark(this.nodeId, this.#bit(name), cssTextOf(style));
657
833
  }
658
834
 
659
835
  /** What atoms of `kind` look like: the inline block holding the label. */
660
836
  defineAtom(kind, style) {
661
- native.atomStyle(this.id, this.#kind(kind), cssTextOf(style));
837
+ native.atomStyle(this.nodeId, this.#kind(kind), cssTextOf(style));
662
838
  }
663
839
 
664
840
  get document() {
@@ -679,7 +855,7 @@ export class RichInput extends Input {
679
855
  }
680
856
  let packedAtoms = "";
681
857
  for (const atom of atoms) packedAtoms += this.#packAtom(atom);
682
- native.richText(this.id, text, packedMarks, packedAtoms);
858
+ native.richText(this.nodeId, text, packedMarks, packedAtoms);
683
859
  super._changed(text, text.length, text.length);
684
860
  }
685
861
 
@@ -689,7 +865,7 @@ export class RichInput extends Input {
689
865
 
690
866
  /** Turns mark `name` on or off over the selection, or for the text typed next. */
691
867
  format(name, on = true) {
692
- native.format(this.id, this.#bit(name), !!on);
868
+ native.format(this.nodeId, this.#bit(name), !!on);
693
869
  }
694
870
 
695
871
  /** Turns mark `name` off where the caret's text has it, on where it does not. */
@@ -700,12 +876,12 @@ export class RichInput extends Input {
700
876
  /** Replaces the text from `start` to `end` with `atom` (`{ kind, label, data }`). */
701
877
  insertAtom(start, end, atom) {
702
878
  const text = this.#document.text;
703
- native.insertAtom(this.id, byteOf(text, start), byteOf(text, end), this.#packAtom(atom));
879
+ native.insertAtom(this.nodeId, byteOf(text, start), byteOf(text, end), this.#packAtom(atom));
704
880
  }
705
881
 
706
882
  setSelectionRange(anchor, focus) {
707
883
  const text = this.#document.text;
708
- native.select(this.id, byteOf(text, anchor), byteOf(text, focus));
884
+ native.select(this.nodeId, byteOf(text, anchor), byteOf(text, focus));
709
885
  }
710
886
 
711
887
  _changed(value, anchor, focus, marks, atoms, active) {
@@ -740,22 +916,8 @@ export function createRichInput(style) {
740
916
  return input;
741
917
  }
742
918
 
743
- // Sends again the relations that name `ref`, after the node with that id changed.
744
- function resolveNaming(ref) {
745
- for (const source of naming.get(ref) ?? []) {
746
- for (const [name, refs] of source._relations) if (refs.includes(ref)) source._sendRelation(name);
747
- }
748
- }
749
-
750
919
  function forget(node) {
751
- nodes.delete(node.id);
752
- if (node._relations) {
753
- for (const refs of node._relations.values()) for (const ref of refs) naming.get(ref)?.delete(node);
754
- }
755
- if (node._elementId && byId.get(node._elementId) === node) {
756
- byId.delete(node._elementId);
757
- resolveNaming(node._elementId);
758
- }
920
+ nodes.delete(node.nodeId);
759
921
  node._forget?.();
760
922
  for (const child of node.childNodes) {
761
923
  child.parentNode = null;
@@ -826,8 +988,10 @@ export function defineKeyframes(name, frames) {
826
988
  }
827
989
 
828
990
  export function mount(node) {
991
+ if (rootNode) clearAdoptedSheets();
829
992
  rootNode = node;
830
- native.root(node.id);
993
+ native.root(node.nodeId);
994
+ syncAdoptedSheets();
831
995
  return node;
832
996
  }
833
997
 
@@ -989,7 +1153,7 @@ function fill(event, kind, a, b, modifiers, d, e, first, second, third, fourth)
989
1153
  } else if (kind >= 19 && kind <= 22) {
990
1154
  event.propertyName = first;
991
1155
  event.elapsedTime = a;
992
- event.pseudoElement = "";
1156
+ event.pseudoElement = second ?? "";
993
1157
  } else if (kind === 27) {
994
1158
  event.target._selected?.(a, b, d);
995
1159
  event.selectionStart = event.target.selectionStart;
@@ -997,7 +1161,7 @@ function fill(event, kind, a, b, modifiers, d, e, first, second, third, fourth)
997
1161
  } else if (kind >= 23) {
998
1162
  event.animationName = first;
999
1163
  event.elapsedTime = a;
1000
- event.pseudoElement = "";
1164
+ event.pseudoElement = second ?? "";
1001
1165
  }
1002
1166
  }
1003
1167
 
@@ -1059,7 +1223,8 @@ function follow(target) {
1059
1223
  // The host calls this before it replaces the realm, on a reload: every node goes, so the
1060
1224
  // next realm starts on an empty tree.
1061
1225
  native.unload = function () {
1062
- for (const node of [...nodes.values()]) if (!node.parentNode && nodes.has(node.id)) node.destroy();
1226
+ importedSheets.clear();
1227
+ for (const node of [...nodes.values()]) if (!node.parentNode && nodes.has(node.nodeId)) node.destroy();
1063
1228
  rootNode = null;
1064
1229
  };
1065
1230