@silkui/core 0.1.12 → 0.1.13

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
@@ -14,19 +14,23 @@ const STATES = { base: 0, hover: 1, active: 2, focus: 3, focusVisible: 4, starti
14
14
 
15
15
  // Event types by the kind number the host dispatches. Up to `selectionchange`, `pointerover`
16
16
  // and `pointerout` the kind is also the bit of the tree's LISTEN_* flags a node listens with;
17
- // copy, cut and paste share bit 30, and beforeinput has bit 31 (see `bitOf`).
17
+ // `error` shares the bit of `load`, the touch kinds share bit 30, copy, cut, paste and
18
+ // beforeinput bit 31, and the requests (closerequest, navigate) bit 18 (see `bitOf`).
18
19
  const TYPES = [
19
20
  "pointerdown", "pointerup", "click", "pointermove", "pointerenter", "pointerleave", "wheel",
20
21
  "keydown", "keyup", "focus", "blur", "input", "scroll", "layout", "pointercancel",
21
22
  "gotpointercapture", "lostpointercapture", "load", "error", "transitionrun", "transitionstart",
22
23
  "transitionend", "transitioncancel", "animationstart", "animationiteration", "animationend",
23
24
  "animationcancel", "selectionchange", "pointerover", "pointerout", "touchstart", "touchmove",
24
- "touchend", "touchcancel", "copy", "cut", "paste", "beforeinput",
25
+ "touchend", "touchcancel", "copy", "cut", "paste", "beforeinput", "closerequest", "navigate",
25
26
  ];
26
27
  const KIND_OF = new Map(TYPES.map((type, kind) => [type, kind]));
27
28
 
28
29
  // The live `Range`s (see Range below), held weakly: a range nobody holds stops being updated.
29
30
  const liveRanges = new Set();
31
+ // The `MutationObserver`s observing a node (see MutationObserver below). While there are none
32
+ // a mutation costs one size check.
33
+ const mutationObservers = new Set();
30
34
 
31
35
  function eachLiveRange(update) {
32
36
  for (const ref of liveRanges) {
@@ -45,8 +49,15 @@ const COPY = KIND_OF.get("copy");
45
49
  const CUT = KIND_OF.get("cut");
46
50
  const PASTE = KIND_OF.get("paste");
47
51
  const BEFORE_INPUT = KIND_OF.get("beforeinput");
48
- // The listen bit of a kind: the touch kinds share bit 30, copy, cut, paste and beforeinput bit 31.
49
- const bitOf = (kind) => (kind < TOUCH_START ? kind : kind < COPY ? 30 : 31);
52
+ const LOAD = KIND_OF.get("load");
53
+ const ERROR = KIND_OF.get("error");
54
+ const CLOSE_REQUEST = KIND_OF.get("closerequest");
55
+ const NAVIGATE = KIND_OF.get("navigate");
56
+ // The listen bit of a kind: `error` shares the bit of `load`, the touch kinds share bit 30,
57
+ // copy, cut, paste and beforeinput bit 31, and the two requests have the bit after `load`.
58
+ const bitOf = (kind) =>
59
+ kind === ERROR ? LOAD : kind < TOUCH_START ? kind : kind < COPY ? 30 : kind < CLOSE_REQUEST ? 31 : LOAD + 1;
60
+ const SHARES_BIT = (kind) => kind >= TOUCH_START || kind === LOAD || kind === ERROR;
50
61
  const KINDS_OF_BIT = (bit) => TYPES.map((_, kind) => kind).filter((kind) => bitOf(kind) === bit);
51
62
  // Compatibility mouse events, as the web fires them after pointer events: each listens
52
63
  // through the pointer kind it follows.
@@ -68,6 +79,7 @@ const NO_BUBBLE = new Set([
68
79
  const CANCELABLE = new Set([
69
80
  "pointerdown", "pointerup", "click", "wheel", "keydown", "keyup", "dragenter", "dragover", "drop",
70
81
  "mousedown", "mouseup", "mousemove", "mouseover", "mouseout", "selectstart", "copy", "cut", "paste", "beforeinput",
82
+ "closerequest", "navigate",
71
83
  ]);
72
84
  // Files dragged from the desktop: the host dispatches these itself, so nodes need no flag.
73
85
  const DRAG_TYPES = new Set(["dragenter", "dragover", "dragleave", "drop"]);
@@ -584,6 +596,11 @@ export class Node {
584
596
  return siblings ? siblings[siblings.indexOf(this) - 1] ?? null : null;
585
597
  }
586
598
 
599
+ /** Whether the node is in the mounted tree. */
600
+ get isConnected() {
601
+ return inDocument(this);
602
+ }
603
+
587
604
  /** 1 for an element, 3 for text, 11 for a document fragment, as in the DOM. */
588
605
  get nodeType() {
589
606
  return 1;
@@ -629,6 +646,7 @@ export class Node {
629
646
  }
630
647
 
631
648
  _shallowClone() {
649
+ if (this._tag !== undefined && this.constructor === Node) return createElement(this._tag);
632
650
  return new Node(this.kind);
633
651
  }
634
652
 
@@ -684,6 +702,7 @@ export class Node {
684
702
  if (old) {
685
703
  const index = old.childNodes.indexOf(child);
686
704
  if (liveRanges.size) eachLiveRange((range) => range._removing(child, old, index));
705
+ if (mutationObservers.size) childListRecord(old, null, child, old.childNodes[index - 1], old.childNodes[index + 1]);
687
706
  old.childNodes.splice(index, 1);
688
707
  }
689
708
  child.parentNode = this;
@@ -698,6 +717,7 @@ export class Node {
698
717
  this._ownChildren().push(child);
699
718
  native.append(this.nodeId, child.nodeId);
700
719
  }
720
+ if (mutationObservers.size) childListRecord(this, child, null, child.previousSibling, before);
701
721
  return child;
702
722
  }
703
723
 
@@ -726,6 +746,7 @@ export class Node {
726
746
  if (child.parentNode !== this) throw domError("NotFoundError", "the node to remove is not a child of this node");
727
747
  const index = this.childNodes.indexOf(child);
728
748
  if (liveRanges.size) eachLiveRange((range) => range._removing(child, this, index));
749
+ if (mutationObservers.size) childListRecord(this, null, child, this.childNodes[index - 1], this.childNodes[index + 1]);
729
750
  this.childNodes.splice(index, 1);
730
751
  child.parentNode = null;
731
752
  native.remove(child.nodeId);
@@ -743,6 +764,7 @@ export class Node {
743
764
  if (parent) {
744
765
  const index = parent.childNodes.indexOf(this);
745
766
  if (liveRanges.size) eachLiveRange((range) => range._removing(this, parent, index));
767
+ if (mutationObservers.size) childListRecord(parent, null, this, parent.childNodes[index - 1], parent.childNodes[index + 1]);
746
768
  parent.childNodes.splice(index, 1);
747
769
  this.parentNode = null;
748
770
  }
@@ -823,6 +845,7 @@ export class Node {
823
845
  setAttribute(name, value) {
824
846
  name = String(name);
825
847
  let text = value == null ? null : String(value);
848
+ if (mutationObservers.size) attributeRecord(this, name, text);
826
849
  if (name === "className" || name === "class") {
827
850
  native.attribute(this.nodeId, "class", text);
828
851
  this.#className = text;
@@ -866,6 +889,38 @@ export class Node {
866
889
  }
867
890
  if (text === null) this.#rare?.attributes?.delete(name);
868
891
  else (this.#more().attributes ??= new Map()).set(name, text);
892
+ if (name === "contenteditable") this.#editableChanged();
893
+ }
894
+
895
+ // An editing host takes focus (as a tab stop, unless its tabindex says otherwise) and hears
896
+ // the tree's edits, which `hostEdit` makes.
897
+ #editableChanged() {
898
+ if (editableValue(this) === 1) {
899
+ this._keep("beforeinput", "focus", "blur");
900
+ if (!this.hasAttribute("tabindex")) native.attribute(this.nodeId, "tabIndex", 0);
901
+ } else if (!this.hasAttribute("tabindex") && !FOCUSABLE_TAGS.has(this._tag)) {
902
+ native.attribute(this.nodeId, "tabIndex", -2147483648);
903
+ }
904
+ }
905
+
906
+ /** "true", "false", "plaintext-only" or "inherit", from the `contenteditable` attribute. */
907
+ get contentEditable() {
908
+ const value = this.getAttribute("contenteditable");
909
+ if (value === null) return "inherit";
910
+ const lower = value.toLowerCase();
911
+ return lower === "" || lower === "true" ? "true" : lower === "false" || lower === "plaintext-only" ? lower : "inherit";
912
+ }
913
+
914
+ set contentEditable(value) {
915
+ const lower = String(value).toLowerCase();
916
+ if (lower === "inherit") this.removeAttribute("contenteditable");
917
+ else if (lower === "true" || lower === "false" || lower === "plaintext-only") this.setAttribute("contenteditable", lower);
918
+ else throw domError("SyntaxError", "contentEditable takes true, false, plaintext-only or inherit");
919
+ }
920
+
921
+ /** Whether the user can edit the element: it is in an editing host (see `contentEditable`). */
922
+ get isContentEditable() {
923
+ return editingHostOf(this) !== null;
869
924
  }
870
925
 
871
926
  // The `id` other nodes' relations name this node by.
@@ -889,7 +944,7 @@ export class Node {
889
944
  #wanted(kind) {
890
945
  const listeners = this.#rare?.listeners;
891
946
  const has = (type) => (listeners?.get(type)?.length ?? 0) > 0;
892
- if (kind >= TOUCH_START) return [KINDS_OF_BIT(bitOf(kind)).some((each) => has(TYPES[each])), (1 << bitOf(kind)) >>> 0];
947
+ if (SHARES_BIT(kind)) return [KINDS_OF_BIT(bitOf(kind)).some((each) => has(TYPES[each])), (1 << bitOf(kind)) >>> 0];
893
948
  const type = TYPES[kind];
894
949
  const wanted = has(type) || (MOUSE_OF.has(type) && has(MOUSE_OF.get(type))) || (kind === CLICK && (this._href || this._activate))
895
950
  || (kind === SELECTION_CHANGE && has("selectstart"));
@@ -1168,6 +1223,7 @@ export class Text extends Node {
1168
1223
  if (value === old && value !== "") return;
1169
1224
  this.#data = value;
1170
1225
  native.setText(this.nodeId, value);
1226
+ if (mutationObservers.size) characterDataRecord(this, old);
1171
1227
  if (this._svgText) svgChanged(this);
1172
1228
  }
1173
1229
 
@@ -1190,6 +1246,56 @@ export class Text extends Node {
1190
1246
 
1191
1247
  Object.defineProperty(Text.prototype, "kind", { value: "text", writable: true, configurable: true });
1192
1248
 
1249
+ // `<br>`: to the tree a text node of U+2028, which breaks the line whatever `white-space`
1250
+ // says and gives an empty block its line, and to scripts an element with no children. Its
1251
+ // attributes stay here: the tree's text nodes have none.
1252
+ const LINE_BREAK = "\u2028";
1253
+
1254
+ export class LineBreak extends Node {
1255
+ #attributes = new Map();
1256
+
1257
+ constructor() {
1258
+ super("text");
1259
+ this.kind = "text";
1260
+ this._tag = "br";
1261
+ native.setText(this.nodeId, LINE_BREAK);
1262
+ }
1263
+
1264
+ get nodeType() { return 1; }
1265
+ get textContent() { return ""; }
1266
+ set textContent(_value) {}
1267
+ getAttribute(name) { return this.#attributes.get(String(name).toLowerCase()) ?? null; }
1268
+ hasAttribute(name) { return this.#attributes.has(String(name).toLowerCase()); }
1269
+ getAttributeNames() { return [...this.#attributes.keys()]; }
1270
+ removeAttribute(name) { this.setAttribute(name, null); }
1271
+
1272
+ setAttribute(name, value) {
1273
+ name = String(name).toLowerCase();
1274
+ if (name === "classname") name = "class";
1275
+ if (value == null) this.#attributes.delete(name);
1276
+ else this.#attributes.set(name, String(value));
1277
+ }
1278
+
1279
+ get className() { return this.getAttribute("class") ?? ""; }
1280
+ set className(value) { this.setAttribute("class", value); }
1281
+ appendChild() { throw domError("HierarchyRequestError", "a br has no children"); }
1282
+ insertBefore() { throw domError("HierarchyRequestError", "a br has no children"); }
1283
+
1284
+ _shallowClone() {
1285
+ const copy = new LineBreak();
1286
+ for (const [name, value] of this.#attributes) copy.setAttribute(name, value);
1287
+ return copy;
1288
+ }
1289
+
1290
+ cloneNode() { return this._shallowClone(); }
1291
+ }
1292
+
1293
+ // A point the tree has in a `<br>` (its text node), as a point in the br's parent.
1294
+ function fromTreePoint(node, offset) {
1295
+ if (!(node instanceof LineBreak) || !node.parentNode) return [node, offset];
1296
+ return [node.parentNode, indexIn(node) + (offset > 0 ? 1 : 0)];
1297
+ }
1298
+
1193
1299
  /**
1194
1300
  * An editable text field. `value` follows what the user types. Selection offsets are UTF-16
1195
1301
  * string indices, as on the web; the tree counts UTF-8 bytes, converted here.
@@ -1434,9 +1540,9 @@ export class Image extends Node {
1434
1540
  }
1435
1541
 
1436
1542
  /**
1437
- * A canvas the application draws with WebGPU, as a `<canvas>`: `width` and `height` are the
1438
- * size of what is drawn in pixels (300 by 150 at first) and `getContext("webgpu")` gives a
1439
- * `GPUCanvasContext`. The node lays out as an image of that size does: its style can
1543
+ * A canvas the application draws with WebGPU or Canvas 2D, as a `<canvas>`: `width` and
1544
+ * `height` are the size of what is drawn in pixels (300 by 150 at first), `getContext("webgpu")`
1545
+ * gives a `GPUCanvasContext` and `getContext("2d")` a `CanvasRenderingContext2D`. The node lays out as an image of that size does: its style can
1440
1546
  * stretch it, and `objectFit` says how the drawing fits. Drawing happens on a GPU device of
1441
1547
  * the application's own, so a canvas that is slow to draw does not slow the rest of the window.
1442
1548
  */
@@ -1444,6 +1550,7 @@ export class Canvas extends Node {
1444
1550
  #width = 300;
1445
1551
  #height = 150;
1446
1552
  #context = null;
1553
+ #kind = "";
1447
1554
 
1448
1555
  constructor() {
1449
1556
  super("canvas");
@@ -1471,12 +1578,17 @@ export class Canvas extends Node {
1471
1578
  this.#context?._resized();
1472
1579
  }
1473
1580
 
1474
- /** The canvas's `GPUCanvasContext` for "webgpu"; null for any other kind of context. */
1475
- getContext(kind) {
1476
- if (kind !== "webgpu") return null;
1477
- if (this.#context) return this.#context;
1478
- const api = native.gpuLoad?.();
1479
- return api ? (this.#context = api.context(this)) : null;
1581
+ /**
1582
+ * The canvas's `GPUCanvasContext` for "webgpu" or `CanvasRenderingContext2D` for "2d"; null
1583
+ * for any other kind, or for a kind other than the one the canvas already has.
1584
+ */
1585
+ getContext(kind, options) {
1586
+ if (kind !== "webgpu" && kind !== "2d") return null;
1587
+ if (this.#context) return this.#kind === kind ? this.#context : null;
1588
+ const api = kind === "2d" ? native.canvas2dLoad?.() : native.gpuLoad?.();
1589
+ if (!api) return null;
1590
+ this.#kind = kind;
1591
+ return (this.#context = api.context(this, options));
1480
1592
  }
1481
1593
 
1482
1594
  setAttribute(name, value) {
@@ -2624,6 +2736,7 @@ export function createElement(tag, options) {
2624
2736
  else if (tag === "textarea") node = new Input();
2625
2737
  else if (tag === "img") node = new Image();
2626
2738
  else if (tag === "canvas") node = new Canvas();
2739
+ else if (tag === "br") return new LineBreak();
2627
2740
  else node = new Node("box");
2628
2741
  node._tag = tag;
2629
2742
  native.attribute(node.nodeId, "element", tag);
@@ -3381,21 +3494,23 @@ export class Selection {
3381
3494
  #sync() {
3382
3495
  if (this.#pending) this.#flush();
3383
3496
  const count = native.selection?.() ?? 0;
3384
- const anchor = count ? nodes.get(geometry(0)) : null;
3385
- const focus = count ? nodes.get(geometry(2)) : null;
3386
- if (!anchor || !focus) {
3497
+ const rawAnchor = count ? nodes.get(geometry(0)) : null;
3498
+ const rawFocus = count ? nodes.get(geometry(2)) : null;
3499
+ if (!rawAnchor || !rawFocus) {
3387
3500
  if (this.#anchor) this.#forget();
3388
3501
  return;
3389
3502
  }
3503
+ const [anchor, anchorOffset] = fromTreePoint(rawAnchor, geometry(1));
3504
+ const [focus, focusOffset] = fromTreePoint(rawFocus, geometry(3));
3390
3505
  const stretches = [];
3391
3506
  for (let i = 0; i < count; i++) {
3392
3507
  const at = 4 + 4 * i;
3393
3508
  const start = nodes.get(geometry(at));
3394
3509
  const end = nodes.get(geometry(at + 2));
3395
- if (start && end) stretches.push([start, geometry(at + 1), end, geometry(at + 3)]);
3510
+ if (start && end) stretches.push([...fromTreePoint(start, geometry(at + 1)), ...fromTreePoint(end, geometry(at + 3))]);
3396
3511
  }
3397
- const same = anchor === this.#anchor && geometry(1) === this.#anchorOffset && focus === this.#focus
3398
- && geometry(3) === this.#focusOffset && stretches.length === this.#ranges.length
3512
+ const same = anchor === this.#anchor && anchorOffset === this.#anchorOffset && focus === this.#focus
3513
+ && focusOffset === this.#focusOffset && stretches.length === this.#ranges.length
3399
3514
  && stretches.every(([a, b, c, d], i) => {
3400
3515
  const range = this.#ranges[i];
3401
3516
  return range._startNode === a && range._startOffset === b && range._endNode === c && range._endOffset === d;
@@ -3403,9 +3518,9 @@ export class Selection {
3403
3518
  if (same) return;
3404
3519
  this.#unhook();
3405
3520
  this.#anchor = anchor;
3406
- this.#anchorOffset = geometry(1);
3521
+ this.#anchorOffset = anchorOffset;
3407
3522
  this.#focus = focus;
3408
- this.#focusOffset = geometry(3);
3523
+ this.#focusOffset = focusOffset;
3409
3524
  this.#backward = comparePoints(anchor, this.#anchorOffset, focus, this.#focusOffset) > 0;
3410
3525
  this.#ranges = stretches.map(([a, b, c, d]) => {
3411
3526
  const range = new Range();
@@ -3637,6 +3752,8 @@ function selectionRecord(target, start) {
3637
3752
  const event = new Event(start === 1 ? "selectstart" : "selectionchange", target);
3638
3753
  if (start !== 1) event.bubbles = false;
3639
3754
  dispatchEvent(event);
3755
+ // As on the web, `selectionchange` is the document's event too.
3756
+ if (start !== 1 && outerTargets.length) outerTargets[0].dispatchEvent?.(new Event("selectionchange", null));
3640
3757
  if (event.defaultPrevented) {
3641
3758
  const selection = getSelection();
3642
3759
  selection.removeAllRanges();
@@ -3647,6 +3764,16 @@ function selectionRecord(target, start) {
3647
3764
  }
3648
3765
 
3649
3766
  let rootNode = null;
3767
+ // What events pass above the root, outermost last: the document and the window of a DOM layer
3768
+ // over the tree (`@silkui/core/globals`). Each has `_run(event, capture)` as a node does.
3769
+ let outerTargets = [];
3770
+ // Events the web does not send on to the document and the window.
3771
+ const NOT_OUTER = new Set(["scroll", "layout", "load", "error"]);
3772
+
3773
+ /** Has events that reach the root go on to `targets` (outermost last), as `@silkui/core/globals` does for `document` and `window`. */
3774
+ export function setOuterTargets(...targets) {
3775
+ outerTargets = targets;
3776
+ }
3650
3777
 
3651
3778
  /** Makes `node` the root of the window's tree. */
3652
3779
  /**
@@ -3801,6 +3928,7 @@ export class Event {
3801
3928
  composedPath() {
3802
3929
  const path = [];
3803
3930
  for (let node = this.target; node; node = node.parentNode) path.push(node);
3931
+ if (outerTargets.length && path[path.length - 1] === rootNode && !NOT_OUTER.has(this.type)) path.push(...outerTargets);
3804
3932
  return path;
3805
3933
  }
3806
3934
  }
@@ -3966,6 +4094,7 @@ function fill(event, kind, a, b, modifiers, d, e, first, second, third, fourth)
3966
4094
  export function dispatchEvent(event) {
3967
4095
  const path = [];
3968
4096
  for (let node = event.target; node; node = node.parentNode) path.push(node);
4097
+ if (outerTargets.length && path[path.length - 1] === rootNode && !NOT_OUTER.has(event.type)) path.push(...outerTargets);
3969
4098
  for (let i = path.length - 1; i > 0 && !event._stopped; i--) {
3970
4099
  event.eventPhase = 1;
3971
4100
  event.currentTarget = path[i];
@@ -4050,6 +4179,7 @@ function compatTap(click, target) {
4050
4179
  native.dispatch = function (kind, id, a, b, modifiers, d, e, first, second, third, fourth) {
4051
4180
  const target = nodes.get(id);
4052
4181
  if (!target) return false;
4182
+ if (kind >= CLOSE_REQUEST) return dispatchRequest(kind, target, a);
4053
4183
  if (kind >= COPY) return dispatchEditing(kind, target, first, second, third);
4054
4184
  if (kind === SELECTION_CHANGE && !(target instanceof Input)) return selectionRecord(target, a);
4055
4185
  if (kind === FOCUS) focusing(target);
@@ -4083,11 +4213,416 @@ native.dispatch = function (kind, id, a, b, modifiers, d, e, first, second, thir
4083
4213
  return prevented;
4084
4214
  };
4085
4215
 
4216
+ // The tree's requests, raised after an Escape, a back key or a back mouse button that nothing
4217
+ // prevented: `closerequest` asks to close what is on top, as a web close watcher hears, and
4218
+ // `navigate` asks to go back or forward, with `navigationType` "traverse" and `direction`
4219
+ // "back" or "forward". The listener that acts stops the event; the tree does nothing itself.
4220
+ function dispatchRequest(kind, target, forward) {
4221
+ const event = new Event(TYPES[kind], target);
4222
+ if (kind === NAVIGATE) {
4223
+ event.navigationType = "traverse";
4224
+ event.direction = forward ? "forward" : "back";
4225
+ }
4226
+ dispatchEvent(event);
4227
+ return event.defaultPrevented;
4228
+ }
4229
+
4230
+ // Editing hosts, as the HTML Standard's contenteditable has them. The tree sends a focused
4231
+ // host's typing, composition, deleting, line breaks and pastes as `beforeinput` records;
4232
+ // unless a listener prevents one, `hostEdit` makes the change in the host's nodes, moves
4233
+ // the selection after it and fires `input`, as a browser's editing does. Editors that keep
4234
+ // their own model (ProseMirror) prevent what they handle and read the rest back from the
4235
+ // nodes, through mutation observers.
4236
+
4237
+ // 1 for an editable `contenteditable` ("", "true", "plaintext-only"), 2 for "false", else 0.
4238
+ function editableValue(node) {
4239
+ const value = node.nodeType === 1 ? node.getAttribute("contenteditable") : null;
4240
+ if (value === null) return 0;
4241
+ const lower = value.toLowerCase();
4242
+ return lower === "" || lower === "true" || lower === "plaintext-only" ? 1 : lower === "false" ? 2 : 0;
4243
+ }
4244
+
4245
+ /** The editing host `node` is in (the outermost editable element up to a `contenteditable="false"`), or null. */
4246
+ export function editingHostOf(node) {
4247
+ let host = null;
4248
+ for (let at = node; at; at = at.parentNode) {
4249
+ const value = editableValue(at);
4250
+ if (value === 2) return host;
4251
+ if (value === 1) host = at;
4252
+ }
4253
+ return host;
4254
+ }
4255
+
4256
+ export class CompositionEvent extends Event {
4257
+ constructor(type, init = {}) {
4258
+ super(String(type), null);
4259
+ this.bubbles = init.bubbles ?? true;
4260
+ this.cancelable = !!init.cancelable;
4261
+ this.composed = init.composed ?? true;
4262
+ this.data = init.data ?? "";
4263
+ }
4264
+ }
4265
+
4266
+ globalThis.CompositionEvent ??= CompositionEvent;
4267
+
4268
+ // Tags that start a block of their own, for joining and splitting paragraphs.
4269
+ const BLOCK_TAGS = new Set([
4270
+ "address", "article", "aside", "blockquote", "dd", "details", "div", "dl", "dt", "fieldset", "figcaption",
4271
+ "figure", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "header", "hr", "li", "main", "nav", "ol",
4272
+ "p", "pre", "section", "summary", "table", "td", "th", "tr", "ul",
4273
+ ]);
4274
+
4275
+ function isBlock(node) {
4276
+ return node.nodeType === 1 && !(node instanceof LineBreak) && (BLOCK_TAGS.has(node.localName) || node.kind === "box" && node._tag === undefined);
4277
+ }
4278
+
4279
+ // The block `node` is in, inside `host` (the host itself when there is none).
4280
+ function blockIn(host, node) {
4281
+ for (let at = node; at && at !== host; at = at.parentNode) if (isBlock(at)) return at;
4282
+ return host;
4283
+ }
4284
+
4285
+ // What the caret steps over: text, `<br>`s and elements with no children (images).
4286
+ function isLeaf(node) {
4287
+ return node.nodeType === 3 ? node.length > 0 : node.nodeType === 1 && node.childNodes.length === 0 && !isBlock(node);
4288
+ }
4289
+
4290
+ // The leaf before (or after) the point (`container`, `offset`) in tree order, inside `host`.
4291
+ function leafBeside(host, container, offset, forward) {
4292
+ let node;
4293
+ if (container.nodeType === 3) node = container;
4294
+ else if (forward) {
4295
+ node = container.childNodes[offset];
4296
+ if (!node) node = following(container, host, true);
4297
+ else if (isLeaf(node)) return node;
4298
+ } else {
4299
+ node = container.childNodes[offset - 1];
4300
+ if (node) {
4301
+ while (node.lastChild) node = node.lastChild;
4302
+ if (isLeaf(node)) return node;
4303
+ } else node = container;
4304
+ }
4305
+ if (forward) {
4306
+ for (let at = node === container && container.nodeType === 3 ? following(node, host, true) : node; at; at = following(at, host)) {
4307
+ if (isLeaf(at)) return at;
4308
+ }
4309
+ } else {
4310
+ for (let at = preceding(node, host); at; at = preceding(at, host)) if (isLeaf(at)) return at;
4311
+ }
4312
+ return null;
4313
+ }
4314
+
4315
+ // The node before `node` in tree order (its previous sibling's last descendant, or its
4316
+ // parent), inside `within`.
4317
+ function preceding(node, within) {
4318
+ if (node === within) return null;
4319
+ let at = node.previousSibling;
4320
+ if (!at) return node.parentNode === within ? null : node.parentNode;
4321
+ while (at.lastChild) at = at.lastChild;
4322
+ return at;
4323
+ }
4324
+
4325
+ const segmenter = typeof Intl !== "undefined" && Intl.Segmenter ? new Intl.Segmenter() : null;
4326
+
4327
+ // The UTF-16 offset of the grapheme boundary before (or after) `offset` in `text`.
4328
+ function graphemeStep(text, offset, forward) {
4329
+ if (segmenter) {
4330
+ let last = 0;
4331
+ for (const { index } of segmenter.segment(text)) {
4332
+ if (forward && index > offset) return index;
4333
+ if (!forward && index >= offset) return last;
4334
+ last = index;
4335
+ }
4336
+ return forward ? text.length : last;
4337
+ }
4338
+ const code = forward ? text.charCodeAt(offset) : text.charCodeAt(offset - 1);
4339
+ const pair = forward ? code >= 0xd800 && code < 0xdc00 : code >= 0xdc00 && code < 0xe000;
4340
+ return forward ? Math.min(text.length, offset + (pair ? 2 : 1)) : Math.max(0, offset - (pair ? 2 : 1));
4341
+ }
4342
+
4343
+ function wordStep(text, offset, forward) {
4344
+ if (forward) {
4345
+ const rest = /^\s*\S*/.exec(text.slice(offset))[0];
4346
+ return offset + Math.max(rest.length, 1);
4347
+ }
4348
+ const before = /\S*\s*$/.exec(text.slice(0, offset))[0];
4349
+ return offset - Math.max(before.length, 1);
4350
+ }
4351
+
4352
+ // Makes (`node`, `offset`) a point between children: splits text there.
4353
+ function elementPoint(node, offset) {
4354
+ if (node.nodeType !== 3) return [node, offset];
4355
+ const parent = node.parentNode;
4356
+ if (offset === 0) return [parent, indexIn(node)];
4357
+ if (offset < node.length) node.splitText(offset);
4358
+ return [parent, indexIn(node) + 1];
4359
+ }
4360
+
4361
+ // Gives an empty block a `<br>`, so it keeps a line for the caret.
4362
+ function keepLine(block) {
4363
+ for (let at = block.firstChild; at; at = following(at, block)) if (isLeaf(at)) return;
4364
+ block.appendChild(new LineBreak());
4365
+ }
4366
+
4367
+ // Moves `from`'s content to the end of `into` and removes `from`, as deleting the boundary
4368
+ // between two paragraphs does. Returns the point where they met.
4369
+ function joinBlocks(into, from) {
4370
+ onlyBreak(into)?.remove();
4371
+ if (leafBeside(into, into, 0, true)) onlyBreak(from)?.remove();
4372
+ const point = into.lastChild?.nodeType === 3 ? [into.lastChild, into.lastChild.length] : [into, into.childNodes.length];
4373
+ while (from.firstChild) into.appendChild(from.firstChild);
4374
+ from.remove();
4375
+ return point;
4376
+ }
4377
+
4378
+ // The `<br>` that alone gives `block` its line, if that is all it holds.
4379
+ function onlyBreak(block) {
4380
+ let found = null;
4381
+ for (let at = block.firstChild; at; at = following(at, block)) {
4382
+ if (!isLeaf(at)) continue;
4383
+ if (found || !(at instanceof LineBreak)) return null;
4384
+ found = at;
4385
+ }
4386
+ return found;
4387
+ }
4388
+
4389
+ // Splits `block` at (`node`, `offset`): what follows goes to a copy of the block (and of each
4390
+ // element on the way) after it. Returns the copy.
4391
+ function splitBlock(block, node, offset) {
4392
+ let [level, at] = elementPoint(node, offset);
4393
+ let carried = null;
4394
+ for (;;) {
4395
+ const copy = level.cloneNode(false);
4396
+ if (carried) copy.appendChild(carried);
4397
+ while (level.childNodes.length > at) copy.appendChild(level.childNodes[at]);
4398
+ if (level === block) {
4399
+ block.parentNode.insertBefore(copy, block.nextSibling);
4400
+ keepLine(block);
4401
+ keepLine(copy);
4402
+ return copy;
4403
+ }
4404
+ carried = copy;
4405
+ at = indexIn(level) + 1;
4406
+ level = level.parentNode;
4407
+ }
4408
+ }
4409
+
4410
+ // The first point in text (or the start) inside `node`.
4411
+ function startIn(node) {
4412
+ for (let at = node; at; at = following(at, node)) {
4413
+ if (at.nodeType === 3) return [at, 0];
4414
+ if (at instanceof LineBreak) return [at.parentNode, indexIn(at)];
4415
+ }
4416
+ return [node, 0];
4417
+ }
4418
+
4419
+ // Inserts `text` at the collapsed point (`node`, `offset`); returns the point after it.
4420
+ // Line breaks in it become `<br>`s.
4421
+ function insertText(node, offset, text) {
4422
+ const lines = text.split(/\r\n|\r|\n/);
4423
+ for (let i = 0; i < lines.length; i++) {
4424
+ if (i > 0) {
4425
+ [node, offset] = elementPoint(node, offset);
4426
+ node.insertBefore(new LineBreak(), node.childNodes[offset] ?? null);
4427
+ offset += 1;
4428
+ }
4429
+ const line = lines[i];
4430
+ if (!line) continue;
4431
+ if (node.nodeType === 3) {
4432
+ node.insertData(offset, line);
4433
+ offset += line.length;
4434
+ continue;
4435
+ }
4436
+ const before = node.childNodes[offset - 1];
4437
+ const after = node.childNodes[offset];
4438
+ if (before?.nodeType === 3) {
4439
+ const at = before.length;
4440
+ before.appendData(line);
4441
+ [node, offset] = [before, at + line.length];
4442
+ } else if (after?.nodeType === 3) {
4443
+ after.insertData(0, line);
4444
+ [node, offset] = [after, line.length];
4445
+ } else {
4446
+ const created = new Text(line);
4447
+ node.insertBefore(created, after ?? null);
4448
+ [node, offset] = [created, line.length];
4449
+ }
4450
+ }
4451
+ return [node, offset];
4452
+ }
4453
+
4454
+ // Deletes what `range` covers; paragraphs it crossed into become one. Returns the point
4455
+ // where the deleted content was.
4456
+ function deleteRange(host, range) {
4457
+ const startBlock = blockIn(host, range.startContainer);
4458
+ const endBlock = blockIn(host, range.endContainer);
4459
+ range.deleteContents();
4460
+ let point = [range.startContainer, range.startOffset];
4461
+ if (startBlock !== endBlock && startBlock.isConnected !== false && endBlock.parentNode && host.contains(endBlock) && host.contains(startBlock)) {
4462
+ point = joinBlocks(startBlock, endBlock);
4463
+ }
4464
+ if (startBlock !== host) keepLine(startBlock);
4465
+ return point;
4466
+ }
4467
+
4468
+ // Deletes one step (a grapheme, a word, to the line's edge) before or after the caret.
4469
+ function deleteStep(host, node, offset, forward, unit) {
4470
+ if (node.nodeType === 3 && (forward ? offset < node.length : offset > 0)) {
4471
+ const data = node.data;
4472
+ const to = unit === "word" ? wordStep(data, offset, forward)
4473
+ : unit === "line" ? (forward ? data.length : 0)
4474
+ : graphemeStep(data, offset, forward);
4475
+ const start = Math.min(offset, to);
4476
+ node.deleteData(start, Math.abs(to - offset));
4477
+ const block = blockIn(host, node);
4478
+ if (block !== host) keepLine(block);
4479
+ return [node, start];
4480
+ }
4481
+ const leaf = leafBeside(host, node, offset, forward);
4482
+ if (!leaf) return [node, offset];
4483
+ const here = blockIn(host, node);
4484
+ const there = blockIn(host, leaf);
4485
+ if (here === there || here === host || there === host) {
4486
+ if (leaf.nodeType === 3) return deleteStep(host, leaf, forward ? 0 : leaf.length, forward, unit);
4487
+ const parent = leaf.parentNode;
4488
+ const index = indexIn(leaf);
4489
+ leaf.remove();
4490
+ if (here !== host) keepLine(here);
4491
+ return [parent, index];
4492
+ }
4493
+ return forward ? joinBlocks(here, there) : joinBlocks(there, here);
4494
+ }
4495
+
4496
+ const compositions = new WeakMap();
4497
+
4498
+ function editEvent(type, host, inputType, data, isComposing, cancelable = true) {
4499
+ const event = new InputEvent(type, { bubbles: true, cancelable, composed: true, inputType, data, isComposing });
4500
+ event.target = host;
4501
+ dispatchEvent(event);
4502
+ return event;
4503
+ }
4504
+
4505
+ function compositionEvent(type, host, data) {
4506
+ const event = new CompositionEvent(type, { data });
4507
+ event.target = host;
4508
+ dispatchEvent(event);
4509
+ }
4510
+
4511
+ // The edit `inputType` with `data` that the tree asked of `host`. Returns whether a listener
4512
+ // prevented it.
4513
+ function hostEdit(host, inputType, data) {
4514
+ const plain = editableValue(host) === 1 && host.getAttribute("contenteditable").toLowerCase() === "plaintext-only";
4515
+ const selection = getSelection();
4516
+ let range = selection.rangeCount ? selection.getRangeAt(0) : null;
4517
+ if (range && (!host.contains(range.startContainer) || !host.contains(range.endContainer))) range = null;
4518
+ const composing = compositions.get(host);
4519
+
4520
+ if (inputType === "insertCompositionText" || composing && inputType === "insertText") {
4521
+ if (!composing && !data) return false;
4522
+ let start;
4523
+ if (!composing) {
4524
+ compositionEvent("compositionstart", host, range ? range.toString() : "");
4525
+ if (!range) return false;
4526
+ start = range.collapsed ? [range.startContainer, range.startOffset] : deleteRange(host, range);
4527
+ } else {
4528
+ start = [composing.node, composing.offset];
4529
+ }
4530
+ const committing = inputType === "insertText";
4531
+ if (!committing) compositionEvent("compositionupdate", host, data);
4532
+ editEvent("beforeinput", host, committing ? "insertFromComposition" : "insertCompositionText", data, !committing, false);
4533
+ let [node, offset] = start;
4534
+ if (composing && composing.node.isConnected !== false && composing.node.nodeType === 3) {
4535
+ composing.node.deleteData(composing.offset, Math.min(composing.length, composing.node.length - composing.offset));
4536
+ }
4537
+ const end = data ? insertText(node, offset, data) : [node, offset];
4538
+ // Text inserted into an element point lands in a text node: the composition starts there.
4539
+ if (node.nodeType !== 3 && end[0].nodeType === 3) [node, offset] = [end[0], end[1] - data.length];
4540
+ selection.collapse(end[0], end[1]);
4541
+ editEvent("input", host, committing ? "insertFromComposition" : "insertCompositionText", data, !committing, false);
4542
+ if (committing || !data) {
4543
+ compositions.delete(host);
4544
+ compositionEvent("compositionend", host, data);
4545
+ } else {
4546
+ compositions.set(host, { node, offset, length: data.length });
4547
+ }
4548
+ return false;
4549
+ }
4550
+
4551
+ const event = editEvent("beforeinput", host, inputType, data || null, false);
4552
+ if (event.defaultPrevented || !range) return event.defaultPrevented;
4553
+ let point;
4554
+ const collapsed = range.collapsed;
4555
+ switch (inputType) {
4556
+ case "insertText":
4557
+ case "insertReplacementText":
4558
+ case "insertFromPaste":
4559
+ case "insertFromDrop": {
4560
+ point = collapsed ? [range.startContainer, range.startOffset] : deleteRange(host, range);
4561
+ point = insertText(point[0], point[1], data);
4562
+ break;
4563
+ }
4564
+ case "insertLineBreak":
4565
+ case "insertParagraph": {
4566
+ point = collapsed ? [range.startContainer, range.startOffset] : deleteRange(host, range);
4567
+ const block = blockIn(host, point[0]);
4568
+ if (inputType === "insertParagraph" && !plain && block !== host) {
4569
+ point = startIn(splitBlock(block, point[0], point[1]));
4570
+ } else {
4571
+ const [parent, index] = elementPoint(point[0], point[1]);
4572
+ parent.insertBefore(new LineBreak(), parent.childNodes[index] ?? null);
4573
+ // A break that ends its block needs another after it for the new line to show.
4574
+ if (!leafBeside(block, parent, index + 1, true)) parent.insertBefore(new LineBreak(), parent.childNodes[index + 1] ?? null);
4575
+ point = [parent, index + 1];
4576
+ }
4577
+ break;
4578
+ }
4579
+ case "deleteByCut":
4580
+ case "deleteByDrag":
4581
+ case "deleteContent":
4582
+ if (collapsed) return false;
4583
+ point = deleteRange(host, range);
4584
+ break;
4585
+ default: {
4586
+ const match = /^delete(Content|Word|SoftLine|HardLine)(Backward|Forward)$/.exec(inputType);
4587
+ if (!match) return false;
4588
+ if (!collapsed) point = deleteRange(host, range);
4589
+ else {
4590
+ const unit = match[1] === "Content" ? "grapheme" : match[1] === "Word" ? "word" : "line";
4591
+ point = deleteStep(host, range.startContainer, range.startOffset, match[2] === "Forward", unit);
4592
+ }
4593
+ }
4594
+ }
4595
+ selection.collapse(point[0], point[1]);
4596
+ editEvent("input", host, inputType, data || null, false, false);
4597
+ return false;
4598
+ }
4599
+
4600
+ /**
4601
+ * The classic editing commands an editor may still call: `insertText`, `delete`,
4602
+ * `forwardDelete`, `insertParagraph`, `insertLineBreak` and `selectAll`, in the focused
4603
+ * editing host. Returns whether it ran.
4604
+ */
4605
+ export function execCommand(command, _showUI = false, value = "") {
4606
+ const selection = getSelection();
4607
+ const node = selection.rangeCount ? selection.getRangeAt(0).startContainer : null;
4608
+ const host = node ? editingHostOf(node) : null;
4609
+ if (!host) return false;
4610
+ if (command === "selectAll") {
4611
+ selection.selectAllChildren(host);
4612
+ return true;
4613
+ }
4614
+ const inputType = { insertText: "insertText", delete: "deleteContentBackward", forwardDelete: "deleteContentForward", insertParagraph: "insertParagraph", insertLineBreak: "insertLineBreak", insertHTML: "insertText" }[command];
4615
+ if (!inputType) return false;
4616
+ hostEdit(host, inputType, inputType === "insertText" ? String(value) : "");
4617
+ return true;
4618
+ }
4619
+
4086
4620
  // Copy, cut and paste as the Clipboard API and events spec has them, and beforeinput. A
4087
4621
  // paste carries the clipboard's text, HTML and a PNG (bytes as a Latin-1 string). A copy or
4088
4622
  // cut a listener prevented puts what it set on `clipboardData` on the clipboard; one it did
4089
4623
  // not prevent lets the tree copy the selection.
4090
4624
  function dispatchEditing(kind, target, first, second, third) {
4625
+ if (kind === BEFORE_INPUT && !(target instanceof Input) && editingHostOf(target) === target) return hostEdit(target, second ?? "", first ?? "");
4091
4626
  let event;
4092
4627
  if (kind === BEFORE_INPUT) {
4093
4628
  event = new InputEvent("beforeinput", { bubbles: true, cancelable: true, composed: true, inputType: second ?? "", data: first ?? "" });
@@ -5749,3 +6284,116 @@ export function frameStats() {
5749
6284
  max: native.frameStats(5),
5750
6285
  };
5751
6286
  }
6287
+
6288
+ // MutationObserver, as in the DOM Standard, for the tree's nodes: child lists, attributes and
6289
+ // text. Records are queued as the mutations happen and delivered in one microtask.
6290
+
6291
+ class MutationRecord {
6292
+ constructor(type, target, fields) {
6293
+ this.type = type;
6294
+ this.target = target;
6295
+ this.addedNodes = fields.addedNodes ?? [];
6296
+ this.removedNodes = fields.removedNodes ?? [];
6297
+ this.previousSibling = fields.previousSibling ?? null;
6298
+ this.nextSibling = fields.nextSibling ?? null;
6299
+ this.attributeName = fields.attributeName ?? null;
6300
+ this.attributeNamespace = null;
6301
+ this.oldValue = fields.oldValue ?? null;
6302
+ }
6303
+ }
6304
+
6305
+ let mutationsQueued = false;
6306
+
6307
+ function queueRecord(type, target, fields, wants, oldValueOption, filterName) {
6308
+ for (const observer of mutationObservers) {
6309
+ let options = null;
6310
+ for (let node = target; node; node = node.parentNode) {
6311
+ const found = observer._targets.get(node);
6312
+ if (found && (node === target || found.subtree) && found[wants]) {
6313
+ if (filterName !== undefined && found.attributeFilter && !found.attributeFilter.includes(filterName)) continue;
6314
+ options = found;
6315
+ break;
6316
+ }
6317
+ }
6318
+ if (!options) continue;
6319
+ const record = new MutationRecord(type, target, fields);
6320
+ if (oldValueOption && !options[oldValueOption]) record.oldValue = null;
6321
+ observer._records.push(record);
6322
+ if (!mutationsQueued) {
6323
+ mutationsQueued = true;
6324
+ queueMicrotask(deliverMutations);
6325
+ }
6326
+ }
6327
+ }
6328
+
6329
+ function deliverMutations() {
6330
+ mutationsQueued = false;
6331
+ for (const observer of [...mutationObservers]) {
6332
+ const records = observer.takeRecords();
6333
+ if (records.length === 0) continue;
6334
+ try {
6335
+ observer._callback.call(observer, records, observer);
6336
+ } catch (error) {
6337
+ reportError(error);
6338
+ }
6339
+ }
6340
+ }
6341
+
6342
+ function childListRecord(parent, added, removed, previousSibling, nextSibling) {
6343
+ queueRecord("childList", parent, {
6344
+ addedNodes: added ? [added] : [],
6345
+ removedNodes: removed ? [removed] : [],
6346
+ previousSibling: previousSibling ?? null,
6347
+ nextSibling: nextSibling ?? null,
6348
+ }, "childList");
6349
+ }
6350
+
6351
+ function attributeRecord(node, name, text) {
6352
+ const old = node.getAttribute(name);
6353
+ if (old === text) return;
6354
+ queueRecord("attributes", node, { attributeName: name, oldValue: old }, "attributes", "attributeOldValue", name);
6355
+ }
6356
+
6357
+ function characterDataRecord(node, old) {
6358
+ queueRecord("characterData", node, { oldValue: old }, "characterData", "characterDataOldValue");
6359
+ }
6360
+
6361
+ export class MutationObserver {
6362
+ constructor(callback) {
6363
+ if (typeof callback !== "function") throw new TypeError("MutationObserver needs a function");
6364
+ this._callback = callback;
6365
+ this._targets = new Map();
6366
+ this._records = [];
6367
+ }
6368
+
6369
+ observe(target, options = {}) {
6370
+ if (!(target instanceof Node)) return;
6371
+ const attributes = options.attributes ?? (options.attributeOldValue !== undefined || options.attributeFilter !== undefined);
6372
+ const characterData = options.characterData ?? options.characterDataOldValue !== undefined;
6373
+ if (!options.childList && !attributes && !characterData) {
6374
+ throw new TypeError("MutationObserver.observe needs childList, attributes or characterData");
6375
+ }
6376
+ this._targets.set(target, {
6377
+ childList: !!options.childList,
6378
+ attributes: !!attributes,
6379
+ characterData: !!characterData,
6380
+ subtree: !!options.subtree,
6381
+ attributeOldValue: !!options.attributeOldValue,
6382
+ characterDataOldValue: !!options.characterDataOldValue,
6383
+ attributeFilter: options.attributeFilter ? Array.from(options.attributeFilter, String) : null,
6384
+ });
6385
+ mutationObservers.add(this);
6386
+ }
6387
+
6388
+ disconnect() {
6389
+ this._targets.clear();
6390
+ this._records = [];
6391
+ mutationObservers.delete(this);
6392
+ }
6393
+
6394
+ takeRecords() {
6395
+ const records = this._records;
6396
+ this._records = [];
6397
+ return records;
6398
+ }
6399
+ }