@silkui/core 0.1.8 → 0.1.10

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/src/index.js CHANGED
@@ -12,21 +12,61 @@ if (!native) throw new Error("@silkui/core needs the __ui functions of a ui-js h
12
12
  const KINDS = { box: 0, text: 1, input: 2, image: 3, icon: 4, canvas: 5 };
13
13
  const STATES = { base: 0, hover: 1, active: 2, focus: 3, focusVisible: 4, starting: 5 };
14
14
 
15
- // Event types in the order of the tree's LISTEN_* flags: the index is the kind number the
16
- // host dispatches and the bit a node listens with.
15
+ // Event types by the kind number the host dispatches. Up to `selectionchange`, `pointerover`
16
+ // and `pointerout` the kind is also the bit of the tree's LISTEN_* flags a node listens with;
17
+ // copy, cut and paste share bit 30, and beforeinput has bit 31 (see `bitOf`).
17
18
  const TYPES = [
18
19
  "pointerdown", "pointerup", "click", "pointermove", "pointerenter", "pointerleave", "wheel",
19
20
  "keydown", "keyup", "focus", "blur", "input", "scroll", "layout", "pointercancel",
20
21
  "gotpointercapture", "lostpointercapture", "load", "error", "transitionrun", "transitionstart",
21
22
  "transitionend", "transitioncancel", "animationstart", "animationiteration", "animationend",
22
- "animationcancel", "selectionchange",
23
+ "animationcancel", "selectionchange", "pointerover", "pointerout", "touchstart", "touchmove",
24
+ "touchend", "touchcancel", "copy", "cut", "paste", "beforeinput",
23
25
  ];
24
26
  const KIND_OF = new Map(TYPES.map((type, kind) => [type, kind]));
27
+
28
+ // The live `Range`s (see Range below), held weakly: a range nobody holds stops being updated.
29
+ const liveRanges = new Set();
30
+
31
+ function eachLiveRange(update) {
32
+ for (const ref of liveRanges) {
33
+ const range = ref.deref();
34
+ if (range) update(range);
35
+ else liveRanges.delete(ref);
36
+ }
37
+ }
38
+
25
39
  const CLICK = KIND_OF.get("click");
40
+ const SELECTION_CHANGE = KIND_OF.get("selectionchange");
41
+ const TOUCH_START = KIND_OF.get("touchstart");
42
+ const COPY = KIND_OF.get("copy");
43
+ const CUT = KIND_OF.get("cut");
44
+ const PASTE = KIND_OF.get("paste");
45
+ const BEFORE_INPUT = KIND_OF.get("beforeinput");
46
+ // The listen bit of a kind: the touch kinds share bit 30, copy, cut, paste and beforeinput bit 31.
47
+ const bitOf = (kind) => (kind < TOUCH_START ? kind : kind < COPY ? 30 : 31);
48
+ const KINDS_OF_BIT = (bit) => TYPES.map((_, kind) => kind).filter((kind) => bitOf(kind) === bit);
49
+ // Compatibility mouse events, as the web fires them after pointer events: each listens
50
+ // through the pointer kind it follows.
51
+ const MOUSE_OF = new Map([
52
+ ["pointerdown", "mousedown"], ["pointerup", "mouseup"], ["pointermove", "mousemove"],
53
+ ["pointerover", "mouseover"], ["pointerout", "mouseout"], ["pointerenter", "mouseenter"],
54
+ ["pointerleave", "mouseleave"],
55
+ ]);
56
+ const POINTER_OF = new Map([...MOUSE_OF].map(([pointer, mouse]) => [mouse, pointer]));
57
+ // Types the tree reports through another kind's records: `selectstart` comes as a
58
+ // `SelectionChange` record at the node pressed.
59
+ const LISTENS_AS = new Map([...POINTER_OF, ["selectstart", "selectionchange"]]);
26
60
  // As on the web: these reach the target alone.
27
- const NO_BUBBLE = new Set(["pointerenter", "pointerleave", "focus", "blur", "scroll", "layout", "load", "error"]);
28
- // The tree has a default action to skip for these.
29
- const CANCELABLE = new Set(["pointerdown", "pointerup", "click", "wheel", "keydown", "keyup", "dragenter", "dragover", "drop"]);
61
+ const NO_BUBBLE = new Set([
62
+ "pointerenter", "pointerleave", "mouseenter", "mouseleave", "focus", "blur", "scroll", "layout", "load",
63
+ "error",
64
+ ]);
65
+ // The tree has a default action to skip for these. Touch records say for themselves.
66
+ const CANCELABLE = new Set([
67
+ "pointerdown", "pointerup", "click", "wheel", "keydown", "keyup", "dragenter", "dragover", "drop",
68
+ "mousedown", "mouseup", "mousemove", "mouseover", "mouseout", "selectstart", "copy", "cut", "paste", "beforeinput",
69
+ ]);
30
70
  // Files dragged from the desktop: the host dispatches these itself, so nodes need no flag.
31
71
  const DRAG_TYPES = new Set(["dragenter", "dragover", "dragleave", "drop"]);
32
72
 
@@ -97,6 +137,8 @@ class Look {
97
137
  #node;
98
138
  #state;
99
139
  // Plain objects share their shape across nodes: a Map here costs four times the memory.
140
+ // A number or string is kept as given, which the caller's style object holds too, and
141
+ // turned into CSS text when it is read: no node keeps a string of its own per value.
100
142
  #values = Object.create(null);
101
143
 
102
144
  constructor(node, state) {
@@ -121,9 +163,9 @@ class Look {
121
163
  }
122
164
  continue;
123
165
  }
166
+ if (this.#values[name] === value) continue;
124
167
  const text = cssValue(name, value);
125
- if (this.#values[name] === text) continue;
126
- this.#values[name] = text;
168
+ this.#values[name] = typeof value === "number" || typeof value === "string" ? value : text;
127
169
  css += cssName(name) + ":" + text + ";";
128
170
  }
129
171
  if (removed) {
@@ -143,14 +185,21 @@ class Look {
143
185
  }
144
186
 
145
187
  get(name) {
146
- return this.#values[name];
188
+ const value = this.#values[name];
189
+ return value === undefined ? undefined : cssValue(name, value);
147
190
  }
148
191
 
149
192
  get cssText() {
150
193
  let css = "";
151
- for (const name in this.#values) css += cssName(name) + ":" + this.#values[name] + ";";
194
+ for (const name in this.#values) css += cssName(name) + ":" + cssValue(name, this.#values[name]) + ";";
152
195
  return css;
153
196
  }
197
+
198
+ _copyTo(look) {
199
+ look.#values = Object.assign(Object.create(null), this.#values);
200
+ const css = this.cssText;
201
+ if (css) native.style(look.#node.nodeId, css, look.#state);
202
+ }
154
203
  }
155
204
 
156
205
  const CLASS_SPACE = /[\t\n\f\r ]/;
@@ -367,26 +416,50 @@ export function updateStyleSheet(id, compiled) {
367
416
  }
368
417
  }
369
418
 
419
+ // What few nodes have, made on first use (see `Node`).
420
+ class NodeState {
421
+ listeners = null;
422
+ // The state looks by name.
423
+ looks = null;
424
+ flags = 0;
425
+ // Kinds the node hears whatever its listeners: an input keeps its value and selection current.
426
+ kept = 0;
427
+ attributes = null;
428
+ classList = null;
429
+ }
430
+
370
431
  /** A node of the tree. Make one with `createBox`, `createText`, `createInput` or `createNode`. */
371
432
  export class Node {
372
- #listeners = null;
373
- // The base look, and the state looks by name: most nodes have the base alone.
433
+ // A node is a handle on the tree's node: it keeps only what the tree cannot answer at once
434
+ // (its place among its siblings, its class, its base look), and puts the state few nodes
435
+ // have (listeners, attributes, state looks) in one record made on first use. Every field
436
+ // is a slot in every node, and a node of up to eight fits its object's own cell.
437
+ // The base look: most nodes have the base alone.
374
438
  #base = null;
375
- #looks = null;
376
- #flags = 0;
377
- #attributes = null;
378
- #classList = null;
439
+ #className = null;
440
+ #rare = null;
379
441
 
380
442
  constructor(kind) {
381
443
  Object.defineProperty(this, "nodeId", { value: ++nextId, enumerable: true });
382
- this.kind = kind;
444
+ // A text node's kind is its prototype's: one slot fewer in the most numerous node.
445
+ if (kind !== "text") this.kind = kind;
383
446
  this.parentNode = null;
384
- // A text leaf has no children: they all share one empty list.
385
- this.childNodes = kind === "text" ? NO_CHILDREN : [];
447
+ // A node with no children shares one empty list, and gets its own at its first child.
448
+ this.childNodes = NO_CHILDREN;
386
449
  nodes.set(this.nodeId, this);
387
450
  native.create(this.nodeId, KINDS[kind]);
388
451
  }
389
452
 
453
+ #more() {
454
+ return (this.#rare ??= new NodeState());
455
+ }
456
+
457
+ // The node's own child list, made on its first child.
458
+ _ownChildren() {
459
+ if (this.childNodes === NO_CHILDREN) this.childNodes = [];
460
+ return this.childNodes;
461
+ }
462
+
390
463
  get adoptedStyleSheets() { return adoptedList(this).proxy; }
391
464
  set adoptedStyleSheets(value) { adoptedList(this).assign(Array.from(value)); }
392
465
 
@@ -408,6 +481,62 @@ export class Node {
408
481
  return siblings ? siblings[siblings.indexOf(this) - 1] ?? null : null;
409
482
  }
410
483
 
484
+ /** 1 for an element, 3 for text, 11 for a document fragment, as in the DOM. */
485
+ get nodeType() {
486
+ return 1;
487
+ }
488
+
489
+ hasChildNodes() {
490
+ return this.childNodes.length > 0;
491
+ }
492
+
493
+ /** A copy with the same looks and attributes, and with `deep` copies of the children. */
494
+ cloneNode(deep = false) {
495
+ const copy = this._shallowClone();
496
+ if (this.#base) this.#base._copyTo(copy.look("base"));
497
+ const looks = this.#rare?.looks;
498
+ for (const state in looks ?? {}) looks[state]._copyTo(copy.look(state));
499
+ for (const [name, value] of this.#rare?.attributes ?? []) copy.setAttribute(name, value);
500
+ if (deep) for (const child of this.childNodes) copy.appendChild(child.cloneNode(true));
501
+ return copy;
502
+ }
503
+
504
+ _shallowClone() {
505
+ return new Node(this.kind);
506
+ }
507
+
508
+ /** Joins adjacent text children and drops empty ones, in the whole subtree. */
509
+ normalize() {
510
+ for (let node = this.firstChild; node; ) {
511
+ if (node.nodeType !== 3) {
512
+ node.normalize();
513
+ node = node.nextSibling;
514
+ continue;
515
+ }
516
+ let next = node.nextSibling;
517
+ if (node.length === 0) {
518
+ node.remove();
519
+ node = next;
520
+ continue;
521
+ }
522
+ let joined = "";
523
+ for (let sibling = next; sibling?.nodeType === 3; sibling = sibling.nextSibling) joined += sibling.data;
524
+ let length = node.length;
525
+ node.replaceData(length, 0, joined);
526
+ for (let current = next; current?.nodeType === 3; current = current.nextSibling) {
527
+ const index = indexIn(current);
528
+ eachLiveRange((range) => range._joined(current, node, length, index));
529
+ length += current.length;
530
+ }
531
+ while (next?.nodeType === 3) {
532
+ const after = next.nextSibling;
533
+ next.remove();
534
+ next = after;
535
+ }
536
+ node = next;
537
+ }
538
+ }
539
+
411
540
  /** Whether `other` is this node or inside it. */
412
541
  contains(other) {
413
542
  for (let node = other; node; node = node.parentNode) if (node === this) return true;
@@ -416,17 +545,30 @@ export class Node {
416
545
 
417
546
  /** Inserts `child` before `before`, or last without it. A child already in the tree moves. */
418
547
  insertBefore(child, before = null) {
419
- if (child.contains(this)) throw new Error("a node cannot be inserted into itself or its own subtree");
420
- if (before && before.parentNode !== this) throw new Error("the node to insert before is not a child of this node");
421
- if (before === child) return child;
548
+ if (child.contains(this)) throw domError("HierarchyRequestError", "a node cannot be inserted into itself or its own subtree");
549
+ if (this.nodeType === 3) throw domError("HierarchyRequestError", "text has no children");
550
+ if (before && before.parentNode !== this) throw domError("NotFoundError", "the node to insert before is not a child of this node");
551
+ if (child.nodeType === 11) {
552
+ for (const node of [...child.childNodes]) this.insertBefore(node, before);
553
+ return child;
554
+ }
555
+ if (before === child) before = child.nextSibling;
422
556
  const old = child.parentNode;
423
- if (old) old.childNodes.splice(old.childNodes.indexOf(child), 1);
557
+ if (old) {
558
+ const index = old.childNodes.indexOf(child);
559
+ if (liveRanges.size) eachLiveRange((range) => range._removing(child, old, index));
560
+ old.childNodes.splice(index, 1);
561
+ }
424
562
  child.parentNode = this;
563
+ if (liveRanges.size) {
564
+ const index = before ? this.childNodes.indexOf(before) : this.childNodes.length;
565
+ eachLiveRange((range) => range._inserted(this, index));
566
+ }
425
567
  if (before) {
426
568
  this.childNodes.splice(this.childNodes.indexOf(before), 0, child);
427
569
  native.insertBefore(this.nodeId, child.nodeId, before.nodeId);
428
570
  } else {
429
- this.childNodes.push(child);
571
+ this._ownChildren().push(child);
430
572
  native.append(this.nodeId, child.nodeId);
431
573
  }
432
574
  return child;
@@ -436,6 +578,17 @@ export class Node {
436
578
  return this.insertBefore(child, null);
437
579
  }
438
580
 
581
+ /** Puts `node` where `child` is and detaches `child`. */
582
+ replaceChild(node, child) {
583
+ if (child.parentNode !== this) throw domError("NotFoundError", "the node to replace is not a child of this node");
584
+ if (node === child) return child;
585
+ let before = child.nextSibling;
586
+ if (before === node) before = node.nextSibling;
587
+ this.removeChild(child);
588
+ this.insertBefore(node, before);
589
+ return child;
590
+ }
591
+
439
592
  /** Appends nodes, and strings as text nodes. */
440
593
  append(...children) {
441
594
  for (const child of children) this.insertBefore(typeof child === "string" ? createText(child) : child, null);
@@ -443,8 +596,10 @@ export class Node {
443
596
 
444
597
  /** Detaches `child` and its subtree. It keeps its state and can be inserted again. */
445
598
  removeChild(child) {
446
- if (child.parentNode !== this) throw new Error("the node to remove is not a child of this node");
447
- this.childNodes.splice(this.childNodes.indexOf(child), 1);
599
+ if (child.parentNode !== this) throw domError("NotFoundError", "the node to remove is not a child of this node");
600
+ const index = this.childNodes.indexOf(child);
601
+ if (liveRanges.size) eachLiveRange((range) => range._removing(child, this, index));
602
+ this.childNodes.splice(index, 1);
448
603
  child.parentNode = null;
449
604
  native.remove(child.nodeId);
450
605
  return child;
@@ -459,7 +614,9 @@ export class Node {
459
614
  if (rootNode && this.contains(rootNode)) { clearAdoptedSheets(); rootNode = null; }
460
615
  const parent = this.parentNode;
461
616
  if (parent) {
462
- parent.childNodes.splice(parent.childNodes.indexOf(this), 1);
617
+ const index = parent.childNodes.indexOf(this);
618
+ if (liveRanges.size) eachLiveRange((range) => range._removing(this, parent, index));
619
+ parent.childNodes.splice(index, 1);
463
620
  this.parentNode = null;
464
621
  }
465
622
  native.destroy(this.nodeId);
@@ -483,8 +640,9 @@ export class Node {
483
640
  look(state) {
484
641
  if (state === "base") return (this.#base ??= new Look(this, 0));
485
642
  if (!(state in STATES)) throw new TypeError("the tree has no look '" + state + "'");
486
- this.#looks ??= Object.create(null);
487
- return (this.#looks[state] ??= new Look(this, STATES[state]));
643
+ const rare = this.#more();
644
+ rare.looks ??= Object.create(null);
645
+ return (rare.looks[state] ??= new Look(this, STATES[state]));
488
646
  }
489
647
 
490
648
  /**
@@ -500,13 +658,13 @@ export class Node {
500
658
  set id(value) { this.setAttribute("id", String(value)); }
501
659
  get className() { return this.getAttribute("class") ?? ""; }
502
660
  set className(value) { this.setAttribute("class", String(value)); }
503
- get classList() { return this.#classList ??= new ClassList(this); }
661
+ get classList() { return this.#more().classList ??= new ClassList(this); }
504
662
 
505
663
  getAttribute(name) {
506
664
  name = String(name);
665
+ if (name === "className" || name === "class") return this.#className;
507
666
  const aria = ariaName(name);
508
- name = aria === null ? name === "className" ? "class" : name : "aria-" + aria;
509
- return this.#attributes?.get(name) ?? null;
667
+ return this.#rare?.attributes?.get(aria === null ? name : "aria-" + aria) ?? null;
510
668
  }
511
669
 
512
670
  hasAttribute(name) { return this.getAttribute(name) !== null; }
@@ -514,9 +672,14 @@ export class Node {
514
672
 
515
673
  setAttribute(name, value) {
516
674
  name = String(name);
517
- const aria = ariaName(name);
518
- name = aria === null ? name === "className" ? "class" : name : "aria-" + aria;
519
675
  const text = value == null ? null : String(value);
676
+ if (name === "className" || name === "class") {
677
+ native.attribute(this.nodeId, "class", text);
678
+ this.#className = text;
679
+ return;
680
+ }
681
+ const aria = ariaName(name);
682
+ if (aria !== null) name = "aria-" + aria;
520
683
  if (name === "role") {
521
684
  if (!native.attribute(this.nodeId, "role", text ?? "")) warnOnce("the tree has no role '" + text + "': it is ignored");
522
685
  } else if (name === "id") {
@@ -535,10 +698,10 @@ export class Node {
535
698
  this.#want(KIND_OF.get("click"));
536
699
  }
537
700
  native.attribute(this.nodeId, name,
538
- name === "class" || name === "lang" || name === "dir" || name.startsWith("data-") ? text : value);
701
+ name === "lang" || name === "dir" || name.startsWith("data-") ? text : value);
539
702
  }
540
- if (text === null) this.#attributes?.delete(name);
541
- else (this.#attributes ??= new Map()).set(name, text);
703
+ if (text === null) this.#rare?.attributes?.delete(name);
704
+ else (this.#more().attributes ??= new Map()).set(name, text);
542
705
  }
543
706
 
544
707
  // The `id` other nodes' relations name this node by.
@@ -551,10 +714,39 @@ export class Node {
551
714
 
552
715
  // Tells the tree which events this node wants: its listeners', and clicks on a link.
553
716
  #want(kind) {
554
- const list = this.#listeners?.get(TYPES[kind]);
555
- const wanted = (list && list.length > 0) || (kind === CLICK && this._href);
556
- const flags = wanted ? this.#flags | (1 << kind) : this.#flags & ~(1 << kind);
557
- if (flags !== this.#flags) native.listen(this.nodeId, (this.#flags = flags));
717
+ const [wanted, bit] = this.#wanted(kind);
718
+ const rare = this.#rare;
719
+ const old = rare?.flags ?? 0;
720
+ const flags = ((wanted ? old | bit : old & ~bit) | (rare?.kept ?? 0) | (this._extra ?? 0)) >>> 0;
721
+ if (flags !== old) native.listen(this.nodeId, (this.#more().flags = flags));
722
+ }
723
+
724
+ // Whether this node's listeners (or link) want `kind`, and the flag bit that carries it.
725
+ #wanted(kind) {
726
+ const listeners = this.#rare?.listeners;
727
+ const has = (type) => (listeners?.get(type)?.length ?? 0) > 0;
728
+ if (kind >= TOUCH_START) return [KINDS_OF_BIT(bitOf(kind)).some((each) => has(TYPES[each])), (1 << bitOf(kind)) >>> 0];
729
+ const type = TYPES[kind];
730
+ const wanted = has(type) || (MOUSE_OF.has(type) && has(MOUSE_OF.get(type))) || (kind === CLICK && this._href)
731
+ || (kind === SELECTION_CHANGE && has("selectstart"));
732
+ return [wanted, 1 << kind];
733
+ }
734
+
735
+ /** Listens again for every kind its listeners, kept kinds and `_extra` flags ask for. */
736
+ _relisten() {
737
+ let flags = (this.#rare?.kept ?? 0) | (this._extra ?? 0);
738
+ for (let kind = 0; kind < TYPES.length; kind++) {
739
+ const [wanted, bit] = this.#wanted(kind);
740
+ if (wanted) flags |= bit;
741
+ }
742
+ flags >>>= 0;
743
+ if (flags !== (this.#rare?.flags ?? 0)) native.listen(this.nodeId, (this.#more().flags = flags));
744
+ }
745
+
746
+ _keep(...types) {
747
+ const rare = this.#more();
748
+ for (const type of types) rare.kept = (rare.kept | (1 << bitOf(KIND_OF.get(type)))) >>> 0;
749
+ this.#want(KIND_OF.get(types[0]));
558
750
  }
559
751
 
560
752
  set tabIndex(value) {
@@ -569,12 +761,114 @@ export class Node {
569
761
  native.focus(this.nodeId);
570
762
  }
571
763
 
764
+ /**
765
+ * Sends the pointer's records here until it lifts, as DOM `setPointerCapture`. Throws
766
+ * `NotFoundError` for a pointer that is not down. The tree moves the capture of the
767
+ * primary pointer; another finger keeps sending to the node it went down on.
768
+ */
769
+ setPointerCapture(pointerId) {
770
+ const pointer = pointers.get(pointerId);
771
+ if (!pointer) throw domError("NotFoundError", `no active pointer with id ${pointerId}`);
772
+ if (!pointer.buttons) return;
773
+ pointer.capture = this;
774
+ if (pointer.primary) native.capture(this.nodeId);
775
+ }
776
+
777
+ releasePointerCapture(pointerId) {
778
+ const pointer = pointers.get(pointerId);
779
+ if (!pointer) throw domError("NotFoundError", `no active pointer with id ${pointerId}`);
780
+ if (pointer.capture !== this) return;
781
+ pointer.capture = null;
782
+ if (pointer.primary) native.capture(0);
783
+ }
784
+
785
+ hasPointerCapture(pointerId) {
786
+ return pointers.get(pointerId)?.capture === this;
787
+ }
788
+
789
+ /** `scrollTo(x, y)` or `scrollTo({ left, top, behavior })`; `behavior: "smooth"` animates, and `auto` follows `scroll-behavior`. */
572
790
  scrollTo(x, y) {
573
- native.scrollTo(this.nodeId, x, y);
791
+ scrollNode(this.nodeId, x, y, 0);
574
792
  }
575
793
 
576
794
  scroll(x, y) {
577
- native.scrollTo(this.nodeId, x, y);
795
+ scrollNode(this.nodeId, x, y, 0);
796
+ }
797
+
798
+ /** As `scrollTo`, by an amount from where the node is scrolled. */
799
+ scrollBy(x, y) {
800
+ scrollNode(this.nodeId, x, y, 4);
801
+ }
802
+
803
+ /** The border box in window coordinates, after any pending layout, as on the web. */
804
+ getBoundingClientRect() {
805
+ return readRect(this.nodeId);
806
+ }
807
+
808
+ /** One rectangle per fragment (a wrapped inline box has one per line). */
809
+ getClientRects() {
810
+ return readRects(native.rects?.(this.nodeId) ?? 0);
811
+ }
812
+
813
+ get clientLeft() { return metric(this.nodeId, 0); }
814
+ get clientTop() { return metric(this.nodeId, 1); }
815
+ get clientWidth() { return metric(this.nodeId, 2); }
816
+ get clientHeight() { return metric(this.nodeId, 3); }
817
+ get scrollWidth() { return metric(this.nodeId, 4); }
818
+ get scrollHeight() { return metric(this.nodeId, 5); }
819
+ get scrollLeft() { return metric(this.nodeId, 6); }
820
+ set scrollLeft(value) { scrollNode(this.nodeId, { left: value }, undefined, 0); }
821
+ get scrollTop() { return metric(this.nodeId, 7); }
822
+ set scrollTop(value) { scrollNode(this.nodeId, { top: value }, undefined, 0); }
823
+ get offsetParent() { return nodes.get(metric(this.nodeId, 8)) ?? null; }
824
+ get offsetLeft() { return metric(this.nodeId, 9); }
825
+ get offsetTop() { return metric(this.nodeId, 10); }
826
+ get offsetWidth() { return metric(this.nodeId, 11); }
827
+ get offsetHeight() { return metric(this.nodeId, 12); }
828
+
829
+ /**
830
+ * Scrolls every scroll container around this node to show it, as on the web: `true` or
831
+ * nothing aligns to the start, `false` to the end, or `{ block, inline, behavior }`.
832
+ * `scroll-margin`, `scroll-padding` and `scroll-snap` apply.
833
+ */
834
+ scrollIntoView(options = true) {
835
+ if (options === null || typeof options !== "object") {
836
+ const top = options !== false;
837
+ native.scrollIntoView?.(this.nodeId, top ? 0 : 2, 3, 0, 0);
838
+ return;
839
+ }
840
+ native.scrollIntoView?.(this.nodeId, alignment(options.block, 0), alignment(options.inline, 3), BEHAVIORS[options.behavior] ?? 0, 0);
841
+ }
842
+
843
+ /** WebKit's: scrolls only containers that do not already show the node, centering it unless `center` is false. */
844
+ scrollIntoViewIfNeeded(center = true) {
845
+ const code = center ? 1 : 3;
846
+ native.scrollIntoView?.(this.nodeId, code, code, 0, 1);
847
+ }
848
+
849
+ /** Whether this node matches CSS `selector`, by the same matcher as stylesheets. */
850
+ matches(selector) {
851
+ return queried(0, this, selector) === 1;
852
+ }
853
+
854
+ webkitMatchesSelector(selector) {
855
+ return this.matches(selector);
856
+ }
857
+
858
+ /** This node or its nearest ancestor that matches `selector`, or null. */
859
+ closest(selector) {
860
+ return nodes.get(queried(1, this, selector)) ?? null;
861
+ }
862
+
863
+ /** The first descendant, in tree order, that matches `selector`, or null. */
864
+ querySelector(selector) {
865
+ return nodes.get(queried(2, this, selector)) ?? null;
866
+ }
867
+
868
+ /** Every descendant that matches `selector`, in tree order: a static list. */
869
+ querySelectorAll(selector) {
870
+ const ids = queried(3, this, selector);
871
+ return typeof ids === "string" && ids !== "" ? ids.split(",").map((id) => nodes.get(Number(id))).filter(Boolean) : [];
578
872
  }
579
873
 
580
874
  /**
@@ -583,25 +877,27 @@ export class Node {
583
877
  * app's own, sent with `dispatchEvent`.
584
878
  */
585
879
  addEventListener(type, listener, options) {
586
- if (listener == null) return;
587
- const kind = KIND_OF.get(type);
880
+ const signal = options?.signal;
881
+ if (listener == null || signal?.aborted) return;
882
+ const kind = KIND_OF.get(LISTENS_AS.get(type) ?? type);
588
883
  const capture = options === true || !!options?.capture;
589
- this.#listeners ??= new Map();
590
- let list = this.#listeners.get(type);
591
- if (!list) this.#listeners.set(type, (list = []));
884
+ const listeners = (this.#more().listeners ??= new Map());
885
+ let list = listeners.get(type);
886
+ if (!list) listeners.set(type, (list = []));
592
887
  if (list.some((entry) => entry.listener === listener && entry.capture === capture)) return;
593
888
  list.push({ listener, capture, once: !!options?.once });
594
889
  if (kind !== undefined) this.#want(kind);
890
+ signal?.addEventListener("abort", () => this.removeEventListener(type, listener, capture), { once: true });
595
891
  }
596
892
 
597
893
  removeEventListener(type, listener, options) {
598
- const list = this.#listeners?.get(type);
894
+ const list = this.#rare?.listeners?.get(type);
599
895
  if (!list) return;
600
896
  const capture = options === true || !!options?.capture;
601
897
  const index = list.findIndex((entry) => entry.listener === listener && entry.capture === capture);
602
898
  if (index < 0) return;
603
899
  list.splice(index, 1);
604
- const kind = KIND_OF.get(type);
900
+ const kind = KIND_OF.get(LISTENS_AS.get(type) ?? type);
605
901
  if (kind !== undefined) this.#want(kind);
606
902
  }
607
903
 
@@ -613,7 +909,7 @@ export class Node {
613
909
 
614
910
  /** Runs the capture or the bubble listeners of `event.type`. Used by the dispatcher. */
615
911
  _run(event, capture) {
616
- const list = this.#listeners?.get(event.type);
912
+ const list = this.#rare?.listeners?.get(event.type);
617
913
  if (!list) return;
618
914
  for (const entry of list.slice()) {
619
915
  if (event._immediate) return;
@@ -643,11 +939,19 @@ export class Text extends Node {
643
939
  }
644
940
 
645
941
  set data(value) {
646
- value = String(value);
647
- if (value === this.#data && value !== "") return;
648
- this.#data = value;
649
- native.setText(this.nodeId, value);
650
- if (this._svgText) svgChanged(this);
942
+ this.replaceData(0, this.#data.length, value == null ? "" : value);
943
+ }
944
+
945
+ get nodeType() {
946
+ return 3;
947
+ }
948
+
949
+ get nodeValue() {
950
+ return this.#data;
951
+ }
952
+
953
+ set nodeValue(value) {
954
+ this.data = value;
651
955
  }
652
956
 
653
957
  get textContent() {
@@ -657,16 +961,91 @@ export class Text extends Node {
657
961
  set textContent(value) {
658
962
  this.data = value;
659
963
  }
964
+
965
+ get length() {
966
+ return this.#data.length;
967
+ }
968
+
969
+ _shallowClone() {
970
+ return new Text(this.#data);
971
+ }
972
+
973
+ substringData(offset, count) {
974
+ offset = offset >>> 0;
975
+ if (offset > this.#data.length) throw domError("IndexSizeError", "the offset is past the end of the text");
976
+ return this.#data.substring(offset, offset + (count >>> 0));
977
+ }
978
+
979
+ appendData(data) {
980
+ this.replaceData(this.#data.length, 0, data);
981
+ }
982
+
983
+ insertData(offset, data) {
984
+ this.replaceData(offset, 0, data);
985
+ }
986
+
987
+ deleteData(offset, count) {
988
+ this.replaceData(offset, count, "");
989
+ }
990
+
991
+ replaceData(offset, count, data) {
992
+ offset = offset >>> 0;
993
+ count = count >>> 0;
994
+ data = String(data);
995
+ const old = this.#data;
996
+ if (offset > old.length) throw domError("IndexSizeError", "the offset is past the end of the text");
997
+ if (offset + count > old.length) count = old.length - offset;
998
+ if (liveRanges.size) eachLiveRange((range) => range._replaced(this, offset, count, data.length));
999
+ const value = old.slice(0, offset) + data + old.slice(offset + count);
1000
+ if (value === old && value !== "") return;
1001
+ this.#data = value;
1002
+ native.setText(this.nodeId, value);
1003
+ if (this._svgText) svgChanged(this);
1004
+ }
1005
+
1006
+ /** Splits at `offset`: this keeps the text before it, and a new next sibling the rest. */
1007
+ splitText(offset) {
1008
+ offset = offset >>> 0;
1009
+ const length = this.#data.length;
1010
+ if (offset > length) throw domError("IndexSizeError", "the offset is past the end of the text");
1011
+ const rest = new Text(this.#data.slice(offset));
1012
+ const parent = this.parentNode;
1013
+ if (parent) {
1014
+ parent.insertBefore(rest, this.nextSibling);
1015
+ const index = indexIn(this);
1016
+ if (liveRanges.size) eachLiveRange((range) => range._split(this, rest, offset, parent, index));
1017
+ }
1018
+ this.replaceData(offset, length - offset, "");
1019
+ return rest;
1020
+ }
660
1021
  }
661
1022
 
662
- /** An editable text field. `value` follows what the user types. */
1023
+ Object.defineProperty(Text.prototype, "kind", { value: "text", writable: true, configurable: true });
1024
+
1025
+ /**
1026
+ * An editable text field. `value` follows what the user types. Selection offsets are UTF-16
1027
+ * string indices, as on the web; the tree counts UTF-8 bytes, converted here.
1028
+ */
663
1029
  export class Input extends Node {
664
1030
  #value = "";
1031
+ #start = 0;
1032
+ #end = 0;
1033
+ #direction = "forward";
665
1034
 
666
1035
  constructor() {
667
1036
  super("input");
668
- this.selectionStart = 0;
669
- this.selectionEnd = 0;
1037
+ this._keep("input", "selectionchange");
1038
+ }
1039
+
1040
+ /** The text the selection offsets index into. */
1041
+ _text() {
1042
+ return this.#value;
1043
+ }
1044
+
1045
+ _shallowClone() {
1046
+ const copy = new this.constructor();
1047
+ copy.value = this.#value;
1048
+ return copy;
670
1049
  }
671
1050
 
672
1051
  get value() {
@@ -674,27 +1053,135 @@ export class Input extends Node {
674
1053
  }
675
1054
 
676
1055
  set value(value) {
677
- this.#value = String(value);
678
- native.setText(this.nodeId, this.#value);
1056
+ value = String(value);
1057
+ if (value === this.#value) return;
1058
+ this.#value = value;
1059
+ native.setText(this.nodeId, value);
1060
+ this.#start = this.#end = value.length;
1061
+ this.#direction = "forward";
1062
+ }
1063
+
1064
+ get selectionStart() {
1065
+ return this.#start;
1066
+ }
1067
+
1068
+ set selectionStart(value) {
1069
+ const start = clampIndex(value, this._text().length);
1070
+ this.setSelectionRange(start, Math.max(start, this.#end), this.#direction);
1071
+ }
1072
+
1073
+ get selectionEnd() {
1074
+ return this.#end;
1075
+ }
1076
+
1077
+ set selectionEnd(value) {
1078
+ this.setSelectionRange(this.#start, clampIndex(value, this._text().length), this.#direction);
1079
+ }
1080
+
1081
+ get selectionDirection() {
1082
+ return this.#direction;
679
1083
  }
680
1084
 
681
- /** Selects from `anchor` to `focus`, as UTF-8 byte offsets in the value. */
682
- setSelectionRange(anchor, focus) {
1085
+ set selectionDirection(value) {
1086
+ this.setSelectionRange(this.#start, this.#end, value);
1087
+ }
1088
+
1089
+ /** Selects `start` to `end`; with `direction` "backward" the caret sits at `start`. */
1090
+ setSelectionRange(start, end, direction = "none") {
1091
+ const text = this._text();
1092
+ end = clampIndex(end, text.length);
1093
+ start = Math.min(clampIndex(start, text.length), end);
1094
+ const backward = direction === "backward";
1095
+ this.#start = start;
1096
+ this.#end = end;
1097
+ this.#direction = backward ? "backward" : "forward";
1098
+ const anchor = byteOf(text, backward ? end : start);
1099
+ const focus = byteOf(text, backward ? start : end);
683
1100
  native.select(this.nodeId, anchor, focus);
684
1101
  }
685
1102
 
1103
+ /** Selects the whole value. */
1104
+ select() {
1105
+ this.setSelectionRange(0, this._text().length);
1106
+ }
1107
+
1108
+ /**
1109
+ * Replaces `start` to `end` (the selection by default) with `replacement`. `selectionMode`
1110
+ * is "select", "start", "end" or "preserve", as on the web.
1111
+ */
1112
+ setRangeText(replacement, start, end, selectionMode = "preserve") {
1113
+ replacement = String(replacement);
1114
+ const text = this._text();
1115
+ if (start === undefined) {
1116
+ start = this.#start;
1117
+ end = this.#end;
1118
+ } else if (end === undefined) {
1119
+ throw new TypeError("setRangeText needs both start and end");
1120
+ } else if (Number(start) > Number(end)) {
1121
+ throw domError("IndexSizeError", "setRangeText: start is after end");
1122
+ }
1123
+ start = clampIndex(start, text.length);
1124
+ end = clampIndex(end, text.length);
1125
+ let selectionStart = this.#start;
1126
+ let selectionEnd = this.#end;
1127
+ const delta = replacement.length - (end - start);
1128
+ const newEnd = start + replacement.length;
1129
+ if (selectionMode === "select") {
1130
+ selectionStart = start;
1131
+ selectionEnd = newEnd;
1132
+ } else if (selectionMode === "start") {
1133
+ selectionStart = selectionEnd = start;
1134
+ } else if (selectionMode === "end") {
1135
+ selectionStart = selectionEnd = newEnd;
1136
+ } else {
1137
+ if (selectionStart > end) selectionStart += delta;
1138
+ else if (selectionStart > start) selectionStart = start;
1139
+ if (selectionEnd > end) selectionEnd += delta;
1140
+ else if (selectionEnd > start) selectionEnd = newEnd;
1141
+ }
1142
+ const direction = this.#direction;
1143
+ this._replace(start, end, replacement);
1144
+ this.setSelectionRange(selectionStart, selectionEnd, direction);
1145
+ }
1146
+
1147
+ _replace(start, end, replacement) {
1148
+ const text = this.#value;
1149
+ this.value = text.slice(0, start) + replacement + text.slice(end);
1150
+ }
1151
+
1152
+ // From the tree: the value and selection in UTF-8 bytes.
686
1153
  _changed(value, anchor, focus) {
687
1154
  this.#value = value;
688
- this.selectionStart = Math.min(anchor, focus);
689
- this.selectionEnd = Math.max(anchor, focus);
1155
+ this.#take(byteIndex(value, anchor), byteIndex(value, focus));
690
1156
  }
691
1157
 
692
1158
  _selected(start, end) {
693
- this.selectionStart = start;
694
- this.selectionEnd = end;
1159
+ const text = this._text();
1160
+ this.#take(byteIndex(text, start), byteIndex(text, end));
1161
+ }
1162
+
1163
+ // The tree reports the low and high offsets only, so a selection it changed reads forward
1164
+ // unless it is the one set here.
1165
+ #take(a, b) {
1166
+ const start = Math.min(a, b);
1167
+ const end = Math.max(a, b);
1168
+ if (start === this.#start && end === this.#end) return;
1169
+ this.#start = start;
1170
+ this.#end = end;
1171
+ this.#direction = "forward";
695
1172
  }
696
1173
  }
697
1174
 
1175
+ function clampIndex(value, length) {
1176
+ const number = Math.trunc(Number(value)) || 0;
1177
+ return Math.min(Math.max(number, 0), length);
1178
+ }
1179
+
1180
+ // A UTF-8 offset from the tree as a string index; NaN and missing read as 0.
1181
+ function byteIndex(text, byte) {
1182
+ return indexOf(text, Number(byte) || 0);
1183
+ }
1184
+
698
1185
  // Inline SVG markup as icon resources: identical markup shares one, freed when no `<svg>`
699
1186
  // shows it. The ids start high, clear of resources a host or a URL table numbers from 1.
700
1187
  const ICONS = new Map();
@@ -772,6 +1259,76 @@ export class Image extends Node {
772
1259
  if (this.#src) dropAddress(this.#src);
773
1260
  this.#src = "";
774
1261
  }
1262
+
1263
+ _shallowClone() {
1264
+ return new Image(this.#src);
1265
+ }
1266
+ }
1267
+
1268
+ /**
1269
+ * A canvas the application draws with WebGPU, as a `<canvas>`: `width` and `height` are the
1270
+ * size of what is drawn in pixels (300 by 150 at first) and `getContext("webgpu")` gives a
1271
+ * `GPUCanvasContext`. The node lays out as an image of that size does: its style can
1272
+ * stretch it, and `objectFit` says how the drawing fits. Drawing happens on a GPU device of
1273
+ * the application's own, so a canvas that is slow to draw does not slow the rest of the window.
1274
+ */
1275
+ export class Canvas extends Node {
1276
+ #width = 300;
1277
+ #height = 150;
1278
+ #context = null;
1279
+
1280
+ constructor() {
1281
+ super("canvas");
1282
+ }
1283
+
1284
+ get width() {
1285
+ return this.#width;
1286
+ }
1287
+
1288
+ set width(value) {
1289
+ value = Math.max(0, Number(value) | 0);
1290
+ if (value === this.#width) return;
1291
+ this.#width = value;
1292
+ this.#context?._resized();
1293
+ }
1294
+
1295
+ get height() {
1296
+ return this.#height;
1297
+ }
1298
+
1299
+ set height(value) {
1300
+ value = Math.max(0, Number(value) | 0);
1301
+ if (value === this.#height) return;
1302
+ this.#height = value;
1303
+ this.#context?._resized();
1304
+ }
1305
+
1306
+ /** The canvas's `GPUCanvasContext` for "webgpu"; null for any other kind of context. */
1307
+ getContext(kind) {
1308
+ if (kind !== "webgpu") return null;
1309
+ if (this.#context) return this.#context;
1310
+ const api = native.gpuLoad?.();
1311
+ return api ? (this.#context = api.context(this)) : null;
1312
+ }
1313
+
1314
+ setAttribute(name, value) {
1315
+ if (name === "width") this.width = value == null ? 300 : value;
1316
+ else if (name === "height") this.height = value == null ? 150 : value;
1317
+ else super.setAttribute(name, value);
1318
+ }
1319
+
1320
+ getAttribute(name) {
1321
+ if (name === "width") return String(this.#width);
1322
+ if (name === "height") return String(this.#height);
1323
+ return super.getAttribute(name);
1324
+ }
1325
+
1326
+ _shallowClone() {
1327
+ const copy = new Canvas();
1328
+ copy.width = this.#width;
1329
+ copy.height = this.#height;
1330
+ return copy;
1331
+ }
775
1332
  }
776
1333
 
777
1334
  const SVG_NAMESPACE = "http://www.w3.org/2000/svg";
@@ -829,6 +1386,38 @@ function svgChanged(node) {
829
1386
  changedSvgs.add(svg);
830
1387
  }
831
1388
 
1389
+ // A live svg: after its first drawing, an `<svg>` whose elements change sends each change to
1390
+ // the tree as it happens (`svgInsert`, `svgAttribute`, `svgRemove`), and the tree draws its
1391
+ // shapes as paths, so a frame of an animation costs what it changes. This needs content the
1392
+ // tree's live svg draws; anything else keeps the svg drawn as markup.
1393
+ const LIVE_TAGS = new Set([
1394
+ "g", "path", "rect", "circle", "ellipse", "line", "polyline", "polygon", "defs", "clipPath",
1395
+ "linearGradient", "radialGradient", "stop", "title", "desc", "metadata",
1396
+ ]);
1397
+ const QUIET_TAGS = new Set(["title", "desc", "metadata"]);
1398
+ const UNLIVE_ATTRIBUTES = new Set(["mask", "filter", "marker", "marker-start", "marker-mid", "marker-end"]);
1399
+ const UNLIVE_STYLE = /(^|;)\s*(mask|filter|marker)[\w-]*\s*:/;
1400
+
1401
+ function liveAttribute(name, text) {
1402
+ return !UNLIVE_ATTRIBUTES.has(name) && !(name === "style" && UNLIVE_STYLE.test(text));
1403
+ }
1404
+
1405
+ /** Whether the tree's live svg can draw `child` and what is in it. */
1406
+ function liveable(child, quiet = false) {
1407
+ if (!(child instanceof SvgElement)) return quiet;
1408
+ if (!LIVE_TAGS.has(child.localName)) return false;
1409
+ for (const [name, value] of child._attributes()) if (!liveAttribute(name, value)) return false;
1410
+ const inner = quiet || QUIET_TAGS.has(child.localName);
1411
+ for (const grandchild of child.childNodes) if (!liveable(grandchild, inner)) return false;
1412
+ return true;
1413
+ }
1414
+
1415
+ /** The live svg `node` is in, or null. */
1416
+ function liveOwner(node) {
1417
+ const svg = svgOwner(node);
1418
+ return svg?._live ? svg : null;
1419
+ }
1420
+
832
1421
  function svgStyle(value) {
833
1422
  if (typeof value !== "object" || value === null) return String(value);
834
1423
  let css = "";
@@ -847,15 +1436,20 @@ const svgChildren = {
847
1436
  if (before === child) return child;
848
1437
  for (let at = this; at; at = at.parentNode) if (at === child) throw new Error("a node cannot be inserted into itself or its own subtree");
849
1438
  const old = child.parentNode;
1439
+ const listening = shapeListeners(child);
850
1440
  if (old) {
1441
+ liveOwner(old)?._removed(child);
851
1442
  svgChanged(old);
852
1443
  old.childNodes.splice(old.childNodes.indexOf(child), 1);
1444
+ if (listening) svgOwner(old)?._listenShapes();
853
1445
  }
854
1446
  child.parentNode = this;
855
1447
  if (before) this.childNodes.splice(this.childNodes.indexOf(before), 0, child);
856
- else this.childNodes.push(child);
1448
+ else (this.childNodes === NO_CHILDREN ? (this.childNodes = []) : this.childNodes).push(child);
857
1449
  if (child instanceof Text) child._svgText = true;
1450
+ liveOwner(this)?._inserted(child, this, before);
858
1451
  svgChanged(this);
1452
+ if (listening) svgOwner(this)?._listenShapes();
859
1453
  return child;
860
1454
  },
861
1455
  appendChild(child) {
@@ -866,9 +1460,11 @@ const svgChildren = {
866
1460
  },
867
1461
  removeChild(child) {
868
1462
  if (child.parentNode !== this) throw new Error("the node to remove is not a child of this node");
1463
+ liveOwner(this)?._removed(child);
869
1464
  svgChanged(this);
870
1465
  this.childNodes.splice(this.childNodes.indexOf(child), 1);
871
1466
  child.parentNode = null;
1467
+ if (shapeListeners(child)) svgOwner(this)?._listenShapes();
872
1468
  return child;
873
1469
  },
874
1470
  get textContent() {
@@ -890,6 +1486,85 @@ const svgChildren = {
890
1486
  },
891
1487
  };
892
1488
 
1489
+ // `element` and what is inside it as `__ui.svgMeasure` reads them (ui-tree `live_svg.measure`):
1490
+ // records split by U+001E, each the parent's record number, the tag, then name/value pairs.
1491
+ function svgPacked(element) {
1492
+ const records = [];
1493
+ const visit = (at, parent) => {
1494
+ const number = records.length + 1;
1495
+ let record = parent + "\x1f" + at.localName;
1496
+ for (const [name, value] of at._attributes()) record += "\x1f" + name + "\x1f" + value;
1497
+ records.push(record);
1498
+ for (const child of at.childNodes) if (child instanceof SvgElement) visit(child, number);
1499
+ };
1500
+ visit(element, 0);
1501
+ return records.join("\x1e");
1502
+ }
1503
+
1504
+ function svgBox(element) {
1505
+ const [x, y, width, height] = native.svgMeasure(0, svgPacked(element), 0).split(" ").map(Number);
1506
+ const Rect = globalThis.DOMRect;
1507
+ return Rect ? new Rect(x, y, width, height) : { x, y, width, height };
1508
+ }
1509
+
1510
+ // Whether `element` or an element inside it has listeners.
1511
+ function shapeListeners(element) {
1512
+ if (!(element instanceof SvgElement)) return false;
1513
+ for (const list of element._listeners?.values() ?? []) if (list.length > 0) return true;
1514
+ return element.childNodes.some(shapeListeners);
1515
+ }
1516
+
1517
+ function quietAncestor(element) {
1518
+ for (let at = element; at && at instanceof SvgElement; at = at.parentNode) if (QUIET_TAGS.has(at.localName)) return true;
1519
+ return false;
1520
+ }
1521
+
1522
+ /** The declarations of `element`'s `style` attribute, read and written as properties. */
1523
+ function svgDeclarations(element) {
1524
+ const read = () => {
1525
+ const map = new Map();
1526
+ for (const part of (element.getAttribute("style") ?? "").split(";")) {
1527
+ const colon = part.indexOf(":");
1528
+ if (colon > 0) map.set(part.slice(0, colon).trim(), part.slice(colon + 1).trim());
1529
+ }
1530
+ return map;
1531
+ };
1532
+ const write = (map) => {
1533
+ let css = "";
1534
+ for (const [name, value] of map) css += name + ": " + value + ";";
1535
+ if (css) element.setAttribute("style", css);
1536
+ else element.removeAttribute("style");
1537
+ };
1538
+ const set = (name, value) => {
1539
+ const map = read();
1540
+ if (value === null || value === undefined || value === "") map.delete(name);
1541
+ else map.set(name, String(value));
1542
+ write(map);
1543
+ };
1544
+ const methods = {
1545
+ setProperty: (name, value) => set(String(name), value),
1546
+ removeProperty: (name) => {
1547
+ const old = read().get(String(name)) ?? "";
1548
+ set(String(name), null);
1549
+ return old;
1550
+ },
1551
+ getPropertyValue: (name) => read().get(String(name)) ?? "",
1552
+ };
1553
+ return new Proxy(methods, {
1554
+ get(target, key) {
1555
+ if (typeof key !== "string") return undefined;
1556
+ if (key in target) return target[key];
1557
+ if (key === "cssText") return element.getAttribute("style") ?? "";
1558
+ return read().get(cssName(key)) ?? "";
1559
+ },
1560
+ set(target, key, value) {
1561
+ if (key === "cssText") element.setAttribute("style", String(value));
1562
+ else if (typeof key === "string") set(cssName(key), value);
1563
+ return true;
1564
+ },
1565
+ });
1566
+ }
1567
+
893
1568
  /** Text in an `<svg>`: its `<text>` and `<title>` contents. */
894
1569
  export class SvgText {
895
1570
  #data;
@@ -908,6 +1583,8 @@ export class SvgText {
908
1583
  value = String(value);
909
1584
  if (value === this.#data) return;
910
1585
  this.#data = value;
1586
+ const live = liveOwner(this);
1587
+ if (live && !QUIET_TAGS.has(this.parentNode?.localName)) live._leave();
911
1588
  svgChanged(this);
912
1589
  }
913
1590
 
@@ -976,11 +1653,40 @@ export class SvgElement {
976
1653
  const text = name === "style" ? svgStyle(value) : String(value);
977
1654
  if (this.#attributes.get(name) === text) return;
978
1655
  this.#attributes.set(name, text);
979
- svgChanged(this);
1656
+ this._written(name, text);
980
1657
  }
981
1658
 
982
1659
  removeAttribute(name) {
983
- if (this.#attributes.delete(svgName(name))) svgChanged(this);
1660
+ name = svgName(name);
1661
+ if (this.#attributes.delete(name)) this._written(name, null);
1662
+ }
1663
+
1664
+ setAttributeNS(namespace, name, value) {
1665
+ this.setAttribute(name, value);
1666
+ }
1667
+
1668
+ getAttributeNS(namespace, name) {
1669
+ return this.getAttribute(name);
1670
+ }
1671
+
1672
+ removeAttributeNS(namespace, name) {
1673
+ this.removeAttribute(name);
1674
+ }
1675
+
1676
+ /** The element's `style` attribute as a declaration object: `style.display = "none"`. */
1677
+ get style() {
1678
+ return this._style ??= svgDeclarations(this);
1679
+ }
1680
+
1681
+ _attributes() {
1682
+ return this.#attributes;
1683
+ }
1684
+
1685
+ _written(name, text) {
1686
+ const live = liveOwner(this);
1687
+ if (!live) svgChanged(this);
1688
+ else if (text !== null && !liveAttribute(name, text)) live._leave();
1689
+ else native.svgAttribute(live.nodeId, this._n, name, text);
984
1690
  }
985
1691
 
986
1692
  get firstChild() {
@@ -1015,17 +1721,73 @@ export class SvgElement {
1015
1721
  this.remove();
1016
1722
  }
1017
1723
 
1018
- addEventListener(type) {
1019
- warnOnce("an element inside an <svg> hears no events: listen on the <svg> ('" + type + "')");
1724
+ /**
1725
+ * Hears pointer events on this element's shapes, as on the web: its `<svg>` turns live (see
1726
+ * `Svg`) and the tree tells which shape is under the pointer.
1727
+ */
1728
+ addEventListener(type, listener, options) {
1729
+ if (listener == null) return;
1730
+ const capture = options === true || !!options?.capture;
1731
+ this._listeners ??= new Map();
1732
+ let list = this._listeners.get(type);
1733
+ if (!list) this._listeners.set(type, (list = []));
1734
+ if (list.some((entry) => entry.listener === listener && entry.capture === capture)) return;
1735
+ list.push({ listener, capture, once: !!options?.once });
1736
+ svgOwner(this)?._listenShapes();
1020
1737
  }
1021
1738
 
1022
- removeEventListener() {}
1023
-
1024
- _markup() {
1025
- let markup = "<" + this.localName;
1026
- for (const [name, value] of this.#attributes) markup += " " + name + '="' + escaped(value, true) + '"';
1027
- if (this.childNodes.length === 0) return markup + "/>";
1028
- return markup + ">" + svgChildren._markupOf(this.childNodes) + "</" + this.localName + ">";
1739
+ removeEventListener(type, listener, options) {
1740
+ const list = this._listeners?.get(type);
1741
+ if (!list) return;
1742
+ const capture = options === true || !!options?.capture;
1743
+ const index = list.findIndex((entry) => entry.listener === listener && entry.capture === capture);
1744
+ if (index < 0) return;
1745
+ list.splice(index, 1);
1746
+ svgOwner(this)?._listenShapes();
1747
+ }
1748
+
1749
+ dispatchEvent(event) {
1750
+ if (typeof event?.type !== "string") throw new TypeError("dispatchEvent takes an Event");
1751
+ return dispatchEvent(adopt(event, this));
1752
+ }
1753
+
1754
+ /** The box of its geometry in its own user space: a shape's fill, a group's children. */
1755
+ getBBox() {
1756
+ return svgBox(this);
1757
+ }
1758
+
1759
+ /** The length of a shape's outline in user units. */
1760
+ getTotalLength() {
1761
+ return Number(native.svgMeasure(1, svgPacked(this), 0));
1762
+ }
1763
+
1764
+ /** The point `distance` along a shape's outline, clamped to its ends. */
1765
+ getPointAtLength(distance) {
1766
+ const [x, y] = native.svgMeasure(2, svgPacked(this), Number(distance) || 0).split(" ").map(Number);
1767
+ return { x, y };
1768
+ }
1769
+
1770
+ _run(event, capture) {
1771
+ const list = this._listeners?.get(event.type);
1772
+ if (!list) return;
1773
+ for (const entry of list.slice()) {
1774
+ if (event._immediate) return;
1775
+ if (entry.capture !== capture) continue;
1776
+ if (entry.once) this.removeEventListener(event.type, entry.listener, entry.capture);
1777
+ try {
1778
+ if (typeof entry.listener === "function") entry.listener.call(this, event);
1779
+ else entry.listener.handleEvent(event);
1780
+ } catch (error) {
1781
+ reportError(error);
1782
+ }
1783
+ }
1784
+ }
1785
+
1786
+ _markup() {
1787
+ let markup = "<" + this.localName;
1788
+ for (const [name, value] of this.#attributes) markup += " " + name + '="' + escaped(value, true) + '"';
1789
+ if (this.childNodes.length === 0) return markup + "/>";
1790
+ return markup + ">" + svgChildren._markupOf(this.childNodes) + "</" + this.localName + ">";
1029
1791
  }
1030
1792
  }
1031
1793
 
@@ -1049,6 +1811,10 @@ function treeAttribute(name) {
1049
1811
  export class Svg extends Node {
1050
1812
  #attributes = new Map();
1051
1813
  #markup = "";
1814
+ // Live: element numbers in use, and freed ones to use again.
1815
+ _live = false;
1816
+ _count = 0;
1817
+ _free = [];
1052
1818
 
1053
1819
  constructor() {
1054
1820
  // The tree's node for drawn SVG markup is an icon; to code it is an `svg`.
@@ -1060,6 +1826,10 @@ export class Svg extends Node {
1060
1826
  svgChanged(this);
1061
1827
  }
1062
1828
 
1829
+ _shallowClone() {
1830
+ return new Svg();
1831
+ }
1832
+
1063
1833
  getAttribute(name) {
1064
1834
  return treeAttribute(String(name)) ? super.getAttribute(name) : this.#attributes.get(svgName(name)) ?? null;
1065
1835
  }
@@ -1079,13 +1849,84 @@ export class Svg extends Node {
1079
1849
  const text = name === "style" ? svgStyle(value) : String(value);
1080
1850
  if (this.#attributes.get(name) === text) return;
1081
1851
  this.#attributes.set(name, text);
1082
- svgChanged(this);
1852
+ this._written(name, text);
1083
1853
  }
1084
1854
 
1085
1855
  removeAttribute(name) {
1086
1856
  name = String(name);
1087
1857
  if (treeAttribute(name)) super.removeAttribute(name);
1088
- else if (this.#attributes.delete(svgName(name))) svgChanged(this);
1858
+ else if (this.#attributes.delete(svgName(name))) this._written(svgName(name), null);
1859
+ }
1860
+
1861
+ setAttributeNS(namespace, name, value) {
1862
+ this.setAttribute(name, value);
1863
+ }
1864
+
1865
+ getAttributeNS(namespace, name) {
1866
+ return this.getAttribute(name);
1867
+ }
1868
+
1869
+ /** The box of what it draws, in its user space (inside `viewBox`). */
1870
+ getBBox() {
1871
+ return svgBox(this);
1872
+ }
1873
+
1874
+ _attributes() {
1875
+ return this.#attributes;
1876
+ }
1877
+
1878
+ _written(name, text) {
1879
+ if (!this._live) svgChanged(this);
1880
+ else if (text !== null && !liveAttribute(name, text)) this._leave();
1881
+ else native.svgAttribute(this.nodeId, 0, name, text);
1882
+ }
1883
+
1884
+ /** Sends the elements to the tree as a live svg, once its markup was drawn and changed. */
1885
+ _goLive() {
1886
+ this._forget();
1887
+ this._live = true;
1888
+ for (const [name, value] of this.#attributes) native.svgAttribute(this.nodeId, 0, name, value);
1889
+ for (const child of this.childNodes) this._inserted(child, this, null);
1890
+ }
1891
+
1892
+ /** Back to markup: content the live svg does not draw came in. */
1893
+ _leave() {
1894
+ if (!this._live) return;
1895
+ this._live = false;
1896
+ this._count = 0;
1897
+ this._free = [];
1898
+ native.svgRemove(this.nodeId, 0);
1899
+ svgChanged(this);
1900
+ }
1901
+
1902
+ _inserted(child, parent, before) {
1903
+ if (!(child instanceof SvgElement)) {
1904
+ if (!QUIET_TAGS.has(parent.localName) && !(parent !== this && svgOwner(parent) && quietAncestor(parent))) this._leave();
1905
+ return;
1906
+ }
1907
+ if (!liveable(child, quietAncestor(parent))) {
1908
+ this._leave();
1909
+ return;
1910
+ }
1911
+ this._send(child, parent === this ? 0 : parent._n, before instanceof SvgElement ? before._n : -1);
1912
+ }
1913
+
1914
+ _send(element, parent, before) {
1915
+ element._n = this._free.pop() ?? ++this._count;
1916
+ native.svgInsert(this.nodeId, element._n, element.localName, parent, before);
1917
+ for (const [name, value] of element._attributes()) native.svgAttribute(this.nodeId, element._n, name, value);
1918
+ for (const child of element.childNodes) if (child instanceof SvgElement) this._send(child, element._n, -1);
1919
+ }
1920
+
1921
+ _removed(child) {
1922
+ if (!(child instanceof SvgElement) || !child._n) return;
1923
+ native.svgRemove(this.nodeId, child._n);
1924
+ const free = (element) => {
1925
+ if (element._n) this._free.push(element._n);
1926
+ element._n = 0;
1927
+ for (const grandchild of element.childNodes) if (grandchild instanceof SvgElement) free(grandchild);
1928
+ };
1929
+ free(child);
1089
1930
  }
1090
1931
 
1091
1932
  /** The markup the tree draws, as `outerHTML` gives it. */
@@ -1101,9 +1942,17 @@ export class Svg extends Node {
1101
1942
  }
1102
1943
 
1103
1944
  _draw() {
1104
- if (!nodes.has(this.nodeId)) return;
1945
+ if (!nodes.has(this.nodeId) || this._live) return;
1946
+ if (this._extra && this.childNodes.every((child) => liveable(child))) {
1947
+ this._goLive();
1948
+ return;
1949
+ }
1105
1950
  const markup = this.outerHTML;
1106
1951
  if (markup === this.#markup) return;
1952
+ if (this.#markup && this.childNodes.every((child) => liveable(child))) {
1953
+ this._goLive();
1954
+ return;
1955
+ }
1107
1956
  this._forget();
1108
1957
  this.#markup = markup;
1109
1958
  native.source(this.nodeId, holdIcon(markup));
@@ -1113,6 +1962,117 @@ export class Svg extends Node {
1113
1962
  if (this.#markup) dropIcon(this.#markup);
1114
1963
  this.#markup = "";
1115
1964
  }
1965
+
1966
+ /**
1967
+ * Listens for what the listeners on its elements need. Elements are told apart only once
1968
+ * the svg is live, so listeners make it go live.
1969
+ */
1970
+ _listenShapes() {
1971
+ let types = new Set();
1972
+ const visit = (element) => {
1973
+ for (const [type, list] of element._listeners ?? []) if (list.length > 0) types.add(type);
1974
+ for (const child of element.childNodes) if (child instanceof SvgElement) visit(child);
1975
+ };
1976
+ for (const child of this.childNodes) if (child instanceof SvgElement) visit(child);
1977
+ let extra = 0;
1978
+ for (const type of types) {
1979
+ const kind = KIND_OF.get(type);
1980
+ if (kind === undefined) continue;
1981
+ extra = (extra | (1 << bitOf(kind))) >>> 0;
1982
+ if (HOVER_TYPES.has(type)) extra |= HOVER_FLAGS;
1983
+ }
1984
+ if (extra === (this._extra ?? 0)) return;
1985
+ this._extra = extra;
1986
+ this._relisten();
1987
+ if (extra && !this._live) svgChanged(this);
1988
+ }
1989
+
1990
+ /** The element numbered `n`, or null. */
1991
+ _numbered(n) {
1992
+ if (!n) return null;
1993
+ const find = (element) => {
1994
+ if (element._n === n) return element;
1995
+ for (const child of element.childNodes) {
1996
+ if (child instanceof SvgElement) {
1997
+ const found = find(child);
1998
+ if (found) return found;
1999
+ }
2000
+ }
2001
+ return null;
2002
+ };
2003
+ for (const child of this.childNodes) {
2004
+ if (child instanceof SvgElement) {
2005
+ const found = find(child);
2006
+ if (found) return found;
2007
+ }
2008
+ }
2009
+ return null;
2010
+ }
2011
+
2012
+ /**
2013
+ * Sends a pointer record that came to the svg to the element under the pointer, with the
2014
+ * over, out, enter and leave events the web sends as the pointer moves between elements.
2015
+ */
2016
+ _pointer(event) {
2017
+ const type = event.type;
2018
+ const leaving = type === "pointerout" || type === "pointerleave" || type === "pointercancel";
2019
+ const shape = leaving ? null : this._numbered(event._element);
2020
+ const old = this._hovered && this._hovered.parentNode && svgOwner(this._hovered) === this ? this._hovered : null;
2021
+ let replaced = false;
2022
+ if (shape !== old && type !== "pointerenter" && type !== "pointerleave") {
2023
+ this._hovered = shape;
2024
+ if (old) {
2025
+ dispatchEvent(pointerCopy("pointerout", old, event));
2026
+ for (let at = old; at instanceof SvgElement && !at.contains(shape); at = at.parentNode) {
2027
+ dispatchEvent(pointerCopy("pointerleave", at, event));
2028
+ }
2029
+ if (type === "pointerout") replaced = true;
2030
+ }
2031
+ if (shape) {
2032
+ dispatchEvent(pointerCopy("pointerover", shape, event));
2033
+ if (type === "pointerover") {
2034
+ replaced = true;
2035
+ this._entering = true;
2036
+ } else {
2037
+ enterChain(shape, old, event);
2038
+ }
2039
+ }
2040
+ }
2041
+ if (replaced) return false;
2042
+ if (type === "pointerenter") {
2043
+ dispatchEvent(event);
2044
+ if (this._entering && this._hovered) enterChain(this._hovered, null, event);
2045
+ this._entering = false;
2046
+ return event.defaultPrevented;
2047
+ }
2048
+ if (shape && type !== "pointerleave") event.target = shape;
2049
+ dispatchEvent(event);
2050
+ return event.defaultPrevented;
2051
+ }
2052
+ }
2053
+
2054
+ // Element listeners for these need the svg's moves, enters and leaves to tell hovering apart.
2055
+ const HOVER_TYPES = new Set(["pointerover", "pointerout", "pointerenter", "pointerleave"]);
2056
+ const HOVER_FLAGS = (1 << 3) | (1 << 4) | (1 << 5) | (1 << 28) | (1 << 29);
2057
+
2058
+ // A pointer event like `base` of type `type` at `target`.
2059
+ function pointerCopy(type, target, base) {
2060
+ const event = new Event(type, target);
2061
+ for (const key of Object.keys(base)) {
2062
+ if (!(key in event) || key === "clientX" || key === "clientY" || key === "x" || key === "y") event[key] = base[key];
2063
+ }
2064
+ event.type = type;
2065
+ event.target = target;
2066
+ event.bubbles = !NO_BUBBLE.has(type);
2067
+ event.cancelable = CANCELABLE.has(type);
2068
+ return event;
2069
+ }
2070
+
2071
+ // pointerenter at `shape` and its element ancestors not containing `from`, outermost first.
2072
+ function enterChain(shape, from, base) {
2073
+ const chain = [];
2074
+ for (let at = shape; at instanceof SvgElement && !(from && at.contains(from)); at = at.parentNode) chain.push(at);
2075
+ for (let i = chain.length - 1; i >= 0; i--) dispatchEvent(pointerCopy("pointerenter", chain[i], base));
1116
2076
  }
1117
2077
 
1118
2078
  for (const name of ["insertBefore", "appendChild", "append", "removeChild"]) Svg.prototype[name] = svgChildren[name];
@@ -1242,6 +2202,12 @@ export class RichInput extends Input {
1242
2202
  return this.#document;
1243
2203
  }
1244
2204
 
2205
+ _shallowClone() {
2206
+ const copy = new RichInput();
2207
+ copy.document = this.#document;
2208
+ return copy;
2209
+ }
2210
+
1245
2211
  /** Replaces the document. The caret goes to the end and the undo history is forgotten. */
1246
2212
  set document(document) {
1247
2213
  const text = String(document?.text ?? "");
@@ -1257,7 +2223,8 @@ export class RichInput extends Input {
1257
2223
  let packedAtoms = "";
1258
2224
  for (const atom of atoms) packedAtoms += this.#packAtom(atom);
1259
2225
  native.richText(this.nodeId, text, packedMarks, packedAtoms);
1260
- super._changed(text, text.length, text.length);
2226
+ const end = byteOf(text, text.length);
2227
+ super._changed(text, end, end);
1261
2228
  }
1262
2229
 
1263
2230
  #packAtom(atom) {
@@ -1280,13 +2247,32 @@ export class RichInput extends Input {
1280
2247
  native.insertAtom(this.nodeId, byteOf(text, start), byteOf(text, end), this.#packAtom(atom));
1281
2248
  }
1282
2249
 
1283
- setSelectionRange(anchor, focus) {
1284
- const text = this.#document.text;
1285
- native.select(this.nodeId, byteOf(text, anchor), byteOf(text, focus));
2250
+ // Marks around the range stay, shifted; the replacement takes none. Atoms in the range go,
2251
+ // and OBJECT characters in the replacement become U+FFFD, since they would name no atom.
2252
+ _replace(start, end, replacement) {
2253
+ const { text, marks, atoms } = this.#document;
2254
+ replacement = replacement.replaceAll(OBJECT, "\ufffd");
2255
+ const delta = replacement.length - (end - start);
2256
+ const shift = (index, inside) => (index <= start ? index : index >= end ? index + delta : inside);
2257
+ const spans = [];
2258
+ for (const span of marks) {
2259
+ const from = shift(span.start, start + replacement.length);
2260
+ const to = shift(span.end, start);
2261
+ if (to > from) spans.push({ start: from, end: to, marks: span.marks });
2262
+ }
2263
+ let before = 0;
2264
+ let inside = 0;
2265
+ for (let i = 0; i < end; i++) {
2266
+ if (text[i] !== OBJECT) continue;
2267
+ if (i < start) before++;
2268
+ else inside++;
2269
+ }
2270
+ const kept = atoms.slice(0, before).concat(atoms.slice(before + inside));
2271
+ this.document = { text: text.slice(0, start) + replacement + text.slice(end), marks: spans, atoms: kept };
1286
2272
  }
1287
2273
 
1288
2274
  _changed(value, anchor, focus, marks, atoms, active) {
1289
- super._changed(value, indexOf(value, anchor), indexOf(value, focus));
2275
+ super._changed(value, anchor, focus);
1290
2276
  if (marks === undefined) return;
1291
2277
  const spans = [];
1292
2278
  for (const part of String(marks).split(";")) {
@@ -1304,8 +2290,7 @@ export class RichInput extends Input {
1304
2290
  }
1305
2291
 
1306
2292
  _selected(start, end, active) {
1307
- const text = this.#document.text;
1308
- super._selected(indexOf(text, start), indexOf(text, end));
2293
+ super._selected(start, end);
1309
2294
  this.activeMarks = this.#names(active ?? 0);
1310
2295
  }
1311
2296
  }
@@ -1317,50 +2302,910 @@ export function createRichInput(style) {
1317
2302
  return input;
1318
2303
  }
1319
2304
 
1320
- function forget(node) {
1321
- nodes.delete(node.nodeId);
1322
- node._forget?.();
1323
- for (const child of node.childNodes) {
1324
- child.parentNode = null;
1325
- forget(child);
2305
+ function forget(node) {
2306
+ nodes.delete(node.nodeId);
2307
+ node._forget?.();
2308
+ for (const child of node.childNodes) {
2309
+ child.parentNode = null;
2310
+ forget(child);
2311
+ }
2312
+ node.childNodes = NO_CHILDREN;
2313
+ }
2314
+
2315
+ export function createNode(kind) {
2316
+ if (kind === "richinput") return new RichInput();
2317
+ if (kind === "svg") return new Svg();
2318
+ if (kind === "img") kind = "image";
2319
+ if (!(kind in KINDS) || kind === "icon") throw new TypeError("the tree has no node kind '" + kind + "'");
2320
+ if (kind === "text") return new Text();
2321
+ if (kind === "input") return new Input();
2322
+ if (kind === "image") return new Image();
2323
+ if (kind === "canvas") return new Canvas();
2324
+ return new Node(kind);
2325
+ }
2326
+
2327
+ /** A box with `style` as its base look and `children` appended. */
2328
+ export function createBox(style, ...children) {
2329
+ const box = new Node("box");
2330
+ if (style) box.style.set(style);
2331
+ box.append(...children);
2332
+ return box;
2333
+ }
2334
+
2335
+ export function createText(data = "") {
2336
+ return new Text(data);
2337
+ }
2338
+
2339
+ /** An image showing `src` (see `Image`), with `style` as its base look. */
2340
+ export function createImage(src, style) {
2341
+ const image = new Image(src);
2342
+ if (style) image.style.set(style);
2343
+ return image;
2344
+ }
2345
+
2346
+ export function createInput(style) {
2347
+ const input = new Input();
2348
+ if (style) input.style.set(style);
2349
+ return input;
2350
+ }
2351
+
2352
+ /**
2353
+ * Nodes held together outside the tree, as the DOM's `DocumentFragment`. Inserting it
2354
+ * inserts its children, in order, and leaves it empty.
2355
+ */
2356
+ export class DocumentFragment extends Node {
2357
+ constructor() {
2358
+ super("box");
2359
+ }
2360
+
2361
+ get nodeType() {
2362
+ return 11;
2363
+ }
2364
+
2365
+ _shallowClone() {
2366
+ return new DocumentFragment();
2367
+ }
2368
+ }
2369
+
2370
+ export function createDocumentFragment() {
2371
+ return new DocumentFragment();
2372
+ }
2373
+
2374
+ // Ranges, as the DOM Standard defines them, over the nodes of this module. Every change to
2375
+ // the tree passes through these nodes, so live ranges follow it here, with no native calls.
2376
+
2377
+ function nodeLength(node) {
2378
+ return node.nodeType === 3 ? node.length : node.childNodes.length;
2379
+ }
2380
+
2381
+ function indexIn(node) {
2382
+ return node.parentNode ? node.parentNode.childNodes.indexOf(node) : 0;
2383
+ }
2384
+
2385
+ function rootOf(node) {
2386
+ while (node.parentNode) node = node.parentNode;
2387
+ return node;
2388
+ }
2389
+
2390
+ function isInclusiveAncestor(ancestor, node) {
2391
+ for (; node; node = node.parentNode) if (node === ancestor) return true;
2392
+ return false;
2393
+ }
2394
+
2395
+ // -1 when `a` comes before `b` in tree order, 1 after, 0 the same node. One root.
2396
+ function treeOrder(a, b) {
2397
+ if (a === b) return 0;
2398
+ const up = [];
2399
+ for (let node = a; node; node = node.parentNode) up.push(node);
2400
+ const other = [];
2401
+ for (let node = b; node; node = node.parentNode) other.push(node);
2402
+ let i = up.length - 1;
2403
+ let j = other.length - 1;
2404
+ while (i >= 0 && j >= 0 && up[i] === other[j]) {
2405
+ i--;
2406
+ j--;
2407
+ }
2408
+ if (i < 0) return -1;
2409
+ if (j < 0) return 1;
2410
+ const siblings = up[i + 1].childNodes;
2411
+ return siblings.indexOf(up[i]) < siblings.indexOf(other[j]) ? -1 : 1;
2412
+ }
2413
+
2414
+ // The position of boundary point (a, aOffset) relative to (b, bOffset): -1 before, 0 equal,
2415
+ // 1 after. Both are in one tree.
2416
+ function comparePoints(a, aOffset, b, bOffset) {
2417
+ if (a === b) return aOffset === bOffset ? 0 : aOffset < bOffset ? -1 : 1;
2418
+ if (treeOrder(a, b) > 0) return -comparePoints(b, bOffset, a, aOffset);
2419
+ if (isInclusiveAncestor(a, b)) {
2420
+ let child = b;
2421
+ while (child.parentNode !== a) child = child.parentNode;
2422
+ if (indexIn(child) < aOffset) return 1;
2423
+ }
2424
+ return -1;
2425
+ }
2426
+
2427
+ // The next node in tree order inside `within`, or null.
2428
+ function following(node, within, skipChildren = false) {
2429
+ if (!skipChildren && node.childNodes.length) return node.childNodes[0];
2430
+ for (; node && node !== within; node = node.parentNode) {
2431
+ const next = node.nextSibling;
2432
+ if (next) return next;
2433
+ }
2434
+ return null;
2435
+ }
2436
+
2437
+ function checkNode(node, what) {
2438
+ if (!(node instanceof Node)) throw new TypeError(what + " is not a node");
2439
+ return node;
2440
+ }
2441
+
2442
+ /** The fields every range has: two boundary points. */
2443
+ export class AbstractRange {
2444
+ constructor() {
2445
+ if (new.target === AbstractRange) throw new TypeError("Illegal constructor");
2446
+ }
2447
+
2448
+ get startContainer() {
2449
+ return this._startNode;
2450
+ }
2451
+
2452
+ get startOffset() {
2453
+ return this._startOffset;
2454
+ }
2455
+
2456
+ get endContainer() {
2457
+ return this._endNode;
2458
+ }
2459
+
2460
+ get endOffset() {
2461
+ return this._endOffset;
2462
+ }
2463
+
2464
+ get collapsed() {
2465
+ return this._startNode === this._endNode && this._startOffset === this._endOffset;
2466
+ }
2467
+ }
2468
+
2469
+ /** A range that does not follow changes to the tree, and is not checked when made. */
2470
+ export class StaticRange extends AbstractRange {
2471
+ constructor(init) {
2472
+ super();
2473
+ if (init == null || typeof init !== "object") throw new TypeError("StaticRange needs its four members");
2474
+ for (const key of ["startContainer", "startOffset", "endContainer", "endOffset"]) {
2475
+ if (init[key] === undefined) throw new TypeError("StaticRange needs " + key);
2476
+ }
2477
+ this._startNode = checkNode(init.startContainer, "startContainer");
2478
+ this._startOffset = init.startOffset >>> 0;
2479
+ this._endNode = checkNode(init.endContainer, "endContainer");
2480
+ this._endOffset = init.endOffset >>> 0;
2481
+ }
2482
+ }
2483
+
2484
+ // The node a new range starts in: the mounted root, else a detached one of its own.
2485
+ let rangeHome = null;
2486
+
2487
+ /** A live range: it follows insertions, removals and text changes, as on the web. */
2488
+ export class Range extends AbstractRange {
2489
+ static START_TO_START = 0;
2490
+ static START_TO_END = 1;
2491
+ static END_TO_END = 2;
2492
+ static END_TO_START = 3;
2493
+
2494
+ constructor() {
2495
+ super();
2496
+ const home = rootNode ?? (rangeHome ??= new Node("box"));
2497
+ this._startNode = this._endNode = home;
2498
+ this._startOffset = this._endOffset = 0;
2499
+ liveRanges.add(new WeakRef(this));
2500
+ }
2501
+
2502
+ get commonAncestorContainer() {
2503
+ let container = this._startNode;
2504
+ while (!isInclusiveAncestor(container, this._endNode)) container = container.parentNode;
2505
+ return container;
2506
+ }
2507
+
2508
+ // Called after the boundary points change; a selection's range tells the tree.
2509
+ _changed() {}
2510
+
2511
+ #set(node, offset, start) {
2512
+ checkNode(node, "the container");
2513
+ offset = offset >>> 0;
2514
+ if (offset > nodeLength(node)) throw domError("IndexSizeError", "the offset is past the end of the node");
2515
+ if (start) {
2516
+ if (rootOf(node) !== rootOf(this._startNode) || comparePoints(node, offset, this._endNode, this._endOffset) > 0) {
2517
+ this._endNode = node;
2518
+ this._endOffset = offset;
2519
+ }
2520
+ this._startNode = node;
2521
+ this._startOffset = offset;
2522
+ } else {
2523
+ if (rootOf(node) !== rootOf(this._startNode) || comparePoints(node, offset, this._startNode, this._startOffset) < 0) {
2524
+ this._startNode = node;
2525
+ this._startOffset = offset;
2526
+ }
2527
+ this._endNode = node;
2528
+ this._endOffset = offset;
2529
+ }
2530
+ this._changed();
2531
+ }
2532
+
2533
+ setStart(node, offset) {
2534
+ this.#set(node, offset, true);
2535
+ }
2536
+
2537
+ setEnd(node, offset) {
2538
+ this.#set(node, offset, false);
2539
+ }
2540
+
2541
+ /** One rectangle per line piece of the range, from the tree's last layout (laid out first if something changed). */
2542
+ getClientRects() {
2543
+ return rangeClientRects(this._startNode, this._startOffset, this._endNode, this._endOffset);
2544
+ }
2545
+
2546
+ getBoundingClientRect() {
2547
+ return rangeBoundingClientRect(this._startNode, this._startOffset, this._endNode, this._endOffset);
2548
+ }
2549
+
2550
+ setStartBefore(node) {
2551
+ this.#set(parentOf(node), indexIn(node), true);
2552
+ }
2553
+
2554
+ setStartAfter(node) {
2555
+ this.#set(parentOf(node), indexIn(node) + 1, true);
2556
+ }
2557
+
2558
+ setEndBefore(node) {
2559
+ this.#set(parentOf(node), indexIn(node), false);
2560
+ }
2561
+
2562
+ setEndAfter(node) {
2563
+ this.#set(parentOf(node), indexIn(node) + 1, false);
2564
+ }
2565
+
2566
+ collapse(toStart = false) {
2567
+ if (toStart) {
2568
+ this._endNode = this._startNode;
2569
+ this._endOffset = this._startOffset;
2570
+ } else {
2571
+ this._startNode = this._endNode;
2572
+ this._startOffset = this._endOffset;
2573
+ }
2574
+ this._changed();
2575
+ }
2576
+
2577
+ selectNode(node) {
2578
+ const parent = parentOf(node);
2579
+ const index = indexIn(node);
2580
+ this.#select(parent, index, parent, index + 1);
2581
+ }
2582
+
2583
+ selectNodeContents(node) {
2584
+ checkNode(node, "the node");
2585
+ this.#select(node, 0, node, nodeLength(node));
2586
+ }
2587
+
2588
+ #select(startNode, startOffset, endNode, endOffset) {
2589
+ this._startNode = startNode;
2590
+ this._startOffset = startOffset;
2591
+ this._endNode = endNode;
2592
+ this._endOffset = endOffset;
2593
+ this._changed();
2594
+ }
2595
+
2596
+ compareBoundaryPoints(how, sourceRange) {
2597
+ how = Number(how) & 0xffff;
2598
+ if (how > 3) throw domError("NotSupportedError", "compareBoundaryPoints takes 0 to 3");
2599
+ if (!(sourceRange instanceof Range)) throw new TypeError("compareBoundaryPoints takes a Range");
2600
+ if (rootOf(this._startNode) !== rootOf(sourceRange._startNode)) throw domError("WrongDocumentError", "the ranges are in different trees");
2601
+ const thisStart = how === 0 || how === 3;
2602
+ const otherStart = how === 0 || how === 1;
2603
+ return comparePoints(
2604
+ thisStart ? this._startNode : this._endNode,
2605
+ thisStart ? this._startOffset : this._endOffset,
2606
+ otherStart ? sourceRange._startNode : sourceRange._endNode,
2607
+ otherStart ? sourceRange._startOffset : sourceRange._endOffset,
2608
+ );
2609
+ }
2610
+
2611
+ #checkPoint(node, offset) {
2612
+ if (offset > nodeLength(node)) throw domError("IndexSizeError", "the offset is past the end of the node");
2613
+ }
2614
+
2615
+ comparePoint(node, offset) {
2616
+ checkNode(node, "the node");
2617
+ offset = offset >>> 0;
2618
+ if (rootOf(node) !== rootOf(this._startNode)) throw domError("WrongDocumentError", "the node is in a different tree");
2619
+ this.#checkPoint(node, offset);
2620
+ if (comparePoints(node, offset, this._startNode, this._startOffset) < 0) return -1;
2621
+ if (comparePoints(node, offset, this._endNode, this._endOffset) > 0) return 1;
2622
+ return 0;
2623
+ }
2624
+
2625
+ isPointInRange(node, offset) {
2626
+ checkNode(node, "the node");
2627
+ offset = offset >>> 0;
2628
+ if (rootOf(node) !== rootOf(this._startNode)) return false;
2629
+ this.#checkPoint(node, offset);
2630
+ return comparePoints(node, offset, this._startNode, this._startOffset) >= 0
2631
+ && comparePoints(node, offset, this._endNode, this._endOffset) <= 0;
2632
+ }
2633
+
2634
+ intersectsNode(node) {
2635
+ checkNode(node, "the node");
2636
+ if (rootOf(node) !== rootOf(this._startNode)) return false;
2637
+ const parent = node.parentNode;
2638
+ if (!parent) return true;
2639
+ const offset = indexIn(node);
2640
+ return comparePoints(parent, offset, this._endNode, this._endOffset) < 0
2641
+ && comparePoints(parent, offset + 1, this._startNode, this._startOffset) > 0;
2642
+ }
2643
+
2644
+ cloneRange() {
2645
+ const copy = new Range();
2646
+ copy.#select(this._startNode, this._startOffset, this._endNode, this._endOffset);
2647
+ return copy;
2648
+ }
2649
+
2650
+ detach() {}
2651
+
2652
+ #contains(node) {
2653
+ return rootOf(node) === rootOf(this._startNode)
2654
+ && comparePoints(node, 0, this._startNode, this._startOffset) > 0
2655
+ && comparePoints(node, nodeLength(node), this._endNode, this._endOffset) < 0;
2656
+ }
2657
+
2658
+ #partlyContains(node) {
2659
+ return isInclusiveAncestor(node, this._startNode) !== isInclusiveAncestor(node, this._endNode);
2660
+ }
2661
+
2662
+ toString() {
2663
+ const start = this._startNode;
2664
+ const end = this._endNode;
2665
+ if (start === end && start.nodeType === 3) return start.data.slice(this._startOffset, this._endOffset);
2666
+ let text = start.nodeType === 3 ? start.data.slice(this._startOffset) : "";
2667
+ const within = this.commonAncestorContainer;
2668
+ for (let node = following(within, within); node; node = following(node, within)) {
2669
+ if (node.nodeType === 3 && this.#contains(node)) text += node.data;
2670
+ }
2671
+ if (end.nodeType === 3) text += end.data.slice(0, this._endOffset);
2672
+ return text;
2673
+ }
2674
+
2675
+ // The parts of the contents algorithms the three of them share.
2676
+ #split() {
2677
+ const startNode = this._startNode;
2678
+ const endNode = this._endNode;
2679
+ const common = this.commonAncestorContainer;
2680
+ const children = common.childNodes;
2681
+ const first = isInclusiveAncestor(startNode, endNode) ? null : children.find((child) => this.#partlyContains(child)) ?? null;
2682
+ let last = null;
2683
+ if (!isInclusiveAncestor(endNode, startNode)) {
2684
+ for (let i = children.length - 1; i >= 0; i--) {
2685
+ if (this.#partlyContains(children[i])) {
2686
+ last = children[i];
2687
+ break;
2688
+ }
2689
+ }
2690
+ }
2691
+ return { common, first, last, contained: children.filter((child) => this.#contains(child)) };
2692
+ }
2693
+
2694
+ // Where the range collapses after its contents leave.
2695
+ #after() {
2696
+ if (isInclusiveAncestor(this._startNode, this._endNode)) return [this._startNode, this._startOffset];
2697
+ let reference = this._startNode;
2698
+ while (reference.parentNode && !isInclusiveAncestor(reference.parentNode, this._endNode)) reference = reference.parentNode;
2699
+ return [reference.parentNode, indexIn(reference) + 1];
2700
+ }
2701
+
2702
+ deleteContents() {
2703
+ if (this.collapsed) return;
2704
+ const startNode = this._startNode;
2705
+ const startOffset = this._startOffset;
2706
+ const endNode = this._endNode;
2707
+ const endOffset = this._endOffset;
2708
+ if (startNode === endNode && startNode.nodeType === 3) {
2709
+ startNode.replaceData(startOffset, endOffset - startOffset, "");
2710
+ return;
2711
+ }
2712
+ const remove = [];
2713
+ const within = this.commonAncestorContainer;
2714
+ for (let node = following(within, within); node; ) {
2715
+ if (this.#contains(node)) {
2716
+ remove.push(node);
2717
+ node = following(node, within, true);
2718
+ } else {
2719
+ node = following(node, within);
2720
+ }
2721
+ }
2722
+ const [node, offset] = this.#after();
2723
+ if (startNode.nodeType === 3) startNode.replaceData(startOffset, startNode.length - startOffset, "");
2724
+ for (const child of remove) child.remove();
2725
+ if (endNode.nodeType === 3) endNode.replaceData(0, endOffset, "");
2726
+ this.#select(node, offset, node, offset);
2727
+ }
2728
+
2729
+ #contents(extract) {
2730
+ const fragment = new DocumentFragment();
2731
+ if (this.collapsed) return fragment;
2732
+ const startNode = this._startNode;
2733
+ const startOffset = this._startOffset;
2734
+ const endNode = this._endNode;
2735
+ const endOffset = this._endOffset;
2736
+ if (startNode === endNode && startNode.nodeType === 3) {
2737
+ const clone = startNode.cloneNode();
2738
+ clone.data = startNode.substringData(startOffset, endOffset - startOffset);
2739
+ fragment.appendChild(clone);
2740
+ if (extract) startNode.replaceData(startOffset, endOffset - startOffset, "");
2741
+ return fragment;
2742
+ }
2743
+ const { first, last, contained } = this.#split();
2744
+ const after = extract ? this.#after() : null;
2745
+ if (first?.nodeType === 3) {
2746
+ const clone = startNode.cloneNode();
2747
+ clone.data = startNode.substringData(startOffset, startNode.length - startOffset);
2748
+ fragment.appendChild(clone);
2749
+ if (extract) startNode.replaceData(startOffset, startNode.length - startOffset, "");
2750
+ } else if (first) {
2751
+ const clone = first.cloneNode();
2752
+ fragment.appendChild(clone);
2753
+ const inner = new Range();
2754
+ inner.#select(startNode, startOffset, first, nodeLength(first));
2755
+ clone.appendChild(inner.#contents(extract));
2756
+ }
2757
+ for (const child of contained) fragment.appendChild(extract ? child : child.cloneNode(true));
2758
+ if (last?.nodeType === 3) {
2759
+ const clone = endNode.cloneNode();
2760
+ clone.data = endNode.substringData(0, endOffset);
2761
+ fragment.appendChild(clone);
2762
+ if (extract) endNode.replaceData(0, endOffset, "");
2763
+ } else if (last) {
2764
+ const clone = last.cloneNode();
2765
+ fragment.appendChild(clone);
2766
+ const inner = new Range();
2767
+ inner.#select(last, 0, endNode, endOffset);
2768
+ clone.appendChild(inner.#contents(extract));
2769
+ }
2770
+ if (extract) this.#select(after[0], after[1], after[0], after[1]);
2771
+ return fragment;
2772
+ }
2773
+
2774
+ /** Moves the contents into a new fragment and collapses the range where they were. */
2775
+ extractContents() {
2776
+ return this.#contents(true);
2777
+ }
2778
+
2779
+ /** Copies the contents into a new fragment. */
2780
+ cloneContents() {
2781
+ return this.#contents(false);
2782
+ }
2783
+
2784
+ /** Inserts `node` at the start of the range. */
2785
+ insertNode(node) {
2786
+ checkNode(node, "the node");
2787
+ const start = this._startNode;
2788
+ if ((start.nodeType === 3 && !start.parentNode) || start === node) {
2789
+ throw domError("HierarchyRequestError", "cannot insert the node there");
2790
+ }
2791
+ let reference = start.nodeType === 3 ? start : start.childNodes[this._startOffset] ?? null;
2792
+ const parent = reference ? reference.parentNode : start;
2793
+ if (isInclusiveAncestor(node, parent)) throw domError("HierarchyRequestError", "a node cannot be inserted into itself");
2794
+ if (parent.nodeType === 3) throw domError("HierarchyRequestError", "text has no children");
2795
+ if (start.nodeType === 3) reference = start.splitText(this._startOffset);
2796
+ if (node === reference) reference = node.nextSibling;
2797
+ if (node.parentNode) node.remove();
2798
+ let offset = reference ? indexIn(reference) : nodeLength(parent);
2799
+ offset += node.nodeType === 11 ? node.childNodes.length : 1;
2800
+ parent.insertBefore(node, reference);
2801
+ if (this.collapsed) this.#set(parent, offset, false);
2802
+ }
2803
+
2804
+ /** Wraps the contents in `newParent`. */
2805
+ surroundContents(newParent) {
2806
+ checkNode(newParent, "the new parent");
2807
+ const within = this.commonAncestorContainer;
2808
+ for (let node = within; node; node = following(node, within)) {
2809
+ if (node.nodeType !== 3 && this.#partlyContains(node)) {
2810
+ throw domError("InvalidStateError", "the range splits an element");
2811
+ }
2812
+ }
2813
+ if (newParent.nodeType === 11) throw domError("InvalidNodeTypeError", "a fragment cannot surround the range");
2814
+ const fragment = this.extractContents();
2815
+ while (newParent.firstChild) newParent.removeChild(newParent.firstChild);
2816
+ this.insertNode(newParent);
2817
+ newParent.appendChild(fragment);
2818
+ this.selectNode(newParent);
2819
+ }
2820
+
2821
+ // The DOM Standard's live range steps, run by the nodes as they change.
2822
+
2823
+ _inserted(parent, index) {
2824
+ const a = this._startNode, b = this._startOffset, c = this._endNode, d = this._endOffset;
2825
+ if (this._startNode === parent && this._startOffset > index) this._startOffset++;
2826
+ if (this._endNode === parent && this._endOffset > index) this._endOffset++;
2827
+ if (a !== this._startNode || b !== this._startOffset || c !== this._endNode || d !== this._endOffset) this._changed();
2828
+ }
2829
+
2830
+ _removing(child, parent, index) {
2831
+ const a = this._startNode, b = this._startOffset, c = this._endNode, d = this._endOffset;
2832
+ if (isInclusiveAncestor(child, this._startNode)) {
2833
+ this._startNode = parent;
2834
+ this._startOffset = index;
2835
+ }
2836
+ if (isInclusiveAncestor(child, this._endNode)) {
2837
+ this._endNode = parent;
2838
+ this._endOffset = index;
2839
+ }
2840
+ if (this._startNode === parent && this._startOffset > index) this._startOffset--;
2841
+ if (this._endNode === parent && this._endOffset > index) this._endOffset--;
2842
+ if (a !== this._startNode || b !== this._startOffset || c !== this._endNode || d !== this._endOffset) this._changed();
2843
+ }
2844
+
2845
+ _replaced(node, offset, count, added) {
2846
+ const a = this._startNode, b = this._startOffset, c = this._endNode, d = this._endOffset;
2847
+ if (this._startNode === node) {
2848
+ if (this._startOffset > offset + count) this._startOffset += added - count;
2849
+ else if (this._startOffset > offset) this._startOffset = offset;
2850
+ }
2851
+ if (this._endNode === node) {
2852
+ if (this._endOffset > offset + count) this._endOffset += added - count;
2853
+ else if (this._endOffset > offset) this._endOffset = offset;
2854
+ }
2855
+ if (a !== this._startNode || b !== this._startOffset || c !== this._endNode || d !== this._endOffset) this._changed();
2856
+ }
2857
+
2858
+ _split(node, rest, offset, parent, index) {
2859
+ const a = this._startNode, b = this._startOffset, c = this._endNode, d = this._endOffset;
2860
+ if (this._startNode === node && this._startOffset > offset) {
2861
+ this._startNode = rest;
2862
+ this._startOffset -= offset;
2863
+ }
2864
+ if (this._endNode === node && this._endOffset > offset) {
2865
+ this._endNode = rest;
2866
+ this._endOffset -= offset;
2867
+ }
2868
+ if (this._startNode === parent && this._startOffset === index + 1) this._startOffset++;
2869
+ if (this._endNode === parent && this._endOffset === index + 1) this._endOffset++;
2870
+ if (a !== this._startNode || b !== this._startOffset || c !== this._endNode || d !== this._endOffset) this._changed();
2871
+ }
2872
+
2873
+ _joined(current, node, length, index) {
2874
+ const a = this._startNode, b = this._startOffset, c = this._endNode, d = this._endOffset;
2875
+ if (this._startNode === current) {
2876
+ this._startNode = node;
2877
+ this._startOffset += length;
2878
+ }
2879
+ if (this._endNode === current) {
2880
+ this._endNode = node;
2881
+ this._endOffset += length;
2882
+ }
2883
+ if (this._startNode === current.parentNode && this._startOffset === index) {
2884
+ this._startNode = node;
2885
+ this._startOffset = length;
2886
+ }
2887
+ if (this._endNode === current.parentNode && this._endOffset === index) {
2888
+ this._endNode = node;
2889
+ this._endOffset = length;
2890
+ }
2891
+ if (a !== this._startNode || b !== this._startOffset || c !== this._endNode || d !== this._endOffset) this._changed();
2892
+ }
2893
+ }
2894
+
2895
+ for (const [name, value] of [["START_TO_START", 0], ["START_TO_END", 1], ["END_TO_END", 2], ["END_TO_START", 3]]) {
2896
+ Object.defineProperty(Range.prototype, name, { value, enumerable: true });
2897
+ }
2898
+
2899
+ function parentOf(node) {
2900
+ checkNode(node, "the node");
2901
+ if (!node.parentNode) throw domError("InvalidNodeTypeError", "the node has no parent");
2902
+ return node.parentNode;
2903
+ }
2904
+
2905
+ /** A new live range, collapsed at the start of the root. */
2906
+ export function createRange() {
2907
+ return new Range();
2908
+ }
2909
+
2910
+ // The document's selection. The tree keeps it (presses, drags, keys, select all) and paints
2911
+ // it; the one `Selection` reads it from there and tells the tree what scripts change. Its
2912
+ // ranges are live Ranges in tree order, one per stretch: a selection across children that
2913
+ // layout reorders (flex order, placed grid cells, positioned boxes) has one per piece seen.
2914
+ const SELECTION = Symbol("selection");
2915
+ let theSelection = null;
2916
+
2917
+ function checkOffset(node, offset) {
2918
+ offset = offset >>> 0;
2919
+ if (offset > nodeLength(node)) throw domError("IndexSizeError", "the offset is past the end of the node");
2920
+ return offset;
2921
+ }
2922
+
2923
+ function inDocument(node) {
2924
+ return rootNode !== null && rootOf(node) === rootNode;
2925
+ }
2926
+
2927
+ /** The document's selection, as `getSelection()` answers it. */
2928
+ export class Selection {
2929
+ #anchor = null;
2930
+ #anchorOffset = 0;
2931
+ #focus = null;
2932
+ #focusOffset = 0;
2933
+ #ranges = [];
2934
+ #backward = false;
2935
+ // Changed by a script and not yet told to the tree.
2936
+ #pending = false;
2937
+
2938
+ constructor(token) {
2939
+ if (token !== SELECTION) throw new TypeError("Illegal constructor");
2940
+ }
2941
+
2942
+ // Reads what the tree has, after telling it what a script changed.
2943
+ #sync() {
2944
+ if (this.#pending) this.#flush();
2945
+ const count = native.selection?.() ?? 0;
2946
+ const anchor = count ? nodes.get(geometry(0)) : null;
2947
+ const focus = count ? nodes.get(geometry(2)) : null;
2948
+ if (!anchor || !focus) {
2949
+ if (this.#anchor) this.#forget();
2950
+ return;
2951
+ }
2952
+ const stretches = [];
2953
+ for (let i = 0; i < count; i++) {
2954
+ const at = 4 + 4 * i;
2955
+ const start = nodes.get(geometry(at));
2956
+ const end = nodes.get(geometry(at + 2));
2957
+ if (start && end) stretches.push([start, geometry(at + 1), end, geometry(at + 3)]);
2958
+ }
2959
+ const same = anchor === this.#anchor && geometry(1) === this.#anchorOffset && focus === this.#focus
2960
+ && geometry(3) === this.#focusOffset && stretches.length === this.#ranges.length
2961
+ && stretches.every(([a, b, c, d], i) => {
2962
+ const range = this.#ranges[i];
2963
+ return range._startNode === a && range._startOffset === b && range._endNode === c && range._endOffset === d;
2964
+ });
2965
+ if (same) return;
2966
+ this.#unhook();
2967
+ this.#anchor = anchor;
2968
+ this.#anchorOffset = geometry(1);
2969
+ this.#focus = focus;
2970
+ this.#focusOffset = geometry(3);
2971
+ this.#backward = comparePoints(anchor, this.#anchorOffset, focus, this.#focusOffset) > 0;
2972
+ this.#ranges = stretches.map(([a, b, c, d]) => {
2973
+ const range = new Range();
2974
+ range._startNode = a;
2975
+ range._startOffset = b;
2976
+ range._endNode = c;
2977
+ range._endOffset = d;
2978
+ return this.#hook(range);
2979
+ });
2980
+ }
2981
+
2982
+ #flush() {
2983
+ this.#pending = false;
2984
+ if (!this.#anchor) native.setSelection?.(0, 0, 0, 0);
2985
+ else native.setSelection?.(this.#anchor.nodeId, this.#anchorOffset, this.#focus.nodeId, this.#focusOffset);
2986
+ }
2987
+
2988
+ #schedule() {
2989
+ if (this.#pending) return;
2990
+ this.#pending = true;
2991
+ queueMicrotask(() => {
2992
+ if (this.#pending) this.#flush();
2993
+ });
2994
+ }
2995
+
2996
+ #hook(range) {
2997
+ range._changed = () => this.#moved(range);
2998
+ return range;
2999
+ }
3000
+
3001
+ #unhook() {
3002
+ for (const range of this.#ranges) delete range._changed;
3003
+ }
3004
+
3005
+ #forget() {
3006
+ this.#unhook();
3007
+ this.#anchor = this.#focus = null;
3008
+ this.#anchorOffset = this.#focusOffset = 0;
3009
+ this.#ranges = [];
3010
+ this.#backward = false;
3011
+ }
3012
+
3013
+ // A script or a mutation moved one of the ranges: the selection becomes that range.
3014
+ #moved(range) {
3015
+ const backward = this.#backward;
3016
+ this.#unhook();
3017
+ this.#ranges = [this.#hook(range)];
3018
+ this.#anchor = backward ? range._endNode : range._startNode;
3019
+ this.#anchorOffset = backward ? range._endOffset : range._startOffset;
3020
+ this.#focus = backward ? range._startNode : range._endNode;
3021
+ this.#focusOffset = backward ? range._startOffset : range._endOffset;
3022
+ this.#schedule();
3023
+ }
3024
+
3025
+ #set(anchor, anchorOffset, focus, focusOffset) {
3026
+ const range = new Range();
3027
+ const forward = comparePoints(anchor, anchorOffset, focus, focusOffset) <= 0;
3028
+ range._startNode = forward ? anchor : focus;
3029
+ range._startOffset = forward ? anchorOffset : focusOffset;
3030
+ range._endNode = forward ? focus : anchor;
3031
+ range._endOffset = forward ? focusOffset : anchorOffset;
3032
+ this.#unhook();
3033
+ this.#ranges = [this.#hook(range)];
3034
+ this.#anchor = anchor;
3035
+ this.#anchorOffset = anchorOffset;
3036
+ this.#focus = focus;
3037
+ this.#focusOffset = focusOffset;
3038
+ this.#backward = !forward;
3039
+ this.#schedule();
3040
+ }
3041
+
3042
+ get anchorNode() { this.#sync(); return this.#anchor; }
3043
+ get anchorOffset() { this.#sync(); return this.#anchorOffset; }
3044
+ get focusNode() { this.#sync(); return this.#focus; }
3045
+ get focusOffset() { this.#sync(); return this.#focusOffset; }
3046
+
3047
+ get isCollapsed() {
3048
+ this.#sync();
3049
+ return this.#anchor === this.#focus && this.#anchorOffset === this.#focusOffset;
3050
+ }
3051
+
3052
+ get rangeCount() { this.#sync(); return this.#ranges.length; }
3053
+
3054
+ /** "None", "Caret" (collapsed) or "Range". */
3055
+ get type() {
3056
+ this.#sync();
3057
+ return !this.#anchor ? "None" : this.isCollapsed ? "Caret" : "Range";
3058
+ }
3059
+
3060
+ /** "forward" when the focus comes after the anchor, "backward" before it, "none" when collapsed. */
3061
+ get direction() {
3062
+ this.#sync();
3063
+ if (!this.#anchor || this.isCollapsed) return "none";
3064
+ return this.#backward ? "backward" : "forward";
3065
+ }
3066
+
3067
+ getRangeAt(index) {
3068
+ this.#sync();
3069
+ index = index >>> 0;
3070
+ if (index >= this.#ranges.length) throw domError("IndexSizeError", "the selection has no range " + index);
3071
+ return this.#ranges[index];
3072
+ }
3073
+
3074
+ /** Selects `range`, which then is the selection's own: changing it changes the selection. Does nothing while something is selected. */
3075
+ addRange(range) {
3076
+ if (!(range instanceof Range)) throw new TypeError("addRange takes a Range");
3077
+ this.#sync();
3078
+ if (this.#ranges.length || !inDocument(range._startNode)) return;
3079
+ this.#unhook();
3080
+ this.#ranges = [this.#hook(range)];
3081
+ this.#anchor = range._startNode;
3082
+ this.#anchorOffset = range._startOffset;
3083
+ this.#focus = range._endNode;
3084
+ this.#focusOffset = range._endOffset;
3085
+ this.#backward = false;
3086
+ this.#schedule();
3087
+ }
3088
+
3089
+ removeRange(range) {
3090
+ this.#sync();
3091
+ if (!this.#ranges.includes(range)) throw domError("NotFoundError", "the range is not in the selection");
3092
+ this.removeAllRanges();
3093
+ }
3094
+
3095
+ removeAllRanges() {
3096
+ if (!this.#anchor && !this.#pending && !this.#ranges.length) {
3097
+ this.#sync();
3098
+ if (!this.#anchor) return;
3099
+ }
3100
+ this.#forget();
3101
+ this.#schedule();
3102
+ }
3103
+
3104
+ empty() { this.removeAllRanges(); }
3105
+
3106
+ /** Puts a caret at (`node`, `offset`); `null` removes the selection. */
3107
+ collapse(node, offset = 0) {
3108
+ if (node === null) return this.removeAllRanges();
3109
+ checkNode(node, "the node");
3110
+ offset = checkOffset(node, offset);
3111
+ if (inDocument(node)) this.#set(node, offset, node, offset);
3112
+ }
3113
+
3114
+ setPosition(node, offset = 0) { return this.collapse(node, offset); }
3115
+
3116
+ collapseToStart() {
3117
+ this.#sync();
3118
+ if (!this.#ranges.length) throw domError("InvalidStateError", "nothing is selected");
3119
+ const first = this.#ranges[0];
3120
+ this.#set(first._startNode, first._startOffset, first._startNode, first._startOffset);
3121
+ }
3122
+
3123
+ collapseToEnd() {
3124
+ this.#sync();
3125
+ if (!this.#ranges.length) throw domError("InvalidStateError", "nothing is selected");
3126
+ const last = this.#ranges[this.#ranges.length - 1];
3127
+ this.#set(last._endNode, last._endOffset, last._endNode, last._endOffset);
3128
+ }
3129
+
3130
+ /** Moves the focus to (`node`, `offset`); the anchor stays. */
3131
+ extend(node, offset = 0) {
3132
+ checkNode(node, "the node");
3133
+ this.#sync();
3134
+ if (!this.#anchor) throw domError("InvalidStateError", "nothing is selected");
3135
+ offset = checkOffset(node, offset);
3136
+ if (inDocument(node)) this.#set(this.#anchor, this.#anchorOffset, node, offset);
3137
+ }
3138
+
3139
+ setBaseAndExtent(anchorNode, anchorOffset, focusNode, focusOffset) {
3140
+ checkNode(anchorNode, "the anchor node");
3141
+ checkNode(focusNode, "the focus node");
3142
+ anchorOffset = checkOffset(anchorNode, anchorOffset);
3143
+ focusOffset = checkOffset(focusNode, focusOffset);
3144
+ if (inDocument(anchorNode) && inDocument(focusNode)) this.#set(anchorNode, anchorOffset, focusNode, focusOffset);
3145
+ }
3146
+
3147
+ selectAllChildren(node) {
3148
+ checkNode(node, "the node");
3149
+ if (inDocument(node)) this.#set(node, 0, node, node.childNodes.length);
1326
3150
  }
1327
- node.childNodes = [];
1328
- }
1329
3151
 
1330
- export function createNode(kind) {
1331
- if (kind === "richinput") return new RichInput();
1332
- if (kind === "svg") return new Svg();
1333
- if (kind === "img") kind = "image";
1334
- if (!(kind in KINDS) || kind === "icon") throw new TypeError("the tree has no node kind '" + kind + "'");
1335
- if (kind === "text") return new Text();
1336
- if (kind === "input") return new Input();
1337
- if (kind === "image") return new Image();
1338
- return new Node(kind);
1339
- }
3152
+ deleteFromDocument() {
3153
+ this.#sync();
3154
+ for (const range of [...this.#ranges]) range.deleteContents();
3155
+ }
1340
3156
 
1341
- /** A box with `style` as its base look and `children` appended. */
1342
- export function createBox(style, ...children) {
1343
- const box = new Node("box");
1344
- if (style) box.style.set(style);
1345
- box.append(...children);
1346
- return box;
1347
- }
3157
+ /** Whether the selection holds all of `node`, or any of it with `allowPartialContainment`. */
3158
+ containsNode(node, allowPartialContainment = false) {
3159
+ checkNode(node, "the node");
3160
+ this.#sync();
3161
+ if (!this.#ranges.length || !inDocument(node)) return false;
3162
+ const parent = node.parentNode;
3163
+ const startNode = parent ?? node;
3164
+ const start = parent ? indexIn(node) : 0;
3165
+ const endNode = parent ?? node;
3166
+ const end = parent ? start + 1 : nodeLength(node);
3167
+ return this.#ranges.some((range) => allowPartialContainment
3168
+ ? comparePoints(startNode, start, range._endNode, range._endOffset) < 0 && comparePoints(endNode, end, range._startNode, range._startOffset) > 0
3169
+ : comparePoints(range._startNode, range._startOffset, startNode, start) <= 0 && comparePoints(endNode, end, range._endNode, range._endOffset) <= 0);
3170
+ }
1348
3171
 
1349
- export function createText(data = "") {
1350
- return new Text(data);
3172
+ getComposedRanges() {
3173
+ this.#sync();
3174
+ return this.#ranges.map((range) => new StaticRange({
3175
+ startContainer: range._startNode, startOffset: range._startOffset, endContainer: range._endNode, endOffset: range._endOffset,
3176
+ }));
3177
+ }
3178
+
3179
+ /** The selected text as copying gives it: rendered white space, line breaks between blocks. */
3180
+ toString() {
3181
+ this.#sync();
3182
+ if (!this.#ranges.length) return "";
3183
+ return native.selectionText?.() ?? this.#ranges.map((range) => range.toString()).join("");
3184
+ }
1351
3185
  }
1352
3186
 
1353
- /** An image showing `src` (see `Image`), with `style` as its base look. */
1354
- export function createImage(src, style) {
1355
- const image = new Image(src);
1356
- if (style) image.style.set(style);
1357
- return image;
3187
+ /** The document's selection: what the user selected, which scripts can read and change. */
3188
+ export function getSelection() {
3189
+ return (theSelection ??= new Selection(SELECTION));
1358
3190
  }
1359
3191
 
1360
- export function createInput(style) {
1361
- const input = new Input();
1362
- if (style) input.style.set(style);
1363
- return input;
3192
+ globalThis.Selection ??= Selection;
3193
+ globalThis.getSelection ??= getSelection;
3194
+
3195
+ // A `SelectionChange` record at a node that is not an input: `selectstart` where a press
3196
+ // started a selection (its `selectionStart` is 1), else the document's `selectionchange` at
3197
+ // the root.
3198
+ function selectionRecord(target, start) {
3199
+ const event = new Event(start === 1 ? "selectstart" : "selectionchange", target);
3200
+ if (start !== 1) event.bubbles = false;
3201
+ dispatchEvent(event);
3202
+ if (event.defaultPrevented) {
3203
+ const selection = getSelection();
3204
+ selection.removeAllRanges();
3205
+ // Read back at once, so the tree stops the press before the pointer moves on.
3206
+ void selection.rangeCount;
3207
+ }
3208
+ return false;
1364
3209
  }
1365
3210
 
1366
3211
  let rootNode = null;
@@ -1522,12 +3367,119 @@ export class Event {
1522
3367
  }
1523
3368
  }
1524
3369
 
3370
+ // The pointers down or hovering, by `pointerId`: their buttons and the node holding their
3371
+ // capture.
3372
+ const pointers = new Map();
3373
+
3374
+ function domError(name, message) {
3375
+ const DOMExceptionClass = globalThis.DOMException;
3376
+ if (DOMExceptionClass) return new DOMExceptionClass(message, name);
3377
+ const error = new Error(message);
3378
+ error.name = name;
3379
+ return error;
3380
+ }
3381
+
3382
+ const POINTER_TYPES = ["mouse", "pen", "touch"];
3383
+ // DOM `buttons` bits by `button`: primary 1, secondary 2, auxiliary 4, back 8, forward 16.
3384
+ const BUTTON_BITS = [1, 4, 2, 8, 16];
3385
+
3386
+ function isPointerKind(kind) {
3387
+ return kind <= 5 || kind === 14 || kind === 28 || kind === 29;
3388
+ }
3389
+
3390
+ // The fingers down, by `identifier`: the `Touch` each last reported.
3391
+ const touches = new Map();
3392
+
3393
+ function touchList(list) {
3394
+ list.item = (index) => list[index] ?? null;
3395
+ return list;
3396
+ }
3397
+
3398
+ // A touch record as DOM `TouchEvent`: the finger it is about is `changedTouches[0]`, and it
3399
+ // goes to the node the finger went down on. No host reports contact size or force: a touch is
3400
+ // 1 by 1 pixel, as its pointer is, with force 0.
3401
+ function fillTouch(event, kind, a, b, bits, d) {
3402
+ const identifier = Math.floor(bits / 256) % 16777216;
3403
+ const touch = {
3404
+ identifier,
3405
+ target: event.target,
3406
+ clientX: a,
3407
+ clientY: b,
3408
+ pageX: a,
3409
+ pageY: b,
3410
+ screenX: a,
3411
+ screenY: b,
3412
+ radiusX: 0.5,
3413
+ radiusY: 0.5,
3414
+ rotationAngle: 0,
3415
+ force: 0,
3416
+ };
3417
+ const start = touches.get(identifier);
3418
+ if (start) touch.target = start.target;
3419
+ if (kind === TOUCH_START || kind === TOUCH_START + 1) touches.set(identifier, touch);
3420
+ else touches.delete(identifier);
3421
+ event.cancelable = d === 1;
3422
+ event.changedTouches = touchList([touch]);
3423
+ event.touches = touchList([...touches.values()]);
3424
+ event.targetTouches = touchList([...touches.values()].filter((t) => t.target === event.target));
3425
+ }
3426
+
3427
+ // The members of DOM `PointerEvent` the record carries (see ui-js-calls `pointerBits`), and the
3428
+ // spec defaults for what no host reports: pressure 0.5 while a button is down, 0 otherwise, and
3429
+ // a contact of 1 by 1 pixel with no tilt.
3430
+ function fillPointer(event, kind, bits, d) {
3431
+ const pointerId = Math.floor(bits / 256) % 16777216;
3432
+ event._element = Math.floor(bits / 4294967296);
3433
+ const pointerType = POINTER_TYPES[Math.floor(bits / 16) % 4] ?? "mouse";
3434
+ const isPrimary = Math.floor(bits / 64) % 2 === 1;
3435
+ let pointer = pointers.get(pointerId);
3436
+ if (!pointer) {
3437
+ pointer = { buttons: 0, capture: null, primary: isPrimary, mute: false };
3438
+ // A click comes after its pointer lifted: it leaves no pointer behind.
3439
+ if (kind !== 2) pointers.set(pointerId, pointer);
3440
+ }
3441
+ if (kind === 0) pointer.buttons |= BUTTON_BITS[d] ?? 0;
3442
+ else if (kind === 1) pointer.buttons &= ~(BUTTON_BITS[d] ?? 0);
3443
+ event.pointerId = pointerId;
3444
+ event.pointerType = pointerType;
3445
+ event.isPrimary = isPrimary;
3446
+ event.buttons = pointer.buttons;
3447
+ event.pressure = pointer.buttons ? 0.5 : 0;
3448
+ event.tangentialPressure = 0;
3449
+ event.tiltX = 0;
3450
+ event.tiltY = 0;
3451
+ event.twist = 0;
3452
+ event.altitudeAngle = Math.PI / 2;
3453
+ event.azimuthAngle = 0;
3454
+ event.width = 1;
3455
+ event.height = 1;
3456
+ if (kind !== 0 && kind !== 1 && kind !== 2) event.button = kind === 3 ? -1 : 0;
3457
+ const coalesced = kind === 3 ? [event] : [];
3458
+ event.getCoalescedEvents = () => coalesced;
3459
+ event.getPredictedEvents = () => [];
3460
+ // A pointer that lifted, or a touch that left, is gone; the mouse stays.
3461
+ if ((kind === 1 && !pointer.buttons) || kind === 14) {
3462
+ pointer.capture = null;
3463
+ if (pointerType !== "mouse") pointers.delete(pointerId);
3464
+ }
3465
+ }
3466
+
1525
3467
  function fill(event, kind, a, b, modifiers, d, e, first, second, third, fourth) {
1526
- if (kind <= 6 || kind === 14) {
3468
+ if (kind >= TOUCH_START && kind < COPY) {
3469
+ fillTouch(event, kind, a, b, modifiers, d);
3470
+ event.shiftKey = (modifiers & 1) !== 0;
3471
+ event.ctrlKey = (modifiers & 2) !== 0;
3472
+ event.altKey = (modifiers & 4) !== 0;
3473
+ event.metaKey = (modifiers & 8) !== 0;
3474
+ return;
3475
+ }
3476
+ if (kind <= 6 || kind === 14 || kind === 28 || kind === 29) {
1527
3477
  event.clientX = event.x = a;
1528
3478
  event.clientY = event.y = b;
1529
3479
  }
1530
- if (kind <= 8 || kind === 14) {
3480
+ if (isPointerKind(kind)) fillPointer(event, kind, modifiers, d);
3481
+ if (kind === 16) for (const pointer of pointers.values()) if (pointer.capture === event.target) pointer.capture = null;
3482
+ if (kind <= 8 || kind === 14 || kind === 28 || kind === 29) {
1531
3483
  event.shiftKey = (modifiers & 1) !== 0;
1532
3484
  event.ctrlKey = (modifiers & 2) !== 0;
1533
3485
  event.altKey = (modifiers & 4) !== 0;
@@ -1621,17 +3573,117 @@ function adopt(event, target) {
1621
3573
  return event;
1622
3574
  }
1623
3575
 
3576
+ // The compatibility mouse event of `type` that follows pointer event `from`.
3577
+ function mouseEvent(type, from, target) {
3578
+ const event = new Event(type, target);
3579
+ for (const name of ["clientX", "clientY", "x", "y", "button", "buttons", "detail", "shiftKey", "ctrlKey", "altKey", "metaKey"]) {
3580
+ event[name] = from[name];
3581
+ }
3582
+ if (type === "mousemove") event.button = 0;
3583
+ return event;
3584
+ }
3585
+
3586
+ // Mouse events after a pointer event of a mouse or pen, as the web sends them: a prevented
3587
+ // `pointerdown` mutes `mousedown`, `mousemove` and `mouseup` until the pointer lifts.
3588
+ function compatMouse(kind, event, target) {
3589
+ const type = MOUSE_OF.get(event.type);
3590
+ if (!type) return;
3591
+ const pointer = pointers.get(event.pointerId);
3592
+ if (kind === 0 && event.defaultPrevented && pointer) pointer.mute = true;
3593
+ const muted = pointer?.mute && (kind === 0 || kind === 1 || kind === 3);
3594
+ if (kind === 1 && pointer) pointer.mute = false;
3595
+ if (!muted && event.isPrimary) dispatchEvent(mouseEvent(type, event, target));
3596
+ }
3597
+
3598
+ // The finger whose prevented `pointerdown` mutes its tap's mouse events.
3599
+ let mutedTap = null;
3600
+
3601
+ // A tap's mouse events come just before its click, as on the web.
3602
+ function compatTap(click, target) {
3603
+ if (mutedTap === click.pointerId) return;
3604
+ for (const type of ["mousemove", "mousedown", "mouseup"]) {
3605
+ const event = mouseEvent(type, click, target);
3606
+ event.buttons = type === "mousedown" ? 1 : 0;
3607
+ dispatchEvent(event);
3608
+ }
3609
+ }
3610
+
1624
3611
  // The host calls this for every event record, before the tree runs the default action.
1625
3612
  native.dispatch = function (kind, id, a, b, modifiers, d, e, first, second, third, fourth) {
1626
3613
  const target = nodes.get(id);
1627
3614
  if (!target) return false;
3615
+ if (kind >= COPY) return dispatchEditing(kind, target, first, second, third);
3616
+ if (kind === SELECTION_CHANGE && !(target instanceof Input)) return selectionRecord(target, a);
1628
3617
  const event = new Event(TYPES[kind], target);
1629
3618
  fill(event, kind, a, b, modifiers, d, e, first, second, third, fourth);
3619
+ const live = target instanceof Svg && target._live && isPointerKind(kind);
3620
+ if (kind === CLICK && event.pointerType === "touch" && event.isPrimary) compatTap(event, target);
3621
+ // A live svg sends pointer records on to the element under the pointer.
3622
+ let prevented;
3623
+ if (live) prevented = target._pointer(event);
3624
+ else {
3625
+ dispatchEvent(event);
3626
+ prevented = event.defaultPrevented;
3627
+ }
3628
+ if (kind === CLICK && !prevented) follow(target);
3629
+ if (kind !== CLICK && isPointerKind(kind)) {
3630
+ if (event.pointerType !== "touch") compatMouse(kind, event, live && event.target instanceof SvgElement ? event.target : target);
3631
+ // A finger's defaults (pan, focus, the tap's click) follow its touch events, not its
3632
+ // pointer events, as on the web.
3633
+ else {
3634
+ if (kind === 0 && event.isPrimary) mutedTap = prevented ? event.pointerId : null;
3635
+ return false;
3636
+ }
3637
+ }
3638
+ return prevented;
3639
+ };
3640
+
3641
+ // Copy, cut and paste as the Clipboard API and events spec has them, and beforeinput. A
3642
+ // paste carries the clipboard's text, HTML and a PNG (bytes as a Latin-1 string). A copy or
3643
+ // cut a listener prevented puts what it set on `clipboardData` on the clipboard; one it did
3644
+ // not prevent lets the tree copy the selection.
3645
+ function dispatchEditing(kind, target, first, second, third) {
3646
+ let event;
3647
+ if (kind === BEFORE_INPUT) {
3648
+ event = new InputEvent("beforeinput", { bubbles: true, cancelable: true, composed: true, inputType: second ?? "", data: first ?? "" });
3649
+ } else {
3650
+ const data = new DataTransfer();
3651
+ if (kind === PASTE) {
3652
+ if (first) data.setData("text/plain", first);
3653
+ if (second) data.setData("text/html", second);
3654
+ if (third) data.items.add(new FileClass([bytesOf(third)], "image.png", { type: "image/png" }));
3655
+ data._mode = "readonly";
3656
+ }
3657
+ event = new ClipboardEvent(TYPES[kind], { bubbles: true, cancelable: true, composed: true, clipboardData: data });
3658
+ }
3659
+ event.target = target;
1630
3660
  dispatchEvent(event);
1631
- if (kind === CLICK && !event.defaultPrevented) follow(target);
3661
+ if (event.clipboardData) {
3662
+ if ((kind === COPY || kind === CUT) && event.defaultPrevented) writeClipboard(event.clipboardData);
3663
+ event.clipboardData._mode = "protected";
3664
+ }
1632
3665
  return event.defaultPrevented;
3666
+ }
3667
+
3668
+ const bytesOf = (text) => {
3669
+ const bytes = new Uint8Array(text.length);
3670
+ for (let i = 0; i < text.length; i++) bytes[i] = text.charCodeAt(i);
3671
+ return bytes;
1633
3672
  };
1634
3673
 
3674
+ // What a prevented copy or cut set, onto the system clipboard.
3675
+ function writeClipboard(data) {
3676
+ const clipboard = globalThis.navigator?.clipboard;
3677
+ const entries = data._entries();
3678
+ if (!clipboard || entries.length === 0) return;
3679
+ const item = {};
3680
+ for (const [type, value] of entries) item[type] = value;
3681
+ const written = entries.length === 1 && entries[0][0] === "text/plain" || typeof globalThis.ClipboardItem !== "function"
3682
+ ? clipboard.writeText(item["text/plain"] ?? "")
3683
+ : clipboard.write([new globalThis.ClipboardItem(item)]);
3684
+ Promise.resolve(written).catch(reportError);
3685
+ }
3686
+
1635
3687
  // The default action of a click: the nearest link around the target opens.
1636
3688
  function follow(target) {
1637
3689
  for (let node = target; node; node = node.parentNode) {
@@ -1693,24 +3745,219 @@ export class DroppedFile {
1693
3745
  }
1694
3746
  }
1695
3747
 
3748
+ // `File` where the runtime has one, else a `Blob` with a name.
3749
+ const FileClass = globalThis.File ?? (globalThis.Blob ? class File extends globalThis.Blob {
3750
+ constructor(parts, name, options = {}) {
3751
+ super(parts, options);
3752
+ this.name = String(name);
3753
+ this.lastModified = options.lastModified ?? Date.now();
3754
+ }
3755
+ } : null);
3756
+
3757
+ const normalFormat = (format) => {
3758
+ const lower = String(format).toLowerCase();
3759
+ return lower === "text" ? "text/plain" : lower === "url" ? "text/uri-list" : lower;
3760
+ };
3761
+
3762
+ /** One entry of a `DataTransfer`, as the web's `DataTransferItem`. */
3763
+ class DataTransferItem {
3764
+ #owner;
3765
+ #value;
3766
+ constructor(owner, kind, type, value) {
3767
+ this.#owner = owner;
3768
+ this.kind = kind;
3769
+ this.type = type;
3770
+ this.#value = value;
3771
+ }
3772
+
3773
+ getAsString(callback) {
3774
+ if (this.kind !== "string" || typeof callback !== "function" || this.#owner._mode === "protected") return;
3775
+ const value = this.#value;
3776
+ queueMicrotask(() => callback(value));
3777
+ }
3778
+
3779
+ getAsFile() {
3780
+ return this.kind === "file" && this.#owner._mode !== "protected" ? this.#value : null;
3781
+ }
3782
+
3783
+ _value() {
3784
+ return this.#value;
3785
+ }
3786
+ }
3787
+
3788
+ /** The entries of a `DataTransfer`, as the web's `DataTransferItemList`. */
3789
+ class DataTransferItemList {
3790
+ #owner;
3791
+ #list = [];
3792
+ constructor(owner) {
3793
+ this.#owner = owner;
3794
+ return new Proxy(this, {
3795
+ get: (self, key) => {
3796
+ if (typeof key === "string" && /^\d+$/.test(key)) return self.length > Number(key) ? self.#list[Number(key)] : undefined;
3797
+ const value = Reflect.get(self, key, self);
3798
+ return typeof value === "function" ? value.bind(self) : value;
3799
+ },
3800
+ });
3801
+ }
3802
+
3803
+ get length() {
3804
+ return this.#owner._mode === "protected" ? 0 : this.#list.length;
3805
+ }
3806
+
3807
+ /** `add(data, type)` for a string, `add(file)` for a file. Read-only data throws. */
3808
+ add(data, type) {
3809
+ this.#owner._writable();
3810
+ if (typeof data === "string") {
3811
+ const format = normalFormat(type ?? "");
3812
+ if (this.#list.some((item) => item.kind === "string" && item.type === format)) {
3813
+ throw domError("NotSupportedError", "The data already holds an item of type " + format);
3814
+ }
3815
+ const item = new DataTransferItem(this.#owner, "string", format, data);
3816
+ this.#list.push(item);
3817
+ return item;
3818
+ }
3819
+ if (data && typeof data === "object") {
3820
+ const item = new DataTransferItem(this.#owner, "file", String(data.type ?? "").toLowerCase(), data);
3821
+ this.#list.push(item);
3822
+ return item;
3823
+ }
3824
+ throw new TypeError("DataTransferItemList.add takes a string and a type, or a File");
3825
+ }
3826
+
3827
+ remove(index) {
3828
+ this.#owner._writable();
3829
+ if (index >= 0 && index < this.#list.length) this.#list.splice(index, 1);
3830
+ }
3831
+
3832
+ clear() {
3833
+ this.#owner._writable();
3834
+ this.#list.length = 0;
3835
+ }
3836
+
3837
+ [Symbol.iterator]() {
3838
+ return (this.#owner._mode === "protected" ? [] : this.#list)[Symbol.iterator]();
3839
+ }
3840
+
3841
+ _all() {
3842
+ return this.#list;
3843
+ }
3844
+ }
3845
+
1696
3846
  /**
1697
- * What a file drag carries, as the web's `DataTransfer`: `types` is `["Files"]` while files
1698
- * are over the window, and `files` lists them in `drop`, as on the web.
3847
+ * What a copy, cut, paste or file drag carries, as the web's `DataTransfer`. `new
3848
+ * DataTransfer()` is empty and writable. A file drag lists the dragged `paths` in `files`;
3849
+ * its `types` is `["Files"]` while they are over the window.
1699
3850
  */
1700
3851
  export class DataTransfer {
3852
+ #items;
1701
3853
  constructor(paths) {
1702
- this.files = paths.map((path) => new DroppedFile(path));
1703
- this.items = this.files.map((file) => ({ kind: "file", type: "", getAsFile: () => file }));
1704
- this.types = ["Files"];
1705
- this.dropEffect = "copy";
1706
- this.effectAllowed = "copy";
3854
+ // "readwrite", "readonly" (paste, drop) or "protected" (after the event).
3855
+ this._mode = "readwrite";
3856
+ this._drag = Array.isArray(paths);
3857
+ paths ??= [];
3858
+ this.#items = new DataTransferItemList(this);
3859
+ for (const path of paths) this.#items.add(new DroppedFile(path));
3860
+ this.dropEffect = paths.length ? "copy" : "none";
3861
+ this.effectAllowed = paths.length ? "copy" : "uninitialized";
3862
+ }
3863
+
3864
+ _writable() {
3865
+ if (this._mode !== "readwrite") throw domError("InvalidStateError", "The DataTransfer is read-only now");
1707
3866
  }
1708
3867
 
1709
- getData() {
1710
- return "";
3868
+ get items() {
3869
+ return this.#items;
3870
+ }
3871
+
3872
+ get types() {
3873
+ if (this._mode === "protected") return Object.freeze([]);
3874
+ const types = [];
3875
+ let files = false;
3876
+ for (const item of this.#items._all()) {
3877
+ if (item.kind === "string") types.push(item.type);
3878
+ else files = true;
3879
+ }
3880
+ if (files || this._drag) types.push("Files");
3881
+ return Object.freeze(types);
3882
+ }
3883
+
3884
+ get files() {
3885
+ if (this._mode === "protected") return Object.freeze([]);
3886
+ return Object.freeze(this.#items._all().filter((item) => item.kind === "file").map((item) => item._value()));
3887
+ }
3888
+
3889
+ getData(format) {
3890
+ if (this._mode === "protected") return "";
3891
+ const type = normalFormat(format);
3892
+ const item = this.#items._all().find((each) => each.kind === "string" && each.type === type);
3893
+ const value = item ? item._value() : "";
3894
+ return type === "text/uri-list" ? (value.split(/\r?\n/).find((line) => line && !line.startsWith("#")) ?? "") : value;
3895
+ }
3896
+
3897
+ setData(format, data) {
3898
+ if (this._mode !== "readwrite") return;
3899
+ const type = normalFormat(format);
3900
+ const list = this.#items._all();
3901
+ const at = list.findIndex((each) => each.kind === "string" && each.type === type);
3902
+ if (at >= 0) list.splice(at, 1);
3903
+ this.#items.add(String(data), type);
3904
+ }
3905
+
3906
+ clearData(format) {
3907
+ if (this._mode !== "readwrite") return;
3908
+ const list = this.#items._all();
3909
+ const type = format === undefined ? null : normalFormat(format);
3910
+ for (let i = list.length - 1; i >= 0; i--) {
3911
+ if (list[i].kind === "string" && (type === null || list[i].type === type)) list.splice(i, 1);
3912
+ }
3913
+ }
3914
+
3915
+ setDragImage() {}
3916
+
3917
+ // The strings, and the PNG files, to put on the clipboard.
3918
+ _entries() {
3919
+ const entries = [];
3920
+ for (const item of this.#items._all()) {
3921
+ if (item.kind === "string") entries.push([item.type, item._value()]);
3922
+ else if (item.type === "image/png" && !entries.some(([type]) => type === "image/png")) entries.push(["image/png", item._value()]);
3923
+ }
3924
+ return entries;
1711
3925
  }
1712
3926
  }
1713
3927
 
3928
+ /** A copy, cut or paste, as the web's `ClipboardEvent`. */
3929
+ export class ClipboardEvent extends Event {
3930
+ constructor(type, init = {}) {
3931
+ super(String(type), null);
3932
+ this.bubbles = !!init.bubbles;
3933
+ this.cancelable = !!init.cancelable;
3934
+ this.composed = !!init.composed;
3935
+ this.clipboardData = init.clipboardData ?? null;
3936
+ }
3937
+ }
3938
+
3939
+ /** An edit about to happen (`beforeinput`), as the web's `InputEvent`. */
3940
+ class InputEvent extends Event {
3941
+ constructor(type, init = {}) {
3942
+ super(String(type), null);
3943
+ this.bubbles = !!init.bubbles;
3944
+ this.cancelable = !!init.cancelable;
3945
+ this.composed = !!init.composed;
3946
+ this.inputType = init.inputType ?? "";
3947
+ this.data = init.data ?? null;
3948
+ this.dataTransfer = init.dataTransfer ?? null;
3949
+ this.isComposing = !!init.isComposing;
3950
+ }
3951
+
3952
+ getTargetRanges() {
3953
+ return [];
3954
+ }
3955
+ }
3956
+
3957
+ globalThis.ClipboardEvent ??= ClipboardEvent;
3958
+ globalThis.InputEvent ??= InputEvent;
3959
+ globalThis.DataTransfer ??= DataTransfer;
3960
+
1714
3961
  let dragTarget = null;
1715
3962
 
1716
3963
  function dragEvent(type, target, x, y, paths) {
@@ -1827,6 +4074,10 @@ export class Notification {
1827
4074
  }
1828
4075
 
1829
4076
  globalThis.Notification ??= Notification;
4077
+ globalThis.AbstractRange ??= AbstractRange;
4078
+ globalThis.StaticRange ??= StaticRange;
4079
+ globalThis.Range ??= Range;
4080
+ globalThis.DocumentFragment ??= DocumentFragment;
1830
4081
 
1831
4082
  function hex(bytes) {
1832
4083
  let text = "";
@@ -1943,6 +4194,422 @@ export function memoryUsage() {
1943
4194
  return footprint > 0 ? { footprint, processes: 1 } : null;
1944
4195
  }
1945
4196
 
4197
+ // Selector queries run in the host on its tree (`__ui.query`); a host without one (the web
4198
+ // canvas build) answers undefined, which reads as no match.
4199
+ function queried(mode, node, selector) {
4200
+ const answer = native.query?.(mode, node.nodeId, String(selector));
4201
+ if (answer === -1) {
4202
+ const message = "'" + selector + "' is not a valid selector";
4203
+ throw typeof DOMException === "function" ? new DOMException(message, "SyntaxError") : new SyntaxError(message);
4204
+ }
4205
+ return answer;
4206
+ }
4207
+
4208
+ // `getComputedStyle`: one native read per property, made when the property is read, so a
4209
+ // declaration stays live and costs nothing for the properties nobody asks for.
4210
+ const readComputed = native.computed ?? (() => undefined);
4211
+ const computedId = Symbol("node");
4212
+ // Property names by the name they were asked by, null for the declaration's own members.
4213
+ const computedNames = new Map();
4214
+ const lowerNames = new Map();
4215
+ function computedName(key, target) {
4216
+ let name = computedNames.get(key);
4217
+ if (name === undefined) {
4218
+ name = key in target ? null : key === "cssFloat" ? "float"
4219
+ : key.replace(/[A-Z]/g, (c) => "-" + c.toLowerCase()).replace(/^(webkit|moz|ms)-/, "-$1-");
4220
+ computedNames.set(key, name);
4221
+ }
4222
+ return name;
4223
+ }
4224
+
4225
+ class CSSStyleDeclaration {
4226
+ constructor(id) { Object.defineProperty(this, computedId, { value: id }); }
4227
+ getPropertyValue(name) {
4228
+ let lower = lowerNames.get(name);
4229
+ if (lower === undefined) {
4230
+ lower = String(name).toLowerCase();
4231
+ if (typeof name === "string") lowerNames.set(name, lower);
4232
+ }
4233
+ return readComputed(this[computedId], lower) ?? "";
4234
+ }
4235
+ getPropertyPriority() { return ""; }
4236
+ setProperty() { throw new TypeError("a computed style cannot be changed"); }
4237
+ removeProperty() { throw new TypeError("a computed style cannot be changed"); }
4238
+ get cssText() { return ""; }
4239
+ get length() { return 0; }
4240
+ item() { return ""; }
4241
+ }
4242
+
4243
+ const computedTraps = {
4244
+ get(target, key, receiver) {
4245
+ if (typeof key === "string") {
4246
+ const name = computedName(key, target);
4247
+ if (name !== null) return readComputed(target[computedId], name) ?? "";
4248
+ }
4249
+ return Reflect.get(target, key, receiver);
4250
+ },
4251
+ set() { throw new TypeError("a computed style cannot be changed"); },
4252
+ };
4253
+
4254
+ /**
4255
+ * The values the tree resolved for `node` (an @silkui/core node, or an element of a DOM layer
4256
+ * over one): typed and animated properties as they are now, box sizes, margins, padding and
4257
+ * border widths as laid out, the rest as cascaded with lengths in pixels. Each property read
4258
+ * is one call into the tree; it applies pending changes and lays out only when something
4259
+ * changed since the last layout. Shorthands, custom properties and pseudo-elements read "".
4260
+ */
4261
+ export function getComputedStyle(node, pseudo) {
4262
+ const id = node?.nodeId ?? node?.node?.nodeId;
4263
+ if (typeof id !== "number") throw new TypeError("getComputedStyle takes a node");
4264
+ return new Proxy(new CSSStyleDeclaration(pseudo ? 0 : id), computedTraps);
4265
+ }
4266
+
4267
+ globalThis.getComputedStyle ??= getComputedStyle;
4268
+
4269
+ // Layout reads. Each lays out first when something changed since the last frame (as a
4270
+ // browser forces layout), leaves its numbers in the bridge and answers how many there are.
4271
+ const geometry = native.geometry ?? (() => 0);
4272
+ const ALIGNMENTS = { start: 0, center: 1, end: 2, nearest: 3 };
4273
+ const BEHAVIORS = { auto: 0, instant: 1, smooth: 2 };
4274
+
4275
+ function alignment(value, fallback) {
4276
+ if (value === undefined) return fallback;
4277
+ const code = ALIGNMENTS[value];
4278
+ if (code === undefined) throw new TypeError("'" + value + "' is not a valid ScrollLogicalPosition");
4279
+ return code;
4280
+ }
4281
+
4282
+ /** A read-only rectangle, as `DOMRect` on the web. */
4283
+ export class DOMRect {
4284
+ constructor(x = 0, y = 0, width = 0, height = 0) {
4285
+ this.x = x;
4286
+ this.y = y;
4287
+ this.width = width;
4288
+ this.height = height;
4289
+ }
4290
+ get left() { return Math.min(this.x, this.x + this.width); }
4291
+ get top() { return Math.min(this.y, this.y + this.height); }
4292
+ get right() { return Math.max(this.x, this.x + this.width); }
4293
+ get bottom() { return Math.max(this.y, this.y + this.height); }
4294
+ toJSON() {
4295
+ const { x, y, width, height, top, right, bottom, left } = this;
4296
+ return { x, y, width, height, top, right, bottom, left };
4297
+ }
4298
+ }
4299
+
4300
+ globalThis.DOMRect ??= DOMRect;
4301
+
4302
+ function metric(id, index) {
4303
+ if (!native.metrics?.(id)) return 0;
4304
+ return geometry(index);
4305
+ }
4306
+
4307
+ function readRect(id) {
4308
+ if (!native.rect?.(id)) return new DOMRect();
4309
+ return new DOMRect(geometry(0), geometry(1), geometry(2), geometry(3));
4310
+ }
4311
+
4312
+ function readRects(count) {
4313
+ const list = [];
4314
+ for (let i = 0; i < count; i++) list.push(new DOMRect(geometry(4 * i), geometry(4 * i + 1), geometry(4 * i + 2), geometry(4 * i + 3)));
4315
+ list.item = (index) => list[index] ?? null;
4316
+ return list;
4317
+ }
4318
+
4319
+ // `scrollTo`, `scroll` and `scrollBy`: numbers, or `{ left, top, behavior }`. `by` is 4 for scrollBy.
4320
+ function scrollNode(id, x, y, by) {
4321
+ let left, top, behavior = 0;
4322
+ if (x !== null && typeof x === "object") {
4323
+ left = x.left;
4324
+ top = x.top;
4325
+ if (x.behavior !== undefined) {
4326
+ behavior = BEHAVIORS[x.behavior];
4327
+ if (behavior === undefined) throw new TypeError("'" + x.behavior + "' is not a valid ScrollBehavior");
4328
+ }
4329
+ } else {
4330
+ left = x;
4331
+ top = y;
4332
+ }
4333
+ // As on the web, a non-finite coordinate counts as 0.
4334
+ const has = (left !== undefined ? 1 : 0) | (top !== undefined ? 2 : 0);
4335
+ const number = (value) => (Number.isFinite(+value) ? +value : 0);
4336
+ if (native.scroll) native.scroll(id, number(left), number(top), behavior, has | by);
4337
+ else if (!by) native.scrollTo(id, number(left), number(top));
4338
+ }
4339
+
4340
+ // IntersectionObserver and ResizeObserver: the tree computes every observation after each
4341
+ // layout and calls `__ui.observed(count)` with only the entries that changed.
4342
+ const observersById = new Map();
4343
+ let nextObserverId = 0;
4344
+
4345
+ function lengths(text, name) {
4346
+ const parts = String(text ?? "0px").trim().split(/\s+/);
4347
+ if (parts.length > 4) throw new SyntaxError("'" + text + "' is not a valid " + name);
4348
+ const values = [], percent = [];
4349
+ for (const part of parts) {
4350
+ const match = /^(-?(?:\d+\.?\d*|\.\d+))(px|%)?$/.exec(part);
4351
+ if (!match || (match[2] === undefined && +match[1] !== 0)) throw new SyntaxError("'" + text + "' is not a valid " + name + ": use px or %");
4352
+ values.push(+match[1]);
4353
+ percent.push(match[2] === "%");
4354
+ }
4355
+ // top, right, bottom, left as in the margin shorthand.
4356
+ const pick = [[0, 0, 0, 0], [0, 1, 0, 1], [0, 1, 2, 1], [0, 1, 2, 3]][values.length - 1];
4357
+ const out = pick.map((i) => values[i]);
4358
+ let bits = 0;
4359
+ pick.forEach((i, side) => { if (percent[i]) bits |= 1 << side; });
4360
+ out.text = pick.map((i) => values[i] + (percent[i] ? "%" : "px")).join(" ");
4361
+ return { values: out, bits };
4362
+ }
4363
+
4364
+ /** As `IntersectionObserverEntry` on the web. */
4365
+ export class IntersectionObserverEntry {
4366
+ constructor(init) { Object.assign(this, init); }
4367
+ }
4368
+
4369
+ /** As `IntersectionObserver` on the web, with `scrollMargin` from version 2. `root` is a node or null for the window. */
4370
+ export class IntersectionObserver {
4371
+ #id = ++nextObserverId;
4372
+ #callback;
4373
+ #targets = new Map();
4374
+ #records = [];
4375
+ #margin;
4376
+ #scroll;
4377
+
4378
+ constructor(callback, options = {}) {
4379
+ if (typeof callback !== "function") throw new TypeError("IntersectionObserver takes a callback");
4380
+ this.#callback = callback;
4381
+ const root = options.root ?? null;
4382
+ if (root !== null && typeof root.nodeId !== "number" && typeof root.node?.nodeId !== "number") throw new TypeError("root must be a node or null");
4383
+ this.root = root;
4384
+ this.#margin = lengths(options.rootMargin, "rootMargin");
4385
+ this.#scroll = lengths(options.scrollMargin, "scrollMargin");
4386
+ let list = options.threshold ?? 0;
4387
+ list = (Array.isArray(list) ? list : [list]).map(Number);
4388
+ for (const value of list) if (!(value >= 0 && value <= 1)) throw new RangeError("Threshold values must be numbers between 0 and 1");
4389
+ list.sort((a, b) => a - b);
4390
+ if (list.length === 0) list.push(0);
4391
+ Object.defineProperties(this, {
4392
+ rootMargin: { value: this.#margin.values.text, enumerable: true },
4393
+ scrollMargin: { value: this.#scroll.values.text, enumerable: true },
4394
+ thresholds: { value: Object.freeze(list), enumerable: true },
4395
+ delay: { value: 0, enumerable: true },
4396
+ trackVisibility: { value: false, enumerable: true },
4397
+ });
4398
+ }
4399
+
4400
+ observe(target) {
4401
+ const id = target?.nodeId ?? target?.node?.nodeId;
4402
+ if (typeof id !== "number") throw new TypeError("observe takes a node");
4403
+ if (this.#targets.has(id)) return;
4404
+ if (this.#targets.size === 0) {
4405
+ const m = this.#margin.values, s = this.#scroll.values;
4406
+ const rootId = this.root ? (this.root.nodeId ?? this.root.node.nodeId) : 0;
4407
+ native.observer?.(this.#id, rootId, m[0], m[1], m[2], m[3], this.#margin.bits | (this.#scroll.bits << 4), s[0], s[1], s[2], s[3]);
4408
+ for (const value of this.thresholds) native.threshold?.(this.#id, value);
4409
+ observersById.set(this.#id, this);
4410
+ }
4411
+ this.#targets.set(id, target);
4412
+ native.observe?.(this.#id, id, 0);
4413
+ }
4414
+
4415
+ unobserve(target) {
4416
+ const id = target?.nodeId ?? target?.node?.nodeId;
4417
+ if (!this.#targets.delete(id)) return;
4418
+ native.unobserve?.(this.#id, id);
4419
+ if (this.#targets.size === 0) observersById.delete(this.#id);
4420
+ }
4421
+
4422
+ disconnect() {
4423
+ if (this.#targets.size === 0) return;
4424
+ this.#targets.clear();
4425
+ native.unobserve?.(this.#id, 0);
4426
+ observersById.delete(this.#id);
4427
+ }
4428
+
4429
+ takeRecords() {
4430
+ const records = this.#records;
4431
+ this.#records = [];
4432
+ return records;
4433
+ }
4434
+
4435
+ // The object `observe` was given: a Foldkit element is its entries' target, not its node.
4436
+ _target(id) { return this.#targets.get(id) ?? null; }
4437
+
4438
+ _queue(entry) { this.#records.push(entry); }
4439
+
4440
+ _deliver() {
4441
+ const records = this.takeRecords();
4442
+ if (records.length === 0) return;
4443
+ try { this.#callback.call(this, records, this); } catch (error) { reportError(error); }
4444
+ }
4445
+ }
4446
+
4447
+ /** As `ResizeObserverEntry` on the web. */
4448
+ export class ResizeObserverEntry {
4449
+ constructor(init) { Object.assign(this, init); }
4450
+ }
4451
+
4452
+ const BOXES = { "content-box": 1, "border-box": 2, "device-pixel-content-box": 3 };
4453
+
4454
+ /** As `ResizeObserver` on the web: entries come after a layout that changed the observed box. */
4455
+ export class ResizeObserver {
4456
+ #id = ++nextObserverId;
4457
+ #callback;
4458
+ #targets = new Map();
4459
+ #records = [];
4460
+
4461
+ constructor(callback) {
4462
+ if (typeof callback !== "function") throw new TypeError("ResizeObserver takes a callback");
4463
+ this.#callback = callback;
4464
+ }
4465
+
4466
+ observe(target, options) {
4467
+ const id = target?.nodeId ?? target?.node?.nodeId;
4468
+ if (typeof id !== "number") throw new TypeError("observe takes a node");
4469
+ const box = BOXES[options?.box ?? "content-box"];
4470
+ if (box === undefined) throw new TypeError("'" + options.box + "' is not a valid ResizeObserverBoxOptions");
4471
+ this.#targets.set(id, target);
4472
+ observersById.set(this.#id, this);
4473
+ native.observe?.(this.#id, id, box);
4474
+ }
4475
+
4476
+ unobserve(target) {
4477
+ const id = target?.nodeId ?? target?.node?.nodeId;
4478
+ if (!this.#targets.delete(id)) return;
4479
+ native.unobserve?.(this.#id, id);
4480
+ if (this.#targets.size === 0) observersById.delete(this.#id);
4481
+ }
4482
+
4483
+ disconnect() {
4484
+ if (this.#targets.size === 0) return;
4485
+ this.#targets.clear();
4486
+ native.unobserve?.(this.#id, 0);
4487
+ observersById.delete(this.#id);
4488
+ }
4489
+
4490
+ // The object `observe` was given: a Foldkit element is its entries' target, not its node.
4491
+ _target(id) { return this.#targets.get(id) ?? null; }
4492
+
4493
+ _queue(entry) { this.#records.push(entry); }
4494
+
4495
+ _deliver() {
4496
+ const records = this.#records;
4497
+ this.#records = [];
4498
+ if (records.length === 0) return;
4499
+ try { this.#callback.call(this, records, this); } catch (error) { reportError(error); }
4500
+ }
4501
+ }
4502
+
4503
+ const size = (inlineSize, blockSize) => Object.freeze([Object.freeze({ inlineSize, blockSize })]);
4504
+
4505
+ native.observed = function (count) {
4506
+ // Read every entry first: a callback's own layout reads reuse the numbers.
4507
+ const time = performance.now();
4508
+ const touched = [];
4509
+ let at = 0;
4510
+ for (let n = 0; n < count; n++) {
4511
+ const kind = geometry(at);
4512
+ const observer = observersById.get(geometry(at + 1));
4513
+ const target = observer?._target(geometry(at + 2)) ?? null;
4514
+ const read = (i) => geometry(at + i);
4515
+ if (kind === 1) {
4516
+ if (observer && target) {
4517
+ observer._queue(new IntersectionObserverEntry({
4518
+ time,
4519
+ target,
4520
+ isIntersecting: read(3) === 1,
4521
+ isVisible: false,
4522
+ intersectionRatio: read(4),
4523
+ boundingClientRect: new DOMRect(read(5), read(6), read(7), read(8)),
4524
+ intersectionRect: new DOMRect(read(9), read(10), read(11), read(12)),
4525
+ rootBounds: new DOMRect(read(13), read(14), read(15), read(16)),
4526
+ }));
4527
+ }
4528
+ at += 17;
4529
+ } else {
4530
+ if (observer && target) {
4531
+ observer._queue(new ResizeObserverEntry({
4532
+ target,
4533
+ contentRect: new DOMRect(read(3), read(4), read(5), read(6)),
4534
+ borderBoxSize: size(read(7), read(8)),
4535
+ contentBoxSize: size(read(9), read(10)),
4536
+ devicePixelContentBoxSize: size(read(11), read(12)),
4537
+ }));
4538
+ }
4539
+ at += 13;
4540
+ }
4541
+ if (observer && !touched.includes(observer)) touched.push(observer);
4542
+ }
4543
+ // ResizeObserver callbacks first, as browsers run them before intersection updates.
4544
+ for (const observer of touched) if (observer instanceof ResizeObserver) observer._deliver();
4545
+ for (const observer of touched) if (observer instanceof IntersectionObserver) observer._deliver();
4546
+ };
4547
+
4548
+ globalThis.IntersectionObserver ??= IntersectionObserver;
4549
+ globalThis.IntersectionObserverEntry ??= IntersectionObserverEntry;
4550
+ globalThis.ResizeObserver ??= ResizeObserver;
4551
+ globalThis.ResizeObserverEntry ??= ResizeObserverEntry;
4552
+
4553
+ /** The topmost node at window point `x`, `y`, or null. */
4554
+ export function elementFromPoint(x, y) {
4555
+ return nodes.get(native.hit?.(Number(x), Number(y)) ?? 0) ?? null;
4556
+ }
4557
+
4558
+ /** Every node at window point `x`, `y`, topmost first. */
4559
+ export function elementsFromPoint(x, y) {
4560
+ const count = native.hits?.(Number(x), Number(y)) ?? 0;
4561
+ const list = [];
4562
+ for (let i = 0; i < count; i++) {
4563
+ const node = nodes.get(geometry(i));
4564
+ if (node) list.push(node);
4565
+ }
4566
+ return list;
4567
+ }
4568
+
4569
+ /** The text position at window point `x`, `y`: `{ offsetNode, offset, getClientRect() }` (UTF-16 offset), or null. */
4570
+ export function caretPositionFromPoint(x, y) {
4571
+ if (!native.caret?.(Number(x), Number(y))) return null;
4572
+ const offsetNode = nodes.get(geometry(0)) ?? null;
4573
+ const offset = geometry(1);
4574
+ const rect = new DOMRect(geometry(2), geometry(3), geometry(4), geometry(5));
4575
+ return { offsetNode, offset, getClientRect: () => rect };
4576
+ }
4577
+
4578
+ /**
4579
+ * The rectangles of the text from (`startNode`, `startOffset`) to (`endNode`, `endOffset`),
4580
+ * offsets in UTF-16 units as in a DOM `Range`: one per line piece, as `Range.getClientRects`.
4581
+ */
4582
+ export function rangeClientRects(startNode, startOffset, endNode, endOffset) {
4583
+ return readRects(native.rangeRects?.(startNode.nodeId, startOffset, endNode.nodeId, endOffset) ?? 0);
4584
+ }
4585
+
4586
+ /** The union of `rangeClientRects`, as `Range.getBoundingClientRect`. */
4587
+ export function rangeBoundingClientRect(startNode, startOffset, endNode, endOffset) {
4588
+ const rects = rangeClientRects(startNode, startOffset, endNode, endOffset);
4589
+ if (rects.length === 0) return new DOMRect();
4590
+ let left = Infinity, top = Infinity, right = -Infinity, bottom = -Infinity;
4591
+ for (const rect of rects) {
4592
+ left = Math.min(left, rect.left);
4593
+ top = Math.min(top, rect.top);
4594
+ right = Math.max(right, rect.right);
4595
+ bottom = Math.max(bottom, rect.bottom);
4596
+ }
4597
+ return new DOMRect(left, top, right - left, bottom - top);
4598
+ }
4599
+
4600
+ /**
4601
+ * `CSS.supports(property, value)` and `CSS.supports(conditionText)`, answered by the same parser
4602
+ * and property catalog as the tree's `@supports`, so a check here and an `@supports` block in a
4603
+ * stylesheet always agree. Also installed as `globalThis.CSS.supports`.
4604
+ */
4605
+ export function supports(conditionOrProperty, value) {
4606
+ if (!native.supports) return false;
4607
+ return arguments.length > 1 ? native.supports(String(conditionOrProperty), String(value)) : native.supports(String(conditionOrProperty));
4608
+ }
4609
+
4610
+ if (typeof globalThis.CSS !== "object" || globalThis.CSS === null) globalThis.CSS = {};
4611
+ globalThis.CSS.supports ??= supports;
4612
+
1946
4613
  let frameStatsSince = 0;
1947
4614
 
1948
4615
  /**