@silkui/core 0.1.8 → 0.1.9

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
@@ -19,14 +19,48 @@ const TYPES = [
19
19
  "keydown", "keyup", "focus", "blur", "input", "scroll", "layout", "pointercancel",
20
20
  "gotpointercapture", "lostpointercapture", "load", "error", "transitionrun", "transitionstart",
21
21
  "transitionend", "transitioncancel", "animationstart", "animationiteration", "animationend",
22
- "animationcancel", "selectionchange",
22
+ "animationcancel", "selectionchange", "pointerover", "pointerout", "touchstart", "touchmove",
23
+ "touchend", "touchcancel",
23
24
  ];
24
25
  const KIND_OF = new Map(TYPES.map((type, kind) => [type, kind]));
26
+
27
+ // The live `Range`s (see Range below), held weakly: a range nobody holds stops being updated.
28
+ const liveRanges = new Set();
29
+
30
+ function eachLiveRange(update) {
31
+ for (const ref of liveRanges) {
32
+ const range = ref.deref();
33
+ if (range) update(range);
34
+ else liveRanges.delete(ref);
35
+ }
36
+ }
37
+
25
38
  const CLICK = KIND_OF.get("click");
39
+ const SELECTION_CHANGE = KIND_OF.get("selectionchange");
40
+ const TOUCH_START = KIND_OF.get("touchstart");
41
+ // The tree has one listener flag for the four touch kinds.
42
+ const TOUCH_FLAG = 1 << 30;
43
+ // Compatibility mouse events, as the web fires them after pointer events: each listens
44
+ // through the pointer kind it follows.
45
+ const MOUSE_OF = new Map([
46
+ ["pointerdown", "mousedown"], ["pointerup", "mouseup"], ["pointermove", "mousemove"],
47
+ ["pointerover", "mouseover"], ["pointerout", "mouseout"], ["pointerenter", "mouseenter"],
48
+ ["pointerleave", "mouseleave"],
49
+ ]);
50
+ const POINTER_OF = new Map([...MOUSE_OF].map(([pointer, mouse]) => [mouse, pointer]));
51
+ // Types the tree reports through another kind's records: `selectstart` comes as a
52
+ // `SelectionChange` record at the node pressed.
53
+ const LISTENS_AS = new Map([...POINTER_OF, ["selectstart", "selectionchange"]]);
26
54
  // 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"]);
55
+ const NO_BUBBLE = new Set([
56
+ "pointerenter", "pointerleave", "mouseenter", "mouseleave", "focus", "blur", "scroll", "layout", "load",
57
+ "error",
58
+ ]);
59
+ // The tree has a default action to skip for these. Touch records say for themselves.
60
+ const CANCELABLE = new Set([
61
+ "pointerdown", "pointerup", "click", "wheel", "keydown", "keyup", "dragenter", "dragover", "drop",
62
+ "mousedown", "mouseup", "mousemove", "mouseover", "mouseout", "selectstart",
63
+ ]);
30
64
  // Files dragged from the desktop: the host dispatches these itself, so nodes need no flag.
31
65
  const DRAG_TYPES = new Set(["dragenter", "dragover", "dragleave", "drop"]);
32
66
 
