@silkui/core 0.1.9 → 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.js CHANGED
@@ -12,15 +12,16 @@ if (!native) throw new Error("@silkui/core needs the __ui functions of a ui-js h
12
12
  const KINDS = { box: 0, text: 1, input: 2, image: 3, icon: 4, canvas: 5 };
13
13
  const STATES = { base: 0, hover: 1, active: 2, focus: 3, focusVisible: 4, starting: 5 };
14
14
 
15
- // Event types in the order of the tree's LISTEN_* flags: the index is the kind number the
16
- // host dispatches and the bit a node listens with.
15
+ // Event types by the kind number the host dispatches. Up to `selectionchange`, `pointerover`
16
+ // and `pointerout` the kind is also the bit of the tree's LISTEN_* flags a node listens with;
17
+ // copy, cut and paste share bit 30, and beforeinput has bit 31 (see `bitOf`).
17
18
  const TYPES = [
18
19
  "pointerdown", "pointerup", "click", "pointermove", "pointerenter", "pointerleave", "wheel",
19
20
  "keydown", "keyup", "focus", "blur", "input", "scroll", "layout", "pointercancel",
20
21
  "gotpointercapture", "lostpointercapture", "load", "error", "transitionrun", "transitionstart",
21
22
  "transitionend", "transitioncancel", "animationstart", "animationiteration", "animationend",
22
23
  "animationcancel", "selectionchange", "pointerover", "pointerout", "touchstart", "touchmove",
23
- "touchend", "touchcancel",
24
+ "touchend", "touchcancel", "copy", "cut", "paste", "beforeinput",
24
25
  ];
25
26
  const KIND_OF = new Map(TYPES.map((type, kind) => [type, kind]));
26
27
 
@@ -38,8 +39,13 @@ function eachLiveRange(update) {
38
39
  const CLICK = KIND_OF.get("click");
39
40
  const SELECTION_CHANGE = KIND_OF.get("selectionchange");
40
41
  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;
42
+ const COPY = KIND_OF.get("copy");
43
+ const CUT = KIND_OF.get("cut");
44
+ const PASTE = KIND_OF.get("paste");
45
+ const BEFORE_INPUT = KIND_OF.get("beforeinput");
46
+ // The listen bit of a kind: the touch kinds share bit 30, copy, cut, paste and beforeinput bit 31.
47
+ const bitOf = (kind) => (kind < TOUCH_START ? kind : kind < COPY ? 30 : 31);
48
+ const KINDS_OF_BIT = (bit) => TYPES.map((_, kind) => kind).filter((kind) => bitOf(kind) === bit);
43
49
  // Compatibility mouse events, as the web fires them after pointer events: each listens
44
50
  // through the pointer kind it follows.
45
51
  const MOUSE_OF = new Map([
@@ -59,7 +65,7 @@ const NO_BUBBLE = new Set([
59
65
  // The tree has a default action to skip for these. Touch records say for themselves.
60
66
  const CANCELABLE = new Set([
61
67
  "pointerdown", "pointerup", "click", "wheel", "keydown", "keyup", "dragenter", "dragover", "drop",
62
- "mousedown", "mouseup", "mousemove", "mouseover", "mouseout", "selectstart",
68
+ "mousedown", "mouseup", "mousemove", "mouseover", "mouseout", "selectstart", "copy", "cut", "paste", "beforeinput",
63
69
  ]);
64
70
  // Files dragged from the desktop: the host dispatches these itself, so nodes need no flag.
65
71
  const DRAG_TYPES = new Set(["dragenter", "dragover", "dragleave", "drop"]);
@@ -131,6 +137,8 @@ class Look {
131
137
  #node;
132
138
  #state;
133
139
  // Plain objects share their shape across nodes: a Map here costs four times the memory.
140
+ // A number or string is kept as given, which the caller's style object holds too, and
141
+ // turned into CSS text when it is read: no node keeps a string of its own per value.
134
142
  #values = Object.create(null);
135
143
 
136
144
  constructor(node, state) {
@@ -155,9 +163,9 @@ class Look {
155
163
  }
156
164
  continue;
157
165
  }
166
+ if (this.#values[name] === value) continue;
158
167
  const text = cssValue(name, value);
159
- if (this.#values[name] === text) continue;
160
- this.#values[name] = text;
168
+ this.#values[name] = typeof value === "number" || typeof value === "string" ? value : text;
161
169
  css += cssName(name) + ":" + text + ";";
162
170
  }
163
171
  if (removed) {
@@ -177,12 +185,13 @@ class Look {
177
185
  }
178
186
 
179
187
  get(name) {
180
- return this.#values[name];
188
+ const value = this.#values[name];
189
+ return value === undefined ? undefined : cssValue(name, value);
181
190
  }
182
191
 
183
192
  get cssText() {
184
193
  let css = "";
185
- for (const name in this.#values) css += cssName(name) + ":" + this.#values[name] + ";";
194
+ for (const name in this.#values) css += cssName(name) + ":" + cssValue(name, this.#values[name]) + ";";
186
195
  return css;
187
196
  }
188
197
 
@@ -407,28 +416,50 @@ export function updateStyleSheet(id, compiled) {
407
416
  }
408
417
  }
409
418
 
419
+ // What few nodes have, made on first use (see `Node`).
420
+ class NodeState {
421
+ listeners = null;
422
+ // The state looks by name.
423
+ looks = null;
424
+ flags = 0;
425
+ // Kinds the node hears whatever its listeners: an input keeps its value and selection current.
426
+ kept = 0;
427
+ attributes = null;
428
+ classList = null;
429
+ }
430
+
410
431
  /** A node of the tree. Make one with `createBox`, `createText`, `createInput` or `createNode`. */
411
432
  export class Node {
412
- #listeners = null;
413
- // The base look, and the state looks by name: most nodes have the base alone.
433
+ // A node is a handle on the tree's node: it keeps only what the tree cannot answer at once
434
+ // (its place among its siblings, its class, its base look), and puts the state few nodes
435
+ // have (listeners, attributes, state looks) in one record made on first use. Every field
436
+ // is a slot in every node, and a node of up to eight fits its object's own cell.
437
+ // The base look: most nodes have the base alone.
414
438
  #base = null;
415
- #looks = null;
416
- #flags = 0;
417
- // Kinds the node hears whatever its listeners: an input keeps its value and selection current.
418
- #kept = 0;
419
- #attributes = null;
420
- #classList = null;
439
+ #className = null;
440
+ #rare = null;
421
441
 
422
442
  constructor(kind) {
423
443
  Object.defineProperty(this, "nodeId", { value: ++nextId, enumerable: true });
424
- this.kind = kind;
444
+ // A text node's kind is its prototype's: one slot fewer in the most numerous node.
445
+ if (kind !== "text") this.kind = kind;
425
446
  this.parentNode = null;
426
- // A text leaf has no children: they all share one empty list.
427
- this.childNodes = kind === "text" ? NO_CHILDREN : [];
447
+ // A node with no children shares one empty list, and gets its own at its first child.
448
+ this.childNodes = NO_CHILDREN;
428
449
  nodes.set(this.nodeId, this);
429
450
  native.create(this.nodeId, KINDS[kind]);
430
451
  }
431
452
 
453
+ #more() {
454
+ return (this.#rare ??= new NodeState());
455
+ }
456
+
457
+ // The node's own child list, made on its first child.
458
+ _ownChildren() {
459
+ if (this.childNodes === NO_CHILDREN) this.childNodes = [];
460
+ return this.childNodes;
461
+ }
462
+
432
463
  get adoptedStyleSheets() { return adoptedList(this).proxy; }
433
464
  set adoptedStyleSheets(value) { adoptedList(this).assign(Array.from(value)); }
434
465
 
@@ -463,8 +494,9 @@ export class Node {
463
494
  cloneNode(deep = false) {
464
495
  const copy = this._shallowClone();
465
496
  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);
497
+ const looks = this.#rare?.looks;
498
+ for (const state in looks ?? {}) looks[state]._copyTo(copy.look(state));
499
+ for (const [name, value] of this.#rare?.attributes ?? []) copy.setAttribute(name, value);
468
500
  if (deep) for (const child of this.childNodes) copy.appendChild(child.cloneNode(true));
469
501
  return copy;
470
502
  }
@@ -536,7 +568,7 @@ export class Node {
536
568
  this.childNodes.splice(this.childNodes.indexOf(before), 0, child);
537
569
  native.insertBefore(this.nodeId, child.nodeId, before.nodeId);
538
570
  } else {
539
- this.childNodes.push(child);
571
+ this._ownChildren().push(child);
540
572
  native.append(this.nodeId, child.nodeId);
541
573
  }
542
574
  return child;
@@ -608,8 +640,9 @@ export class Node {
608
640
  look(state) {
609
641
  if (state === "base") return (this.#base ??= new Look(this, 0));
610
642
  if (!(state in STATES)) throw new TypeError("the tree has no look '" + state + "'");
611
- this.#looks ??= Object.create(null);
612
- return (this.#looks[state] ??= new Look(this, STATES[state]));
643
+ const rare = this.#more();
644
+ rare.looks ??= Object.create(null);
645
+ return (rare.looks[state] ??= new Look(this, STATES[state]));
613
646
  }
614
647
 
615
648
  /**
@@ -625,13 +658,13 @@ export class Node {
625
658
  set id(value) { this.setAttribute("id", String(value)); }
626
659
  get className() { return this.getAttribute("class") ?? ""; }
627
660
  set className(value) { this.setAttribute("class", String(value)); }
628
- get classList() { return this.#classList ??= new ClassList(this); }
661
+ get classList() { return this.#more().classList ??= new ClassList(this); }
629
662
 
630
663
  getAttribute(name) {
631
664
  name = String(name);
665
+ if (name === "className" || name === "class") return this.#className;
632
666
  const aria = ariaName(name);
633
- name = aria === null ? name === "className" ? "class" : name : "aria-" + aria;
634
- return this.#attributes?.get(name) ?? null;
667
+ return this.#rare?.attributes?.get(aria === null ? name : "aria-" + aria) ?? null;
635
668
  }
636
669
 
637
670
  hasAttribute(name) { return this.getAttribute(name) !== null; }
@@ -639,9 +672,14 @@ export class Node {
639
672
 
640
673
  setAttribute(name, value) {
641
674
  name = String(name);
642
- const aria = ariaName(name);
643
- name = aria === null ? name === "className" ? "class" : name : "aria-" + aria;
644
675
  const text = value == null ? null : String(value);
676
+ if (name === "className" || name === "class") {
677
+ native.attribute(this.nodeId, "class", text);
678
+ this.#className = text;
679
+ return;
680
+ }
681
+ const aria = ariaName(name);
682
+ if (aria !== null) name = "aria-" + aria;
645
683
  if (name === "role") {
646
684
  if (!native.attribute(this.nodeId, "role", text ?? "")) warnOnce("the tree has no role '" + text + "': it is ignored");
647
685
  } else if (name === "id") {
@@ -660,10 +698,10 @@ export class Node {
660
698
  this.#want(KIND_OF.get("click"));
661
699
  }
662
700
  native.attribute(this.nodeId, name,
663
- name === "class" || name === "lang" || name === "dir" || name.startsWith("data-") ? text : value);
701
+ name === "lang" || name === "dir" || name.startsWith("data-") ? text : value);
664
702
  }
665
- if (text === null) this.#attributes?.delete(name);
666
- else (this.#attributes ??= new Map()).set(name, text);
703
+ if (text === null) this.#rare?.attributes?.delete(name);
704
+ else (this.#more().attributes ??= new Map()).set(name, text);
667
705
  }
668
706
 
669
707
  // The `id` other nodes' relations name this node by.
@@ -676,24 +714,38 @@ export class Node {
676
714
 
677
715
  // Tells the tree which events this node wants: its listeners', and clicks on a link.
678
716
  #want(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;
717
+ const [wanted, bit] = this.#wanted(kind);
718
+ const rare = this.#rare;
719
+ const old = rare?.flags ?? 0;
720
+ const flags = ((wanted ? old | bit : old & ~bit) | (rare?.kept ?? 0) | (this._extra ?? 0)) >>> 0;
721
+ if (flags !== old) native.listen(this.nodeId, (this.#more().flags = flags));
722
+ }
723
+
724
+ // Whether this node's listeners (or link) want `kind`, and the flag bit that carries it.
725
+ #wanted(kind) {
726
+ const listeners = this.#rare?.listeners;
727
+ const has = (type) => (listeners?.get(type)?.length ?? 0) > 0;
728
+ if (kind >= TOUCH_START) return [KINDS_OF_BIT(bitOf(kind)).some((each) => has(TYPES[each])), (1 << bitOf(kind)) >>> 0];
729
+ const type = TYPES[kind];
730
+ const wanted = has(type) || (MOUSE_OF.has(type) && has(MOUSE_OF.get(type))) || (kind === CLICK && this._href)
731
+ || (kind === SELECTION_CHANGE && has("selectstart"));
732
+ return [wanted, 1 << kind];
733
+ }
734
+
735
+ /** Listens again for every kind its listeners, kept kinds and `_extra` flags ask for. */
736
+ _relisten() {
737
+ let flags = (this.#rare?.kept ?? 0) | (this._extra ?? 0);
738
+ for (let kind = 0; kind < TYPES.length; kind++) {
739
+ const [wanted, bit] = this.#wanted(kind);
740
+ if (wanted) flags |= bit;
690
741
  }
691
- const flags = (wanted ? this.#flags | bit : this.#flags & ~bit) | this.#kept;
692
- if (flags !== this.#flags) native.listen(this.nodeId, (this.#flags = flags));
742
+ flags >>>= 0;
743
+ if (flags !== (this.#rare?.flags ?? 0)) native.listen(this.nodeId, (this.#more().flags = flags));
693
744
  }
694
745
 
695
746
  _keep(...types) {
696
- for (const type of types) this.#kept |= 1 << KIND_OF.get(type);
747
+ const rare = this.#more();
748
+ for (const type of types) rare.kept = (rare.kept | (1 << bitOf(KIND_OF.get(type)))) >>> 0;
697
749
  this.#want(KIND_OF.get(types[0]));
698
750
  }
699
751
 
@@ -829,9 +881,9 @@ export class Node {
829
881
  if (listener == null || signal?.aborted) return;
830
882
  const kind = KIND_OF.get(LISTENS_AS.get(type) ?? type);
831
883
  const capture = options === true || !!options?.capture;
832
- this.#listeners ??= new Map();
833
- let list = this.#listeners.get(type);
834
- if (!list) this.#listeners.set(type, (list = []));
884
+ const listeners = (this.#more().listeners ??= new Map());
885
+ let list = listeners.get(type);
886
+ if (!list) listeners.set(type, (list = []));
835
887
  if (list.some((entry) => entry.listener === listener && entry.capture === capture)) return;
836
888
  list.push({ listener, capture, once: !!options?.once });
837
889
  if (kind !== undefined) this.#want(kind);
@@ -839,7 +891,7 @@ export class Node {
839
891
  }
840
892
 
841
893
  removeEventListener(type, listener, options) {
842
- const list = this.#listeners?.get(type);
894
+ const list = this.#rare?.listeners?.get(type);
843
895
  if (!list) return;
844
896
  const capture = options === true || !!options?.capture;
845
897
  const index = list.findIndex((entry) => entry.listener === listener && entry.capture === capture);
@@ -857,7 +909,7 @@ export class Node {
857
909
 
858
910
  /** Runs the capture or the bubble listeners of `event.type`. Used by the dispatcher. */
859
911
  _run(event, capture) {
860
- const list = this.#listeners?.get(event.type);
912
+ const list = this.#rare?.listeners?.get(event.type);
861
913
  if (!list) return;
862
914
  for (const entry of list.slice()) {
863
915
  if (event._immediate) return;
@@ -968,6 +1020,8 @@ export class Text extends Node {
968
1020
  }
969
1021
  }
970
1022
 
1023
+ Object.defineProperty(Text.prototype, "kind", { value: "text", writable: true, configurable: true });
1024
+
971
1025
  /**
972
1026
  * An editable text field. `value` follows what the user types. Selection offsets are UTF-16
973
1027
  * string indices, as on the web; the tree counts UTF-8 bytes, converted here.
@@ -1211,6 +1265,72 @@ export class Image extends Node {
1211
1265
  }
1212
1266
  }
1213
1267
 
1268
+ /**
1269
+ * A canvas the application draws with WebGPU, as a `<canvas>`: `width` and `height` are the
1270
+ * size of what is drawn in pixels (300 by 150 at first) and `getContext("webgpu")` gives a
1271
+ * `GPUCanvasContext`. The node lays out as an image of that size does: its style can
1272
+ * stretch it, and `objectFit` says how the drawing fits. Drawing happens on a GPU device of
1273
+ * the application's own, so a canvas that is slow to draw does not slow the rest of the window.
1274
+ */
1275
+ export class Canvas extends Node {
1276
+ #width = 300;
1277
+ #height = 150;
1278
+ #context = null;
1279
+
1280
+ constructor() {
1281
+ super("canvas");
1282
+ }
1283
+
1284
+ get width() {
1285
+ return this.#width;
1286
+ }
1287
+
1288
+ set width(value) {
1289
+ value = Math.max(0, Number(value) | 0);
1290
+ if (value === this.#width) return;
1291
+ this.#width = value;
1292
+ this.#context?._resized();
1293
+ }
1294
+
1295
+ get height() {
1296
+ return this.#height;
1297
+ }
1298
+
1299
+ set height(value) {
1300
+ value = Math.max(0, Number(value) | 0);
1301
+ if (value === this.#height) return;
1302
+ this.#height = value;
1303
+ this.#context?._resized();
1304
+ }
1305
+
1306
+ /** The canvas's `GPUCanvasContext` for "webgpu"; null for any other kind of context. */
1307
+ getContext(kind) {
1308
+ if (kind !== "webgpu") return null;
1309
+ if (this.#context) return this.#context;
1310
+ const api = native.gpuLoad?.();
1311
+ return api ? (this.#context = api.context(this)) : null;
1312
+ }
1313
+
1314
+ setAttribute(name, value) {
1315
+ if (name === "width") this.width = value == null ? 300 : value;
1316
+ else if (name === "height") this.height = value == null ? 150 : value;
1317
+ else super.setAttribute(name, value);
1318
+ }
1319
+
1320
+ getAttribute(name) {
1321
+ if (name === "width") return String(this.#width);
1322
+ if (name === "height") return String(this.#height);
1323
+ return super.getAttribute(name);
1324
+ }
1325
+
1326
+ _shallowClone() {
1327
+ const copy = new Canvas();
1328
+ copy.width = this.#width;
1329
+ copy.height = this.#height;
1330
+ return copy;
1331
+ }
1332
+ }
1333
+
1214
1334
  const SVG_NAMESPACE = "http://www.w3.org/2000/svg";
1215
1335
 
1216
1336
  // SVG attribute names that are camel case in SVG itself. Any other name with a capital letter
@@ -1266,6 +1386,38 @@ function svgChanged(node) {
1266
1386
  changedSvgs.add(svg);
1267
1387
  }
1268
1388
 
1389
+ // A live svg: after its first drawing, an `<svg>` whose elements change sends each change to
1390
+ // the tree as it happens (`svgInsert`, `svgAttribute`, `svgRemove`), and the tree draws its
1391
+ // shapes as paths, so a frame of an animation costs what it changes. This needs content the
1392
+ // tree's live svg draws; anything else keeps the svg drawn as markup.
1393
+ const LIVE_TAGS = new Set([
1394
+ "g", "path", "rect", "circle", "ellipse", "line", "polyline", "polygon", "defs", "clipPath",
1395
+ "linearGradient", "radialGradient", "stop", "title", "desc", "metadata",
1396
+ ]);
1397
+ const QUIET_TAGS = new Set(["title", "desc", "metadata"]);
1398
+ const UNLIVE_ATTRIBUTES = new Set(["mask", "filter", "marker", "marker-start", "marker-mid", "marker-end"]);
1399
+ const UNLIVE_STYLE = /(^|;)\s*(mask|filter|marker)[\w-]*\s*:/;
1400
+
1401
+ function liveAttribute(name, text) {
1402
+ return !UNLIVE_ATTRIBUTES.has(name) && !(name === "style" && UNLIVE_STYLE.test(text));
1403
+ }
1404
+
1405
+ /** Whether the tree's live svg can draw `child` and what is in it. */
1406
+ function liveable(child, quiet = false) {
1407
+ if (!(child instanceof SvgElement)) return quiet;
1408
+ if (!LIVE_TAGS.has(child.localName)) return false;
1409
+ for (const [name, value] of child._attributes()) if (!liveAttribute(name, value)) return false;
1410
+ const inner = quiet || QUIET_TAGS.has(child.localName);
1411
+ for (const grandchild of child.childNodes) if (!liveable(grandchild, inner)) return false;
1412
+ return true;
1413
+ }
1414
+
1415
+ /** The live svg `node` is in, or null. */
1416
+ function liveOwner(node) {
1417
+ const svg = svgOwner(node);
1418
+ return svg?._live ? svg : null;
1419
+ }
1420
+
1269
1421
  function svgStyle(value) {
1270
1422
  if (typeof value !== "object" || value === null) return String(value);
1271
1423
  let css = "";
@@ -1284,15 +1436,20 @@ const svgChildren = {
1284
1436
  if (before === child) return child;
1285
1437
  for (let at = this; at; at = at.parentNode) if (at === child) throw new Error("a node cannot be inserted into itself or its own subtree");
1286
1438
  const old = child.parentNode;
1439
+ const listening = shapeListeners(child);
1287
1440
  if (old) {
1441
+ liveOwner(old)?._removed(child);
1288
1442
  svgChanged(old);
1289
1443
  old.childNodes.splice(old.childNodes.indexOf(child), 1);
1444
+ if (listening) svgOwner(old)?._listenShapes();
1290
1445
  }
1291
1446
  child.parentNode = this;
1292
1447
  if (before) this.childNodes.splice(this.childNodes.indexOf(before), 0, child);
1293
- else this.childNodes.push(child);
1448
+ else (this.childNodes === NO_CHILDREN ? (this.childNodes = []) : this.childNodes).push(child);
1294
1449
  if (child instanceof Text) child._svgText = true;
1450
+ liveOwner(this)?._inserted(child, this, before);
1295
1451
  svgChanged(this);
1452
+ if (listening) svgOwner(this)?._listenShapes();
1296
1453
  return child;
1297
1454
  },
1298
1455
  appendChild(child) {
@@ -1303,9 +1460,11 @@ const svgChildren = {
1303
1460
  },
1304
1461
  removeChild(child) {
1305
1462
  if (child.parentNode !== this) throw new Error("the node to remove is not a child of this node");
1463
+ liveOwner(this)?._removed(child);
1306
1464
  svgChanged(this);
1307
1465
  this.childNodes.splice(this.childNodes.indexOf(child), 1);
1308
1466
  child.parentNode = null;
1467
+ if (shapeListeners(child)) svgOwner(this)?._listenShapes();
1309
1468
  return child;
1310
1469
  },
1311
1470
  get textContent() {
@@ -1327,6 +1486,85 @@ const svgChildren = {
1327
1486
  },
1328
1487
  };
1329
1488
 
1489
+ // `element` and what is inside it as `__ui.svgMeasure` reads them (ui-tree `live_svg.measure`):
1490
+ // records split by U+001E, each the parent's record number, the tag, then name/value pairs.
1491
+ function svgPacked(element) {
1492
+ const records = [];
1493
+ const visit = (at, parent) => {
1494
+ const number = records.length + 1;
1495
+ let record = parent + "\x1f" + at.localName;
1496
+ for (const [name, value] of at._attributes()) record += "\x1f" + name + "\x1f" + value;
1497
+ records.push(record);
1498
+ for (const child of at.childNodes) if (child instanceof SvgElement) visit(child, number);
1499
+ };
1500
+ visit(element, 0);
1501
+ return records.join("\x1e");
1502
+ }
1503
+
1504
+ function svgBox(element) {
1505
+ const [x, y, width, height] = native.svgMeasure(0, svgPacked(element), 0).split(" ").map(Number);
1506
+ const Rect = globalThis.DOMRect;
1507
+ return Rect ? new Rect(x, y, width, height) : { x, y, width, height };
1508
+ }
1509
+
1510
+ // Whether `element` or an element inside it has listeners.
1511
+ function shapeListeners(element) {
1512
+ if (!(element instanceof SvgElement)) return false;
1513
+ for (const list of element._listeners?.values() ?? []) if (list.length > 0) return true;
1514
+ return element.childNodes.some(shapeListeners);
1515
+ }
1516
+
1517
+ function quietAncestor(element) {
1518
+ for (let at = element; at && at instanceof SvgElement; at = at.parentNode) if (QUIET_TAGS.has(at.localName)) return true;
1519
+ return false;
1520
+ }
1521
+
1522
+ /** The declarations of `element`'s `style` attribute, read and written as properties. */
1523
+ function svgDeclarations(element) {
1524
+ const read = () => {
1525
+ const map = new Map();
1526
+ for (const part of (element.getAttribute("style") ?? "").split(";")) {
1527
+ const colon = part.indexOf(":");
1528
+ if (colon > 0) map.set(part.slice(0, colon).trim(), part.slice(colon + 1).trim());
1529
+ }
1530
+ return map;
1531
+ };
1532
+ const write = (map) => {
1533
+ let css = "";
1534
+ for (const [name, value] of map) css += name + ": " + value + ";";
1535
+ if (css) element.setAttribute("style", css);
1536
+ else element.removeAttribute("style");
1537
+ };
1538
+ const set = (name, value) => {
1539
+ const map = read();
1540
+ if (value === null || value === undefined || value === "") map.delete(name);
1541
+ else map.set(name, String(value));
1542
+ write(map);
1543
+ };
1544
+ const methods = {
1545
+ setProperty: (name, value) => set(String(name), value),
1546
+ removeProperty: (name) => {
1547
+ const old = read().get(String(name)) ?? "";
1548
+ set(String(name), null);
1549
+ return old;
1550
+ },
1551
+ getPropertyValue: (name) => read().get(String(name)) ?? "",
1552
+ };
1553
+ return new Proxy(methods, {
1554
+ get(target, key) {
1555
+ if (typeof key !== "string") return undefined;
1556
+ if (key in target) return target[key];
1557
+ if (key === "cssText") return element.getAttribute("style") ?? "";
1558
+ return read().get(cssName(key)) ?? "";
1559
+ },
1560
+ set(target, key, value) {
1561
+ if (key === "cssText") element.setAttribute("style", String(value));
1562
+ else if (typeof key === "string") set(cssName(key), value);
1563
+ return true;
1564
+ },
1565
+ });
1566
+ }
1567
+
1330
1568
  /** Text in an `<svg>`: its `<text>` and `<title>` contents. */
1331
1569
  export class SvgText {
1332
1570
  #data;
@@ -1345,6 +1583,8 @@ export class SvgText {
1345
1583
  value = String(value);
1346
1584
  if (value === this.#data) return;
1347
1585
  this.#data = value;
1586
+ const live = liveOwner(this);
1587
+ if (live && !QUIET_TAGS.has(this.parentNode?.localName)) live._leave();
1348
1588
  svgChanged(this);
1349
1589
  }
1350
1590
 
@@ -1413,11 +1653,40 @@ export class SvgElement {
1413
1653
  const text = name === "style" ? svgStyle(value) : String(value);
1414
1654
  if (this.#attributes.get(name) === text) return;
1415
1655
  this.#attributes.set(name, text);
1416
- svgChanged(this);
1656
+ this._written(name, text);
1417
1657
  }
1418
1658
 
1419
1659
  removeAttribute(name) {
1420
- if (this.#attributes.delete(svgName(name))) svgChanged(this);
1660
+ name = svgName(name);
1661
+ if (this.#attributes.delete(name)) this._written(name, null);
1662
+ }
1663
+
1664
+ setAttributeNS(namespace, name, value) {
1665
+ this.setAttribute(name, value);
1666
+ }
1667
+
1668
+ getAttributeNS(namespace, name) {
1669
+ return this.getAttribute(name);
1670
+ }
1671
+
1672
+ removeAttributeNS(namespace, name) {
1673
+ this.removeAttribute(name);
1674
+ }
1675
+
1676
+ /** The element's `style` attribute as a declaration object: `style.display = "none"`. */
1677
+ get style() {
1678
+ return this._style ??= svgDeclarations(this);
1679
+ }
1680
+
1681
+ _attributes() {
1682
+ return this.#attributes;
1683
+ }
1684
+
1685
+ _written(name, text) {
1686
+ const live = liveOwner(this);
1687
+ if (!live) svgChanged(this);
1688
+ else if (text !== null && !liveAttribute(name, text)) live._leave();
1689
+ else native.svgAttribute(live.nodeId, this._n, name, text);
1421
1690
  }
1422
1691
 
1423
1692
  get firstChild() {
@@ -1452,11 +1721,67 @@ export class SvgElement {
1452
1721
  this.remove();
1453
1722
  }
1454
1723
 
1455
- addEventListener(type) {
1456
- warnOnce("an element inside an <svg> hears no events: listen on the <svg> ('" + type + "')");
1724
+ /**
1725
+ * Hears pointer events on this element's shapes, as on the web: its `<svg>` turns live (see
1726
+ * `Svg`) and the tree tells which shape is under the pointer.
1727
+ */
1728
+ addEventListener(type, listener, options) {
1729
+ if (listener == null) return;
1730
+ const capture = options === true || !!options?.capture;
1731
+ this._listeners ??= new Map();
1732
+ let list = this._listeners.get(type);
1733
+ if (!list) this._listeners.set(type, (list = []));
1734
+ if (list.some((entry) => entry.listener === listener && entry.capture === capture)) return;
1735
+ list.push({ listener, capture, once: !!options?.once });
1736
+ svgOwner(this)?._listenShapes();
1457
1737
  }
1458
1738
 
1459
- removeEventListener() {}
1739
+ removeEventListener(type, listener, options) {
1740
+ const list = this._listeners?.get(type);
1741
+ if (!list) return;
1742
+ const capture = options === true || !!options?.capture;
1743
+ const index = list.findIndex((entry) => entry.listener === listener && entry.capture === capture);
1744
+ if (index < 0) return;
1745
+ list.splice(index, 1);
1746
+ svgOwner(this)?._listenShapes();
1747
+ }
1748
+
1749
+ dispatchEvent(event) {
1750
+ if (typeof event?.type !== "string") throw new TypeError("dispatchEvent takes an Event");
1751
+ return dispatchEvent(adopt(event, this));
1752
+ }
1753
+
1754
+ /** The box of its geometry in its own user space: a shape's fill, a group's children. */
1755
+ getBBox() {
1756
+ return svgBox(this);
1757
+ }
1758
+
1759
+ /** The length of a shape's outline in user units. */
1760
+ getTotalLength() {
1761
+ return Number(native.svgMeasure(1, svgPacked(this), 0));
1762
+ }
1763
+
1764
+ /** The point `distance` along a shape's outline, clamped to its ends. */
1765
+ getPointAtLength(distance) {
1766
+ const [x, y] = native.svgMeasure(2, svgPacked(this), Number(distance) || 0).split(" ").map(Number);
1767
+ return { x, y };
1768
+ }
1769
+
1770
+ _run(event, capture) {
1771
+ const list = this._listeners?.get(event.type);
1772
+ if (!list) return;
1773
+ for (const entry of list.slice()) {
1774
+ if (event._immediate) return;
1775
+ if (entry.capture !== capture) continue;
1776
+ if (entry.once) this.removeEventListener(event.type, entry.listener, entry.capture);
1777
+ try {
1778
+ if (typeof entry.listener === "function") entry.listener.call(this, event);
1779
+ else entry.listener.handleEvent(event);
1780
+ } catch (error) {
1781
+ reportError(error);
1782
+ }
1783
+ }
1784
+ }
1460
1785
 
1461
1786
  _markup() {
1462
1787
  let markup = "<" + this.localName;
@@ -1486,6 +1811,10 @@ function treeAttribute(name) {
1486
1811
  export class Svg extends Node {
1487
1812
  #attributes = new Map();
1488
1813
  #markup = "";
1814
+ // Live: element numbers in use, and freed ones to use again.
1815
+ _live = false;
1816
+ _count = 0;
1817
+ _free = [];
1489
1818
 
1490
1819
  constructor() {
1491
1820
  // The tree's node for drawn SVG markup is an icon; to code it is an `svg`.
@@ -1520,13 +1849,84 @@ export class Svg extends Node {
1520
1849
  const text = name === "style" ? svgStyle(value) : String(value);
1521
1850
  if (this.#attributes.get(name) === text) return;
1522
1851
  this.#attributes.set(name, text);
1523
- svgChanged(this);
1852
+ this._written(name, text);
1524
1853
  }
1525
1854
 
1526
1855
  removeAttribute(name) {
1527
1856
  name = String(name);
1528
1857
  if (treeAttribute(name)) super.removeAttribute(name);
1529
- else if (this.#attributes.delete(svgName(name))) svgChanged(this);
1858
+ else if (this.#attributes.delete(svgName(name))) this._written(svgName(name), null);
1859
+ }
1860
+
1861
+ setAttributeNS(namespace, name, value) {
1862
+ this.setAttribute(name, value);
1863
+ }
1864
+
1865
+ getAttributeNS(namespace, name) {
1866
+ return this.getAttribute(name);
1867
+ }
1868
+
1869
+ /** The box of what it draws, in its user space (inside `viewBox`). */
1870
+ getBBox() {
1871
+ return svgBox(this);
1872
+ }
1873
+
1874
+ _attributes() {
1875
+ return this.#attributes;
1876
+ }
1877
+
1878
+ _written(name, text) {
1879
+ if (!this._live) svgChanged(this);
1880
+ else if (text !== null && !liveAttribute(name, text)) this._leave();
1881
+ else native.svgAttribute(this.nodeId, 0, name, text);
1882
+ }
1883
+
1884
+ /** Sends the elements to the tree as a live svg, once its markup was drawn and changed. */
1885
+ _goLive() {
1886
+ this._forget();
1887
+ this._live = true;
1888
+ for (const [name, value] of this.#attributes) native.svgAttribute(this.nodeId, 0, name, value);
1889
+ for (const child of this.childNodes) this._inserted(child, this, null);
1890
+ }
1891
+
1892
+ /** Back to markup: content the live svg does not draw came in. */
1893
+ _leave() {
1894
+ if (!this._live) return;
1895
+ this._live = false;
1896
+ this._count = 0;
1897
+ this._free = [];
1898
+ native.svgRemove(this.nodeId, 0);
1899
+ svgChanged(this);
1900
+ }
1901
+
1902
+ _inserted(child, parent, before) {
1903
+ if (!(child instanceof SvgElement)) {
1904
+ if (!QUIET_TAGS.has(parent.localName) && !(parent !== this && svgOwner(parent) && quietAncestor(parent))) this._leave();
1905
+ return;
1906
+ }
1907
+ if (!liveable(child, quietAncestor(parent))) {
1908
+ this._leave();
1909
+ return;
1910
+ }
1911
+ this._send(child, parent === this ? 0 : parent._n, before instanceof SvgElement ? before._n : -1);
1912
+ }
1913
+
1914
+ _send(element, parent, before) {
1915
+ element._n = this._free.pop() ?? ++this._count;
1916
+ native.svgInsert(this.nodeId, element._n, element.localName, parent, before);
1917
+ for (const [name, value] of element._attributes()) native.svgAttribute(this.nodeId, element._n, name, value);
1918
+ for (const child of element.childNodes) if (child instanceof SvgElement) this._send(child, element._n, -1);
1919
+ }
1920
+
1921
+ _removed(child) {
1922
+ if (!(child instanceof SvgElement) || !child._n) return;
1923
+ native.svgRemove(this.nodeId, child._n);
1924
+ const free = (element) => {
1925
+ if (element._n) this._free.push(element._n);
1926
+ element._n = 0;
1927
+ for (const grandchild of element.childNodes) if (grandchild instanceof SvgElement) free(grandchild);
1928
+ };
1929
+ free(child);
1530
1930
  }
1531
1931
 
1532
1932
  /** The markup the tree draws, as `outerHTML` gives it. */
@@ -1542,9 +1942,17 @@ export class Svg extends Node {
1542
1942
  }
1543
1943
 
1544
1944
  _draw() {
1545
- if (!nodes.has(this.nodeId)) return;
1945
+ if (!nodes.has(this.nodeId) || this._live) return;
1946
+ if (this._extra && this.childNodes.every((child) => liveable(child))) {
1947
+ this._goLive();
1948
+ return;
1949
+ }
1546
1950
  const markup = this.outerHTML;
1547
1951
  if (markup === this.#markup) return;
1952
+ if (this.#markup && this.childNodes.every((child) => liveable(child))) {
1953
+ this._goLive();
1954
+ return;
1955
+ }
1548
1956
  this._forget();
1549
1957
  this.#markup = markup;
1550
1958
  native.source(this.nodeId, holdIcon(markup));
@@ -1554,6 +1962,117 @@ export class Svg extends Node {
1554
1962
  if (this.#markup) dropIcon(this.#markup);
1555
1963
  this.#markup = "";
1556
1964
  }
1965
+
1966
+ /**
1967
+ * Listens for what the listeners on its elements need. Elements are told apart only once
1968
+ * the svg is live, so listeners make it go live.
1969
+ */
1970
+ _listenShapes() {
1971
+ let types = new Set();
1972
+ const visit = (element) => {
1973
+ for (const [type, list] of element._listeners ?? []) if (list.length > 0) types.add(type);
1974
+ for (const child of element.childNodes) if (child instanceof SvgElement) visit(child);
1975
+ };
1976
+ for (const child of this.childNodes) if (child instanceof SvgElement) visit(child);
1977
+ let extra = 0;
1978
+ for (const type of types) {
1979
+ const kind = KIND_OF.get(type);
1980
+ if (kind === undefined) continue;
1981
+ extra = (extra | (1 << bitOf(kind))) >>> 0;
1982
+ if (HOVER_TYPES.has(type)) extra |= HOVER_FLAGS;
1983
+ }
1984
+ if (extra === (this._extra ?? 0)) return;
1985
+ this._extra = extra;
1986
+ this._relisten();
1987
+ if (extra && !this._live) svgChanged(this);
1988
+ }
1989
+
1990
+ /** The element numbered `n`, or null. */
1991
+ _numbered(n) {
1992
+ if (!n) return null;
1993
+ const find = (element) => {
1994
+ if (element._n === n) return element;
1995
+ for (const child of element.childNodes) {
1996
+ if (child instanceof SvgElement) {
1997
+ const found = find(child);
1998
+ if (found) return found;
1999
+ }
2000
+ }
2001
+ return null;
2002
+ };
2003
+ for (const child of this.childNodes) {
2004
+ if (child instanceof SvgElement) {
2005
+ const found = find(child);
2006
+ if (found) return found;
2007
+ }
2008
+ }
2009
+ return null;
2010
+ }
2011
+
2012
+ /**
2013
+ * Sends a pointer record that came to the svg to the element under the pointer, with the
2014
+ * over, out, enter and leave events the web sends as the pointer moves between elements.
2015
+ */
2016
+ _pointer(event) {
2017
+ const type = event.type;
2018
+ const leaving = type === "pointerout" || type === "pointerleave" || type === "pointercancel";
2019
+ const shape = leaving ? null : this._numbered(event._element);
2020
+ const old = this._hovered && this._hovered.parentNode && svgOwner(this._hovered) === this ? this._hovered : null;
2021
+ let replaced = false;
2022
+ if (shape !== old && type !== "pointerenter" && type !== "pointerleave") {
2023
+ this._hovered = shape;
2024
+ if (old) {
2025
+ dispatchEvent(pointerCopy("pointerout", old, event));
2026
+ for (let at = old; at instanceof SvgElement && !at.contains(shape); at = at.parentNode) {
2027
+ dispatchEvent(pointerCopy("pointerleave", at, event));
2028
+ }
2029
+ if (type === "pointerout") replaced = true;
2030
+ }
2031
+ if (shape) {
2032
+ dispatchEvent(pointerCopy("pointerover", shape, event));
2033
+ if (type === "pointerover") {
2034
+ replaced = true;
2035
+ this._entering = true;
2036
+ } else {
2037
+ enterChain(shape, old, event);
2038
+ }
2039
+ }
2040
+ }
2041
+ if (replaced) return false;
2042
+ if (type === "pointerenter") {
2043
+ dispatchEvent(event);
2044
+ if (this._entering && this._hovered) enterChain(this._hovered, null, event);
2045
+ this._entering = false;
2046
+ return event.defaultPrevented;
2047
+ }
2048
+ if (shape && type !== "pointerleave") event.target = shape;
2049
+ dispatchEvent(event);
2050
+ return event.defaultPrevented;
2051
+ }
2052
+ }
2053
+
2054
+ // Element listeners for these need the svg's moves, enters and leaves to tell hovering apart.
2055
+ const HOVER_TYPES = new Set(["pointerover", "pointerout", "pointerenter", "pointerleave"]);
2056
+ const HOVER_FLAGS = (1 << 3) | (1 << 4) | (1 << 5) | (1 << 28) | (1 << 29);
2057
+
2058
+ // A pointer event like `base` of type `type` at `target`.
2059
+ function pointerCopy(type, target, base) {
2060
+ const event = new Event(type, target);
2061
+ for (const key of Object.keys(base)) {
2062
+ if (!(key in event) || key === "clientX" || key === "clientY" || key === "x" || key === "y") event[key] = base[key];
2063
+ }
2064
+ event.type = type;
2065
+ event.target = target;
2066
+ event.bubbles = !NO_BUBBLE.has(type);
2067
+ event.cancelable = CANCELABLE.has(type);
2068
+ return event;
2069
+ }
2070
+
2071
+ // pointerenter at `shape` and its element ancestors not containing `from`, outermost first.
2072
+ function enterChain(shape, from, base) {
2073
+ const chain = [];
2074
+ for (let at = shape; at instanceof SvgElement && !(from && at.contains(from)); at = at.parentNode) chain.push(at);
2075
+ for (let i = chain.length - 1; i >= 0; i--) dispatchEvent(pointerCopy("pointerenter", chain[i], base));
1557
2076
  }
1558
2077
 
1559
2078
  for (const name of ["insertBefore", "appendChild", "append", "removeChild"]) Svg.prototype[name] = svgChildren[name];
@@ -1790,7 +2309,7 @@ function forget(node) {
1790
2309
  child.parentNode = null;
1791
2310
  forget(child);
1792
2311
  }
1793
- node.childNodes = [];
2312
+ node.childNodes = NO_CHILDREN;
1794
2313
  }
1795
2314
 
1796
2315
  export function createNode(kind) {
@@ -1801,6 +2320,7 @@ export function createNode(kind) {
1801
2320
  if (kind === "text") return new Text();
1802
2321
  if (kind === "input") return new Input();
1803
2322
  if (kind === "image") return new Image();
2323
+ if (kind === "canvas") return new Canvas();
1804
2324
  return new Node(kind);
1805
2325
  }
1806
2326
 
@@ -2879,7 +3399,7 @@ function touchList(list) {
2879
3399
  // goes to the node the finger went down on. No host reports contact size or force: a touch is
2880
3400
  // 1 by 1 pixel, as its pointer is, with force 0.
2881
3401
  function fillTouch(event, kind, a, b, bits, d) {
2882
- const identifier = Math.floor(bits / 256);
3402
+ const identifier = Math.floor(bits / 256) % 16777216;
2883
3403
  const touch = {
2884
3404
  identifier,
2885
3405
  target: event.target,
@@ -2908,7 +3428,8 @@ function fillTouch(event, kind, a, b, bits, d) {
2908
3428
  // spec defaults for what no host reports: pressure 0.5 while a button is down, 0 otherwise, and
2909
3429
  // a contact of 1 by 1 pixel with no tilt.
2910
3430
  function fillPointer(event, kind, bits, d) {
2911
- const pointerId = Math.floor(bits / 256);
3431
+ const pointerId = Math.floor(bits / 256) % 16777216;
3432
+ event._element = Math.floor(bits / 4294967296);
2912
3433
  const pointerType = POINTER_TYPES[Math.floor(bits / 16) % 4] ?? "mouse";
2913
3434
  const isPrimary = Math.floor(bits / 64) % 2 === 1;
2914
3435
  let pointer = pointers.get(pointerId);
@@ -2944,7 +3465,7 @@ function fillPointer(event, kind, bits, d) {
2944
3465
  }
2945
3466
 
2946
3467
  function fill(event, kind, a, b, modifiers, d, e, first, second, third, fourth) {
2947
- if (kind >= TOUCH_START) {
3468
+ if (kind >= TOUCH_START && kind < COPY) {
2948
3469
  fillTouch(event, kind, a, b, modifiers, d);
2949
3470
  event.shiftKey = (modifiers & 1) !== 0;
2950
3471
  event.ctrlKey = (modifiers & 2) !== 0;
@@ -3091,24 +3612,78 @@ function compatTap(click, target) {
3091
3612
  native.dispatch = function (kind, id, a, b, modifiers, d, e, first, second, third, fourth) {
3092
3613
  const target = nodes.get(id);
3093
3614
  if (!target) return false;
3615
+ if (kind >= COPY) return dispatchEditing(kind, target, first, second, third);
3094
3616
  if (kind === SELECTION_CHANGE && !(target instanceof Input)) return selectionRecord(target, a);
3095
3617
  const event = new Event(TYPES[kind], target);
3096
3618
  fill(event, kind, a, b, modifiers, d, e, first, second, third, fourth);
3619
+ const live = target instanceof Svg && target._live && isPointerKind(kind);
3097
3620
  if (kind === CLICK && event.pointerType === "touch" && event.isPrimary) compatTap(event, target);
3098
- dispatchEvent(event);
3099
- if (kind === CLICK && !event.defaultPrevented) follow(target);
3621
+ // A live svg sends pointer records on to the element under the pointer.
3622
+ let prevented;
3623
+ if (live) prevented = target._pointer(event);
3624
+ else {
3625
+ dispatchEvent(event);
3626
+ prevented = event.defaultPrevented;
3627
+ }
3628
+ if (kind === CLICK && !prevented) follow(target);
3100
3629
  if (kind !== CLICK && isPointerKind(kind)) {
3101
- if (event.pointerType !== "touch") compatMouse(kind, event, target);
3630
+ if (event.pointerType !== "touch") compatMouse(kind, event, live && event.target instanceof SvgElement ? event.target : target);
3102
3631
  // A finger's defaults (pan, focus, the tap's click) follow its touch events, not its
3103
3632
  // pointer events, as on the web.
3104
3633
  else {
3105
- if (kind === 0 && event.isPrimary) mutedTap = event.defaultPrevented ? event.pointerId : null;
3634
+ if (kind === 0 && event.isPrimary) mutedTap = prevented ? event.pointerId : null;
3106
3635
  return false;
3107
3636
  }
3108
3637
  }
3638
+ return prevented;
3639
+ };
3640
+
3641
+ // Copy, cut and paste as the Clipboard API and events spec has them, and beforeinput. A
3642
+ // paste carries the clipboard's text, HTML and a PNG (bytes as a Latin-1 string). A copy or
3643
+ // cut a listener prevented puts what it set on `clipboardData` on the clipboard; one it did
3644
+ // not prevent lets the tree copy the selection.
3645
+ function dispatchEditing(kind, target, first, second, third) {
3646
+ let event;
3647
+ if (kind === BEFORE_INPUT) {
3648
+ event = new InputEvent("beforeinput", { bubbles: true, cancelable: true, composed: true, inputType: second ?? "", data: first ?? "" });
3649
+ } else {
3650
+ const data = new DataTransfer();
3651
+ if (kind === PASTE) {
3652
+ if (first) data.setData("text/plain", first);
3653
+ if (second) data.setData("text/html", second);
3654
+ if (third) data.items.add(new FileClass([bytesOf(third)], "image.png", { type: "image/png" }));
3655
+ data._mode = "readonly";
3656
+ }
3657
+ event = new ClipboardEvent(TYPES[kind], { bubbles: true, cancelable: true, composed: true, clipboardData: data });
3658
+ }
3659
+ event.target = target;
3660
+ dispatchEvent(event);
3661
+ if (event.clipboardData) {
3662
+ if ((kind === COPY || kind === CUT) && event.defaultPrevented) writeClipboard(event.clipboardData);
3663
+ event.clipboardData._mode = "protected";
3664
+ }
3109
3665
  return event.defaultPrevented;
3666
+ }
3667
+
3668
+ const bytesOf = (text) => {
3669
+ const bytes = new Uint8Array(text.length);
3670
+ for (let i = 0; i < text.length; i++) bytes[i] = text.charCodeAt(i);
3671
+ return bytes;
3110
3672
  };
3111
3673
 
3674
+ // What a prevented copy or cut set, onto the system clipboard.
3675
+ function writeClipboard(data) {
3676
+ const clipboard = globalThis.navigator?.clipboard;
3677
+ const entries = data._entries();
3678
+ if (!clipboard || entries.length === 0) return;
3679
+ const item = {};
3680
+ for (const [type, value] of entries) item[type] = value;
3681
+ const written = entries.length === 1 && entries[0][0] === "text/plain" || typeof globalThis.ClipboardItem !== "function"
3682
+ ? clipboard.writeText(item["text/plain"] ?? "")
3683
+ : clipboard.write([new globalThis.ClipboardItem(item)]);
3684
+ Promise.resolve(written).catch(reportError);
3685
+ }
3686
+
3112
3687
  // The default action of a click: the nearest link around the target opens.
3113
3688
  function follow(target) {
3114
3689
  for (let node = target; node; node = node.parentNode) {
@@ -3170,24 +3745,219 @@ export class DroppedFile {
3170
3745
  }
3171
3746
  }
3172
3747
 
3748
+ // `File` where the runtime has one, else a `Blob` with a name.
3749
+ const FileClass = globalThis.File ?? (globalThis.Blob ? class File extends globalThis.Blob {
3750
+ constructor(parts, name, options = {}) {
3751
+ super(parts, options);
3752
+ this.name = String(name);
3753
+ this.lastModified = options.lastModified ?? Date.now();
3754
+ }
3755
+ } : null);
3756
+
3757
+ const normalFormat = (format) => {
3758
+ const lower = String(format).toLowerCase();
3759
+ return lower === "text" ? "text/plain" : lower === "url" ? "text/uri-list" : lower;
3760
+ };
3761
+
3762
+ /** One entry of a `DataTransfer`, as the web's `DataTransferItem`. */
3763
+ class DataTransferItem {
3764
+ #owner;
3765
+ #value;
3766
+ constructor(owner, kind, type, value) {
3767
+ this.#owner = owner;
3768
+ this.kind = kind;
3769
+ this.type = type;
3770
+ this.#value = value;
3771
+ }
3772
+
3773
+ getAsString(callback) {
3774
+ if (this.kind !== "string" || typeof callback !== "function" || this.#owner._mode === "protected") return;
3775
+ const value = this.#value;
3776
+ queueMicrotask(() => callback(value));
3777
+ }
3778
+
3779
+ getAsFile() {
3780
+ return this.kind === "file" && this.#owner._mode !== "protected" ? this.#value : null;
3781
+ }
3782
+
3783
+ _value() {
3784
+ return this.#value;
3785
+ }
3786
+ }
3787
+
3788
+ /** The entries of a `DataTransfer`, as the web's `DataTransferItemList`. */
3789
+ class DataTransferItemList {
3790
+ #owner;
3791
+ #list = [];
3792
+ constructor(owner) {
3793
+ this.#owner = owner;
3794
+ return new Proxy(this, {
3795
+ get: (self, key) => {
3796
+ if (typeof key === "string" && /^\d+$/.test(key)) return self.length > Number(key) ? self.#list[Number(key)] : undefined;
3797
+ const value = Reflect.get(self, key, self);
3798
+ return typeof value === "function" ? value.bind(self) : value;
3799
+ },
3800
+ });
3801
+ }
3802
+
3803
+ get length() {
3804
+ return this.#owner._mode === "protected" ? 0 : this.#list.length;
3805
+ }
3806
+
3807
+ /** `add(data, type)` for a string, `add(file)` for a file. Read-only data throws. */
3808
+ add(data, type) {
3809
+ this.#owner._writable();
3810
+ if (typeof data === "string") {
3811
+ const format = normalFormat(type ?? "");
3812
+ if (this.#list.some((item) => item.kind === "string" && item.type === format)) {
3813
+ throw domError("NotSupportedError", "The data already holds an item of type " + format);
3814
+ }
3815
+ const item = new DataTransferItem(this.#owner, "string", format, data);
3816
+ this.#list.push(item);
3817
+ return item;
3818
+ }
3819
+ if (data && typeof data === "object") {
3820
+ const item = new DataTransferItem(this.#owner, "file", String(data.type ?? "").toLowerCase(), data);
3821
+ this.#list.push(item);
3822
+ return item;
3823
+ }
3824
+ throw new TypeError("DataTransferItemList.add takes a string and a type, or a File");
3825
+ }
3826
+
3827
+ remove(index) {
3828
+ this.#owner._writable();
3829
+ if (index >= 0 && index < this.#list.length) this.#list.splice(index, 1);
3830
+ }
3831
+
3832
+ clear() {
3833
+ this.#owner._writable();
3834
+ this.#list.length = 0;
3835
+ }
3836
+
3837
+ [Symbol.iterator]() {
3838
+ return (this.#owner._mode === "protected" ? [] : this.#list)[Symbol.iterator]();
3839
+ }
3840
+
3841
+ _all() {
3842
+ return this.#list;
3843
+ }
3844
+ }
3845
+
3173
3846
  /**
3174
- * What a file drag carries, as the web's `DataTransfer`: `types` is `["Files"]` while files
3175
- * are over the window, and `files` lists them in `drop`, as on the web.
3847
+ * What a copy, cut, paste or file drag carries, as the web's `DataTransfer`. `new
3848
+ * DataTransfer()` is empty and writable. A file drag lists the dragged `paths` in `files`;
3849
+ * its `types` is `["Files"]` while they are over the window.
3176
3850
  */
3177
3851
  export class DataTransfer {
3852
+ #items;
3178
3853
  constructor(paths) {
3179
- this.files = paths.map((path) => new DroppedFile(path));
3180
- this.items = this.files.map((file) => ({ kind: "file", type: "", getAsFile: () => file }));
3181
- this.types = ["Files"];
3182
- this.dropEffect = "copy";
3183
- this.effectAllowed = "copy";
3854
+ // "readwrite", "readonly" (paste, drop) or "protected" (after the event).
3855
+ this._mode = "readwrite";
3856
+ this._drag = Array.isArray(paths);
3857
+ paths ??= [];
3858
+ this.#items = new DataTransferItemList(this);
3859
+ for (const path of paths) this.#items.add(new DroppedFile(path));
3860
+ this.dropEffect = paths.length ? "copy" : "none";
3861
+ this.effectAllowed = paths.length ? "copy" : "uninitialized";
3862
+ }
3863
+
3864
+ _writable() {
3865
+ if (this._mode !== "readwrite") throw domError("InvalidStateError", "The DataTransfer is read-only now");
3866
+ }
3867
+
3868
+ get items() {
3869
+ return this.#items;
3870
+ }
3871
+
3872
+ get types() {
3873
+ if (this._mode === "protected") return Object.freeze([]);
3874
+ const types = [];
3875
+ let files = false;
3876
+ for (const item of this.#items._all()) {
3877
+ if (item.kind === "string") types.push(item.type);
3878
+ else files = true;
3879
+ }
3880
+ if (files || this._drag) types.push("Files");
3881
+ return Object.freeze(types);
3882
+ }
3883
+
3884
+ get files() {
3885
+ if (this._mode === "protected") return Object.freeze([]);
3886
+ return Object.freeze(this.#items._all().filter((item) => item.kind === "file").map((item) => item._value()));
3887
+ }
3888
+
3889
+ getData(format) {
3890
+ if (this._mode === "protected") return "";
3891
+ const type = normalFormat(format);
3892
+ const item = this.#items._all().find((each) => each.kind === "string" && each.type === type);
3893
+ const value = item ? item._value() : "";
3894
+ return type === "text/uri-list" ? (value.split(/\r?\n/).find((line) => line && !line.startsWith("#")) ?? "") : value;
3184
3895
  }
3185
3896
 
3186
- getData() {
3187
- return "";
3897
+ setData(format, data) {
3898
+ if (this._mode !== "readwrite") return;
3899
+ const type = normalFormat(format);
3900
+ const list = this.#items._all();
3901
+ const at = list.findIndex((each) => each.kind === "string" && each.type === type);
3902
+ if (at >= 0) list.splice(at, 1);
3903
+ this.#items.add(String(data), type);
3904
+ }
3905
+
3906
+ clearData(format) {
3907
+ if (this._mode !== "readwrite") return;
3908
+ const list = this.#items._all();
3909
+ const type = format === undefined ? null : normalFormat(format);
3910
+ for (let i = list.length - 1; i >= 0; i--) {
3911
+ if (list[i].kind === "string" && (type === null || list[i].type === type)) list.splice(i, 1);
3912
+ }
3913
+ }
3914
+
3915
+ setDragImage() {}
3916
+
3917
+ // The strings, and the PNG files, to put on the clipboard.
3918
+ _entries() {
3919
+ const entries = [];
3920
+ for (const item of this.#items._all()) {
3921
+ if (item.kind === "string") entries.push([item.type, item._value()]);
3922
+ else if (item.type === "image/png" && !entries.some(([type]) => type === "image/png")) entries.push(["image/png", item._value()]);
3923
+ }
3924
+ return entries;
3925
+ }
3926
+ }
3927
+
3928
+ /** A copy, cut or paste, as the web's `ClipboardEvent`. */
3929
+ export class ClipboardEvent extends Event {
3930
+ constructor(type, init = {}) {
3931
+ super(String(type), null);
3932
+ this.bubbles = !!init.bubbles;
3933
+ this.cancelable = !!init.cancelable;
3934
+ this.composed = !!init.composed;
3935
+ this.clipboardData = init.clipboardData ?? null;
3936
+ }
3937
+ }
3938
+
3939
+ /** An edit about to happen (`beforeinput`), as the web's `InputEvent`. */
3940
+ class InputEvent extends Event {
3941
+ constructor(type, init = {}) {
3942
+ super(String(type), null);
3943
+ this.bubbles = !!init.bubbles;
3944
+ this.cancelable = !!init.cancelable;
3945
+ this.composed = !!init.composed;
3946
+ this.inputType = init.inputType ?? "";
3947
+ this.data = init.data ?? null;
3948
+ this.dataTransfer = init.dataTransfer ?? null;
3949
+ this.isComposing = !!init.isComposing;
3950
+ }
3951
+
3952
+ getTargetRanges() {
3953
+ return [];
3188
3954
  }
3189
3955
  }
3190
3956
 
3957
+ globalThis.ClipboardEvent ??= ClipboardEvent;
3958
+ globalThis.InputEvent ??= InputEvent;
3959
+ globalThis.DataTransfer ??= DataTransfer;
3960
+
3191
3961
  let dragTarget = null;
3192
3962
 
3193
3963
  function dragEvent(type, target, x, y, paths) {