@@ -151,6 +185,12 @@ class Look {
151
185
  for (const name in this.#values) css += cssName(name) + ":" + this.#values[name] + ";";
152
186
  return css;
153
187
  }
188
+
189
+ _copyTo(look) {
190
+ look.#values = Object.assign(Object.create(null), this.#values);
191
+ const css = this.cssText;
192
+ if (css) native.style(look.#node.nodeId, css, look.#state);
193
+ }
154
194
  }
155
195
 
156
196
  const CLASS_SPACE = /[\t\n\f\r ]/;
@@ -374,6 +414,8 @@ export class Node {
374
414
  #base = null;
375
415
  #looks = null;
376
416
  #flags = 0;
417
+ // Kinds the node hears whatever its listeners: an input keeps its value and selection current.
418
+ #kept = 0;
377
419
  #attributes = null;
378
420
  #classList = null;
379
421
 
@@ -408,6 +450,61 @@ export class Node {
408
450
  return siblings ? siblings[siblings.indexOf(this) - 1] ?? null : null;
409
451
  }
410
452
 
453
+ /** 1 for an element, 3 for text, 11 for a document fragment, as in the DOM. */
454
+ get nodeType() {
455
+ return 1;
456
+ }
457
+
458
+ hasChildNodes() {
459
+ return this.childNodes.length > 0;
460
+ }
461
+
462
+ /** A copy with the same looks and attributes, and with `deep` copies of the children. */
463
+ cloneNode(deep = false) {
464
+ const copy = this._shallowClone();
465
+ if (this.#base) this.#base._copyTo(copy.look("base"));
466
+ for (const state in this.#looks ?? {}) this.#looks[state]._copyTo(copy.look(state));
467
+ for (const [name, value] of this.#attributes ?? []) copy.setAttribute(name, value);
468
+ if (deep) for (const child of this.childNodes) copy.appendChild(child.cloneNode(true));
469
+ return copy;
470
+ }
471
+
472
+ _shallowClone() {
473
+ return new Node(this.kind);
474
+ }
475
+
476
+ /** Joins adjacent text children and drops empty ones, in the whole subtree. */
477
+ normalize() {
478
+ for (let node = this.firstChild; node; ) {
479
+ if (node.nodeType !== 3) {
480
+ node.normalize();
481
+ node = node.nextSibling;
482
+ continue;
483
+ }
484
+ let next = node.nextSibling;
485
+ if (node.length === 0) {
486
+ node.remove();
487
+ node = next;
488
+ continue;
489
+ }
490
+ let joined = "";
491
+ for (let sibling = next; sibling?.nodeType === 3; sibling = sibling.nextSibling) joined += sibling.data;
492
+ let length = node.length;
493
+ node.replaceData(length, 0, joined);
494
+ for (let current = next; current?.nodeType === 3; current = current.nextSibling) {
495
+ const index = indexIn(current);
496
+ eachLiveRange((range) => range._joined(current, node, length, index));
497
+ length += current.length;
498
+ }
499
+ while (next?.nodeType === 3) {
500
+ const after = next.nextSibling;
501
+ next.remove();
502
+ next = after;
503
+ }
504
+ node = next;
505
+ }
506
+ }
507
+
411
508
  /** Whether `other` is this node or inside it. */
412
509
  contains(other) {
413
510
  for (let node = other; node; node = node.parentNode) if (node === this) return true;
@@ -416,12 +513,25 @@ export class Node {
416
513
 
417
514
  /** Inserts `child` before `before`, or last without it. A child already in the tree moves. */
418
515
  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;
516
+ if (child.contains(this)) throw domError("HierarchyRequestError", "a node cannot be inserted into itself or its own subtree");
517
+ if (this.nodeType === 3) throw domError("HierarchyRequestError", "text has no children");
518
+ if (before && before.parentNode !== this) throw domError("NotFoundError", "the node to insert before is not a child of this node");
519
+ if (child.nodeType === 11) {
520
+ for (const node of [...child.childNodes]) this.insertBefore(node, before);
521
+ return child;
522
+ }
523
+ if (before === child) before = child.nextSibling;
422
524
  const old = child.parentNode;
423
- if (old) old.childNodes.splice(old.childNodes.indexOf(child), 1);
525
+ if (old) {
526
+ const index = old.childNodes.indexOf(child);
527
+ if (liveRanges.size) eachLiveRange((range) => range._removing(child, old, index));
528
+ old.childNodes.splice(index, 1);
529
+ }
424
530
  child.parentNode = this;
531
+ if (liveRanges.size) {
532
+ const index = before ? this.childNodes.indexOf(before) : this.childNodes.length;
533
+ eachLiveRange((range) => range._inserted(this, index));
534
+ }
425
535
  if (before) {
426
536
  this.childNodes.splice(this.childNodes.indexOf(before), 0, child);
427
537
  native.insertBefore(this.nodeId, child.nodeId, before.nodeId);
@@ -436,6 +546,17 @@ export class Node {
436
546
  return this.insertBefore(child, null);
437
547
  }
438
548
 
549
+ /** Puts `node` where `child` is and detaches `child`. */
550
+ replaceChild(node, child) {
551
+ if (child.parentNode !== this) throw domError("NotFoundError", "the node to replace is not a child of this node");
552
+ if (node === child) return child;
553
+ let before = child.nextSibling;
554
+ if (before === node) before = node.nextSibling;
555
+ this.removeChild(child);
556
+ this.insertBefore(node, before);
557
+ return child;
558
+ }
559
+
439
560
  /** Appends nodes, and strings as text nodes. */
440
561
  append(...children) {
441
562
  for (const child of children) this.insertBefore(typeof child === "string" ? createText(child) : child, null);
@@ -443,8 +564,10 @@ export class Node {
443
564
 
444
565
  /** Detaches `child` and its subtree. It keeps its state and can be inserted again. */
445
566
  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);
567
+ if (child.parentNode !== this) throw domError("NotFoundError", "the node to remove is not a child of this node");
568
+ const index = this.childNodes.indexOf(child);
569
+ if (liveRanges.size) eachLiveRange((range) => range._removing(child, this, index));
570
+ this.childNodes.splice(index, 1);
448
571
  child.parentNode = null;
449
572
  native.remove(child.nodeId);
450
573
  return child;
@@ -459,7 +582,9 @@ export class Node {
459
582
  if (rootNode && this.contains(rootNode)) { clearAdoptedSheets(); rootNode = null; }
460
583
  const parent = this.parentNode;
461
584
  if (parent) {
462
- parent.childNodes.splice(parent.childNodes.indexOf(this), 1);
585
+ const index = parent.childNodes.indexOf(this);
586
+ if (liveRanges.size) eachLiveRange((range) => range._removing(this, parent, index));
587
+ parent.childNodes.splice(index, 1);
463
588
  this.parentNode = null;
464
589
  }
465
590
  native.destroy(this.nodeId);
@@ -551,12 +676,27 @@ export class Node {
551
676
 
552
677
  // Tells the tree which events this node wants: its listeners', and clicks on a link.
553
678
  #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);
679
+ const has = (type) => (this.#listeners?.get(type)?.length ?? 0) > 0;
680
+ let wanted;
681
+ let bit;
682
+ if (kind >= TOUCH_START) {
683
+ wanted = TYPES.slice(TOUCH_START).some(has);
684
+ bit = TOUCH_FLAG;
685
+ } else {
686
+ const type = TYPES[kind];
687
+ wanted = has(type) || (MOUSE_OF.has(type) && has(MOUSE_OF.get(type))) || (kind === CLICK && this._href)
688
+ || (kind === SELECTION_CHANGE && has("selectstart"));
689
+ bit = 1 << kind;
690
+ }
691
+ const flags = (wanted ? this.#flags | bit : this.#flags & ~bit) | this.#kept;
557
692
  if (flags !== this.#flags) native.listen(this.nodeId, (this.#flags = flags));
558
693
  }
559
694
 
695
+ _keep(...types) {
696
+ for (const type of types) this.#kept |= 1 << KIND_OF.get(type);
697
+ this.#want(KIND_OF.get(types[0]));
698
+ }
699
+
560
700
  set tabIndex(value) {
561
701
  native.attribute(this.nodeId, "tabIndex", value);
562
702
  }
@@ -569,12 +709,114 @@ export class Node {
569
709
  native.focus(this.nodeId);
570
710
  }
571
711
 
712
+ /**
713
+ * Sends the pointer's records here until it lifts, as DOM `setPointerCapture`. Throws
714
+ * `NotFoundError` for a pointer that is not down. The tree moves the capture of the
715
+ * primary pointer; another finger keeps sending to the node it went down on.
716
+ */
717
+ setPointerCapture(pointerId) {
718
+ const pointer = pointers.get(pointerId);
719
+ if (!pointer) throw domError("NotFoundError", `no active pointer with id ${pointerId}`);
720
+ if (!pointer.buttons) return;
721
+ pointer.capture = this;
722
+ if (pointer.primary) native.capture(this.nodeId);
723
+ }
724
+
725
+ releasePointerCapture(pointerId) {
726
+ const pointer = pointers.get(pointerId);
727
+ if (!pointer) throw domError("NotFoundError", `no active pointer with id ${pointerId}`);
728
+ if (pointer.capture !== this) return;
729
+ pointer.capture = null;
730
+ if (pointer.primary) native.capture(0);
731
+ }
732
+
733
+ hasPointerCapture(pointerId) {
734
+ return pointers.get(pointerId)?.capture === this;
735
+ }
736
+
737
+ /** `scrollTo(x, y)` or `scrollTo({ left, top, behavior })`; `behavior: "smooth"` animates, and `auto` follows `scroll-behavior`. */
572
738
  scrollTo(x, y) {
573
- native.scrollTo(this.nodeId, x, y);
739
+ scrollNode(this.nodeId, x, y, 0);
574
740
  }
575
741
 
576
742
  scroll(x, y) {
577
- native.scrollTo(this.nodeId, x, y);
743
+ scrollNode(this.nodeId, x, y, 0);
744
+ }
745
+
746
+ /** As `scrollTo`, by an amount from where the node is scrolled. */
747
+ scrollBy(x, y) {
748
+ scrollNode(this.nodeId, x, y, 4);
749
+ }
750
+
751
+ /** The border box in window coordinates, after any pending layout, as on the web. */
752
+ getBoundingClientRect() {
753
+ return readRect(this.nodeId);
754
+ }
755
+
756
+ /** One rectangle per fragment (a wrapped inline box has one per line). */
757
+ getClientRects() {
758
+ return readRects(native.rects?.(this.nodeId) ?? 0);
759
+ }
760
+
761
+ get clientLeft() { return metric(this.nodeId, 0); }
762
+ get clientTop() { return metric(this.nodeId, 1); }
763
+ get clientWidth() { return metric(this.nodeId, 2); }
764
+ get clientHeight() { return metric(this.nodeId, 3); }
765
+ get scrollWidth() { return metric(this.nodeId, 4); }
766
+ get scrollHeight() { return metric(this.nodeId, 5); }
767
+ get scrollLeft() { return metric(this.nodeId, 6); }
768
+ set scrollLeft(value) { scrollNode(this.nodeId, { left: value }, undefined, 0); }
769
+ get scrollTop() { return metric(this.nodeId, 7); }
770
+ set scrollTop(value) { scrollNode(this.nodeId, { top: value }, undefined, 0); }
771
+ get offsetParent() { return nodes.get(metric(this.nodeId, 8)) ?? null; }
772
+ get offsetLeft() { return metric(this.nodeId, 9); }
773
+ get offsetTop() { return metric(this.nodeId, 10); }
774
+ get offsetWidth() { return metric(this.nodeId, 11); }
775
+ get offsetHeight() { return metric(this.nodeId, 12); }
776
+
777
+ /**
778
+ * Scrolls every scroll container around this node to show it, as on the web: `true` or
779
+ * nothing aligns to the start, `false` to the end, or `{ block, inline, behavior }`.
780
+ * `scroll-margin`, `scroll-padding` and `scroll-snap` apply.
781
+ */
782
+ scrollIntoView(options = true) {
783
+ if (options === null || typeof options !== "object") {
784
+ const top = options !== false;
785
+ native.scrollIntoView?.(this.nodeId, top ? 0 : 2, 3, 0, 0);
786
+ return;
787
+ }
788
+ native.scrollIntoView?.(this.nodeId, alignment(options.block, 0), alignment(options.inline, 3), BEHAVIORS[options.behavior] ?? 0, 0);
789
+ }
790
+
791
+ /** WebKit's: scrolls only containers that do not already show the node, centering it unless `center` is false. */
792
+ scrollIntoViewIfNeeded(center = true) {
793
+ const code = center ? 1 : 3;
794
+ native.scrollIntoView?.(this.nodeId, code, code, 0, 1);
795
+ }
796
+
797
+ /** Whether this node matches CSS `selector`, by the same matcher as stylesheets. */
798
+ matches(selector) {
799
+ return queried(0, this, selector) === 1;
800
+ }
801
+
802
+ webkitMatchesSelector(selector) {
803
+ return this.matches(selector);
804
+ }
805
+
806
+ /** This node or its nearest ancestor that matches `selector`, or null. */
807
+ closest(selector) {
808
+ return nodes.get(queried(1, this, selector)) ?? null;
809
+ }
810
+
811
+ /** The first descendant, in tree order, that matches `selector`, or null. */
812
+ querySelector(selector) {
813
+ return nodes.get(queried(2, this, selector)) ?? null;
814
+ }
815
+
816
+ /** Every descendant that matches `selector`, in tree order: a static list. */
817
+ querySelectorAll(selector) {
818
+ const ids = queried(3, this, selector);
819
+ return typeof ids === "string" && ids !== "" ? ids.split(",").map((id) => nodes.get(Number(id))).filter(Boolean) : [];
578
820
  }
579
821
 
580
822
  /**
@@ -583,8 +825,9 @@ export class Node {
583
825
  * app's own, sent with `dispatchEvent`.
584
826
  */
585
827
  addEventListener(type, listener, options) {
586
- if (listener == null) return;
587
- const kind = KIND_OF.get(type);
828
+ const signal = options?.signal;
829
+ if (listener == null || signal?.aborted) return;
830
+ const kind = KIND_OF.get(LISTENS_AS.get(type) ?? type);
588
831
  const capture = options === true || !!options?.capture;
589
832
  this.#listeners ??= new Map();
590
833
  let list = this.#listeners.get(type);
@@ -592,6 +835,7 @@ export class Node {
592
835
  if (list.some((entry) => entry.listener === listener && entry.capture === capture)) return;
593
836
  list.push({ listener, capture, once: !!options?.once });
594
837
  if (kind !== undefined) this.#want(kind);
838
+ signal?.addEventListener("abort", () => this.removeEventListener(type, listener, capture), { once: true });
595
839
  }
596
840
 
597
841
  removeEventListener(type, listener, options) {
@@ -601,7 +845,7 @@ export class Node {
601
845
  const index = list.findIndex((entry) => entry.listener === listener && entry.capture === capture);
602
846
  if (index < 0) return;
603
847
  list.splice(index, 1);
604
- const kind = KIND_OF.get(type);
848
+ const kind = KIND_OF.get(LISTENS_AS.get(type) ?? type);
605
849
  if (kind !== undefined) this.#want(kind);
606
850
  }
607
851
 
@@ -643,11 +887,19 @@ export class Text extends Node {
643
887
  }
644
888
 
645
889
  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);
890
+ this.replaceData(0, this.#data.length, value == null ? "" : value);
891
+ }
892
+
893
+ get nodeType() {
894
+ return 3;
895
+ }
896
+
897
+ get nodeValue() {
898
+ return this.#data;
899
+ }
900
+
901
+ set nodeValue(value) {
902
+ this.data = value;
651
903
  }
652
904
 
653
905
  get textContent() {
@@ -657,16 +909,89 @@ export class Text extends Node {
657
909
  set textContent(value) {
658
910
  this.data = value;
659
911
  }
912
+
913
+ get length() {
914
+ return this.#data.length;
915
+ }
916
+
917
+ _shallowClone() {
918
+ return new Text(this.#data);
919
+ }
920
+
921
+ substringData(offset, count) {
922
+ offset = offset >>> 0;
923
+ if (offset > this.#data.length) throw domError("IndexSizeError", "the offset is past the end of the text");
924
+ return this.#data.substring(offset, offset + (count >>> 0));
925
+ }
926
+
927
+ appendData(data) {
928
+ this.replaceData(this.#data.length, 0, data);
929
+ }
930
+
931
+ insertData(offset, data) {
932
+ this.replaceData(offset, 0, data);
933
+ }
934
+
935
+ deleteData(offset, count) {
936
+ this.replaceData(offset, count, "");
937
+ }
938
+
939
+ replaceData(offset, count, data) {
940
+ offset = offset >>> 0;
941
+ count = count >>> 0;
942
+ data = String(data);
943
+ const old = this.#data;
944
+ if (offset > old.length) throw domError("IndexSizeError", "the offset is past the end of the text");
945
+ if (offset + count > old.length) count = old.length - offset;
946
+ if (liveRanges.size) eachLiveRange((range) => range._replaced(this, offset, count, data.length));
947
+ const value = old.slice(0, offset) + data + old.slice(offset + count);
948
+ if (value === old && value !== "") return;
949
+ this.#data = value;
950
+ native.setText(this.nodeId, value);
951
+ if (this._svgText) svgChanged(this);
952
+ }
953
+
954
+ /** Splits at `offset`: this keeps the text before it, and a new next sibling the rest. */
955
+ splitText(offset) {
956
+ offset = offset >>> 0;
957
+ const length = this.#data.length;
958
+ if (offset > length) throw domError("IndexSizeError", "the offset is past the end of the text");
959
+ const rest = new Text(this.#data.slice(offset));
960
+ const parent = this.parentNode;
961
+ if (parent) {
962
+ parent.insertBefore(rest, this.nextSibling);
963
+ const index = indexIn(this);
964
+ if (liveRanges.size) eachLiveRange((range) => range._split(this, rest, offset, parent, index));
965
+ }
966
+ this.replaceData(offset, length - offset, "");
967
+ return rest;
968
+ }
660
969
  }
661
970
 
662
- /** An editable text field. `value` follows what the user types. */
971
+ /**
972
+ * An editable text field. `value` follows what the user types. Selection offsets are UTF-16
973
+ * string indices, as on the web; the tree counts UTF-8 bytes, converted here.
974
+ */
663
975
  export class Input extends Node {
664
976
  #value = "";
977
+ #start = 0;
978
+ #end = 0;
979
+ #direction = "forward";
665
980
 
666
981
  constructor() {
667
982
  super("input");
668
- this.selectionStart = 0;
669
- this.selectionEnd = 0;
983
+ this._keep("input", "selectionchange");
984
+ }
985
+
986
+ /** The text the selection offsets index into. */
987
+ _text() {
988
+ return this.#value;
989
+ }
990
+
991
+ _shallowClone() {
992
+ const copy = new this.constructor();
993
+ copy.value = this.#value;
994
+ return copy;
670
995
  }
671
996
 
672
997
  get value() {
@@ -674,27 +999,135 @@ export class Input extends Node {
674
999
  }
675
1000
 
676
1001
  set value(value) {
677
- this.#value = String(value);
678
- native.setText(this.nodeId, this.#value);
1002
+ value = String(value);
1003
+ if (value === this.#value) return;
1004
+ this.#value = value;
1005
+ native.setText(this.nodeId, value);
1006
+ this.#start = this.#end = value.length;
1007
+ this.#direction = "forward";
1008
+ }
1009
+
1010
+ get selectionStart() {
1011
+ return this.#start;
1012
+ }
1013
+
1014
+ set selectionStart(value) {
1015
+ const start = clampIndex(value, this._text().length);
1016
+ this.setSelectionRange(start, Math.max(start, this.#end), this.#direction);
1017
+ }
1018
+
1019
+ get selectionEnd() {
1020
+ return this.#end;
1021
+ }
1022
+
1023
+ set selectionEnd(value) {
1024
+ this.setSelectionRange(this.#start, clampIndex(value, this._text().length), this.#direction);
1025
+ }
1026
+
1027
+ get selectionDirection() {
1028
+ return this.#direction;
1029
+ }
1030
+
1031
+ set selectionDirection(value) {
1032
+ this.setSelectionRange(this.#start, this.#end, value);
679
1033
  }
680
1034
 
681
- /** Selects from `anchor` to `focus`, as UTF-8 byte offsets in the value. */
682
- setSelectionRange(anchor, focus) {
1035
+ /** Selects `start` to `end`; with `direction` "backward" the caret sits at `start`. */
1036
+ setSelectionRange(start, end, direction = "none") {
1037
+ const text = this._text();
1038
+ end = clampIndex(end, text.length);
1039
+ start = Math.min(clampIndex(start, text.length), end);
1040
+ const backward = direction === "backward";
1041
+ this.#start = start;
1042
+ this.#end = end;
1043
+ this.#direction = backward ? "backward" : "forward";
1044
+ const anchor = byteOf(text, backward ? end : start);
1045
+ const focus = byteOf(text, backward ? start : end);
683
1046
  native.select(this.nodeId, anchor, focus);
684
1047
  }
685
1048
 
1049
+ /** Selects the whole value. */
1050
+ select() {
1051
+ this.setSelectionRange(0, this._text().length);
1052
+ }
1053
+
1054
+ /**
1055
+ * Replaces `start` to `end` (the selection by default) with `replacement`. `selectionMode`
1056
+ * is "select", "start", "end" or "preserve", as on the web.
1057
+ */
1058
+ setRangeText(replacement, start, end, selectionMode = "preserve") {
1059
+ replacement = String(replacement);
1060
+ const text = this._text();
1061
+ if (start === undefined) {
1062
+ start = this.#start;
1063
+ end = this.#end;
1064
+ } else if (end === undefined) {
1065
+ throw new TypeError("setRangeText needs both start and end");
1066
+ } else if (Number(start) > Number(end)) {
1067
+ throw domError("IndexSizeError", "setRangeText: start is after end");
1068
+ }
1069
+ start = clampIndex(start, text.length);
1070
+ end = clampIndex(end, text.length);
1071
+ let selectionStart = this.#start;
1072
+ let selectionEnd = this.#end;
1073
+ const delta = replacement.length - (end - start);
1074
+ const newEnd = start + replacement.length;
1075
+ if (selectionMode === "select") {
1076
+ selectionStart = start;
1077
+ selectionEnd = newEnd;
1078
+ } else if (selectionMode === "start") {
1079
+ selectionStart = selectionEnd = start;
1080
+ } else if (selectionMode === "end") {
1081
+ selectionStart = selectionEnd = newEnd;
1082
+ } else {
1083
+ if (selectionStart > end) selectionStart += delta;
1084
+ else if (selectionStart > start) selectionStart = start;
1085
+ if (selectionEnd > end) selectionEnd += delta;
1086
+ else if (selectionEnd > start) selectionEnd = newEnd;
1087
+ }
1088
+ const direction = this.#direction;
1089
+ this._replace(start, end, replacement);
1090
+ this.setSelectionRange(selectionStart, selectionEnd, direction);
1091
+ }
1092
+
1093
+ _replace(start, end, replacement) {
1094
+ const text = this.#value;
1095
+ this.value = text.slice(0, start) + replacement + text.slice(end);
1096
+ }
1097
+
1098
+ // From the tree: the value and selection in UTF-8 bytes.
686
1099
  _changed(value, anchor, focus) {
687
1100
  this.#value = value;
688
- this.selectionStart = Math.min(anchor, focus);
689
- this.selectionEnd = Math.max(anchor, focus);
1101
+ this.#take(byteIndex(value, anchor), byteIndex(value, focus));
690
1102
  }
691
1103
 
692
1104
  _selected(start, end) {
693
- this.selectionStart = start;
694
- this.selectionEnd = end;
1105
+ const text = this._text();
1106
+ this.#take(byteIndex(text, start), byteIndex(text, end));
1107
+ }
1108
+
1109
+ // The tree reports the low and high offsets only, so a selection it changed reads forward
1110
+ // unless it is the one set here.
1111
+ #take(a, b) {
1112
+ const start = Math.min(a, b);
1113
+ const end = Math.max(a, b);
1114
+ if (start === this.#start && end === this.#end) return;
1115
+ this.#start = start;
1116
+ this.#end = end;
1117
+ this.#direction = "forward";
695
1118
  }
696
1119
  }
697
1120
 
1121
+ function clampIndex(value, length) {
1122
+ const number = Math.trunc(Number(value)) || 0;
1123
+ return Math.min(Math.max(number, 0), length);
1124
+ }
1125
+
1126
+ // A UTF-8 offset from the tree as a string index; NaN and missing read as 0.
1127
+ function byteIndex(text, byte) {
1128
+ return indexOf(text, Number(byte) || 0);
1129
+ }
1130
+
698
1131
  // Inline SVG markup as icon resources: identical markup shares one, freed when no `<svg>`
699
1132
  // shows it. The ids start high, clear of resources a host or a URL table numbers from 1.
700
1133
  const ICONS = new Map();
@@ -772,6 +1205,10 @@ export class Image extends Node {
772
1205
  if (this.#src) dropAddress(this.#src);
773
1206
  this.#src = "";
774
1207
  }
1208
+
1209
+ _shallowClone() {
1210
+ return new Image(this.#src);
1211
+ }
775
1212
  }
776
1213
 
777
1214
  const SVG_NAMESPACE = "http://www.w3.org/2000/svg";
@@ -1060,6 +1497,10 @@ export class Svg extends Node {
1060
1497
  svgChanged(this);
1061
1498
  }
1062
1499
 
1500
+ _shallowClone() {
1501
+ return new Svg();
1502
+ }
1503
+
1063
1504
  getAttribute(name) {
1064
1505
  return treeAttribute(String(name)) ? super.getAttribute(name) : this.#attributes.get(svgName(name)) ?? null;
1065
1506
  }
@@ -1242,6 +1683,12 @@ export class RichInput extends Input {
1242
1683
  return this.#document;
1243
1684
  }
1244
1685
 
1686
+ _shallowClone() {
1687
+ const copy = new RichInput();
1688
+ copy.document = this.#document;
1689
+ return copy;
1690
+ }
1691
+
1245
1692
  /** Replaces the document. The caret goes to the end and the undo history is forgotten. */
1246
1693
  set document(document) {
1247
1694
  const text = String(document?.text ?? "");
@@ -1257,7 +1704,8 @@ export class RichInput extends Input {
1257
1704
  let packedAtoms = "";
1258
1705
  for (const atom of atoms) packedAtoms += this.#packAtom(atom);
1259
1706
  native.richText(this.nodeId, text, packedMarks, packedAtoms);
1260
- super._changed(text, text.length, text.length);
1707
+ const end = byteOf(text, text.length);
1708
+ super._changed(text, end, end);
1261
1709
  }
1262
1710
 
1263
1711
  #packAtom(atom) {
@@ -1280,13 +1728,32 @@ export class RichInput extends Input {
1280
1728
  native.insertAtom(this.nodeId, byteOf(text, start), byteOf(text, end), this.#packAtom(atom));
1281
1729
  }
1282
1730
 
1283
- setSelectionRange(anchor, focus) {
1284
- const text = this.#document.text;
1285
- native.select(this.nodeId, byteOf(text, anchor), byteOf(text, focus));
1731
+ // Marks around the range stay, shifted; the replacement takes none. Atoms in the range go,
1732
+ // and OBJECT characters in the replacement become U+FFFD, since they would name no atom.
1733
+ _replace(start, end, replacement) {
1734
+ const { text, marks, atoms } = this.#document;
1735
+ replacement = replacement.replaceAll(OBJECT, "\ufffd");
1736
+ const delta = replacement.length - (end - start);
1737
+ const shift = (index, inside) => (index <= start ? index : index >= end ? index + delta : inside);
1738
+ const spans = [];
1739
+ for (const span of marks) {
1740
+ const from = shift(span.start, start + replacement.length);
1741
+ const to = shift(span.end, start);
1742
+ if (to > from) spans.push({ start: from, end: to, marks: span.marks });
1743
+ }
1744
+ let before = 0;
1745
+ let inside = 0;
1746
+ for (let i = 0; i < end; i++) {
1747
+ if (text[i] !== OBJECT) continue;
1748
+ if (i < start) before++;
1749
+ else inside++;
1750
+ }
1751
+ const kept = atoms.slice(0, before).concat(atoms.slice(before + inside));
1752
+ this.document = { text: text.slice(0, start) + replacement + text.slice(end), marks: spans, atoms: kept };
1286
1753
  }
1287
1754
 
1288
1755
  _changed(value, anchor, focus, marks, atoms, active) {
1289
- super._changed(value, indexOf(value, anchor), indexOf(value, focus));
1756
+ super._changed(value, anchor, focus);
1290
1757
  if (marks === undefined) return;
1291
1758
  const spans = [];
1292
1759
  for (const part of String(marks).split(";")) {
@@ -1304,8 +1771,7 @@ export class RichInput extends Input {
1304
1771
  }
1305
1772
 
1306
1773
  _selected(start, end, active) {
1307
- const text = this.#document.text;
1308
- super._selected(indexOf(text, start), indexOf(text, end));
1774
+ super._selected(start, end);
1309
1775
  this.activeMarks = this.#names(active ?? 0);
1310
1776
  }
1311
1777
  }
@@ -1363,100 +1829,959 @@ export function createInput(style) {
1363
1829
  return input;
1364
1830
  }
1365
1831
 
1366
- let rootNode = null;
1367
-
1368
- /** Makes `node` the root of the window's tree. */
1369
1832
  /**
1370
- * Defines `@keyframes name` as CSS would: `{ from: { opacity: 0 }, "50%": {...}, to: {...} }`,
1371
- * with selectors such as `"0%, 100%"` too. Style objects name it in `animation` or
1372
- * `animationName`. Defining a name again replaces its rule; `null` removes it.
1833
+ * Nodes held together outside the tree, as the DOM's `DocumentFragment`. Inserting it
1834
+ * inserts its children, in order, and leaves it empty.
1373
1835
  */
1374
- export function defineKeyframes(name, frames) {
1375
- for (const selector of Object.keys(frames ?? {})) {
1376
- let css = "";
1377
- const declarations = frames[selector];
1378
- for (const property of Object.keys(declarations)) {
1379
- const value = declarations[property];
1380
- if (value === null || value === undefined || value === "") continue;
1381
- css += cssName(property) + ":" + cssValue(property, value) + ";";
1382
- }
1383
- for (const part of selector.split(",")) {
1384
- const text = part.trim().toLowerCase();
1385
- const offset = text === "from" ? 0 : text === "to" ? 1 : parseFloat(text) / 100;
1386
- if (!(offset >= 0 && offset <= 1)) throw new Error(`@silkui/core: bad keyframe selector '${part}'`);
1387
- native.keyframe(offset, css);
1388
- }
1836
+ export class DocumentFragment extends Node {
1837
+ constructor() {
1838
+ super("box");
1839
+ }
1840
+
1841
+ get nodeType() {
1842
+ return 11;
1843
+ }
1844
+
1845
+ _shallowClone() {
1846
+ return new DocumentFragment();
1389
1847
  }
1390
- native.keyframes(String(name));
1391
1848
  }
1392
1849
 
1393
- export function mount(node) {
1394
- if (rootNode) clearAdoptedSheets();
1395
- rootNode = node;
1396
- native.root(node.nodeId);
1397
- syncAdoptedSheets();
1850
+ export function createDocumentFragment() {
1851
+ return new DocumentFragment();
1852
+ }
1853
+
1854
+ // Ranges, as the DOM Standard defines them, over the nodes of this module. Every change to
1855
+ // the tree passes through these nodes, so live ranges follow it here, with no native calls.
1856
+
1857
+ function nodeLength(node) {
1858
+ return node.nodeType === 3 ? node.length : node.childNodes.length;
1859
+ }
1860
+
1861
+ function indexIn(node) {
1862
+ return node.parentNode ? node.parentNode.childNodes.indexOf(node) : 0;
1863
+ }
1864
+
1865
+ function rootOf(node) {
1866
+ while (node.parentNode) node = node.parentNode;
1398
1867
  return node;
1399
1868
  }
1400
1869
 
1401
- export function root() {
1402
- return rootNode;
1870
+ function isInclusiveAncestor(ancestor, node) {
1871
+ for (; node; node = node.parentNode) if (node === ancestor) return true;
1872
+ return false;
1403
1873
  }
1404
1874
 
1405
- // The live regions `announce` speaks through, one per politeness, made on first use.
1406
- const regions = Object.create(null);
1407
- // A box screen readers read and nothing shows, as the web's visually hidden pattern.
1408
- const VISUALLY_HIDDEN = {
1409
- position: "absolute",
1410
- width: 1,
1411
- height: 1,
1412
- margin: -1,
1413
- overflow: "hidden",
1414
- clipPath: "inset(50%)",
1415
- whiteSpace: "nowrap",
1416
- pointerEvents: "none",
1417
- };
1875
+ // -1 when `a` comes before `b` in tree order, 1 after, 0 the same node. One root.
1876
+ function treeOrder(a, b) {
1877
+ if (a === b) return 0;
1878
+ const up = [];
1879
+ for (let node = a; node; node = node.parentNode) up.push(node);
1880
+ const other = [];
1881
+ for (let node = b; node; node = node.parentNode) other.push(node);
1882
+ let i = up.length - 1;
1883
+ let j = other.length - 1;
1884
+ while (i >= 0 && j >= 0 && up[i] === other[j]) {
1885
+ i--;
1886
+ j--;
1887
+ }
1888
+ if (i < 0) return -1;
1889
+ if (j < 0) return 1;
1890
+ const siblings = up[i + 1].childNodes;
1891
+ return siblings.indexOf(up[i]) < siblings.indexOf(other[j]) ? -1 : 1;
1892
+ }
1418
1893
 
1419
- /**
1420
- * Has screen readers say `message` without showing it, as a toast or a "Saved" would. Polite
1421
- * messages wait for the reader to finish; `{ politeness: "assertive" }` interrupts it. The
1422
- * same message twice is said twice. Nothing happens before `mount`.
1423
- */
1424
- export function announce(message, { politeness = "polite" } = {}) {
1425
- if (!rootNode) return;
1426
- const key = politeness === "assertive" ? "assertive" : "polite";
1427
- let region = regions[key];
1428
- if (!region || region.parentNode !== rootNode) {
1429
- region = regions[key] = createBox(VISUALLY_HIDDEN);
1430
- region.setAttribute("aria-live", key);
1431
- region.setAttribute("aria-atomic", "true");
1432
- rootNode.appendChild(region);
1894
+ // The position of boundary point (a, aOffset) relative to (b, bOffset): -1 before, 0 equal,
1895
+ // 1 after. Both are in one tree.
1896
+ function comparePoints(a, aOffset, b, bOffset) {
1897
+ if (a === b) return aOffset === bOffset ? 0 : aOffset < bOffset ? -1 : 1;
1898
+ if (treeOrder(a, b) > 0) return -comparePoints(b, bOffset, a, aOffset);
1899
+ if (isInclusiveAncestor(a, b)) {
1900
+ let child = b;
1901
+ while (child.parentNode !== a) child = child.parentNode;
1902
+ if (indexIn(child) < aOffset) return 1;
1433
1903
  }
1434
- // A region announces changes, not what it holds when it appears, so the text waits a
1435
- // moment; each message is a node of its own so a repeat is a change too.
1436
- setTimeout(() => {
1437
- if (region.parentNode !== rootNode) return;
1438
- for (const child of region.childNodes.slice()) child.destroy();
1439
- const text = createText(String(message));
1440
- region.appendChild(text);
1441
- setTimeout(() => {
1442
- if (text.parentNode === region) text.destroy();
1443
- }, ANNOUNCEMENT_LIFETIME);
1444
- }, ANNOUNCEMENT_DELAY);
1904
+ return -1;
1445
1905
  }
1446
1906
 
1447
- const ANNOUNCEMENT_DELAY = 100;
1448
- const ANNOUNCEMENT_LIFETIME = 7000;
1907
+ // The next node in tree order inside `within`, or null.
1908
+ function following(node, within, skipChildren = false) {
1909
+ if (!skipChildren && node.childNodes.length) return node.childNodes[0];
1910
+ for (; node && node !== within; node = node.parentNode) {
1911
+ const next = node.nextSibling;
1912
+ if (next) return next;
1913
+ }
1914
+ return null;
1915
+ }
1449
1916
 
1450
- /** The node with tree id `id`, for hosts and tools. */
1451
- export function nodeById(id) {
1452
- return nodes.get(id) ?? null;
1917
+ function checkNode(node, what) {
1918
+ if (!(node instanceof Node)) throw new TypeError(what + " is not a node");
1919
+ return node;
1453
1920
  }
1454
1921
 
1455
- // The option bits of `__ui.markdown`.
1456
- const MARKDOWN_FLAGS = { tables: 1, strikethrough: 2, taskLists: 4, autolinkLiterals: 8, footnotes: 16, frontmatter: 32, alerts: 64 };
1457
- const GFM = 1 | 2 | 4 | 8;
1922
+ /** The fields every range has: two boundary points. */
1923
+ export class AbstractRange {
1924
+ constructor() {
1925
+ if (new.target === AbstractRange) throw new TypeError("Illegal constructor");
1926
+ }
1458
1927
 
1459
- /**
1928
+ get startContainer() {
1929
+ return this._startNode;
1930
+ }
1931
+
1932
+ get startOffset() {
1933
+ return this._startOffset;
1934
+ }
1935
+
1936
+ get endContainer() {
1937
+ return this._endNode;
1938
+ }
1939
+
1940
+ get endOffset() {
1941
+ return this._endOffset;
1942
+ }
1943
+
1944
+ get collapsed() {
1945
+ return this._startNode === this._endNode && this._startOffset === this._endOffset;
1946
+ }
1947
+ }
1948
+
1949
+ /** A range that does not follow changes to the tree, and is not checked when made. */
1950
+ export class StaticRange extends AbstractRange {
1951
+ constructor(init) {
1952
+ super();
1953
+ if (init == null || typeof init !== "object") throw new TypeError("StaticRange needs its four members");
1954
+ for (const key of ["startContainer", "startOffset", "endContainer", "endOffset"]) {
1955
+ if (init[key] === undefined) throw new TypeError("StaticRange needs " + key);
1956
+ }
1957
+ this._startNode = checkNode(init.startContainer, "startContainer");
1958
+ this._startOffset = init.startOffset >>> 0;
1959
+ this._endNode = checkNode(init.endContainer, "endContainer");
1960
+ this._endOffset = init.endOffset >>> 0;
1961
+ }
1962
+ }
1963
+
1964
+ // The node a new range starts in: the mounted root, else a detached one of its own.
1965
+ let rangeHome = null;
1966
+
1967
+ /** A live range: it follows insertions, removals and text changes, as on the web. */
1968
+ export class Range extends AbstractRange {
1969
+ static START_TO_START = 0;
1970
+ static START_TO_END = 1;
1971
+ static END_TO_END = 2;
1972
+ static END_TO_START = 3;
1973
+
1974
+ constructor() {
1975
+ super();
1976
+ const home = rootNode ?? (rangeHome ??= new Node("box"));
1977
+ this._startNode = this._endNode = home;
1978
+ this._startOffset = this._endOffset = 0;
1979
+ liveRanges.add(new WeakRef(this));
1980
+ }
1981
+
1982
+ get commonAncestorContainer() {
1983
+ let container = this._startNode;
1984
+ while (!isInclusiveAncestor(container, this._endNode)) container = container.parentNode;
1985
+ return container;
1986
+ }
1987
+
1988
+ // Called after the boundary points change; a selection's range tells the tree.
1989
+ _changed() {}
1990
+
1991
+ #set(node, offset, start) {
1992
+ checkNode(node, "the container");
1993
+ offset = offset >>> 0;
1994
+ if (offset > nodeLength(node)) throw domError("IndexSizeError", "the offset is past the end of the node");
1995
+ if (start) {
1996
+ if (rootOf(node) !== rootOf(this._startNode) || comparePoints(node, offset, this._endNode, this._endOffset) > 0) {
1997
+ this._endNode = node;
1998
+ this._endOffset = offset;
1999
+ }
2000
+ this._startNode = node;
2001
+ this._startOffset = offset;
2002
+ } else {
2003
+ if (rootOf(node) !== rootOf(this._startNode) || comparePoints(node, offset, this._startNode, this._startOffset) < 0) {
2004
+ this._startNode = node;
2005
+ this._startOffset = offset;
2006
+ }
2007
+ this._endNode = node;
2008
+ this._endOffset = offset;
2009
+ }
2010
+ this._changed();
2011
+ }
2012
+
2013
+ setStart(node, offset) {
2014
+ this.#set(node, offset, true);
2015
+ }
2016
+
2017
+ setEnd(node, offset) {
2018
+ this.#set(node, offset, false);
2019
+ }
2020
+
2021
+ /** One rectangle per line piece of the range, from the tree's last layout (laid out first if something changed). */
2022
+ getClientRects() {
2023
+ return rangeClientRects(this._startNode, this._startOffset, this._endNode, this._endOffset);
2024
+ }
2025
+
2026
+ getBoundingClientRect() {
2027
+ return rangeBoundingClientRect(this._startNode, this._startOffset, this._endNode, this._endOffset);
2028
+ }
2029
+
2030
+ setStartBefore(node) {
2031
+ this.#set(parentOf(node), indexIn(node), true);
2032
+ }
2033
+
2034
+ setStartAfter(node) {
2035
+ this.#set(parentOf(node), indexIn(node) + 1, true);
2036
+ }
2037
+
2038
+ setEndBefore(node) {
2039
+ this.#set(parentOf(node), indexIn(node), false);
2040
+ }
2041
+
2042
+ setEndAfter(node) {
2043
+ this.#set(parentOf(node), indexIn(node) + 1, false);
2044
+ }
2045
+
2046
+ collapse(toStart = false) {
2047
+ if (toStart) {
2048
+ this._endNode = this._startNode;
2049
+ this._endOffset = this._startOffset;
2050
+ } else {
2051
+ this._startNode = this._endNode;
2052
+ this._startOffset = this._endOffset;
2053
+ }
2054
+ this._changed();
2055
+ }
2056
+
2057
+ selectNode(node) {
2058
+ const parent = parentOf(node);
2059
+ const index = indexIn(node);
2060
+ this.#select(parent, index, parent, index + 1);
2061
+ }
2062
+
2063
+ selectNodeContents(node) {
2064
+ checkNode(node, "the node");
2065
+ this.#select(node, 0, node, nodeLength(node));
2066
+ }
2067
+
2068
+ #select(startNode, startOffset, endNode, endOffset) {
2069
+ this._startNode = startNode;
2070
+ this._startOffset = startOffset;
2071
+ this._endNode = endNode;
2072
+ this._endOffset = endOffset;
2073
+ this._changed();
2074
+ }
2075
+
2076
+ compareBoundaryPoints(how, sourceRange) {
2077
+ how = Number(how) & 0xffff;
2078
+ if (how > 3) throw domError("NotSupportedError", "compareBoundaryPoints takes 0 to 3");
2079
+ if (!(sourceRange instanceof Range)) throw new TypeError("compareBoundaryPoints takes a Range");
2080
+ if (rootOf(this._startNode) !== rootOf(sourceRange._startNode)) throw domError("WrongDocumentError", "the ranges are in different trees");
2081
+ const thisStart = how === 0 || how === 3;
2082
+ const otherStart = how === 0 || how === 1;
2083
+ return comparePoints(
2084
+ thisStart ? this._startNode : this._endNode,
2085
+ thisStart ? this._startOffset : this._endOffset,
2086
+ otherStart ? sourceRange._startNode : sourceRange._endNode,
2087
+ otherStart ? sourceRange._startOffset : sourceRange._endOffset,
2088
+ );
2089
+ }
2090
+
2091
+ #checkPoint(node, offset) {
2092
+ if (offset > nodeLength(node)) throw domError("IndexSizeError", "the offset is past the end of the node");
2093
+ }
2094
+
2095
+ comparePoint(node, offset) {
2096
+ checkNode(node, "the node");
2097
+ offset = offset >>> 0;
2098
+ if (rootOf(node) !== rootOf(this._startNode)) throw domError("WrongDocumentError", "the node is in a different tree");
2099
+ this.#checkPoint(node, offset);
2100
+ if (comparePoints(node, offset, this._startNode, this._startOffset) < 0) return -1;
2101
+ if (comparePoints(node, offset, this._endNode, this._endOffset) > 0) return 1;
2102
+ return 0;
2103
+ }
2104
+
2105
+ isPointInRange(node, offset) {
2106
+ checkNode(node, "the node");
2107
+ offset = offset >>> 0;
2108
+ if (rootOf(node) !== rootOf(this._startNode)) return false;
2109
+ this.#checkPoint(node, offset);
2110
+ return comparePoints(node, offset, this._startNode, this._startOffset) >= 0
2111
+ && comparePoints(node, offset, this._endNode, this._endOffset) <= 0;
2112
+ }
2113
+
2114
+ intersectsNode(node) {
2115
+ checkNode(node, "the node");
2116
+ if (rootOf(node) !== rootOf(this._startNode)) return false;
2117
+ const parent = node.parentNode;
2118
+ if (!parent) return true;
2119
+ const offset = indexIn(node);
2120
+ return comparePoints(parent, offset, this._endNode, this._endOffset) < 0
2121
+ && comparePoints(parent, offset + 1, this._startNode, this._startOffset) > 0;
2122
+ }
2123
+
2124
+ cloneRange() {
2125
+ const copy = new Range();
2126
+ copy.#select(this._startNode, this._startOffset, this._endNode, this._endOffset);
2127
+ return copy;
2128
+ }
2129
+
2130
+ detach() {}
2131
+
2132
+ #contains(node) {
2133
+ return rootOf(node) === rootOf(this._startNode)
2134
+ && comparePoints(node, 0, this._startNode, this._startOffset) > 0
2135
+ && comparePoints(node, nodeLength(node), this._endNode, this._endOffset) < 0;
2136
+ }
2137
+
2138
+ #partlyContains(node) {
2139
+ return isInclusiveAncestor(node, this._startNode) !== isInclusiveAncestor(node, this._endNode);
2140
+ }
2141
+
2142
+ toString() {
2143
+ const start = this._startNode;
2144
+ const end = this._endNode;
2145
+ if (start === end && start.nodeType === 3) return start.data.slice(this._startOffset, this._endOffset);
2146
+ let text = start.nodeType === 3 ? start.data.slice(this._startOffset) : "";
2147
+ const within = this.commonAncestorContainer;
2148
+ for (let node = following(within, within); node; node = following(node, within)) {
2149
+ if (node.nodeType === 3 && this.#contains(node)) text += node.data;
2150
+ }
2151
+ if (end.nodeType === 3) text += end.data.slice(0, this._endOffset);
2152
+ return text;
2153
+ }
2154
+
2155
+ // The parts of the contents algorithms the three of them share.
2156
+ #split() {
2157
+ const startNode = this._startNode;
2158
+ const endNode = this._endNode;
2159
+ const common = this.commonAncestorContainer;
2160
+ const children = common.childNodes;
2161
+ const first = isInclusiveAncestor(startNode, endNode) ? null : children.find((child) => this.#partlyContains(child)) ?? null;
2162
+ let last = null;
2163
+ if (!isInclusiveAncestor(endNode, startNode)) {
2164
+ for (let i = children.length - 1; i >= 0; i--) {
2165
+ if (this.#partlyContains(children[i])) {
2166
+ last = children[i];
2167
+ break;
2168
+ }
2169
+ }
2170
+ }
2171
+ return { common, first, last, contained: children.filter((child) => this.#contains(child)) };
2172
+ }
2173
+
2174
+ // Where the range collapses after its contents leave.
2175
+ #after() {
2176
+ if (isInclusiveAncestor(this._startNode, this._endNode)) return [this._startNode, this._startOffset];
2177
+ let reference = this._startNode;
2178
+ while (reference.parentNode && !isInclusiveAncestor(reference.parentNode, this._endNode)) reference = reference.parentNode;
2179
+ return [reference.parentNode, indexIn(reference) + 1];
2180
+ }
2181
+
2182
+ deleteContents() {
2183
+ if (this.collapsed) return;
2184
+ const startNode = this._startNode;
2185
+ const startOffset = this._startOffset;
2186
+ const endNode = this._endNode;
2187
+ const endOffset = this._endOffset;
2188
+ if (startNode === endNode && startNode.nodeType === 3) {
2189
+ startNode.replaceData(startOffset, endOffset - startOffset, "");
2190
+ return;
2191
+ }
2192
+ const remove = [];
2193
+ const within = this.commonAncestorContainer;
2194
+ for (let node = following(within, within); node; ) {
2195
+ if (this.#contains(node)) {
2196
+ remove.push(node);
2197
+ node = following(node, within, true);
2198
+ } else {
2199
+ node = following(node, within);
2200
+ }
2201
+ }
2202
+ const [node, offset] = this.#after();
2203
+ if (startNode.nodeType === 3) startNode.replaceData(startOffset, startNode.length - startOffset, "");
2204
+ for (const child of remove) child.remove();
2205
+ if (endNode.nodeType === 3) endNode.replaceData(0, endOffset, "");
2206
+ this.#select(node, offset, node, offset);
2207
+ }
2208
+
2209
+ #contents(extract) {
2210
+ const fragment = new DocumentFragment();
2211
+ if (this.collapsed) return fragment;
2212
+ const startNode = this._startNode;
2213
+ const startOffset = this._startOffset;
2214
+ const endNode = this._endNode;
2215
+ const endOffset = this._endOffset;
2216
+ if (startNode === endNode && startNode.nodeType === 3) {
2217
+ const clone = startNode.cloneNode();
2218
+ clone.data = startNode.substringData(startOffset, endOffset - startOffset);
2219
+ fragment.appendChild(clone);
2220
+ if (extract) startNode.replaceData(startOffset, endOffset - startOffset, "");
2221
+ return fragment;
2222
+ }
2223
+ const { first, last, contained } = this.#split();
2224
+ const after = extract ? this.#after() : null;
2225
+ if (first?.nodeType === 3) {
2226
+ const clone = startNode.cloneNode();
2227
+ clone.data = startNode.substringData(startOffset, startNode.length - startOffset);
2228
+ fragment.appendChild(clone);
2229
+ if (extract) startNode.replaceData(startOffset, startNode.length - startOffset, "");
2230
+ } else if (first) {
2231
+ const clone = first.cloneNode();
2232
+ fragment.appendChild(clone);
2233
+ const inner = new Range();
2234
+ inner.#select(startNode, startOffset, first, nodeLength(first));
2235
+ clone.appendChild(inner.#contents(extract));
2236
+ }
2237
+ for (const child of contained) fragment.appendChild(extract ? child : child.cloneNode(true));
2238
+ if (last?.nodeType === 3) {
2239
+ const clone = endNode.cloneNode();
2240
+ clone.data = endNode.substringData(0, endOffset);
2241
+ fragment.appendChild(clone);
2242
+ if (extract) endNode.replaceData(0, endOffset, "");
2243
+ } else if (last) {
2244
+ const clone = last.cloneNode();
2245
+ fragment.appendChild(clone);
2246
+ const inner = new Range();
2247
+ inner.#select(last, 0, endNode, endOffset);
2248
+ clone.appendChild(inner.#contents(extract));
2249
+ }
2250
+ if (extract) this.#select(after[0], after[1], after[0], after[1]);
2251
+ return fragment;
2252
+ }
2253
+
2254
+ /** Moves the contents into a new fragment and collapses the range where they were. */
2255
+ extractContents() {
2256
+ return this.#contents(true);
2257
+ }
2258
+
2259
+ /** Copies the contents into a new fragment. */
2260
+ cloneContents() {
2261
+ return this.#contents(false);
2262
+ }
2263
+
2264
+ /** Inserts `node` at the start of the range. */
2265
+ insertNode(node) {
2266
+ checkNode(node, "the node");
2267
+ const start = this._startNode;
2268
+ if ((start.nodeType === 3 && !start.parentNode) || start === node) {
2269
+ throw domError("HierarchyRequestError", "cannot insert the node there");
2270
+ }
2271
+ let reference = start.nodeType === 3 ? start : start.childNodes[this._startOffset] ?? null;
2272
+ const parent = reference ? reference.parentNode : start;
2273
+ if (isInclusiveAncestor(node, parent)) throw domError("HierarchyRequestError", "a node cannot be inserted into itself");
2274
+ if (parent.nodeType === 3) throw domError("HierarchyRequestError", "text has no children");
2275
+ if (start.nodeType === 3) reference = start.splitText(this._startOffset);
2276
+ if (node === reference) reference = node.nextSibling;
2277
+ if (node.parentNode) node.remove();
2278
+ let offset = reference ? indexIn(reference) : nodeLength(parent);
2279
+ offset += node.nodeType === 11 ? node.childNodes.length : 1;
2280
+ parent.insertBefore(node, reference);
2281
+ if (this.collapsed) this.#set(parent, offset, false);
2282
+ }
2283
+
2284
+ /** Wraps the contents in `newParent`. */
2285
+ surroundContents(newParent) {
2286
+ checkNode(newParent, "the new parent");
2287
+ const within = this.commonAncestorContainer;
2288
+ for (let node = within; node; node = following(node, within)) {
2289
+ if (node.nodeType !== 3 && this.#partlyContains(node)) {
2290
+ throw domError("InvalidStateError", "the range splits an element");
2291
+ }
2292
+ }
2293
+ if (newParent.nodeType === 11) throw domError("InvalidNodeTypeError", "a fragment cannot surround the range");
2294
+ const fragment = this.extractContents();
2295
+ while (newParent.firstChild) newParent.removeChild(newParent.firstChild);
2296
+ this.insertNode(newParent);
2297
+ newParent.appendChild(fragment);
2298
+ this.selectNode(newParent);
2299
+ }
2300
+
2301
+ // The DOM Standard's live range steps, run by the nodes as they change.
2302
+
2303
+ _inserted(parent, index) {
2304
+ const a = this._startNode, b = this._startOffset, c = this._endNode, d = this._endOffset;
2305
+ if (this._startNode === parent && this._startOffset > index) this._startOffset++;
2306
+ if (this._endNode === parent && this._endOffset > index) this._endOffset++;
2307
+ if (a !== this._startNode || b !== this._startOffset || c !== this._endNode || d !== this._endOffset) this._changed();
2308
+ }
2309
+
2310
+ _removing(child, parent, index) {
2311
+ const a = this._startNode, b = this._startOffset, c = this._endNode, d = this._endOffset;
2312
+ if (isInclusiveAncestor(child, this._startNode)) {
2313
+ this._startNode = parent;
2314
+ this._startOffset = index;
2315
+ }
2316
+ if (isInclusiveAncestor(child, this._endNode)) {
2317
+ this._endNode = parent;
2318
+ this._endOffset = index;
2319
+ }
2320
+ if (this._startNode === parent && this._startOffset > index) this._startOffset--;
2321
+ if (this._endNode === parent && this._endOffset > index) this._endOffset--;
2322
+ if (a !== this._startNode || b !== this._startOffset || c !== this._endNode || d !== this._endOffset) this._changed();
2323
+ }
2324
+
2325
+ _replaced(node, offset, count, added) {
2326
+ const a = this._startNode, b = this._startOffset, c = this._endNode, d = this._endOffset;
2327
+ if (this._startNode === node) {
2328
+ if (this._startOffset > offset + count) this._startOffset += added - count;
2329
+ else if (this._startOffset > offset) this._startOffset = offset;
2330
+ }
2331
+ if (this._endNode === node) {
2332
+ if (this._endOffset > offset + count) this._endOffset += added - count;
2333
+ else if (this._endOffset > offset) this._endOffset = offset;
2334
+ }
2335
+ if (a !== this._startNode || b !== this._startOffset || c !== this._endNode || d !== this._endOffset) this._changed();
2336
+ }
2337
+
2338
+ _split(node, rest, offset, parent, index) {
2339
+ const a = this._startNode, b = this._startOffset, c = this._endNode, d = this._endOffset;
2340
+ if (this._startNode === node && this._startOffset > offset) {
2341
+ this._startNode = rest;
2342
+ this._startOffset -= offset;
2343
+ }
2344
+ if (this._endNode === node && this._endOffset > offset) {
2345
+ this._endNode = rest;
2346
+ this._endOffset -= offset;
2347
+ }
2348
+ if (this._startNode === parent && this._startOffset === index + 1) this._startOffset++;
2349
+ if (this._endNode === parent && this._endOffset === index + 1) this._endOffset++;
2350
+ if (a !== this._startNode || b !== this._startOffset || c !== this._endNode || d !== this._endOffset) this._changed();
2351
+ }
2352
+
2353
+ _joined(current, node, length, index) {
2354
+ const a = this._startNode, b = this._startOffset, c = this._endNode, d = this._endOffset;
2355
+ if (this._startNode === current) {
2356
+ this._startNode = node;
2357
+ this._startOffset += length;
2358
+ }
2359
+ if (this._endNode === current) {
2360
+ this._endNode = node;
2361
+ this._endOffset += length;
2362
+ }
2363
+ if (this._startNode === current.parentNode && this._startOffset === index) {
2364
+ this._startNode = node;
2365
+ this._startOffset = length;
2366
+ }
2367
+ if (this._endNode === current.parentNode && this._endOffset === index) {
2368
+ this._endNode = node;
2369
+ this._endOffset = length;
2370
+ }
2371
+ if (a !== this._startNode || b !== this._startOffset || c !== this._endNode || d !== this._endOffset) this._changed();
2372
+ }
2373
+ }
2374
+
2375
+ for (const [name, value] of [["START_TO_START", 0], ["START_TO_END", 1], ["END_TO_END", 2], ["END_TO_START", 3]]) {
2376
+ Object.defineProperty(Range.prototype, name, { value, enumerable: true });
2377
+ }
2378
+
2379
+ function parentOf(node) {
2380
+ checkNode(node, "the node");
2381
+ if (!node.parentNode) throw domError("InvalidNodeTypeError", "the node has no parent");
2382
+ return node.parentNode;
2383
+ }
2384
+
2385
+ /** A new live range, collapsed at the start of the root. */
2386
+ export function createRange() {
2387
+ return new Range();
2388
+ }
2389
+
2390
+ // The document's selection. The tree keeps it (presses, drags, keys, select all) and paints
2391
+ // it; the one `Selection` reads it from there and tells the tree what scripts change. Its
2392
+ // ranges are live Ranges in tree order, one per stretch: a selection across children that
2393
+ // layout reorders (flex order, placed grid cells, positioned boxes) has one per piece seen.
2394
+ const SELECTION = Symbol("selection");
2395
+ let theSelection = null;
2396
+
2397
+ function checkOffset(node, offset) {
2398
+ offset = offset >>> 0;
2399
+ if (offset > nodeLength(node)) throw domError("IndexSizeError", "the offset is past the end of the node");
2400
+ return offset;
2401
+ }
2402
+
2403
+ function inDocument(node) {
2404
+ return rootNode !== null && rootOf(node) === rootNode;
2405
+ }
2406
+
2407
+ /** The document's selection, as `getSelection()` answers it. */
2408
+ export class Selection {
2409
+ #anchor = null;
2410
+ #anchorOffset = 0;
2411
+ #focus = null;
2412
+ #focusOffset = 0;
2413
+ #ranges = [];
2414
+ #backward = false;
2415
+ // Changed by a script and not yet told to the tree.
2416
+ #pending = false;
2417
+
2418
+ constructor(token) {
2419
+ if (token !== SELECTION) throw new TypeError("Illegal constructor");
2420
+ }
2421
+
2422
+ // Reads what the tree has, after telling it what a script changed.
2423
+ #sync() {
2424
+ if (this.#pending) this.#flush();
2425
+ const count = native.selection?.() ?? 0;
2426
+ const anchor = count ? nodes.get(geometry(0)) : null;
2427
+ const focus = count ? nodes.get(geometry(2)) : null;
2428
+ if (!anchor || !focus) {
2429
+ if (this.#anchor) this.#forget();
2430
+ return;
2431
+ }
2432
+ const stretches = [];
2433
+ for (let i = 0; i < count; i++) {
2434
+ const at = 4 + 4 * i;
2435
+ const start = nodes.get(geometry(at));
2436
+ const end = nodes.get(geometry(at + 2));
2437
+ if (start && end) stretches.push([start, geometry(at + 1), end, geometry(at + 3)]);
2438
+ }
2439
+ const same = anchor === this.#anchor && geometry(1) === this.#anchorOffset && focus === this.#focus
2440
+ && geometry(3) === this.#focusOffset && stretches.length === this.#ranges.length
2441
+ && stretches.every(([a, b, c, d], i) => {
2442
+ const range = this.#ranges[i];
2443
+ return range._startNode === a && range._startOffset === b && range._endNode === c && range._endOffset === d;
2444
+ });
2445
+ if (same) return;
2446
+ this.#unhook();
2447
+ this.#anchor = anchor;
2448
+ this.#anchorOffset = geometry(1);
2449
+ this.#focus = focus;
2450
+ this.#focusOffset = geometry(3);
2451
+ this.#backward = comparePoints(anchor, this.#anchorOffset, focus, this.#focusOffset) > 0;
2452
+ this.#ranges = stretches.map(([a, b, c, d]) => {
2453
+ const range = new Range();
2454
+ range._startNode = a;
2455
+ range._startOffset = b;
2456
+ range._endNode = c;
2457
+ range._endOffset = d;
2458
+ return this.#hook(range);
2459
+ });
2460
+ }
2461
+
2462
+ #flush() {
2463
+ this.#pending = false;
2464
+ if (!this.#anchor) native.setSelection?.(0, 0, 0, 0);
2465
+ else native.setSelection?.(this.#anchor.nodeId, this.#anchorOffset, this.#focus.nodeId, this.#focusOffset);
2466
+ }
2467
+
2468
+ #schedule() {
2469
+ if (this.#pending) return;
2470
+ this.#pending = true;
2471
+ queueMicrotask(() => {
2472
+ if (this.#pending) this.#flush();
2473
+ });
2474
+ }
2475
+
2476
+ #hook(range) {
2477
+ range._changed = () => this.#moved(range);
2478
+ return range;
2479
+ }
2480
+
2481
+ #unhook() {
2482
+ for (const range of this.#ranges) delete range._changed;
2483
+ }
2484
+
2485
+ #forget() {
2486
+ this.#unhook();
2487
+ this.#anchor = this.#focus = null;
2488
+ this.#anchorOffset = this.#focusOffset = 0;
2489
+ this.#ranges = [];
2490
+ this.#backward = false;
2491
+ }
2492
+
2493
+ // A script or a mutation moved one of the ranges: the selection becomes that range.
2494
+ #moved(range) {
2495
+ const backward = this.#backward;
2496
+ this.#unhook();
2497
+ this.#ranges = [this.#hook(range)];
2498
+ this.#anchor = backward ? range._endNode : range._startNode;
2499
+ this.#anchorOffset = backward ? range._endOffset : range._startOffset;
2500
+ this.#focus = backward ? range._startNode : range._endNode;
2501
+ this.#focusOffset = backward ? range._startOffset : range._endOffset;
2502
+ this.#schedule();
2503
+ }
2504
+
2505
+ #set(anchor, anchorOffset, focus, focusOffset) {
2506
+ const range = new Range();
2507
+ const forward = comparePoints(anchor, anchorOffset, focus, focusOffset) <= 0;
2508
+ range._startNode = forward ? anchor : focus;
2509
+ range._startOffset = forward ? anchorOffset : focusOffset;
2510
+ range._endNode = forward ? focus : anchor;
2511
+ range._endOffset = forward ? focusOffset : anchorOffset;
2512
+ this.#unhook();
2513
+ this.#ranges = [this.#hook(range)];
2514
+ this.#anchor = anchor;
2515
+ this.#anchorOffset = anchorOffset;
2516
+ this.#focus = focus;
2517
+ this.#focusOffset = focusOffset;
2518
+ this.#backward = !forward;
2519
+ this.#schedule();
2520
+ }
2521
+
2522
+ get anchorNode() { this.#sync(); return this.#anchor; }
2523
+ get anchorOffset() { this.#sync(); return this.#anchorOffset; }
2524
+ get focusNode() { this.#sync(); return this.#focus; }
2525
+ get focusOffset() { this.#sync(); return this.#focusOffset; }
2526
+
2527
+ get isCollapsed() {
2528
+ this.#sync();
2529
+ return this.#anchor === this.#focus && this.#anchorOffset === this.#focusOffset;
2530
+ }
2531
+
2532
+ get rangeCount() { this.#sync(); return this.#ranges.length; }
2533
+
2534
+ /** "None", "Caret" (collapsed) or "Range". */
2535
+ get type() {
2536
+ this.#sync();
2537
+ return !this.#anchor ? "None" : this.isCollapsed ? "Caret" : "Range";
2538
+ }
2539
+
2540
+ /** "forward" when the focus comes after the anchor, "backward" before it, "none" when collapsed. */
2541
+ get direction() {
2542
+ this.#sync();
2543
+ if (!this.#anchor || this.isCollapsed) return "none";
2544
+ return this.#backward ? "backward" : "forward";
2545
+ }
2546
+
2547
+ getRangeAt(index) {
2548
+ this.#sync();
2549
+ index = index >>> 0;
2550
+ if (index >= this.#ranges.length) throw domError("IndexSizeError", "the selection has no range " + index);
2551
+ return this.#ranges[index];
2552
+ }
2553
+
2554
+ /** Selects `range`, which then is the selection's own: changing it changes the selection. Does nothing while something is selected. */
2555
+ addRange(range) {
2556
+ if (!(range instanceof Range)) throw new TypeError("addRange takes a Range");
2557
+ this.#sync();
2558
+ if (this.#ranges.length || !inDocument(range._startNode)) return;
2559
+ this.#unhook();
2560
+ this.#ranges = [this.#hook(range)];
2561
+ this.#anchor = range._startNode;
2562
+ this.#anchorOffset = range._startOffset;
2563
+ this.#focus = range._endNode;
2564
+ this.#focusOffset = range._endOffset;
2565
+ this.#backward = false;
2566
+ this.#schedule();
2567
+ }
2568
+
2569
+ removeRange(range) {
2570
+ this.#sync();
2571
+ if (!this.#ranges.includes(range)) throw domError("NotFoundError", "the range is not in the selection");
2572
+ this.removeAllRanges();
2573
+ }
2574
+
2575
+ removeAllRanges() {
2576
+ if (!this.#anchor && !this.#pending && !this.#ranges.length) {
2577
+ this.#sync();
2578
+ if (!this.#anchor) return;
2579
+ }
2580
+ this.#forget();
2581
+ this.#schedule();
2582
+ }
2583
+
2584
+ empty() { this.removeAllRanges(); }
2585
+
2586
+ /** Puts a caret at (`node`, `offset`); `null` removes the selection. */
2587
+ collapse(node, offset = 0) {
2588
+ if (node === null) return this.removeAllRanges();
2589
+ checkNode(node, "the node");
2590
+ offset = checkOffset(node, offset);
2591
+ if (inDocument(node)) this.#set(node, offset, node, offset);
2592
+ }
2593
+
2594
+ setPosition(node, offset = 0) { return this.collapse(node, offset); }
2595
+
2596
+ collapseToStart() {
2597
+ this.#sync();
2598
+ if (!this.#ranges.length) throw domError("InvalidStateError", "nothing is selected");
2599
+ const first = this.#ranges[0];
2600
+ this.#set(first._startNode, first._startOffset, first._startNode, first._startOffset);
2601
+ }
2602
+
2603
+ collapseToEnd() {
2604
+ this.#sync();
2605
+ if (!this.#ranges.length) throw domError("InvalidStateError", "nothing is selected");
2606
+ const last = this.#ranges[this.#ranges.length - 1];
2607
+ this.#set(last._endNode, last._endOffset, last._endNode, last._endOffset);
2608
+ }
2609
+
2610
+ /** Moves the focus to (`node`, `offset`); the anchor stays. */
2611
+ extend(node, offset = 0) {
2612
+ checkNode(node, "the node");
2613
+ this.#sync();
2614
+ if (!this.#anchor) throw domError("InvalidStateError", "nothing is selected");
2615
+ offset = checkOffset(node, offset);
2616
+ if (inDocument(node)) this.#set(this.#anchor, this.#anchorOffset, node, offset);
2617
+ }
2618
+
2619
+ setBaseAndExtent(anchorNode, anchorOffset, focusNode, focusOffset) {
2620
+ checkNode(anchorNode, "the anchor node");
2621
+ checkNode(focusNode, "the focus node");
2622
+ anchorOffset = checkOffset(anchorNode, anchorOffset);
2623
+ focusOffset = checkOffset(focusNode, focusOffset);
2624
+ if (inDocument(anchorNode) && inDocument(focusNode)) this.#set(anchorNode, anchorOffset, focusNode, focusOffset);
2625
+ }
2626
+
2627
+ selectAllChildren(node) {
2628
+ checkNode(node, "the node");
2629
+ if (inDocument(node)) this.#set(node, 0, node, node.childNodes.length);
2630
+ }
2631
+
2632
+ deleteFromDocument() {
2633
+ this.#sync();
2634
+ for (const range of [...this.#ranges]) range.deleteContents();
2635
+ }
2636
+
2637
+ /** Whether the selection holds all of `node`, or any of it with `allowPartialContainment`. */
2638
+ containsNode(node, allowPartialContainment = false) {
2639
+ checkNode(node, "the node");
2640
+ this.#sync();
2641
+ if (!this.#ranges.length || !inDocument(node)) return false;
2642
+ const parent = node.parentNode;
2643
+ const startNode = parent ?? node;
2644
+ const start = parent ? indexIn(node) : 0;
2645
+ const endNode = parent ?? node;
2646
+ const end = parent ? start + 1 : nodeLength(node);
2647
+ return this.#ranges.some((range) => allowPartialContainment
2648
+ ? comparePoints(startNode, start, range._endNode, range._endOffset) < 0 && comparePoints(endNode, end, range._startNode, range._startOffset) > 0
2649
+ : comparePoints(range._startNode, range._startOffset, startNode, start) <= 0 && comparePoints(endNode, end, range._endNode, range._endOffset) <= 0);
2650
+ }
2651
+
2652
+ getComposedRanges() {
2653
+ this.#sync();
2654
+ return this.#ranges.map((range) => new StaticRange({
2655
+ startContainer: range._startNode, startOffset: range._startOffset, endContainer: range._endNode, endOffset: range._endOffset,
2656
+ }));
2657
+ }
2658
+
2659
+ /** The selected text as copying gives it: rendered white space, line breaks between blocks. */
2660
+ toString() {
2661
+ this.#sync();
2662
+ if (!this.#ranges.length) return "";
2663
+ return native.selectionText?.() ?? this.#ranges.map((range) => range.toString()).join("");
2664
+ }
2665
+ }
2666
+
2667
+ /** The document's selection: what the user selected, which scripts can read and change. */
2668
+ export function getSelection() {
2669
+ return (theSelection ??= new Selection(SELECTION));
2670
+ }
2671
+
2672
+ globalThis.Selection ??= Selection;
2673
+ globalThis.getSelection ??= getSelection;
2674
+
2675
+ // A `SelectionChange` record at a node that is not an input: `selectstart` where a press
2676
+ // started a selection (its `selectionStart` is 1), else the document's `selectionchange` at
2677
+ // the root.
2678
+ function selectionRecord(target, start) {
2679
+ const event = new Event(start === 1 ? "selectstart" : "selectionchange", target);
2680
+ if (start !== 1) event.bubbles = false;
2681
+ dispatchEvent(event);
2682
+ if (event.defaultPrevented) {
2683
+ const selection = getSelection();
2684
+ selection.removeAllRanges();
2685
+ // Read back at once, so the tree stops the press before the pointer moves on.
2686
+ void selection.rangeCount;
2687
+ }
2688
+ return false;
2689
+ }
2690
+
2691
+ let rootNode = null;
2692
+
2693
+ /** Makes `node` the root of the window's tree. */
2694
+ /**
2695
+ * Defines `@keyframes name` as CSS would: `{ from: { opacity: 0 }, "50%": {...}, to: {...} }`,
2696
+ * with selectors such as `"0%, 100%"` too. Style objects name it in `animation` or
2697
+ * `animationName`. Defining a name again replaces its rule; `null` removes it.
2698
+ */
2699
+ export function defineKeyframes(name, frames) {
2700
+ for (const selector of Object.keys(frames ?? {})) {
2701
+ let css = "";
2702
+ const declarations = frames[selector];
2703
+ for (const property of Object.keys(declarations)) {
2704
+ const value = declarations[property];
2705
+ if (value === null || value === undefined || value === "") continue;
2706
+ css += cssName(property) + ":" + cssValue(property, value) + ";";
2707
+ }
2708
+ for (const part of selector.split(",")) {
2709
+ const text = part.trim().toLowerCase();
2710
+ const offset = text === "from" ? 0 : text === "to" ? 1 : parseFloat(text) / 100;
2711
+ if (!(offset >= 0 && offset <= 1)) throw new Error(`@silkui/core: bad keyframe selector '${part}'`);
2712
+ native.keyframe(offset, css);
2713
+ }
2714
+ }
2715
+ native.keyframes(String(name));
2716
+ }
2717
+
2718
+ export function mount(node) {
2719
+ if (rootNode) clearAdoptedSheets();
2720
+ rootNode = node;
2721
+ native.root(node.nodeId);
2722
+ syncAdoptedSheets();
2723
+ return node;
2724
+ }
2725
+
2726
+ export function root() {
2727
+ return rootNode;
2728
+ }
2729
+
2730
+ // The live regions `announce` speaks through, one per politeness, made on first use.
2731
+ const regions = Object.create(null);
2732
+ // A box screen readers read and nothing shows, as the web's visually hidden pattern.
2733
+ const VISUALLY_HIDDEN = {
2734
+ position: "absolute",
2735
+ width: 1,
2736
+ height: 1,
2737
+ margin: -1,
2738
+ overflow: "hidden",
2739
+ clipPath: "inset(50%)",
2740
+ whiteSpace: "nowrap",
2741
+ pointerEvents: "none",
2742
+ };
2743
+
2744
+ /**
2745
+ * Has screen readers say `message` without showing it, as a toast or a "Saved" would. Polite
2746
+ * messages wait for the reader to finish; `{ politeness: "assertive" }` interrupts it. The
2747
+ * same message twice is said twice. Nothing happens before `mount`.
2748
+ */
2749
+ export function announce(message, { politeness = "polite" } = {}) {
2750
+ if (!rootNode) return;
2751
+ const key = politeness === "assertive" ? "assertive" : "polite";
2752
+ let region = regions[key];
2753
+ if (!region || region.parentNode !== rootNode) {
2754
+ region = regions[key] = createBox(VISUALLY_HIDDEN);
2755
+ region.setAttribute("aria-live", key);
2756
+ region.setAttribute("aria-atomic", "true");
2757
+ rootNode.appendChild(region);
2758
+ }
2759
+ // A region announces changes, not what it holds when it appears, so the text waits a
2760
+ // moment; each message is a node of its own so a repeat is a change too.
2761
+ setTimeout(() => {
2762
+ if (region.parentNode !== rootNode) return;
2763
+ for (const child of region.childNodes.slice()) child.destroy();
2764
+ const text = createText(String(message));
2765
+ region.appendChild(text);
2766
+ setTimeout(() => {
2767
+ if (text.parentNode === region) text.destroy();
2768
+ }, ANNOUNCEMENT_LIFETIME);
2769
+ }, ANNOUNCEMENT_DELAY);
2770
+ }
2771
+
2772
+ const ANNOUNCEMENT_DELAY = 100;
2773
+ const ANNOUNCEMENT_LIFETIME = 7000;
2774
+
2775
+ /** The node with tree id `id`, for hosts and tools. */
2776
+ export function nodeById(id) {
2777
+ return nodes.get(id) ?? null;
2778
+ }
2779
+
2780
+ // The option bits of `__ui.markdown`.
2781
+ const MARKDOWN_FLAGS = { tables: 1, strikethrough: 2, taskLists: 4, autolinkLiterals: 8, footnotes: 16, frontmatter: 32, alerts: 64 };
2782
+ const GFM = 1 | 2 | 4 | 8;
2783
+
2784
+ /**
1460
2785
  * The syntax tree of Markdown `text`, in the shape of mdast (what remark gives): plain
1461
2786
  * objects with `type` and `children`. CommonMark, with GitHub's tables, strikethrough,
1462
2787
  * task lists and autolinks unless `gfm` is false. `footnotes`, `frontmatter` and
@@ -1522,12 +2847,118 @@ export class Event {
1522
2847
  }
1523
2848
  }
1524
2849
 
2850
+ // The pointers down or hovering, by `pointerId`: their buttons and the node holding their
2851
+ // capture.
2852
+ const pointers = new Map();
2853
+
2854
+ function domError(name, message) {
2855
+ const DOMExceptionClass = globalThis.DOMException;
2856
+ if (DOMExceptionClass) return new DOMExceptionClass(message, name);
2857
+ const error = new Error(message);
2858
+ error.name = name;
2859
+ return error;
2860
+ }
2861
+
2862
+ const POINTER_TYPES = ["mouse", "pen", "touch"];
2863
+ // DOM `buttons` bits by `button`: primary 1, secondary 2, auxiliary 4, back 8, forward 16.
2864
+ const BUTTON_BITS = [1, 4, 2, 8, 16];
2865
+
2866
+ function isPointerKind(kind) {
2867
+ return kind <= 5 || kind === 14 || kind === 28 || kind === 29;
2868
+ }
2869
+
2870
+ // The fingers down, by `identifier`: the `Touch` each last reported.
2871
+ const touches = new Map();
2872
+
2873
+ function touchList(list) {
2874
+ list.item = (index) => list[index] ?? null;
2875
+ return list;
2876
+ }
2877
+
2878
+ // A touch record as DOM `TouchEvent`: the finger it is about is `changedTouches[0]`, and it
2879
+ // goes to the node the finger went down on. No host reports contact size or force: a touch is
2880
+ // 1 by 1 pixel, as its pointer is, with force 0.
2881
+ function fillTouch(event, kind, a, b, bits, d) {
2882
+ const identifier = Math.floor(bits / 256);
2883
+ const touch = {
2884
+ identifier,
2885
+ target: event.target,
2886
+ clientX: a,
2887
+ clientY: b,
2888
+ pageX: a,
2889
+ pageY: b,
2890
+ screenX: a,
2891
+ screenY: b,
2892
+ radiusX: 0.5,
2893
+ radiusY: 0.5,
2894
+ rotationAngle: 0,
2895
+ force: 0,
2896
+ };
2897
+ const start = touches.get(identifier);
2898
+ if (start) touch.target = start.target;
2899
+ if (kind === TOUCH_START || kind === TOUCH_START + 1) touches.set(identifier, touch);
2900
+ else touches.delete(identifier);
2901
+ event.cancelable = d === 1;
2902
+ event.changedTouches = touchList([touch]);
2903
+ event.touches = touchList([...touches.values()]);
2904
+ event.targetTouches = touchList([...touches.values()].filter((t) => t.target === event.target));
2905
+ }
2906
+
2907
+ // The members of DOM `PointerEvent` the record carries (see ui-js-calls `pointerBits`), and the
2908
+ // spec defaults for what no host reports: pressure 0.5 while a button is down, 0 otherwise, and
2909
+ // a contact of 1 by 1 pixel with no tilt.
2910
+ function fillPointer(event, kind, bits, d) {
2911
+ const pointerId = Math.floor(bits / 256);
2912
+ const pointerType = POINTER_TYPES[Math.floor(bits / 16) % 4] ?? "mouse";
2913
+ const isPrimary = Math.floor(bits / 64) % 2 === 1;
2914
+ let pointer = pointers.get(pointerId);
2915
+ if (!pointer) {
2916
+ pointer = { buttons: 0, capture: null, primary: isPrimary, mute: false };
2917
+ // A click comes after its pointer lifted: it leaves no pointer behind.
2918
+ if (kind !== 2) pointers.set(pointerId, pointer);
2919
+ }
2920
+ if (kind === 0) pointer.buttons |= BUTTON_BITS[d] ?? 0;
2921
+ else if (kind === 1) pointer.buttons &= ~(BUTTON_BITS[d] ?? 0);
2922
+ event.pointerId = pointerId;
2923
+ event.pointerType = pointerType;
2924
+ event.isPrimary = isPrimary;
2925
+ event.buttons = pointer.buttons;
2926
+ event.pressure = pointer.buttons ? 0.5 : 0;
2927
+ event.tangentialPressure = 0;
2928
+ event.tiltX = 0;
2929
+ event.tiltY = 0;
2930
+ event.twist = 0;
2931
+ event.altitudeAngle = Math.PI / 2;
2932
+ event.azimuthAngle = 0;
2933
+ event.width = 1;
2934
+ event.height = 1;
2935
+ if (kind !== 0 && kind !== 1 && kind !== 2) event.button = kind === 3 ? -1 : 0;
2936
+ const coalesced = kind === 3 ? [event] : [];
2937
+ event.getCoalescedEvents = () => coalesced;
2938
+ event.getPredictedEvents = () => [];
2939
+ // A pointer that lifted, or a touch that left, is gone; the mouse stays.
2940
+ if ((kind === 1 && !pointer.buttons) || kind === 14) {
2941
+ pointer.capture = null;
2942
+ if (pointerType !== "mouse") pointers.delete(pointerId);
2943
+ }
2944
+ }
2945
+
1525
2946
  function fill(event, kind, a, b, modifiers, d, e, first, second, third, fourth) {
1526
- if (kind <= 6 || kind === 14) {
2947
+ if (kind >= TOUCH_START) {
2948
+ fillTouch(event, kind, a, b, modifiers, d);
2949
+ event.shiftKey = (modifiers & 1) !== 0;
2950
+ event.ctrlKey = (modifiers & 2) !== 0;
2951
+ event.altKey = (modifiers & 4) !== 0;
2952
+ event.metaKey = (modifiers & 8) !== 0;
2953
+ return;
2954
+ }
2955
+ if (kind <= 6 || kind === 14 || kind === 28 || kind === 29) {
1527
2956
  event.clientX = event.x = a;
1528
2957
  event.clientY = event.y = b;
1529
2958
  }
1530
- if (kind <= 8 || kind === 14) {
2959
+ if (isPointerKind(kind)) fillPointer(event, kind, modifiers, d);
2960
+ if (kind === 16) for (const pointer of pointers.values()) if (pointer.capture === event.target) pointer.capture = null;
2961
+ if (kind <= 8 || kind === 14 || kind === 28 || kind === 29) {
1531
2962
  event.shiftKey = (modifiers & 1) !== 0;
1532
2963
  event.ctrlKey = (modifiers & 2) !== 0;
1533
2964
  event.altKey = (modifiers & 4) !== 0;
@@ -1621,14 +3052,60 @@ function adopt(event, target) {
1621
3052
  return event;
1622
3053
  }
1623
3054
 
3055
+ // The compatibility mouse event of `type` that follows pointer event `from`.
3056
+ function mouseEvent(type, from, target) {
3057
+ const event = new Event(type, target);
3058
+ for (const name of ["clientX", "clientY", "x", "y", "button", "buttons", "detail", "shiftKey", "ctrlKey", "altKey", "metaKey"]) {
3059
+ event[name] = from[name];
3060
+ }
3061
+ if (type === "mousemove") event.button = 0;
3062
+ return event;
3063
+ }
3064
+
3065
+ // Mouse events after a pointer event of a mouse or pen, as the web sends them: a prevented
3066
+ // `pointerdown` mutes `mousedown`, `mousemove` and `mouseup` until the pointer lifts.
3067
+ function compatMouse(kind, event, target) {
3068
+ const type = MOUSE_OF.get(event.type);
3069
+ if (!type) return;
3070
+ const pointer = pointers.get(event.pointerId);
3071
+ if (kind === 0 && event.defaultPrevented && pointer) pointer.mute = true;
3072
+ const muted = pointer?.mute && (kind === 0 || kind === 1 || kind === 3);
3073
+ if (kind === 1 && pointer) pointer.mute = false;
3074
+ if (!muted && event.isPrimary) dispatchEvent(mouseEvent(type, event, target));
3075
+ }
3076
+
3077
+ // The finger whose prevented `pointerdown` mutes its tap's mouse events.
3078
+ let mutedTap = null;
3079
+
3080
+ // A tap's mouse events come just before its click, as on the web.
3081
+ function compatTap(click, target) {
3082
+ if (mutedTap === click.pointerId) return;
3083
+ for (const type of ["mousemove", "mousedown", "mouseup"]) {
3084
+ const event = mouseEvent(type, click, target);
3085
+ event.buttons = type === "mousedown" ? 1 : 0;
3086
+ dispatchEvent(event);
3087
+ }
3088
+ }
3089
+
1624
3090
  // The host calls this for every event record, before the tree runs the default action.
1625
3091
  native.dispatch = function (kind, id, a, b, modifiers, d, e, first, second, third, fourth) {
1626
3092
  const target = nodes.get(id);
1627
3093
  if (!target) return false;
3094
+ if (kind === SELECTION_CHANGE && !(target instanceof Input)) return selectionRecord(target, a);
1628
3095
  const event = new Event(TYPES[kind], target);
1629
3096
  fill(event, kind, a, b, modifiers, d, e, first, second, third, fourth);
3097
+ if (kind === CLICK && event.pointerType === "touch" && event.isPrimary) compatTap(event, target);
1630
3098
  dispatchEvent(event);
1631
3099
  if (kind === CLICK && !event.defaultPrevented) follow(target);
3100
+ if (kind !== CLICK && isPointerKind(kind)) {
3101
+ if (event.pointerType !== "touch") compatMouse(kind, event, target);
3102
+ // A finger's defaults (pan, focus, the tap's click) follow its touch events, not its
3103
+ // pointer events, as on the web.
3104
+ else {
3105
+ if (kind === 0 && event.isPrimary) mutedTap = event.defaultPrevented ? event.pointerId : null;
3106
+ return false;
3107
+ }
3108
+ }
1632
3109
  return event.defaultPrevented;
1633
3110
  };
1634
3111
 
@@ -1827,6 +3304,10 @@ export class Notification {
1827
3304
  }
1828
3305
 
1829
3306
  globalThis.Notification ??= Notification;
3307
+ globalThis.AbstractRange ??= AbstractRange;
3308
+ globalThis.StaticRange ??= StaticRange;
3309
+ globalThis.Range ??= Range;
3310
+ globalThis.DocumentFragment ??= DocumentFragment;
1830
3311
 
1831
3312
  function hex(bytes) {
1832
3313
  let text = "";
@@ -1943,6 +3424,422 @@ export function memoryUsage() {
1943
3424
  return footprint > 0 ? { footprint, processes: 1 } : null;
1944
3425
  }
1945
3426
 
3427
+ // Selector queries run in the host on its tree (`__ui.query`); a host without one (the web
3428
+ // canvas build) answers undefined, which reads as no match.
3429
+ function queried(mode, node, selector) {
3430
+ const answer = native.query?.(mode, node.nodeId, String(selector));
3431
+ if (answer === -1) {
3432
+ const message = "'" + selector + "' is not a valid selector";
3433
+ throw typeof DOMException === "function" ? new DOMException(message, "SyntaxError") : new SyntaxError(message);
3434
+ }
3435
+ return answer;
3436
+ }
3437
+
3438
+ // `getComputedStyle`: one native read per property, made when the property is read, so a
3439
+ // declaration stays live and costs nothing for the properties nobody asks for.
3440
+ const readComputed = native.computed ?? (() => undefined);
3441
+ const computedId = Symbol("node");
3442
+ // Property names by the name they were asked by, null for the declaration's own members.
3443
+ const computedNames = new Map();
3444
+ const lowerNames = new Map();
3445
+ function computedName(key, target) {
3446
+ let name = computedNames.get(key);
3447
+ if (name === undefined) {
3448
+ name = key in target ? null : key === "cssFloat" ? "float"
3449
+ : key.replace(/[A-Z]/g, (c) => "-" + c.toLowerCase()).replace(/^(webkit|moz|ms)-/, "-$1-");
3450
+ computedNames.set(key, name);
3451
+ }
3452
+ return name;
3453
+ }
3454
+
3455
+ class CSSStyleDeclaration {
3456
+ constructor(id) { Object.defineProperty(this, computedId, { value: id }); }
3457
+ getPropertyValue(name) {
3458
+ let lower = lowerNames.get(name);
3459
+ if (lower === undefined) {
3460
+ lower = String(name).toLowerCase();
3461
+ if (typeof name === "string") lowerNames.set(name, lower);
3462
+ }
3463
+ return readComputed(this[computedId], lower) ?? "";
3464
+ }
3465
+ getPropertyPriority() { return ""; }
3466
+ setProperty() { throw new TypeError("a computed style cannot be changed"); }
3467
+ removeProperty() { throw new TypeError("a computed style cannot be changed"); }
3468
+ get cssText() { return ""; }
3469
+ get length() { return 0; }
3470
+ item() { return ""; }
3471
+ }
3472
+
3473
+ const computedTraps = {
3474
+ get(target, key, receiver) {
3475
+ if (typeof key === "string") {
3476
+ const name = computedName(key, target);
3477
+ if (name !== null) return readComputed(target[computedId], name) ?? "";
3478
+ }
3479
+ return Reflect.get(target, key, receiver);
3480
+ },
3481
+ set() { throw new TypeError("a computed style cannot be changed"); },
3482
+ };
3483
+
3484
+ /**
3485
+ * The values the tree resolved for `node` (an @silkui/core node, or an element of a DOM layer
3486
+ * over one): typed and animated properties as they are now, box sizes, margins, padding and
3487
+ * border widths as laid out, the rest as cascaded with lengths in pixels. Each property read
3488
+ * is one call into the tree; it applies pending changes and lays out only when something
3489
+ * changed since the last layout. Shorthands, custom properties and pseudo-elements read "".
3490
+ */
3491
+ export function getComputedStyle(node, pseudo) {
3492
+ const id = node?.nodeId ?? node?.node?.nodeId;
3493
+ if (typeof id !== "number") throw new TypeError("getComputedStyle takes a node");
3494
+ return new Proxy(new CSSStyleDeclaration(pseudo ? 0 : id), computedTraps);
3495
+ }
3496
+
3497
+ globalThis.getComputedStyle ??= getComputedStyle;
3498
+
3499
+ // Layout reads. Each lays out first when something changed since the last frame (as a
3500
+ // browser forces layout), leaves its numbers in the bridge and answers how many there are.
3501
+ const geometry = native.geometry ?? (() => 0);
3502
+ const ALIGNMENTS = { start: 0, center: 1, end: 2, nearest: 3 };
3503
+ const BEHAVIORS = { auto: 0, instant: 1, smooth: 2 };
3504
+
3505
+ function alignment(value, fallback) {
3506
+ if (value === undefined) return fallback;
3507
+ const code = ALIGNMENTS[value];
3508
+ if (code === undefined) throw new TypeError("'" + value + "' is not a valid ScrollLogicalPosition");
3509
+ return code;
3510
+ }
3511
+
3512
+ /** A read-only rectangle, as `DOMRect` on the web. */
3513
+ export class DOMRect {
3514
+ constructor(x = 0, y = 0, width = 0, height = 0) {
3515
+ this.x = x;
3516
+ this.y = y;
3517
+ this.width = width;
3518
+ this.height = height;
3519
+ }
3520
+ get left() { return Math.min(this.x, this.x + this.width); }
3521
+ get top() { return Math.min(this.y, this.y + this.height); }
3522
+ get right() { return Math.max(this.x, this.x + this.width); }
3523
+ get bottom() { return Math.max(this.y, this.y + this.height); }
3524
+ toJSON() {
3525
+ const { x, y, width, height, top, right, bottom, left } = this;
3526
+ return { x, y, width, height, top, right, bottom, left };
3527
+ }
3528
+ }
3529
+
3530
+ globalThis.DOMRect ??= DOMRect;
3531
+
3532
+ function metric(id, index) {
3533
+ if (!native.metrics?.(id)) return 0;
3534
+ return geometry(index);
3535
+ }
3536
+
3537
+ function readRect(id) {
3538
+ if (!native.rect?.(id)) return new DOMRect();
3539
+ return new DOMRect(geometry(0), geometry(1), geometry(2), geometry(3));
3540
+ }
3541
+
3542
+ function readRects(count) {
3543
+ const list = [];
3544
+ 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)));
3545
+ list.item = (index) => list[index] ?? null;
3546
+ return list;
3547
+ }
3548
+
3549
+ // `scrollTo`, `scroll` and `scrollBy`: numbers, or `{ left, top, behavior }`. `by` is 4 for scrollBy.
3550
+ function scrollNode(id, x, y, by) {
3551
+ let left, top, behavior = 0;
3552
+ if (x !== null && typeof x === "object") {
3553
+ left = x.left;
3554
+ top = x.top;
3555
+ if (x.behavior !== undefined) {
3556
+ behavior = BEHAVIORS[x.behavior];
3557
+ if (behavior === undefined) throw new TypeError("'" + x.behavior + "' is not a valid ScrollBehavior");
3558
+ }
3559
+ } else {
3560
+ left = x;
3561
+ top = y;
3562
+ }
3563
+ // As on the web, a non-finite coordinate counts as 0.
3564
+ const has = (left !== undefined ? 1 : 0) | (top !== undefined ? 2 : 0);
3565
+ const number = (value) => (Number.isFinite(+value) ? +value : 0);
3566
+ if (native.scroll) native.scroll(id, number(left), number(top), behavior, has | by);
3567
+ else if (!by) native.scrollTo(id, number(left), number(top));
3568
+ }
3569
+
3570
+ // IntersectionObserver and ResizeObserver: the tree computes every observation after each
3571
+ // layout and calls `__ui.observed(count)` with only the entries that changed.
3572
+ const observersById = new Map();
3573
+ let nextObserverId = 0;
3574
+
3575
+ function lengths(text, name) {
3576
+ const parts = String(text ?? "0px").trim().split(/\s+/);
3577
+ if (parts.length > 4) throw new SyntaxError("'" + text + "' is not a valid " + name);
3578
+ const values = [], percent = [];
3579
+ for (const part of parts) {
3580
+ const match = /^(-?(?:\d+\.?\d*|\.\d+))(px|%)?$/.exec(part);
3581
+ if (!match || (match[2] === undefined && +match[1] !== 0)) throw new SyntaxError("'" + text + "' is not a valid " + name + ": use px or %");
3582
+ values.push(+match[1]);
3583
+ percent.push(match[2] === "%");
3584
+ }
3585
+ // top, right, bottom, left as in the margin shorthand.
3586
+ const pick = [[0, 0, 0, 0], [0, 1, 0, 1], [0, 1, 2, 1], [0, 1, 2, 3]][values.length - 1];
3587
+ const out = pick.map((i) => values[i]);
3588
+ let bits = 0;
3589
+ pick.forEach((i, side) => { if (percent[i]) bits |= 1 << side; });
3590
+ out.text = pick.map((i) => values[i] + (percent[i] ? "%" : "px")).join(" ");
3591
+ return { values: out, bits };
3592
+ }
3593
+
3594
+ /** As `IntersectionObserverEntry` on the web. */
3595
+ export class IntersectionObserverEntry {
3596
+ constructor(init) { Object.assign(this, init); }
3597
+ }
3598
+
3599
+ /** As `IntersectionObserver` on the web, with `scrollMargin` from version 2. `root` is a node or null for the window. */
3600
+ export class IntersectionObserver {
3601
+ #id = ++nextObserverId;
3602
+ #callback;
3603
+ #targets = new Map();
3604
+ #records = [];
3605
+ #margin;
3606
+ #scroll;
3607
+
3608
+ constructor(callback, options = {}) {
3609
+ if (typeof callback !== "function") throw new TypeError("IntersectionObserver takes a callback");
3610
+ this.#callback = callback;
3611
+ const root = options.root ?? null;
3612
+ if (root !== null && typeof root.nodeId !== "number" && typeof root.node?.nodeId !== "number") throw new TypeError("root must be a node or null");
3613
+ this.root = root;
3614
+ this.#margin = lengths(options.rootMargin, "rootMargin");
3615
+ this.#scroll = lengths(options.scrollMargin, "scrollMargin");
3616
+ let list = options.threshold ?? 0;
3617
+ list = (Array.isArray(list) ? list : [list]).map(Number);
3618
+ for (const value of list) if (!(value >= 0 && value <= 1)) throw new RangeError("Threshold values must be numbers between 0 and 1");
3619
+ list.sort((a, b) => a - b);
3620
+ if (list.length === 0) list.push(0);
3621
+ Object.defineProperties(this, {
3622
+ rootMargin: { value: this.#margin.values.text, enumerable: true },
3623
+ scrollMargin: { value: this.#scroll.values.text, enumerable: true },
3624
+ thresholds: { value: Object.freeze(list), enumerable: true },
3625
+ delay: { value: 0, enumerable: true },
3626
+ trackVisibility: { value: false, enumerable: true },
3627
+ });
3628
+ }
3629
+
3630
+ observe(target) {
3631
+ const id = target?.nodeId ?? target?.node?.nodeId;
3632
+ if (typeof id !== "number") throw new TypeError("observe takes a node");
3633
+ if (this.#targets.has(id)) return;
3634
+ if (this.#targets.size === 0) {
3635
+ const m = this.#margin.values, s = this.#scroll.values;
3636
+ const rootId = this.root ? (this.root.nodeId ?? this.root.node.nodeId) : 0;
3637
+ 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]);
3638
+ for (const value of this.thresholds) native.threshold?.(this.#id, value);
3639
+ observersById.set(this.#id, this);
3640
+ }
3641
+ this.#targets.set(id, target);
3642
+ native.observe?.(this.#id, id, 0);
3643
+ }
3644
+
3645
+ unobserve(target) {
3646
+ const id = target?.nodeId ?? target?.node?.nodeId;
3647
+ if (!this.#targets.delete(id)) return;
3648
+ native.unobserve?.(this.#id, id);
3649
+ if (this.#targets.size === 0) observersById.delete(this.#id);
3650
+ }
3651
+
3652
+ disconnect() {
3653
+ if (this.#targets.size === 0) return;
3654
+ this.#targets.clear();
3655
+ native.unobserve?.(this.#id, 0);
3656
+ observersById.delete(this.#id);
3657
+ }
3658
+
3659
+ takeRecords() {
3660
+ const records = this.#records;
3661
+ this.#records = [];
3662
+ return records;
3663
+ }
3664
+
3665
+ // The object `observe` was given: a Foldkit element is its entries' target, not its node.
3666
+ _target(id) { return this.#targets.get(id) ?? null; }
3667
+
3668
+ _queue(entry) { this.#records.push(entry); }
3669
+
3670
+ _deliver() {
3671
+ const records = this.takeRecords();
3672
+ if (records.length === 0) return;
3673
+ try { this.#callback.call(this, records, this); } catch (error) { reportError(error); }
3674
+ }
3675
+ }
3676
+
3677
+ /** As `ResizeObserverEntry` on the web. */
3678
+ export class ResizeObserverEntry {
3679
+ constructor(init) { Object.assign(this, init); }
3680
+ }
3681
+
3682
+ const BOXES = { "content-box": 1, "border-box": 2, "device-pixel-content-box": 3 };
3683
+
3684
+ /** As `ResizeObserver` on the web: entries come after a layout that changed the observed box. */
3685
+ export class ResizeObserver {
3686
+ #id = ++nextObserverId;
3687
+ #callback;
3688
+ #targets = new Map();
3689
+ #records = [];
3690
+
3691
+ constructor(callback) {
3692
+ if (typeof callback !== "function") throw new TypeError("ResizeObserver takes a callback");
3693
+ this.#callback = callback;
3694
+ }
3695
+
3696
+ observe(target, options) {
3697
+ const id = target?.nodeId ?? target?.node?.nodeId;
3698
+ if (typeof id !== "number") throw new TypeError("observe takes a node");
3699
+ const box = BOXES[options?.box ?? "content-box"];
3700
+ if (box === undefined) throw new TypeError("'" + options.box + "' is not a valid ResizeObserverBoxOptions");
3701
+ this.#targets.set(id, target);
3702
+ observersById.set(this.#id, this);
3703
+ native.observe?.(this.#id, id, box);
3704
+ }
3705
+
3706
+ unobserve(target) {
3707
+ const id = target?.nodeId ?? target?.node?.nodeId;
3708
+ if (!this.#targets.delete(id)) return;
3709
+ native.unobserve?.(this.#id, id);
3710
+ if (this.#targets.size === 0) observersById.delete(this.#id);
3711
+ }
3712
+
3713
+ disconnect() {
3714
+ if (this.#targets.size === 0) return;
3715
+ this.#targets.clear();
3716
+ native.unobserve?.(this.#id, 0);
3717
+ observersById.delete(this.#id);
3718
+ }
3719
+
3720
+ // The object `observe` was given: a Foldkit element is its entries' target, not its node.
3721
+ _target(id) { return this.#targets.get(id) ?? null; }
3722
+
3723
+ _queue(entry) { this.#records.push(entry); }
3724
+
3725
+ _deliver() {
3726
+ const records = this.#records;
3727
+ this.#records = [];
3728
+ if (records.length === 0) return;
3729
+ try { this.#callback.call(this, records, this); } catch (error) { reportError(error); }
3730
+ }
3731
+ }
3732
+
3733
+ const size = (inlineSize, blockSize) => Object.freeze([Object.freeze({ inlineSize, blockSize })]);
3734
+
3735
+ native.observed = function (count) {
3736
+ // Read every entry first: a callback's own layout reads reuse the numbers.
3737
+ const time = performance.now();
3738
+ const touched = [];
3739
+ let at = 0;
3740
+ for (let n = 0; n < count; n++) {
3741
+ const kind = geometry(at);
3742
+ const observer = observersById.get(geometry(at + 1));
3743
+ const target = observer?._target(geometry(at + 2)) ?? null;
3744
+ const read = (i) => geometry(at + i);
3745
+ if (kind === 1) {
3746
+ if (observer && target) {
3747
+ observer._queue(new IntersectionObserverEntry({
3748
+ time,
3749
+ target,
3750
+ isIntersecting: read(3) === 1,
3751
+ isVisible: false,
3752
+ intersectionRatio: read(4),
3753
+ boundingClientRect: new DOMRect(read(5), read(6), read(7), read(8)),
3754
+ intersectionRect: new DOMRect(read(9), read(10), read(11), read(12)),
3755
+ rootBounds: new DOMRect(read(13), read(14), read(15), read(16)),
3756
+ }));
3757
+ }
3758
+ at += 17;
3759
+ } else {
3760
+ if (observer && target) {
3761
+ observer._queue(new ResizeObserverEntry({
3762
+ target,
3763
+ contentRect: new DOMRect(read(3), read(4), read(5), read(6)),
3764
+ borderBoxSize: size(read(7), read(8)),
3765
+ contentBoxSize: size(read(9), read(10)),
3766
+ devicePixelContentBoxSize: size(read(11), read(12)),
3767
+ }));
3768
+ }
3769
+ at += 13;
3770
+ }
3771
+ if (observer && !touched.includes(observer)) touched.push(observer);
3772
+ }
3773
+ // ResizeObserver callbacks first, as browsers run them before intersection updates.
3774
+ for (const observer of touched) if (observer instanceof ResizeObserver) observer._deliver();
3775
+ for (const observer of touched) if (observer instanceof IntersectionObserver) observer._deliver();
3776
+ };
3777
+
3778
+ globalThis.IntersectionObserver ??= IntersectionObserver;
3779
+ globalThis.IntersectionObserverEntry ??= IntersectionObserverEntry;
3780
+ globalThis.ResizeObserver ??= ResizeObserver;
3781
+ globalThis.ResizeObserverEntry ??= ResizeObserverEntry;
3782
+
3783
+ /** The topmost node at window point `x`, `y`, or null. */
3784
+ export function elementFromPoint(x, y) {
3785
+ return nodes.get(native.hit?.(Number(x), Number(y)) ?? 0) ?? null;
3786
+ }
3787
+
3788
+ /** Every node at window point `x`, `y`, topmost first. */
3789
+ export function elementsFromPoint(x, y) {
3790
+ const count = native.hits?.(Number(x), Number(y)) ?? 0;
3791
+ const list = [];
3792
+ for (let i = 0; i < count; i++) {
3793
+ const node = nodes.get(geometry(i));
3794
+ if (node) list.push(node);
3795
+ }
3796
+ return list;
3797
+ }
3798
+
3799
+ /** The text position at window point `x`, `y`: `{ offsetNode, offset, getClientRect() }` (UTF-16 offset), or null. */
3800
+ export function caretPositionFromPoint(x, y) {
3801
+ if (!native.caret?.(Number(x), Number(y))) return null;
3802
+ const offsetNode = nodes.get(geometry(0)) ?? null;
3803
+ const offset = geometry(1);
3804
+ const rect = new DOMRect(geometry(2), geometry(3), geometry(4), geometry(5));
3805
+ return { offsetNode, offset, getClientRect: () => rect };
3806
+ }
3807
+
3808
+ /**
3809
+ * The rectangles of the text from (`startNode`, `startOffset`) to (`endNode`, `endOffset`),
3810
+ * offsets in UTF-16 units as in a DOM `Range`: one per line piece, as `Range.getClientRects`.
3811
+ */
3812
+ export function rangeClientRects(startNode, startOffset, endNode, endOffset) {
3813
+ return readRects(native.rangeRects?.(startNode.nodeId, startOffset, endNode.nodeId, endOffset) ?? 0);
3814
+ }
3815
+
3816
+ /** The union of `rangeClientRects`, as `Range.getBoundingClientRect`. */
3817
+ export function rangeBoundingClientRect(startNode, startOffset, endNode, endOffset) {
3818
+ const rects = rangeClientRects(startNode, startOffset, endNode, endOffset);
3819
+ if (rects.length === 0) return new DOMRect();
3820
+ let left = Infinity, top = Infinity, right = -Infinity, bottom = -Infinity;
3821
+ for (const rect of rects) {
3822
+ left = Math.min(left, rect.left);
3823
+ top = Math.min(top, rect.top);
3824
+ right = Math.max(right, rect.right);
3825
+ bottom = Math.max(bottom, rect.bottom);
3826
+ }
3827
+ return new DOMRect(left, top, right - left, bottom - top);
3828
+ }
3829
+
3830
+ /**
3831
+ * `CSS.supports(property, value)` and `CSS.supports(conditionText)`, answered by the same parser
3832
+ * and property catalog as the tree's `@supports`, so a check here and an `@supports` block in a
3833
+ * stylesheet always agree. Also installed as `globalThis.CSS.supports`.
3834
+ */
3835
+ export function supports(conditionOrProperty, value) {
3836
+ if (!native.supports) return false;
3837
+ return arguments.length > 1 ? native.supports(String(conditionOrProperty), String(value)) : native.supports(String(conditionOrProperty));
3838
+ }
3839
+
3840
+ if (typeof globalThis.CSS !== "object" || globalThis.CSS === null) globalThis.CSS = {};
3841
+ globalThis.CSS.supports ??= supports;
3842
+
1946
3843
  let frameStatsSince = 0;
1947
3844
 
1948
3845
  /**