@rollstack/rscanvas 0.1.0

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/dist/index.mjs ADDED
@@ -0,0 +1,4507 @@
1
+ // src/object_node.ts
2
+ var RSObjectNode = class {
3
+ constructor(container, object, worldX, worldY, worldWidth, worldHeight, type, id, isEditing, rotation = 0) {
4
+ this._highlighted = false;
5
+ this._highlightColor = "#00d4aa";
6
+ this._dirtyHighlight = true;
7
+ this._object = object;
8
+ this._x = worldX;
9
+ this._y = worldY;
10
+ this._width = worldWidth;
11
+ this._height = worldHeight;
12
+ this._type = type;
13
+ this._id = id;
14
+ this._isEditing = isEditing;
15
+ this._containerNode = document.createElement("div");
16
+ this._containerNode.style.position = "absolute";
17
+ this._containerNode.style.overflow = "hidden";
18
+ this._containerNode.style.userSelect = "none";
19
+ this._containerNode.style.webkitUserSelect = "none";
20
+ this._containerNode.style.transformOrigin = "50% 50%";
21
+ this._rotation = rotation;
22
+ this._dirtyXY = true;
23
+ this._dirtySize = true;
24
+ this._dirtyRotation = true;
25
+ this._dirtyState = true;
26
+ container.appendChild(this._containerNode);
27
+ }
28
+ getType() {
29
+ return this._type;
30
+ }
31
+ getId() {
32
+ return this._id;
33
+ }
34
+ getContainerNode() {
35
+ return this._containerNode;
36
+ }
37
+ getObject() {
38
+ return this._object;
39
+ }
40
+ highlight(color) {
41
+ if (this._highlighted && this._highlightColor === color) {
42
+ return;
43
+ }
44
+ this._highlighted = true;
45
+ this._highlightColor = color;
46
+ this._dirtyHighlight = true;
47
+ }
48
+ unhighlight() {
49
+ if (!this._highlighted) {
50
+ return;
51
+ }
52
+ this._dirtyHighlight = true;
53
+ this._highlighted = false;
54
+ }
55
+ interacts(worldX, worldY) {
56
+ if (this._rotation === 0) {
57
+ return worldX >= this._x && worldX <= this._x + this._width && worldY >= this._y && worldY <= this._y + this._height;
58
+ }
59
+ const pivotX = this._x + this._width / 2;
60
+ const pivotY = this._y + this._height / 2;
61
+ const dx = worldX - pivotX;
62
+ const dy = worldY - pivotY;
63
+ const c = Math.cos(-this._rotation);
64
+ const s = Math.sin(-this._rotation);
65
+ const localX = dx * c - dy * s;
66
+ const localY = dx * s + dy * c;
67
+ const hw = this._width / 2;
68
+ const hh = this._height / 2;
69
+ return localX >= -hw && localX <= hw && localY >= -hh && localY <= hh;
70
+ }
71
+ getX() {
72
+ return this._x;
73
+ }
74
+ getY() {
75
+ return this._y;
76
+ }
77
+ getWidth() {
78
+ return this._width;
79
+ }
80
+ getHeight() {
81
+ return this._height;
82
+ }
83
+ getRotation() {
84
+ return this._rotation;
85
+ }
86
+ getOptionsSFCT(options) {
87
+ this._object.getStateSFCT(options);
88
+ }
89
+ move(x, y) {
90
+ if (this._x !== x || this._y !== y) {
91
+ this._x = x;
92
+ this._y = y;
93
+ this._dirtyXY = true;
94
+ }
95
+ }
96
+ translate(dx, dy) {
97
+ this._x += dx;
98
+ this._y += dy;
99
+ this._dirtyXY = true;
100
+ }
101
+ resize(width, height) {
102
+ if (this._width !== width || this._height !== height) {
103
+ this._width = width;
104
+ this._height = height;
105
+ this._dirtySize = true;
106
+ }
107
+ }
108
+ rotate(angle) {
109
+ if (this._rotation !== angle) {
110
+ this._rotation = angle;
111
+ this._dirtyRotation = true;
112
+ }
113
+ }
114
+ render() {
115
+ if (this._dirtyXY) {
116
+ this._dirtyXY = false;
117
+ this._containerNode.style.left = `${this._x}px`;
118
+ this._containerNode.style.top = `${this._y}px`;
119
+ }
120
+ if (this._dirtySize) {
121
+ this._dirtySize = false;
122
+ this._containerNode.style.width = `${this._width}px`;
123
+ this._containerNode.style.height = `${this._height}px`;
124
+ }
125
+ if (this._dirtyRotation) {
126
+ this._dirtyRotation = false;
127
+ this._containerNode.style.transform = `rotate(${this._rotation}rad)`;
128
+ }
129
+ if (this._dirtyState && !this._isEditing(this._id)) {
130
+ this._dirtyState = false;
131
+ this._object.renderSFCT(this._containerNode);
132
+ }
133
+ if (this._dirtyHighlight) {
134
+ this._dirtyHighlight = false;
135
+ const outline = this._highlighted ? `3px solid ${this._highlightColor}` : "none";
136
+ this._containerNode.style.outline = outline;
137
+ }
138
+ const editing = this._isEditing(this._id);
139
+ const userSelect = editing ? "text" : "none";
140
+ if (this._containerNode.style.userSelect !== userSelect) {
141
+ this._containerNode.style.userSelect = userSelect;
142
+ this._containerNode.style.webkitUserSelect = userSelect;
143
+ }
144
+ }
145
+ updateState(state) {
146
+ if (!this._object.isStateEqual(state)) {
147
+ this._object.updateState(state);
148
+ this._dirtyState = true;
149
+ }
150
+ }
151
+ destroy() {
152
+ this._object.destroy();
153
+ this._containerNode.remove();
154
+ }
155
+ };
156
+
157
+ // src/objects/text_object.ts
158
+ var RSTextObject = class {
159
+ constructor(state) {
160
+ this._state = { text: "" };
161
+ this._state.text = state.text;
162
+ }
163
+ isStateEqual(state) {
164
+ return this._state.text === state.text;
165
+ }
166
+ updateState(state) {
167
+ this._state.text = state.text;
168
+ }
169
+ getStateSFCT(state) {
170
+ state.text = this._state.text;
171
+ }
172
+ renderSFCT(node) {
173
+ node.textContent = this._state.text;
174
+ }
175
+ destroy() {
176
+ }
177
+ };
178
+
179
+ // src/objects/image_object.ts
180
+ var RSImageObject = class {
181
+ constructor(state) {
182
+ this._imgNode = null;
183
+ this._state = state;
184
+ }
185
+ _getUrl() {
186
+ if (this._state.type === "url") {
187
+ return this._state.url ?? "";
188
+ }
189
+ try {
190
+ return localStorage.getItem(this._state.key ?? "") ?? "";
191
+ } catch {
192
+ return "";
193
+ }
194
+ }
195
+ isStateEqual(state) {
196
+ if (this._state.type !== state.type) {
197
+ return false;
198
+ }
199
+ if (this._state.type === "url" && state.type === "url") {
200
+ return (this._state.url ?? "") === (state.url ?? "");
201
+ }
202
+ if (this._state.type === "localStorage" && state.type === "localStorage") {
203
+ return (this._state.key ?? "") === (state.key ?? "");
204
+ }
205
+ return false;
206
+ }
207
+ updateState(state) {
208
+ this._state = state;
209
+ }
210
+ getStateSFCT(state) {
211
+ const out = state;
212
+ out.type = this._state.type;
213
+ if (this._state.type === "url") {
214
+ out.url = this._state.url ?? "";
215
+ delete out.key;
216
+ } else {
217
+ out.key = this._state.key ?? "";
218
+ delete out.url;
219
+ }
220
+ }
221
+ renderSFCT(node) {
222
+ const url = this._getUrl();
223
+ if (!this._imgNode) {
224
+ this._imgNode = document.createElement("img");
225
+ this._imgNode.draggable = false;
226
+ this._imgNode.style.width = "100%";
227
+ this._imgNode.style.height = "100%";
228
+ node.replaceChildren(this._imgNode);
229
+ }
230
+ this._imgNode.src = url;
231
+ if (url.startsWith("http://") || url.startsWith("https://")) {
232
+ this._imgNode.setAttribute("crossorigin", "anonymous");
233
+ } else {
234
+ this._imgNode.removeAttribute("crossorigin");
235
+ }
236
+ }
237
+ destroy() {
238
+ this._imgNode?.remove();
239
+ this._imgNode = null;
240
+ }
241
+ };
242
+
243
+ // node_modules/orderedmap/dist/index.js
244
+ function OrderedMap(content) {
245
+ this.content = content;
246
+ }
247
+ OrderedMap.prototype = {
248
+ constructor: OrderedMap,
249
+ find: function(key) {
250
+ for (var i = 0; i < this.content.length; i += 2)
251
+ if (this.content[i] === key) return i;
252
+ return -1;
253
+ },
254
+ // :: (string) → ?any
255
+ // Retrieve the value stored under `key`, or return undefined when
256
+ // no such key exists.
257
+ get: function(key) {
258
+ var found2 = this.find(key);
259
+ return found2 == -1 ? void 0 : this.content[found2 + 1];
260
+ },
261
+ // :: (string, any, ?string) → OrderedMap
262
+ // Create a new map by replacing the value of `key` with a new
263
+ // value, or adding a binding to the end of the map. If `newKey` is
264
+ // given, the key of the binding will be replaced with that key.
265
+ update: function(key, value, newKey) {
266
+ var self = newKey && newKey != key ? this.remove(newKey) : this;
267
+ var found2 = self.find(key), content = self.content.slice();
268
+ if (found2 == -1) {
269
+ content.push(newKey || key, value);
270
+ } else {
271
+ content[found2 + 1] = value;
272
+ if (newKey) content[found2] = newKey;
273
+ }
274
+ return new OrderedMap(content);
275
+ },
276
+ // :: (string) → OrderedMap
277
+ // Return a map with the given key removed, if it existed.
278
+ remove: function(key) {
279
+ var found2 = this.find(key);
280
+ if (found2 == -1) return this;
281
+ var content = this.content.slice();
282
+ content.splice(found2, 2);
283
+ return new OrderedMap(content);
284
+ },
285
+ // :: (string, any) → OrderedMap
286
+ // Add a new key to the start of the map.
287
+ addToStart: function(key, value) {
288
+ return new OrderedMap([key, value].concat(this.remove(key).content));
289
+ },
290
+ // :: (string, any) → OrderedMap
291
+ // Add a new key to the end of the map.
292
+ addToEnd: function(key, value) {
293
+ var content = this.remove(key).content.slice();
294
+ content.push(key, value);
295
+ return new OrderedMap(content);
296
+ },
297
+ // :: (string, string, any) → OrderedMap
298
+ // Add a key after the given key. If `place` is not found, the new
299
+ // key is added to the end.
300
+ addBefore: function(place, key, value) {
301
+ var without = this.remove(key), content = without.content.slice();
302
+ var found2 = without.find(place);
303
+ content.splice(found2 == -1 ? content.length : found2, 0, key, value);
304
+ return new OrderedMap(content);
305
+ },
306
+ // :: ((key: string, value: any))
307
+ // Call the given function for each key/value pair in the map, in
308
+ // order.
309
+ forEach: function(f) {
310
+ for (var i = 0; i < this.content.length; i += 2)
311
+ f(this.content[i], this.content[i + 1]);
312
+ },
313
+ // :: (union<Object, OrderedMap>) → OrderedMap
314
+ // Create a new map by prepending the keys in this map that don't
315
+ // appear in `map` before the keys in `map`.
316
+ prepend: function(map) {
317
+ map = OrderedMap.from(map);
318
+ if (!map.size) return this;
319
+ return new OrderedMap(map.content.concat(this.subtract(map).content));
320
+ },
321
+ // :: (union<Object, OrderedMap>) → OrderedMap
322
+ // Create a new map by appending the keys in this map that don't
323
+ // appear in `map` after the keys in `map`.
324
+ append: function(map) {
325
+ map = OrderedMap.from(map);
326
+ if (!map.size) return this;
327
+ return new OrderedMap(this.subtract(map).content.concat(map.content));
328
+ },
329
+ // :: (union<Object, OrderedMap>) → OrderedMap
330
+ // Create a map containing all the keys in this map that don't
331
+ // appear in `map`.
332
+ subtract: function(map) {
333
+ var result = this;
334
+ map = OrderedMap.from(map);
335
+ for (var i = 0; i < map.content.length; i += 2)
336
+ result = result.remove(map.content[i]);
337
+ return result;
338
+ },
339
+ // :: () → Object
340
+ // Turn ordered map into a plain object.
341
+ toObject: function() {
342
+ var result = {};
343
+ this.forEach(function(key, value) {
344
+ result[key] = value;
345
+ });
346
+ return result;
347
+ },
348
+ // :: number
349
+ // The amount of keys in this map.
350
+ get size() {
351
+ return this.content.length >> 1;
352
+ }
353
+ };
354
+ OrderedMap.from = function(value) {
355
+ if (value instanceof OrderedMap) return value;
356
+ var content = [];
357
+ if (value) for (var prop in value) content.push(prop, value[prop]);
358
+ return new OrderedMap(content);
359
+ };
360
+ var dist_default = OrderedMap;
361
+
362
+ // node_modules/prosemirror-model/dist/index.js
363
+ function findDiffStart(a, b, pos) {
364
+ for (let i = 0; ; i++) {
365
+ if (i == a.childCount || i == b.childCount)
366
+ return a.childCount == b.childCount ? null : pos;
367
+ let childA = a.child(i), childB = b.child(i);
368
+ if (childA == childB) {
369
+ pos += childA.nodeSize;
370
+ continue;
371
+ }
372
+ if (!childA.sameMarkup(childB))
373
+ return pos;
374
+ if (childA.isText && childA.text != childB.text) {
375
+ for (let j = 0; childA.text[j] == childB.text[j]; j++)
376
+ pos++;
377
+ return pos;
378
+ }
379
+ if (childA.content.size || childB.content.size) {
380
+ let inner = findDiffStart(childA.content, childB.content, pos + 1);
381
+ if (inner != null)
382
+ return inner;
383
+ }
384
+ pos += childA.nodeSize;
385
+ }
386
+ }
387
+ function findDiffEnd(a, b, posA, posB) {
388
+ for (let iA = a.childCount, iB = b.childCount; ; ) {
389
+ if (iA == 0 || iB == 0)
390
+ return iA == iB ? null : { a: posA, b: posB };
391
+ let childA = a.child(--iA), childB = b.child(--iB), size = childA.nodeSize;
392
+ if (childA == childB) {
393
+ posA -= size;
394
+ posB -= size;
395
+ continue;
396
+ }
397
+ if (!childA.sameMarkup(childB))
398
+ return { a: posA, b: posB };
399
+ if (childA.isText && childA.text != childB.text) {
400
+ let same = 0, minSize = Math.min(childA.text.length, childB.text.length);
401
+ while (same < minSize && childA.text[childA.text.length - same - 1] == childB.text[childB.text.length - same - 1]) {
402
+ same++;
403
+ posA--;
404
+ posB--;
405
+ }
406
+ return { a: posA, b: posB };
407
+ }
408
+ if (childA.content.size || childB.content.size) {
409
+ let inner = findDiffEnd(childA.content, childB.content, posA - 1, posB - 1);
410
+ if (inner)
411
+ return inner;
412
+ }
413
+ posA -= size;
414
+ posB -= size;
415
+ }
416
+ }
417
+ var Fragment = class _Fragment {
418
+ /**
419
+ @internal
420
+ */
421
+ constructor(content, size) {
422
+ this.content = content;
423
+ this.size = size || 0;
424
+ if (size == null)
425
+ for (let i = 0; i < content.length; i++)
426
+ this.size += content[i].nodeSize;
427
+ }
428
+ /**
429
+ Invoke a callback for all descendant nodes between the given two
430
+ positions (relative to start of this fragment). Doesn't descend
431
+ into a node when the callback returns `false`.
432
+ */
433
+ nodesBetween(from, to, f, nodeStart = 0, parent) {
434
+ for (let i = 0, pos = 0; pos < to; i++) {
435
+ let child = this.content[i], end = pos + child.nodeSize;
436
+ if (end > from && f(child, nodeStart + pos, parent || null, i) !== false && child.content.size) {
437
+ let start = pos + 1;
438
+ child.nodesBetween(Math.max(0, from - start), Math.min(child.content.size, to - start), f, nodeStart + start);
439
+ }
440
+ pos = end;
441
+ }
442
+ }
443
+ /**
444
+ Call the given callback for every descendant node. `pos` will be
445
+ relative to the start of the fragment. The callback may return
446
+ `false` to prevent traversal of a given node's children.
447
+ */
448
+ descendants(f) {
449
+ this.nodesBetween(0, this.size, f);
450
+ }
451
+ /**
452
+ Extract the text between `from` and `to`. See the same method on
453
+ [`Node`](https://prosemirror.net/docs/ref/#model.Node.textBetween).
454
+ */
455
+ textBetween(from, to, blockSeparator, leafText) {
456
+ let text = "", first = true;
457
+ this.nodesBetween(from, to, (node, pos) => {
458
+ let nodeText = node.isText ? node.text.slice(Math.max(from, pos) - pos, to - pos) : !node.isLeaf ? "" : leafText ? typeof leafText === "function" ? leafText(node) : leafText : node.type.spec.leafText ? node.type.spec.leafText(node) : "";
459
+ if (node.isBlock && (node.isLeaf && nodeText || node.isTextblock) && blockSeparator) {
460
+ if (first)
461
+ first = false;
462
+ else
463
+ text += blockSeparator;
464
+ }
465
+ text += nodeText;
466
+ }, 0);
467
+ return text;
468
+ }
469
+ /**
470
+ Create a new fragment containing the combined content of this
471
+ fragment and the other.
472
+ */
473
+ append(other) {
474
+ if (!other.size)
475
+ return this;
476
+ if (!this.size)
477
+ return other;
478
+ let last = this.lastChild, first = other.firstChild, content = this.content.slice(), i = 0;
479
+ if (last.isText && last.sameMarkup(first)) {
480
+ content[content.length - 1] = last.withText(last.text + first.text);
481
+ i = 1;
482
+ }
483
+ for (; i < other.content.length; i++)
484
+ content.push(other.content[i]);
485
+ return new _Fragment(content, this.size + other.size);
486
+ }
487
+ /**
488
+ Cut out the sub-fragment between the two given positions.
489
+ */
490
+ cut(from, to = this.size) {
491
+ if (from == 0 && to == this.size)
492
+ return this;
493
+ let result = [], size = 0;
494
+ if (to > from)
495
+ for (let i = 0, pos = 0; pos < to; i++) {
496
+ let child = this.content[i], end = pos + child.nodeSize;
497
+ if (end > from) {
498
+ if (pos < from || end > to) {
499
+ if (child.isText)
500
+ child = child.cut(Math.max(0, from - pos), Math.min(child.text.length, to - pos));
501
+ else
502
+ child = child.cut(Math.max(0, from - pos - 1), Math.min(child.content.size, to - pos - 1));
503
+ }
504
+ result.push(child);
505
+ size += child.nodeSize;
506
+ }
507
+ pos = end;
508
+ }
509
+ return new _Fragment(result, size);
510
+ }
511
+ /**
512
+ @internal
513
+ */
514
+ cutByIndex(from, to) {
515
+ if (from == to)
516
+ return _Fragment.empty;
517
+ if (from == 0 && to == this.content.length)
518
+ return this;
519
+ return new _Fragment(this.content.slice(from, to));
520
+ }
521
+ /**
522
+ Create a new fragment in which the node at the given index is
523
+ replaced by the given node.
524
+ */
525
+ replaceChild(index, node) {
526
+ let current = this.content[index];
527
+ if (current == node)
528
+ return this;
529
+ let copy = this.content.slice();
530
+ let size = this.size + node.nodeSize - current.nodeSize;
531
+ copy[index] = node;
532
+ return new _Fragment(copy, size);
533
+ }
534
+ /**
535
+ Create a new fragment by prepending the given node to this
536
+ fragment.
537
+ */
538
+ addToStart(node) {
539
+ return new _Fragment([node].concat(this.content), this.size + node.nodeSize);
540
+ }
541
+ /**
542
+ Create a new fragment by appending the given node to this
543
+ fragment.
544
+ */
545
+ addToEnd(node) {
546
+ return new _Fragment(this.content.concat(node), this.size + node.nodeSize);
547
+ }
548
+ /**
549
+ Compare this fragment to another one.
550
+ */
551
+ eq(other) {
552
+ if (this.content.length != other.content.length)
553
+ return false;
554
+ for (let i = 0; i < this.content.length; i++)
555
+ if (!this.content[i].eq(other.content[i]))
556
+ return false;
557
+ return true;
558
+ }
559
+ /**
560
+ The first child of the fragment, or `null` if it is empty.
561
+ */
562
+ get firstChild() {
563
+ return this.content.length ? this.content[0] : null;
564
+ }
565
+ /**
566
+ The last child of the fragment, or `null` if it is empty.
567
+ */
568
+ get lastChild() {
569
+ return this.content.length ? this.content[this.content.length - 1] : null;
570
+ }
571
+ /**
572
+ The number of child nodes in this fragment.
573
+ */
574
+ get childCount() {
575
+ return this.content.length;
576
+ }
577
+ /**
578
+ Get the child node at the given index. Raise an error when the
579
+ index is out of range.
580
+ */
581
+ child(index) {
582
+ let found2 = this.content[index];
583
+ if (!found2)
584
+ throw new RangeError("Index " + index + " out of range for " + this);
585
+ return found2;
586
+ }
587
+ /**
588
+ Get the child node at the given index, if it exists.
589
+ */
590
+ maybeChild(index) {
591
+ return this.content[index] || null;
592
+ }
593
+ /**
594
+ Call `f` for every child node, passing the node, its offset
595
+ into this parent node, and its index.
596
+ */
597
+ forEach(f) {
598
+ for (let i = 0, p = 0; i < this.content.length; i++) {
599
+ let child = this.content[i];
600
+ f(child, p, i);
601
+ p += child.nodeSize;
602
+ }
603
+ }
604
+ /**
605
+ Find the first position at which this fragment and another
606
+ fragment differ, or `null` if they are the same.
607
+ */
608
+ findDiffStart(other, pos = 0) {
609
+ return findDiffStart(this, other, pos);
610
+ }
611
+ /**
612
+ Find the first position, searching from the end, at which this
613
+ fragment and the given fragment differ, or `null` if they are
614
+ the same. Since this position will not be the same in both
615
+ nodes, an object with two separate positions is returned.
616
+ */
617
+ findDiffEnd(other, pos = this.size, otherPos = other.size) {
618
+ return findDiffEnd(this, other, pos, otherPos);
619
+ }
620
+ /**
621
+ Find the index and inner offset corresponding to a given relative
622
+ position in this fragment. The result object will be reused
623
+ (overwritten) the next time the function is called. @internal
624
+ */
625
+ findIndex(pos) {
626
+ if (pos == 0)
627
+ return retIndex(0, pos);
628
+ if (pos == this.size)
629
+ return retIndex(this.content.length, pos);
630
+ if (pos > this.size || pos < 0)
631
+ throw new RangeError(`Position ${pos} outside of fragment (${this})`);
632
+ for (let i = 0, curPos = 0; ; i++) {
633
+ let cur = this.child(i), end = curPos + cur.nodeSize;
634
+ if (end >= pos) {
635
+ if (end == pos)
636
+ return retIndex(i + 1, end);
637
+ return retIndex(i, curPos);
638
+ }
639
+ curPos = end;
640
+ }
641
+ }
642
+ /**
643
+ Return a debugging string that describes this fragment.
644
+ */
645
+ toString() {
646
+ return "<" + this.toStringInner() + ">";
647
+ }
648
+ /**
649
+ @internal
650
+ */
651
+ toStringInner() {
652
+ return this.content.join(", ");
653
+ }
654
+ /**
655
+ Create a JSON-serializeable representation of this fragment.
656
+ */
657
+ toJSON() {
658
+ return this.content.length ? this.content.map((n) => n.toJSON()) : null;
659
+ }
660
+ /**
661
+ Deserialize a fragment from its JSON representation.
662
+ */
663
+ static fromJSON(schema2, value) {
664
+ if (!value)
665
+ return _Fragment.empty;
666
+ if (!Array.isArray(value))
667
+ throw new RangeError("Invalid input for Fragment.fromJSON");
668
+ return new _Fragment(value.map(schema2.nodeFromJSON));
669
+ }
670
+ /**
671
+ Build a fragment from an array of nodes. Ensures that adjacent
672
+ text nodes with the same marks are joined together.
673
+ */
674
+ static fromArray(array) {
675
+ if (!array.length)
676
+ return _Fragment.empty;
677
+ let joined, size = 0;
678
+ for (let i = 0; i < array.length; i++) {
679
+ let node = array[i];
680
+ size += node.nodeSize;
681
+ if (i && node.isText && array[i - 1].sameMarkup(node)) {
682
+ if (!joined)
683
+ joined = array.slice(0, i);
684
+ joined[joined.length - 1] = node.withText(joined[joined.length - 1].text + node.text);
685
+ } else if (joined) {
686
+ joined.push(node);
687
+ }
688
+ }
689
+ return new _Fragment(joined || array, size);
690
+ }
691
+ /**
692
+ Create a fragment from something that can be interpreted as a
693
+ set of nodes. For `null`, it returns the empty fragment. For a
694
+ fragment, the fragment itself. For a node or array of nodes, a
695
+ fragment containing those nodes.
696
+ */
697
+ static from(nodes2) {
698
+ if (!nodes2)
699
+ return _Fragment.empty;
700
+ if (nodes2 instanceof _Fragment)
701
+ return nodes2;
702
+ if (Array.isArray(nodes2))
703
+ return this.fromArray(nodes2);
704
+ if (nodes2.attrs)
705
+ return new _Fragment([nodes2], nodes2.nodeSize);
706
+ throw new RangeError("Can not convert " + nodes2 + " to a Fragment" + (nodes2.nodesBetween ? " (looks like multiple versions of prosemirror-model were loaded)" : ""));
707
+ }
708
+ };
709
+ Fragment.empty = new Fragment([], 0);
710
+ var found = { index: 0, offset: 0 };
711
+ function retIndex(index, offset) {
712
+ found.index = index;
713
+ found.offset = offset;
714
+ return found;
715
+ }
716
+ function compareDeep(a, b) {
717
+ if (a === b)
718
+ return true;
719
+ if (!(a && typeof a == "object") || !(b && typeof b == "object"))
720
+ return false;
721
+ let array = Array.isArray(a);
722
+ if (Array.isArray(b) != array)
723
+ return false;
724
+ if (array) {
725
+ if (a.length != b.length)
726
+ return false;
727
+ for (let i = 0; i < a.length; i++)
728
+ if (!compareDeep(a[i], b[i]))
729
+ return false;
730
+ } else {
731
+ for (let p in a)
732
+ if (!(p in b) || !compareDeep(a[p], b[p]))
733
+ return false;
734
+ for (let p in b)
735
+ if (!(p in a))
736
+ return false;
737
+ }
738
+ return true;
739
+ }
740
+ var Mark = class _Mark {
741
+ /**
742
+ @internal
743
+ */
744
+ constructor(type, attrs) {
745
+ this.type = type;
746
+ this.attrs = attrs;
747
+ }
748
+ /**
749
+ Given a set of marks, create a new set which contains this one as
750
+ well, in the right position. If this mark is already in the set,
751
+ the set itself is returned. If any marks that are set to be
752
+ [exclusive](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) with this mark are present,
753
+ those are replaced by this one.
754
+ */
755
+ addToSet(set) {
756
+ let copy, placed = false;
757
+ for (let i = 0; i < set.length; i++) {
758
+ let other = set[i];
759
+ if (this.eq(other))
760
+ return set;
761
+ if (this.type.excludes(other.type)) {
762
+ if (!copy)
763
+ copy = set.slice(0, i);
764
+ } else if (other.type.excludes(this.type)) {
765
+ return set;
766
+ } else {
767
+ if (!placed && other.type.rank > this.type.rank) {
768
+ if (!copy)
769
+ copy = set.slice(0, i);
770
+ copy.push(this);
771
+ placed = true;
772
+ }
773
+ if (copy)
774
+ copy.push(other);
775
+ }
776
+ }
777
+ if (!copy)
778
+ copy = set.slice();
779
+ if (!placed)
780
+ copy.push(this);
781
+ return copy;
782
+ }
783
+ /**
784
+ Remove this mark from the given set, returning a new set. If this
785
+ mark is not in the set, the set itself is returned.
786
+ */
787
+ removeFromSet(set) {
788
+ for (let i = 0; i < set.length; i++)
789
+ if (this.eq(set[i]))
790
+ return set.slice(0, i).concat(set.slice(i + 1));
791
+ return set;
792
+ }
793
+ /**
794
+ Test whether this mark is in the given set of marks.
795
+ */
796
+ isInSet(set) {
797
+ for (let i = 0; i < set.length; i++)
798
+ if (this.eq(set[i]))
799
+ return true;
800
+ return false;
801
+ }
802
+ /**
803
+ Test whether this mark has the same type and attributes as
804
+ another mark.
805
+ */
806
+ eq(other) {
807
+ return this == other || this.type == other.type && compareDeep(this.attrs, other.attrs);
808
+ }
809
+ /**
810
+ Convert this mark to a JSON-serializeable representation.
811
+ */
812
+ toJSON() {
813
+ let obj = { type: this.type.name };
814
+ for (let _ in this.attrs) {
815
+ obj.attrs = this.attrs;
816
+ break;
817
+ }
818
+ return obj;
819
+ }
820
+ /**
821
+ Deserialize a mark from JSON.
822
+ */
823
+ static fromJSON(schema2, json) {
824
+ if (!json)
825
+ throw new RangeError("Invalid input for Mark.fromJSON");
826
+ let type = schema2.marks[json.type];
827
+ if (!type)
828
+ throw new RangeError(`There is no mark type ${json.type} in this schema`);
829
+ let mark = type.create(json.attrs);
830
+ type.checkAttrs(mark.attrs);
831
+ return mark;
832
+ }
833
+ /**
834
+ Test whether two sets of marks are identical.
835
+ */
836
+ static sameSet(a, b) {
837
+ if (a == b)
838
+ return true;
839
+ if (a.length != b.length)
840
+ return false;
841
+ for (let i = 0; i < a.length; i++)
842
+ if (!a[i].eq(b[i]))
843
+ return false;
844
+ return true;
845
+ }
846
+ /**
847
+ Create a properly sorted mark set from null, a single mark, or an
848
+ unsorted array of marks.
849
+ */
850
+ static setFrom(marks2) {
851
+ if (!marks2 || Array.isArray(marks2) && marks2.length == 0)
852
+ return _Mark.none;
853
+ if (marks2 instanceof _Mark)
854
+ return [marks2];
855
+ let copy = marks2.slice();
856
+ copy.sort((a, b) => a.type.rank - b.type.rank);
857
+ return copy;
858
+ }
859
+ };
860
+ Mark.none = [];
861
+ var ReplaceError = class extends Error {
862
+ };
863
+ var Slice = class _Slice {
864
+ /**
865
+ Create a slice. When specifying a non-zero open depth, you must
866
+ make sure that there are nodes of at least that depth at the
867
+ appropriate side of the fragment—i.e. if the fragment is an
868
+ empty paragraph node, `openStart` and `openEnd` can't be greater
869
+ than 1.
870
+
871
+ It is not necessary for the content of open nodes to conform to
872
+ the schema's content constraints, though it should be a valid
873
+ start/end/middle for such a node, depending on which sides are
874
+ open.
875
+ */
876
+ constructor(content, openStart, openEnd) {
877
+ this.content = content;
878
+ this.openStart = openStart;
879
+ this.openEnd = openEnd;
880
+ }
881
+ /**
882
+ The size this slice would add when inserted into a document.
883
+ */
884
+ get size() {
885
+ return this.content.size - this.openStart - this.openEnd;
886
+ }
887
+ /**
888
+ @internal
889
+ */
890
+ insertAt(pos, fragment) {
891
+ let content = insertInto(this.content, pos + this.openStart, fragment);
892
+ return content && new _Slice(content, this.openStart, this.openEnd);
893
+ }
894
+ /**
895
+ @internal
896
+ */
897
+ removeBetween(from, to) {
898
+ return new _Slice(removeRange(this.content, from + this.openStart, to + this.openStart), this.openStart, this.openEnd);
899
+ }
900
+ /**
901
+ Tests whether this slice is equal to another slice.
902
+ */
903
+ eq(other) {
904
+ return this.content.eq(other.content) && this.openStart == other.openStart && this.openEnd == other.openEnd;
905
+ }
906
+ /**
907
+ @internal
908
+ */
909
+ toString() {
910
+ return this.content + "(" + this.openStart + "," + this.openEnd + ")";
911
+ }
912
+ /**
913
+ Convert a slice to a JSON-serializable representation.
914
+ */
915
+ toJSON() {
916
+ if (!this.content.size)
917
+ return null;
918
+ let json = { content: this.content.toJSON() };
919
+ if (this.openStart > 0)
920
+ json.openStart = this.openStart;
921
+ if (this.openEnd > 0)
922
+ json.openEnd = this.openEnd;
923
+ return json;
924
+ }
925
+ /**
926
+ Deserialize a slice from its JSON representation.
927
+ */
928
+ static fromJSON(schema2, json) {
929
+ if (!json)
930
+ return _Slice.empty;
931
+ let openStart = json.openStart || 0, openEnd = json.openEnd || 0;
932
+ if (typeof openStart != "number" || typeof openEnd != "number")
933
+ throw new RangeError("Invalid input for Slice.fromJSON");
934
+ return new _Slice(Fragment.fromJSON(schema2, json.content), openStart, openEnd);
935
+ }
936
+ /**
937
+ Create a slice from a fragment by taking the maximum possible
938
+ open value on both side of the fragment.
939
+ */
940
+ static maxOpen(fragment, openIsolating = true) {
941
+ let openStart = 0, openEnd = 0;
942
+ for (let n = fragment.firstChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.firstChild)
943
+ openStart++;
944
+ for (let n = fragment.lastChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.lastChild)
945
+ openEnd++;
946
+ return new _Slice(fragment, openStart, openEnd);
947
+ }
948
+ };
949
+ Slice.empty = new Slice(Fragment.empty, 0, 0);
950
+ function removeRange(content, from, to) {
951
+ let { index, offset } = content.findIndex(from), child = content.maybeChild(index);
952
+ let { index: indexTo, offset: offsetTo } = content.findIndex(to);
953
+ if (offset == from || child.isText) {
954
+ if (offsetTo != to && !content.child(indexTo).isText)
955
+ throw new RangeError("Removing non-flat range");
956
+ return content.cut(0, from).append(content.cut(to));
957
+ }
958
+ if (index != indexTo)
959
+ throw new RangeError("Removing non-flat range");
960
+ return content.replaceChild(index, child.copy(removeRange(child.content, from - offset - 1, to - offset - 1)));
961
+ }
962
+ function insertInto(content, dist, insert, parent) {
963
+ let { index, offset } = content.findIndex(dist), child = content.maybeChild(index);
964
+ if (offset == dist || child.isText) {
965
+ if (parent && !parent.canReplace(index, index, insert))
966
+ return null;
967
+ return content.cut(0, dist).append(insert).append(content.cut(dist));
968
+ }
969
+ let inner = insertInto(child.content, dist - offset - 1, insert, child);
970
+ return inner && content.replaceChild(index, child.copy(inner));
971
+ }
972
+ function replace($from, $to, slice) {
973
+ if (slice.openStart > $from.depth)
974
+ throw new ReplaceError("Inserted content deeper than insertion position");
975
+ if ($from.depth - slice.openStart != $to.depth - slice.openEnd)
976
+ throw new ReplaceError("Inconsistent open depths");
977
+ return replaceOuter($from, $to, slice, 0);
978
+ }
979
+ function replaceOuter($from, $to, slice, depth) {
980
+ let index = $from.index(depth), node = $from.node(depth);
981
+ if (index == $to.index(depth) && depth < $from.depth - slice.openStart) {
982
+ let inner = replaceOuter($from, $to, slice, depth + 1);
983
+ return node.copy(node.content.replaceChild(index, inner));
984
+ } else if (!slice.content.size) {
985
+ return close(node, replaceTwoWay($from, $to, depth));
986
+ } else if (!slice.openStart && !slice.openEnd && $from.depth == depth && $to.depth == depth) {
987
+ let parent = $from.parent, content = parent.content;
988
+ return close(parent, content.cut(0, $from.parentOffset).append(slice.content).append(content.cut($to.parentOffset)));
989
+ } else {
990
+ let { start, end } = prepareSliceForReplace(slice, $from);
991
+ return close(node, replaceThreeWay($from, start, end, $to, depth));
992
+ }
993
+ }
994
+ function checkJoin(main, sub) {
995
+ if (!sub.type.compatibleContent(main.type))
996
+ throw new ReplaceError("Cannot join " + sub.type.name + " onto " + main.type.name);
997
+ }
998
+ function joinable($before, $after, depth) {
999
+ let node = $before.node(depth);
1000
+ checkJoin(node, $after.node(depth));
1001
+ return node;
1002
+ }
1003
+ function addNode(child, target) {
1004
+ let last = target.length - 1;
1005
+ if (last >= 0 && child.isText && child.sameMarkup(target[last]))
1006
+ target[last] = child.withText(target[last].text + child.text);
1007
+ else
1008
+ target.push(child);
1009
+ }
1010
+ function addRange($start, $end, depth, target) {
1011
+ let node = ($end || $start).node(depth);
1012
+ let startIndex = 0, endIndex = $end ? $end.index(depth) : node.childCount;
1013
+ if ($start) {
1014
+ startIndex = $start.index(depth);
1015
+ if ($start.depth > depth) {
1016
+ startIndex++;
1017
+ } else if ($start.textOffset) {
1018
+ addNode($start.nodeAfter, target);
1019
+ startIndex++;
1020
+ }
1021
+ }
1022
+ for (let i = startIndex; i < endIndex; i++)
1023
+ addNode(node.child(i), target);
1024
+ if ($end && $end.depth == depth && $end.textOffset)
1025
+ addNode($end.nodeBefore, target);
1026
+ }
1027
+ function close(node, content) {
1028
+ node.type.checkContent(content);
1029
+ return node.copy(content);
1030
+ }
1031
+ function replaceThreeWay($from, $start, $end, $to, depth) {
1032
+ let openStart = $from.depth > depth && joinable($from, $start, depth + 1);
1033
+ let openEnd = $to.depth > depth && joinable($end, $to, depth + 1);
1034
+ let content = [];
1035
+ addRange(null, $from, depth, content);
1036
+ if (openStart && openEnd && $start.index(depth) == $end.index(depth)) {
1037
+ checkJoin(openStart, openEnd);
1038
+ addNode(close(openStart, replaceThreeWay($from, $start, $end, $to, depth + 1)), content);
1039
+ } else {
1040
+ if (openStart)
1041
+ addNode(close(openStart, replaceTwoWay($from, $start, depth + 1)), content);
1042
+ addRange($start, $end, depth, content);
1043
+ if (openEnd)
1044
+ addNode(close(openEnd, replaceTwoWay($end, $to, depth + 1)), content);
1045
+ }
1046
+ addRange($to, null, depth, content);
1047
+ return new Fragment(content);
1048
+ }
1049
+ function replaceTwoWay($from, $to, depth) {
1050
+ let content = [];
1051
+ addRange(null, $from, depth, content);
1052
+ if ($from.depth > depth) {
1053
+ let type = joinable($from, $to, depth + 1);
1054
+ addNode(close(type, replaceTwoWay($from, $to, depth + 1)), content);
1055
+ }
1056
+ addRange($to, null, depth, content);
1057
+ return new Fragment(content);
1058
+ }
1059
+ function prepareSliceForReplace(slice, $along) {
1060
+ let extra = $along.depth - slice.openStart, parent = $along.node(extra);
1061
+ let node = parent.copy(slice.content);
1062
+ for (let i = extra - 1; i >= 0; i--)
1063
+ node = $along.node(i).copy(Fragment.from(node));
1064
+ return {
1065
+ start: node.resolveNoCache(slice.openStart + extra),
1066
+ end: node.resolveNoCache(node.content.size - slice.openEnd - extra)
1067
+ };
1068
+ }
1069
+ var ResolvedPos = class _ResolvedPos {
1070
+ /**
1071
+ @internal
1072
+ */
1073
+ constructor(pos, path, parentOffset) {
1074
+ this.pos = pos;
1075
+ this.path = path;
1076
+ this.parentOffset = parentOffset;
1077
+ this.depth = path.length / 3 - 1;
1078
+ }
1079
+ /**
1080
+ @internal
1081
+ */
1082
+ resolveDepth(val) {
1083
+ if (val == null)
1084
+ return this.depth;
1085
+ if (val < 0)
1086
+ return this.depth + val;
1087
+ return val;
1088
+ }
1089
+ /**
1090
+ The parent node that the position points into. Note that even if
1091
+ a position points into a text node, that node is not considered
1092
+ the parent—text nodes are ‘flat’ in this model, and have no content.
1093
+ */
1094
+ get parent() {
1095
+ return this.node(this.depth);
1096
+ }
1097
+ /**
1098
+ The root node in which the position was resolved.
1099
+ */
1100
+ get doc() {
1101
+ return this.node(0);
1102
+ }
1103
+ /**
1104
+ The ancestor node at the given level. `p.node(p.depth)` is the
1105
+ same as `p.parent`.
1106
+ */
1107
+ node(depth) {
1108
+ return this.path[this.resolveDepth(depth) * 3];
1109
+ }
1110
+ /**
1111
+ The index into the ancestor at the given level. If this points
1112
+ at the 3rd node in the 2nd paragraph on the top level, for
1113
+ example, `p.index(0)` is 1 and `p.index(1)` is 2.
1114
+ */
1115
+ index(depth) {
1116
+ return this.path[this.resolveDepth(depth) * 3 + 1];
1117
+ }
1118
+ /**
1119
+ The index pointing after this position into the ancestor at the
1120
+ given level.
1121
+ */
1122
+ indexAfter(depth) {
1123
+ depth = this.resolveDepth(depth);
1124
+ return this.index(depth) + (depth == this.depth && !this.textOffset ? 0 : 1);
1125
+ }
1126
+ /**
1127
+ The (absolute) position at the start of the node at the given
1128
+ level.
1129
+ */
1130
+ start(depth) {
1131
+ depth = this.resolveDepth(depth);
1132
+ return depth == 0 ? 0 : this.path[depth * 3 - 1] + 1;
1133
+ }
1134
+ /**
1135
+ The (absolute) position at the end of the node at the given
1136
+ level.
1137
+ */
1138
+ end(depth) {
1139
+ depth = this.resolveDepth(depth);
1140
+ return this.start(depth) + this.node(depth).content.size;
1141
+ }
1142
+ /**
1143
+ The (absolute) position directly before the wrapping node at the
1144
+ given level, or, when `depth` is `this.depth + 1`, the original
1145
+ position.
1146
+ */
1147
+ before(depth) {
1148
+ depth = this.resolveDepth(depth);
1149
+ if (!depth)
1150
+ throw new RangeError("There is no position before the top-level node");
1151
+ return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1];
1152
+ }
1153
+ /**
1154
+ The (absolute) position directly after the wrapping node at the
1155
+ given level, or the original position when `depth` is `this.depth + 1`.
1156
+ */
1157
+ after(depth) {
1158
+ depth = this.resolveDepth(depth);
1159
+ if (!depth)
1160
+ throw new RangeError("There is no position after the top-level node");
1161
+ return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1] + this.path[depth * 3].nodeSize;
1162
+ }
1163
+ /**
1164
+ When this position points into a text node, this returns the
1165
+ distance between the position and the start of the text node.
1166
+ Will be zero for positions that point between nodes.
1167
+ */
1168
+ get textOffset() {
1169
+ return this.pos - this.path[this.path.length - 1];
1170
+ }
1171
+ /**
1172
+ Get the node directly after the position, if any. If the position
1173
+ points into a text node, only the part of that node after the
1174
+ position is returned.
1175
+ */
1176
+ get nodeAfter() {
1177
+ let parent = this.parent, index = this.index(this.depth);
1178
+ if (index == parent.childCount)
1179
+ return null;
1180
+ let dOff = this.pos - this.path[this.path.length - 1], child = parent.child(index);
1181
+ return dOff ? parent.child(index).cut(dOff) : child;
1182
+ }
1183
+ /**
1184
+ Get the node directly before the position, if any. If the
1185
+ position points into a text node, only the part of that node
1186
+ before the position is returned.
1187
+ */
1188
+ get nodeBefore() {
1189
+ let index = this.index(this.depth);
1190
+ let dOff = this.pos - this.path[this.path.length - 1];
1191
+ if (dOff)
1192
+ return this.parent.child(index).cut(0, dOff);
1193
+ return index == 0 ? null : this.parent.child(index - 1);
1194
+ }
1195
+ /**
1196
+ Get the position at the given index in the parent node at the
1197
+ given depth (which defaults to `this.depth`).
1198
+ */
1199
+ posAtIndex(index, depth) {
1200
+ depth = this.resolveDepth(depth);
1201
+ let node = this.path[depth * 3], pos = depth == 0 ? 0 : this.path[depth * 3 - 1] + 1;
1202
+ for (let i = 0; i < index; i++)
1203
+ pos += node.child(i).nodeSize;
1204
+ return pos;
1205
+ }
1206
+ /**
1207
+ Get the marks at this position, factoring in the surrounding
1208
+ marks' [`inclusive`](https://prosemirror.net/docs/ref/#model.MarkSpec.inclusive) property. If the
1209
+ position is at the start of a non-empty node, the marks of the
1210
+ node after it (if any) are returned.
1211
+ */
1212
+ marks() {
1213
+ let parent = this.parent, index = this.index();
1214
+ if (parent.content.size == 0)
1215
+ return Mark.none;
1216
+ if (this.textOffset)
1217
+ return parent.child(index).marks;
1218
+ let main = parent.maybeChild(index - 1), other = parent.maybeChild(index);
1219
+ if (!main) {
1220
+ let tmp = main;
1221
+ main = other;
1222
+ other = tmp;
1223
+ }
1224
+ let marks2 = main.marks;
1225
+ for (var i = 0; i < marks2.length; i++)
1226
+ if (marks2[i].type.spec.inclusive === false && (!other || !marks2[i].isInSet(other.marks)))
1227
+ marks2 = marks2[i--].removeFromSet(marks2);
1228
+ return marks2;
1229
+ }
1230
+ /**
1231
+ Get the marks after the current position, if any, except those
1232
+ that are non-inclusive and not present at position `$end`. This
1233
+ is mostly useful for getting the set of marks to preserve after a
1234
+ deletion. Will return `null` if this position is at the end of
1235
+ its parent node or its parent node isn't a textblock (in which
1236
+ case no marks should be preserved).
1237
+ */
1238
+ marksAcross($end) {
1239
+ let after = this.parent.maybeChild(this.index());
1240
+ if (!after || !after.isInline)
1241
+ return null;
1242
+ let marks2 = after.marks, next = $end.parent.maybeChild($end.index());
1243
+ for (var i = 0; i < marks2.length; i++)
1244
+ if (marks2[i].type.spec.inclusive === false && (!next || !marks2[i].isInSet(next.marks)))
1245
+ marks2 = marks2[i--].removeFromSet(marks2);
1246
+ return marks2;
1247
+ }
1248
+ /**
1249
+ The depth up to which this position and the given (non-resolved)
1250
+ position share the same parent nodes.
1251
+ */
1252
+ sharedDepth(pos) {
1253
+ for (let depth = this.depth; depth > 0; depth--)
1254
+ if (this.start(depth) <= pos && this.end(depth) >= pos)
1255
+ return depth;
1256
+ return 0;
1257
+ }
1258
+ /**
1259
+ Returns a range based on the place where this position and the
1260
+ given position diverge around block content. If both point into
1261
+ the same textblock, for example, a range around that textblock
1262
+ will be returned. If they point into different blocks, the range
1263
+ around those blocks in their shared ancestor is returned. You can
1264
+ pass in an optional predicate that will be called with a parent
1265
+ node to see if a range into that parent is acceptable.
1266
+ */
1267
+ blockRange(other = this, pred) {
1268
+ if (other.pos < this.pos)
1269
+ return other.blockRange(this);
1270
+ for (let d = this.depth - (this.parent.inlineContent || this.pos == other.pos ? 1 : 0); d >= 0; d--)
1271
+ if (other.pos <= this.end(d) && (!pred || pred(this.node(d))))
1272
+ return new NodeRange(this, other, d);
1273
+ return null;
1274
+ }
1275
+ /**
1276
+ Query whether the given position shares the same parent node.
1277
+ */
1278
+ sameParent(other) {
1279
+ return this.pos - this.parentOffset == other.pos - other.parentOffset;
1280
+ }
1281
+ /**
1282
+ Return the greater of this and the given position.
1283
+ */
1284
+ max(other) {
1285
+ return other.pos > this.pos ? other : this;
1286
+ }
1287
+ /**
1288
+ Return the smaller of this and the given position.
1289
+ */
1290
+ min(other) {
1291
+ return other.pos < this.pos ? other : this;
1292
+ }
1293
+ /**
1294
+ @internal
1295
+ */
1296
+ toString() {
1297
+ let str = "";
1298
+ for (let i = 1; i <= this.depth; i++)
1299
+ str += (str ? "/" : "") + this.node(i).type.name + "_" + this.index(i - 1);
1300
+ return str + ":" + this.parentOffset;
1301
+ }
1302
+ /**
1303
+ @internal
1304
+ */
1305
+ static resolve(doc2, pos) {
1306
+ if (!(pos >= 0 && pos <= doc2.content.size))
1307
+ throw new RangeError("Position " + pos + " out of range");
1308
+ let path = [];
1309
+ let start = 0, parentOffset = pos;
1310
+ for (let node = doc2; ; ) {
1311
+ let { index, offset } = node.content.findIndex(parentOffset);
1312
+ let rem = parentOffset - offset;
1313
+ path.push(node, index, start + offset);
1314
+ if (!rem)
1315
+ break;
1316
+ node = node.child(index);
1317
+ if (node.isText)
1318
+ break;
1319
+ parentOffset = rem - 1;
1320
+ start += offset + 1;
1321
+ }
1322
+ return new _ResolvedPos(pos, path, parentOffset);
1323
+ }
1324
+ /**
1325
+ @internal
1326
+ */
1327
+ static resolveCached(doc2, pos) {
1328
+ let cache = resolveCache.get(doc2);
1329
+ if (cache) {
1330
+ for (let i = 0; i < cache.elts.length; i++) {
1331
+ let elt = cache.elts[i];
1332
+ if (elt.pos == pos)
1333
+ return elt;
1334
+ }
1335
+ } else {
1336
+ resolveCache.set(doc2, cache = new ResolveCache());
1337
+ }
1338
+ let result = cache.elts[cache.i] = _ResolvedPos.resolve(doc2, pos);
1339
+ cache.i = (cache.i + 1) % resolveCacheSize;
1340
+ return result;
1341
+ }
1342
+ };
1343
+ var ResolveCache = class {
1344
+ constructor() {
1345
+ this.elts = [];
1346
+ this.i = 0;
1347
+ }
1348
+ };
1349
+ var resolveCacheSize = 12;
1350
+ var resolveCache = /* @__PURE__ */ new WeakMap();
1351
+ var NodeRange = class {
1352
+ /**
1353
+ Construct a node range. `$from` and `$to` should point into the
1354
+ same node until at least the given `depth`, since a node range
1355
+ denotes an adjacent set of nodes in a single parent node.
1356
+ */
1357
+ constructor($from, $to, depth) {
1358
+ this.$from = $from;
1359
+ this.$to = $to;
1360
+ this.depth = depth;
1361
+ }
1362
+ /**
1363
+ The position at the start of the range.
1364
+ */
1365
+ get start() {
1366
+ return this.$from.before(this.depth + 1);
1367
+ }
1368
+ /**
1369
+ The position at the end of the range.
1370
+ */
1371
+ get end() {
1372
+ return this.$to.after(this.depth + 1);
1373
+ }
1374
+ /**
1375
+ The parent node that the range points into.
1376
+ */
1377
+ get parent() {
1378
+ return this.$from.node(this.depth);
1379
+ }
1380
+ /**
1381
+ The start index of the range in the parent node.
1382
+ */
1383
+ get startIndex() {
1384
+ return this.$from.index(this.depth);
1385
+ }
1386
+ /**
1387
+ The end index of the range in the parent node.
1388
+ */
1389
+ get endIndex() {
1390
+ return this.$to.indexAfter(this.depth);
1391
+ }
1392
+ };
1393
+ var emptyAttrs = /* @__PURE__ */ Object.create(null);
1394
+ var Node = class _Node {
1395
+ /**
1396
+ @internal
1397
+ */
1398
+ constructor(type, attrs, content, marks2 = Mark.none) {
1399
+ this.type = type;
1400
+ this.attrs = attrs;
1401
+ this.marks = marks2;
1402
+ this.content = content || Fragment.empty;
1403
+ }
1404
+ /**
1405
+ The array of this node's child nodes.
1406
+ */
1407
+ get children() {
1408
+ return this.content.content;
1409
+ }
1410
+ /**
1411
+ The size of this node, as defined by the integer-based [indexing
1412
+ scheme](https://prosemirror.net/docs/guide/#doc.indexing). For text nodes, this is the
1413
+ amount of characters. For other leaf nodes, it is one. For
1414
+ non-leaf nodes, it is the size of the content plus two (the
1415
+ start and end token).
1416
+ */
1417
+ get nodeSize() {
1418
+ return this.isLeaf ? 1 : 2 + this.content.size;
1419
+ }
1420
+ /**
1421
+ The number of children that the node has.
1422
+ */
1423
+ get childCount() {
1424
+ return this.content.childCount;
1425
+ }
1426
+ /**
1427
+ Get the child node at the given index. Raises an error when the
1428
+ index is out of range.
1429
+ */
1430
+ child(index) {
1431
+ return this.content.child(index);
1432
+ }
1433
+ /**
1434
+ Get the child node at the given index, if it exists.
1435
+ */
1436
+ maybeChild(index) {
1437
+ return this.content.maybeChild(index);
1438
+ }
1439
+ /**
1440
+ Call `f` for every child node, passing the node, its offset
1441
+ into this parent node, and its index.
1442
+ */
1443
+ forEach(f) {
1444
+ this.content.forEach(f);
1445
+ }
1446
+ /**
1447
+ Invoke a callback for all descendant nodes recursively between
1448
+ the given two positions that are relative to start of this
1449
+ node's content. The callback is invoked with the node, its
1450
+ position relative to the original node (method receiver),
1451
+ its parent node, and its child index. When the callback returns
1452
+ false for a given node, that node's children will not be
1453
+ recursed over. The last parameter can be used to specify a
1454
+ starting position to count from.
1455
+ */
1456
+ nodesBetween(from, to, f, startPos = 0) {
1457
+ this.content.nodesBetween(from, to, f, startPos, this);
1458
+ }
1459
+ /**
1460
+ Call the given callback for every descendant node. Doesn't
1461
+ descend into a node when the callback returns `false`.
1462
+ */
1463
+ descendants(f) {
1464
+ this.nodesBetween(0, this.content.size, f);
1465
+ }
1466
+ /**
1467
+ Concatenates all the text nodes found in this fragment and its
1468
+ children.
1469
+ */
1470
+ get textContent() {
1471
+ return this.isLeaf && this.type.spec.leafText ? this.type.spec.leafText(this) : this.textBetween(0, this.content.size, "");
1472
+ }
1473
+ /**
1474
+ Get all text between positions `from` and `to`. When
1475
+ `blockSeparator` is given, it will be inserted to separate text
1476
+ from different block nodes. If `leafText` is given, it'll be
1477
+ inserted for every non-text leaf node encountered, otherwise
1478
+ [`leafText`](https://prosemirror.net/docs/ref/#model.NodeSpec.leafText) will be used.
1479
+ */
1480
+ textBetween(from, to, blockSeparator, leafText) {
1481
+ return this.content.textBetween(from, to, blockSeparator, leafText);
1482
+ }
1483
+ /**
1484
+ Returns this node's first child, or `null` if there are no
1485
+ children.
1486
+ */
1487
+ get firstChild() {
1488
+ return this.content.firstChild;
1489
+ }
1490
+ /**
1491
+ Returns this node's last child, or `null` if there are no
1492
+ children.
1493
+ */
1494
+ get lastChild() {
1495
+ return this.content.lastChild;
1496
+ }
1497
+ /**
1498
+ Test whether two nodes represent the same piece of document.
1499
+ */
1500
+ eq(other) {
1501
+ return this == other || this.sameMarkup(other) && this.content.eq(other.content);
1502
+ }
1503
+ /**
1504
+ Compare the markup (type, attributes, and marks) of this node to
1505
+ those of another. Returns `true` if both have the same markup.
1506
+ */
1507
+ sameMarkup(other) {
1508
+ return this.hasMarkup(other.type, other.attrs, other.marks);
1509
+ }
1510
+ /**
1511
+ Check whether this node's markup correspond to the given type,
1512
+ attributes, and marks.
1513
+ */
1514
+ hasMarkup(type, attrs, marks2) {
1515
+ return this.type == type && compareDeep(this.attrs, attrs || type.defaultAttrs || emptyAttrs) && Mark.sameSet(this.marks, marks2 || Mark.none);
1516
+ }
1517
+ /**
1518
+ Create a new node with the same markup as this node, containing
1519
+ the given content (or empty, if no content is given).
1520
+ */
1521
+ copy(content = null) {
1522
+ if (content == this.content)
1523
+ return this;
1524
+ return new _Node(this.type, this.attrs, content, this.marks);
1525
+ }
1526
+ /**
1527
+ Create a copy of this node, with the given set of marks instead
1528
+ of the node's own marks.
1529
+ */
1530
+ mark(marks2) {
1531
+ return marks2 == this.marks ? this : new _Node(this.type, this.attrs, this.content, marks2);
1532
+ }
1533
+ /**
1534
+ Create a copy of this node with only the content between the
1535
+ given positions. If `to` is not given, it defaults to the end of
1536
+ the node.
1537
+ */
1538
+ cut(from, to = this.content.size) {
1539
+ if (from == 0 && to == this.content.size)
1540
+ return this;
1541
+ return this.copy(this.content.cut(from, to));
1542
+ }
1543
+ /**
1544
+ Cut out the part of the document between the given positions, and
1545
+ return it as a `Slice` object.
1546
+ */
1547
+ slice(from, to = this.content.size, includeParents = false) {
1548
+ if (from == to)
1549
+ return Slice.empty;
1550
+ let $from = this.resolve(from), $to = this.resolve(to);
1551
+ let depth = includeParents ? 0 : $from.sharedDepth(to);
1552
+ let start = $from.start(depth), node = $from.node(depth);
1553
+ let content = node.content.cut($from.pos - start, $to.pos - start);
1554
+ return new Slice(content, $from.depth - depth, $to.depth - depth);
1555
+ }
1556
+ /**
1557
+ Replace the part of the document between the given positions with
1558
+ the given slice. The slice must 'fit', meaning its open sides
1559
+ must be able to connect to the surrounding content, and its
1560
+ content nodes must be valid children for the node they are placed
1561
+ into. If any of this is violated, an error of type
1562
+ [`ReplaceError`](https://prosemirror.net/docs/ref/#model.ReplaceError) is thrown.
1563
+ */
1564
+ replace(from, to, slice) {
1565
+ return replace(this.resolve(from), this.resolve(to), slice);
1566
+ }
1567
+ /**
1568
+ Find the node directly after the given position.
1569
+ */
1570
+ nodeAt(pos) {
1571
+ for (let node = this; ; ) {
1572
+ let { index, offset } = node.content.findIndex(pos);
1573
+ node = node.maybeChild(index);
1574
+ if (!node)
1575
+ return null;
1576
+ if (offset == pos || node.isText)
1577
+ return node;
1578
+ pos -= offset + 1;
1579
+ }
1580
+ }
1581
+ /**
1582
+ Find the (direct) child node after the given offset, if any,
1583
+ and return it along with its index and offset relative to this
1584
+ node.
1585
+ */
1586
+ childAfter(pos) {
1587
+ let { index, offset } = this.content.findIndex(pos);
1588
+ return { node: this.content.maybeChild(index), index, offset };
1589
+ }
1590
+ /**
1591
+ Find the (direct) child node before the given offset, if any,
1592
+ and return it along with its index and offset relative to this
1593
+ node.
1594
+ */
1595
+ childBefore(pos) {
1596
+ if (pos == 0)
1597
+ return { node: null, index: 0, offset: 0 };
1598
+ let { index, offset } = this.content.findIndex(pos);
1599
+ if (offset < pos)
1600
+ return { node: this.content.child(index), index, offset };
1601
+ let node = this.content.child(index - 1);
1602
+ return { node, index: index - 1, offset: offset - node.nodeSize };
1603
+ }
1604
+ /**
1605
+ Resolve the given position in the document, returning an
1606
+ [object](https://prosemirror.net/docs/ref/#model.ResolvedPos) with information about its context.
1607
+ */
1608
+ resolve(pos) {
1609
+ return ResolvedPos.resolveCached(this, pos);
1610
+ }
1611
+ /**
1612
+ @internal
1613
+ */
1614
+ resolveNoCache(pos) {
1615
+ return ResolvedPos.resolve(this, pos);
1616
+ }
1617
+ /**
1618
+ Test whether a given mark or mark type occurs in this document
1619
+ between the two given positions.
1620
+ */
1621
+ rangeHasMark(from, to, type) {
1622
+ let found2 = false;
1623
+ if (to > from)
1624
+ this.nodesBetween(from, to, (node) => {
1625
+ if (type.isInSet(node.marks))
1626
+ found2 = true;
1627
+ return !found2;
1628
+ });
1629
+ return found2;
1630
+ }
1631
+ /**
1632
+ True when this is a block (non-inline node)
1633
+ */
1634
+ get isBlock() {
1635
+ return this.type.isBlock;
1636
+ }
1637
+ /**
1638
+ True when this is a textblock node, a block node with inline
1639
+ content.
1640
+ */
1641
+ get isTextblock() {
1642
+ return this.type.isTextblock;
1643
+ }
1644
+ /**
1645
+ True when this node allows inline content.
1646
+ */
1647
+ get inlineContent() {
1648
+ return this.type.inlineContent;
1649
+ }
1650
+ /**
1651
+ True when this is an inline node (a text node or a node that can
1652
+ appear among text).
1653
+ */
1654
+ get isInline() {
1655
+ return this.type.isInline;
1656
+ }
1657
+ /**
1658
+ True when this is a text node.
1659
+ */
1660
+ get isText() {
1661
+ return this.type.isText;
1662
+ }
1663
+ /**
1664
+ True when this is a leaf node.
1665
+ */
1666
+ get isLeaf() {
1667
+ return this.type.isLeaf;
1668
+ }
1669
+ /**
1670
+ True when this is an atom, i.e. when it does not have directly
1671
+ editable content. This is usually the same as `isLeaf`, but can
1672
+ be configured with the [`atom` property](https://prosemirror.net/docs/ref/#model.NodeSpec.atom)
1673
+ on a node's spec (typically used when the node is displayed as
1674
+ an uneditable [node view](https://prosemirror.net/docs/ref/#view.NodeView)).
1675
+ */
1676
+ get isAtom() {
1677
+ return this.type.isAtom;
1678
+ }
1679
+ /**
1680
+ Return a string representation of this node for debugging
1681
+ purposes.
1682
+ */
1683
+ toString() {
1684
+ if (this.type.spec.toDebugString)
1685
+ return this.type.spec.toDebugString(this);
1686
+ let name = this.type.name;
1687
+ if (this.content.size)
1688
+ name += "(" + this.content.toStringInner() + ")";
1689
+ return wrapMarks(this.marks, name);
1690
+ }
1691
+ /**
1692
+ Get the content match in this node at the given index.
1693
+ */
1694
+ contentMatchAt(index) {
1695
+ let match = this.type.contentMatch.matchFragment(this.content, 0, index);
1696
+ if (!match)
1697
+ throw new Error("Called contentMatchAt on a node with invalid content");
1698
+ return match;
1699
+ }
1700
+ /**
1701
+ Test whether replacing the range between `from` and `to` (by
1702
+ child index) with the given replacement fragment (which defaults
1703
+ to the empty fragment) would leave the node's content valid. You
1704
+ can optionally pass `start` and `end` indices into the
1705
+ replacement fragment.
1706
+ */
1707
+ canReplace(from, to, replacement = Fragment.empty, start = 0, end = replacement.childCount) {
1708
+ let one = this.contentMatchAt(from).matchFragment(replacement, start, end);
1709
+ let two = one && one.matchFragment(this.content, to);
1710
+ if (!two || !two.validEnd)
1711
+ return false;
1712
+ for (let i = start; i < end; i++)
1713
+ if (!this.type.allowsMarks(replacement.child(i).marks))
1714
+ return false;
1715
+ return true;
1716
+ }
1717
+ /**
1718
+ Test whether replacing the range `from` to `to` (by index) with
1719
+ a node of the given type would leave the node's content valid.
1720
+ */
1721
+ canReplaceWith(from, to, type, marks2) {
1722
+ if (marks2 && !this.type.allowsMarks(marks2))
1723
+ return false;
1724
+ let start = this.contentMatchAt(from).matchType(type);
1725
+ let end = start && start.matchFragment(this.content, to);
1726
+ return end ? end.validEnd : false;
1727
+ }
1728
+ /**
1729
+ Test whether the given node's content could be appended to this
1730
+ node. If that node is empty, this will only return true if there
1731
+ is at least one node type that can appear in both nodes (to avoid
1732
+ merging completely incompatible nodes).
1733
+ */
1734
+ canAppend(other) {
1735
+ if (other.content.size)
1736
+ return this.canReplace(this.childCount, this.childCount, other.content);
1737
+ else
1738
+ return this.type.compatibleContent(other.type);
1739
+ }
1740
+ /**
1741
+ Check whether this node and its descendants conform to the
1742
+ schema, and raise an exception when they do not.
1743
+ */
1744
+ check() {
1745
+ this.type.checkContent(this.content);
1746
+ this.type.checkAttrs(this.attrs);
1747
+ let copy = Mark.none;
1748
+ for (let i = 0; i < this.marks.length; i++) {
1749
+ let mark = this.marks[i];
1750
+ mark.type.checkAttrs(mark.attrs);
1751
+ copy = mark.addToSet(copy);
1752
+ }
1753
+ if (!Mark.sameSet(copy, this.marks))
1754
+ throw new RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map((m) => m.type.name)}`);
1755
+ this.content.forEach((node) => node.check());
1756
+ }
1757
+ /**
1758
+ Return a JSON-serializeable representation of this node.
1759
+ */
1760
+ toJSON() {
1761
+ let obj = { type: this.type.name };
1762
+ for (let _ in this.attrs) {
1763
+ obj.attrs = this.attrs;
1764
+ break;
1765
+ }
1766
+ if (this.content.size)
1767
+ obj.content = this.content.toJSON();
1768
+ if (this.marks.length)
1769
+ obj.marks = this.marks.map((n) => n.toJSON());
1770
+ return obj;
1771
+ }
1772
+ /**
1773
+ Deserialize a node from its JSON representation.
1774
+ */
1775
+ static fromJSON(schema2, json) {
1776
+ if (!json)
1777
+ throw new RangeError("Invalid input for Node.fromJSON");
1778
+ let marks2 = void 0;
1779
+ if (json.marks) {
1780
+ if (!Array.isArray(json.marks))
1781
+ throw new RangeError("Invalid mark data for Node.fromJSON");
1782
+ marks2 = json.marks.map(schema2.markFromJSON);
1783
+ }
1784
+ if (json.type == "text") {
1785
+ if (typeof json.text != "string")
1786
+ throw new RangeError("Invalid text node in JSON");
1787
+ return schema2.text(json.text, marks2);
1788
+ }
1789
+ let content = Fragment.fromJSON(schema2, json.content);
1790
+ let node = schema2.nodeType(json.type).create(json.attrs, content, marks2);
1791
+ node.type.checkAttrs(node.attrs);
1792
+ return node;
1793
+ }
1794
+ };
1795
+ Node.prototype.text = void 0;
1796
+ var TextNode = class _TextNode extends Node {
1797
+ /**
1798
+ @internal
1799
+ */
1800
+ constructor(type, attrs, content, marks2) {
1801
+ super(type, attrs, null, marks2);
1802
+ if (!content)
1803
+ throw new RangeError("Empty text nodes are not allowed");
1804
+ this.text = content;
1805
+ }
1806
+ toString() {
1807
+ if (this.type.spec.toDebugString)
1808
+ return this.type.spec.toDebugString(this);
1809
+ return wrapMarks(this.marks, JSON.stringify(this.text));
1810
+ }
1811
+ get textContent() {
1812
+ return this.text;
1813
+ }
1814
+ textBetween(from, to) {
1815
+ return this.text.slice(from, to);
1816
+ }
1817
+ get nodeSize() {
1818
+ return this.text.length;
1819
+ }
1820
+ mark(marks2) {
1821
+ return marks2 == this.marks ? this : new _TextNode(this.type, this.attrs, this.text, marks2);
1822
+ }
1823
+ withText(text) {
1824
+ if (text == this.text)
1825
+ return this;
1826
+ return new _TextNode(this.type, this.attrs, text, this.marks);
1827
+ }
1828
+ cut(from = 0, to = this.text.length) {
1829
+ if (from == 0 && to == this.text.length)
1830
+ return this;
1831
+ return this.withText(this.text.slice(from, to));
1832
+ }
1833
+ eq(other) {
1834
+ return this.sameMarkup(other) && this.text == other.text;
1835
+ }
1836
+ toJSON() {
1837
+ let base = super.toJSON();
1838
+ base.text = this.text;
1839
+ return base;
1840
+ }
1841
+ };
1842
+ function wrapMarks(marks2, str) {
1843
+ for (let i = marks2.length - 1; i >= 0; i--)
1844
+ str = marks2[i].type.name + "(" + str + ")";
1845
+ return str;
1846
+ }
1847
+ var ContentMatch = class _ContentMatch {
1848
+ /**
1849
+ @internal
1850
+ */
1851
+ constructor(validEnd) {
1852
+ this.validEnd = validEnd;
1853
+ this.next = [];
1854
+ this.wrapCache = [];
1855
+ }
1856
+ /**
1857
+ @internal
1858
+ */
1859
+ static parse(string, nodeTypes) {
1860
+ let stream = new TokenStream(string, nodeTypes);
1861
+ if (stream.next == null)
1862
+ return _ContentMatch.empty;
1863
+ let expr = parseExpr(stream);
1864
+ if (stream.next)
1865
+ stream.err("Unexpected trailing text");
1866
+ let match = dfa(nfa(expr));
1867
+ checkForDeadEnds(match, stream);
1868
+ return match;
1869
+ }
1870
+ /**
1871
+ Match a node type, returning a match after that node if
1872
+ successful.
1873
+ */
1874
+ matchType(type) {
1875
+ for (let i = 0; i < this.next.length; i++)
1876
+ if (this.next[i].type == type)
1877
+ return this.next[i].next;
1878
+ return null;
1879
+ }
1880
+ /**
1881
+ Try to match a fragment. Returns the resulting match when
1882
+ successful.
1883
+ */
1884
+ matchFragment(frag, start = 0, end = frag.childCount) {
1885
+ let cur = this;
1886
+ for (let i = start; cur && i < end; i++)
1887
+ cur = cur.matchType(frag.child(i).type);
1888
+ return cur;
1889
+ }
1890
+ /**
1891
+ @internal
1892
+ */
1893
+ get inlineContent() {
1894
+ return this.next.length != 0 && this.next[0].type.isInline;
1895
+ }
1896
+ /**
1897
+ Get the first matching node type at this match position that can
1898
+ be generated.
1899
+ */
1900
+ get defaultType() {
1901
+ for (let i = 0; i < this.next.length; i++) {
1902
+ let { type } = this.next[i];
1903
+ if (!(type.isText || type.hasRequiredAttrs()))
1904
+ return type;
1905
+ }
1906
+ return null;
1907
+ }
1908
+ /**
1909
+ @internal
1910
+ */
1911
+ compatible(other) {
1912
+ for (let i = 0; i < this.next.length; i++)
1913
+ for (let j = 0; j < other.next.length; j++)
1914
+ if (this.next[i].type == other.next[j].type)
1915
+ return true;
1916
+ return false;
1917
+ }
1918
+ /**
1919
+ Try to match the given fragment, and if that fails, see if it can
1920
+ be made to match by inserting nodes in front of it. When
1921
+ successful, return a fragment of inserted nodes (which may be
1922
+ empty if nothing had to be inserted). When `toEnd` is true, only
1923
+ return a fragment if the resulting match goes to the end of the
1924
+ content expression.
1925
+ */
1926
+ fillBefore(after, toEnd = false, startIndex = 0) {
1927
+ let seen = [this];
1928
+ function search(match, types) {
1929
+ let finished = match.matchFragment(after, startIndex);
1930
+ if (finished && (!toEnd || finished.validEnd))
1931
+ return Fragment.from(types.map((tp) => tp.createAndFill()));
1932
+ for (let i = 0; i < match.next.length; i++) {
1933
+ let { type, next } = match.next[i];
1934
+ if (!(type.isText || type.hasRequiredAttrs()) && seen.indexOf(next) == -1) {
1935
+ seen.push(next);
1936
+ let found2 = search(next, types.concat(type));
1937
+ if (found2)
1938
+ return found2;
1939
+ }
1940
+ }
1941
+ return null;
1942
+ }
1943
+ return search(this, []);
1944
+ }
1945
+ /**
1946
+ Find a set of wrapping node types that would allow a node of the
1947
+ given type to appear at this position. The result may be empty
1948
+ (when it fits directly) and will be null when no such wrapping
1949
+ exists.
1950
+ */
1951
+ findWrapping(target) {
1952
+ for (let i = 0; i < this.wrapCache.length; i += 2)
1953
+ if (this.wrapCache[i] == target)
1954
+ return this.wrapCache[i + 1];
1955
+ let computed = this.computeWrapping(target);
1956
+ this.wrapCache.push(target, computed);
1957
+ return computed;
1958
+ }
1959
+ /**
1960
+ @internal
1961
+ */
1962
+ computeWrapping(target) {
1963
+ let seen = /* @__PURE__ */ Object.create(null), active = [{ match: this, type: null, via: null }];
1964
+ while (active.length) {
1965
+ let current = active.shift(), match = current.match;
1966
+ if (match.matchType(target)) {
1967
+ let result = [];
1968
+ for (let obj = current; obj.type; obj = obj.via)
1969
+ result.push(obj.type);
1970
+ return result.reverse();
1971
+ }
1972
+ for (let i = 0; i < match.next.length; i++) {
1973
+ let { type, next } = match.next[i];
1974
+ if (!type.isLeaf && !type.hasRequiredAttrs() && !(type.name in seen) && (!current.type || next.validEnd)) {
1975
+ active.push({ match: type.contentMatch, type, via: current });
1976
+ seen[type.name] = true;
1977
+ }
1978
+ }
1979
+ }
1980
+ return null;
1981
+ }
1982
+ /**
1983
+ The number of outgoing edges this node has in the finite
1984
+ automaton that describes the content expression.
1985
+ */
1986
+ get edgeCount() {
1987
+ return this.next.length;
1988
+ }
1989
+ /**
1990
+ Get the _n_​th outgoing edge from this node in the finite
1991
+ automaton that describes the content expression.
1992
+ */
1993
+ edge(n) {
1994
+ if (n >= this.next.length)
1995
+ throw new RangeError(`There's no ${n}th edge in this content match`);
1996
+ return this.next[n];
1997
+ }
1998
+ /**
1999
+ @internal
2000
+ */
2001
+ toString() {
2002
+ let seen = [];
2003
+ function scan(m) {
2004
+ seen.push(m);
2005
+ for (let i = 0; i < m.next.length; i++)
2006
+ if (seen.indexOf(m.next[i].next) == -1)
2007
+ scan(m.next[i].next);
2008
+ }
2009
+ scan(this);
2010
+ return seen.map((m, i) => {
2011
+ let out = i + (m.validEnd ? "*" : " ") + " ";
2012
+ for (let i2 = 0; i2 < m.next.length; i2++)
2013
+ out += (i2 ? ", " : "") + m.next[i2].type.name + "->" + seen.indexOf(m.next[i2].next);
2014
+ return out;
2015
+ }).join("\n");
2016
+ }
2017
+ };
2018
+ ContentMatch.empty = new ContentMatch(true);
2019
+ var TokenStream = class {
2020
+ constructor(string, nodeTypes) {
2021
+ this.string = string;
2022
+ this.nodeTypes = nodeTypes;
2023
+ this.inline = null;
2024
+ this.pos = 0;
2025
+ this.tokens = string.split(/\s*(?=\b|\W|$)/);
2026
+ if (this.tokens[this.tokens.length - 1] == "")
2027
+ this.tokens.pop();
2028
+ if (this.tokens[0] == "")
2029
+ this.tokens.shift();
2030
+ }
2031
+ get next() {
2032
+ return this.tokens[this.pos];
2033
+ }
2034
+ eat(tok) {
2035
+ return this.next == tok && (this.pos++ || true);
2036
+ }
2037
+ err(str) {
2038
+ throw new SyntaxError(str + " (in content expression '" + this.string + "')");
2039
+ }
2040
+ };
2041
+ function parseExpr(stream) {
2042
+ let exprs = [];
2043
+ do {
2044
+ exprs.push(parseExprSeq(stream));
2045
+ } while (stream.eat("|"));
2046
+ return exprs.length == 1 ? exprs[0] : { type: "choice", exprs };
2047
+ }
2048
+ function parseExprSeq(stream) {
2049
+ let exprs = [];
2050
+ do {
2051
+ exprs.push(parseExprSubscript(stream));
2052
+ } while (stream.next && stream.next != ")" && stream.next != "|");
2053
+ return exprs.length == 1 ? exprs[0] : { type: "seq", exprs };
2054
+ }
2055
+ function parseExprSubscript(stream) {
2056
+ let expr = parseExprAtom(stream);
2057
+ for (; ; ) {
2058
+ if (stream.eat("+"))
2059
+ expr = { type: "plus", expr };
2060
+ else if (stream.eat("*"))
2061
+ expr = { type: "star", expr };
2062
+ else if (stream.eat("?"))
2063
+ expr = { type: "opt", expr };
2064
+ else if (stream.eat("{"))
2065
+ expr = parseExprRange(stream, expr);
2066
+ else
2067
+ break;
2068
+ }
2069
+ return expr;
2070
+ }
2071
+ function parseNum(stream) {
2072
+ if (/\D/.test(stream.next))
2073
+ stream.err("Expected number, got '" + stream.next + "'");
2074
+ let result = Number(stream.next);
2075
+ stream.pos++;
2076
+ return result;
2077
+ }
2078
+ function parseExprRange(stream, expr) {
2079
+ let min = parseNum(stream), max = min;
2080
+ if (stream.eat(",")) {
2081
+ if (stream.next != "}")
2082
+ max = parseNum(stream);
2083
+ else
2084
+ max = -1;
2085
+ }
2086
+ if (!stream.eat("}"))
2087
+ stream.err("Unclosed braced range");
2088
+ return { type: "range", min, max, expr };
2089
+ }
2090
+ function resolveName(stream, name) {
2091
+ let types = stream.nodeTypes, type = types[name];
2092
+ if (type)
2093
+ return [type];
2094
+ let result = [];
2095
+ for (let typeName in types) {
2096
+ let type2 = types[typeName];
2097
+ if (type2.isInGroup(name))
2098
+ result.push(type2);
2099
+ }
2100
+ if (result.length == 0)
2101
+ stream.err("No node type or group '" + name + "' found");
2102
+ return result;
2103
+ }
2104
+ function parseExprAtom(stream) {
2105
+ if (stream.eat("(")) {
2106
+ let expr = parseExpr(stream);
2107
+ if (!stream.eat(")"))
2108
+ stream.err("Missing closing paren");
2109
+ return expr;
2110
+ } else if (!/\W/.test(stream.next)) {
2111
+ let exprs = resolveName(stream, stream.next).map((type) => {
2112
+ if (stream.inline == null)
2113
+ stream.inline = type.isInline;
2114
+ else if (stream.inline != type.isInline)
2115
+ stream.err("Mixing inline and block content");
2116
+ return { type: "name", value: type };
2117
+ });
2118
+ stream.pos++;
2119
+ return exprs.length == 1 ? exprs[0] : { type: "choice", exprs };
2120
+ } else {
2121
+ stream.err("Unexpected token '" + stream.next + "'");
2122
+ }
2123
+ }
2124
+ function nfa(expr) {
2125
+ let nfa2 = [[]];
2126
+ connect(compile(expr, 0), node());
2127
+ return nfa2;
2128
+ function node() {
2129
+ return nfa2.push([]) - 1;
2130
+ }
2131
+ function edge(from, to, term) {
2132
+ let edge2 = { term, to };
2133
+ nfa2[from].push(edge2);
2134
+ return edge2;
2135
+ }
2136
+ function connect(edges, to) {
2137
+ edges.forEach((edge2) => edge2.to = to);
2138
+ }
2139
+ function compile(expr2, from) {
2140
+ if (expr2.type == "choice") {
2141
+ return expr2.exprs.reduce((out, expr3) => out.concat(compile(expr3, from)), []);
2142
+ } else if (expr2.type == "seq") {
2143
+ for (let i = 0; ; i++) {
2144
+ let next = compile(expr2.exprs[i], from);
2145
+ if (i == expr2.exprs.length - 1)
2146
+ return next;
2147
+ connect(next, from = node());
2148
+ }
2149
+ } else if (expr2.type == "star") {
2150
+ let loop = node();
2151
+ edge(from, loop);
2152
+ connect(compile(expr2.expr, loop), loop);
2153
+ return [edge(loop)];
2154
+ } else if (expr2.type == "plus") {
2155
+ let loop = node();
2156
+ connect(compile(expr2.expr, from), loop);
2157
+ connect(compile(expr2.expr, loop), loop);
2158
+ return [edge(loop)];
2159
+ } else if (expr2.type == "opt") {
2160
+ return [edge(from)].concat(compile(expr2.expr, from));
2161
+ } else if (expr2.type == "range") {
2162
+ let cur = from;
2163
+ for (let i = 0; i < expr2.min; i++) {
2164
+ let next = node();
2165
+ connect(compile(expr2.expr, cur), next);
2166
+ cur = next;
2167
+ }
2168
+ if (expr2.max == -1) {
2169
+ connect(compile(expr2.expr, cur), cur);
2170
+ } else {
2171
+ for (let i = expr2.min; i < expr2.max; i++) {
2172
+ let next = node();
2173
+ edge(cur, next);
2174
+ connect(compile(expr2.expr, cur), next);
2175
+ cur = next;
2176
+ }
2177
+ }
2178
+ return [edge(cur)];
2179
+ } else if (expr2.type == "name") {
2180
+ return [edge(from, void 0, expr2.value)];
2181
+ } else {
2182
+ throw new Error("Unknown expr type");
2183
+ }
2184
+ }
2185
+ }
2186
+ function cmp(a, b) {
2187
+ return b - a;
2188
+ }
2189
+ function nullFrom(nfa2, node) {
2190
+ let result = [];
2191
+ scan(node);
2192
+ return result.sort(cmp);
2193
+ function scan(node2) {
2194
+ let edges = nfa2[node2];
2195
+ if (edges.length == 1 && !edges[0].term)
2196
+ return scan(edges[0].to);
2197
+ result.push(node2);
2198
+ for (let i = 0; i < edges.length; i++) {
2199
+ let { term, to } = edges[i];
2200
+ if (!term && result.indexOf(to) == -1)
2201
+ scan(to);
2202
+ }
2203
+ }
2204
+ }
2205
+ function dfa(nfa2) {
2206
+ let labeled = /* @__PURE__ */ Object.create(null);
2207
+ return explore(nullFrom(nfa2, 0));
2208
+ function explore(states) {
2209
+ let out = [];
2210
+ states.forEach((node) => {
2211
+ nfa2[node].forEach(({ term, to }) => {
2212
+ if (!term)
2213
+ return;
2214
+ let set;
2215
+ for (let i = 0; i < out.length; i++)
2216
+ if (out[i][0] == term)
2217
+ set = out[i][1];
2218
+ nullFrom(nfa2, to).forEach((node2) => {
2219
+ if (!set)
2220
+ out.push([term, set = []]);
2221
+ if (set.indexOf(node2) == -1)
2222
+ set.push(node2);
2223
+ });
2224
+ });
2225
+ });
2226
+ let state = labeled[states.join(",")] = new ContentMatch(states.indexOf(nfa2.length - 1) > -1);
2227
+ for (let i = 0; i < out.length; i++) {
2228
+ let states2 = out[i][1].sort(cmp);
2229
+ state.next.push({ type: out[i][0], next: labeled[states2.join(",")] || explore(states2) });
2230
+ }
2231
+ return state;
2232
+ }
2233
+ }
2234
+ function checkForDeadEnds(match, stream) {
2235
+ for (let i = 0, work = [match]; i < work.length; i++) {
2236
+ let state = work[i], dead = !state.validEnd, nodes2 = [];
2237
+ for (let j = 0; j < state.next.length; j++) {
2238
+ let { type, next } = state.next[j];
2239
+ nodes2.push(type.name);
2240
+ if (dead && !(type.isText || type.hasRequiredAttrs()))
2241
+ dead = false;
2242
+ if (work.indexOf(next) == -1)
2243
+ work.push(next);
2244
+ }
2245
+ if (dead)
2246
+ stream.err("Only non-generatable nodes (" + nodes2.join(", ") + ") in a required position (see https://prosemirror.net/docs/guide/#generatable)");
2247
+ }
2248
+ }
2249
+ function defaultAttrs(attrs) {
2250
+ let defaults = /* @__PURE__ */ Object.create(null);
2251
+ for (let attrName in attrs) {
2252
+ let attr = attrs[attrName];
2253
+ if (!attr.hasDefault)
2254
+ return null;
2255
+ defaults[attrName] = attr.default;
2256
+ }
2257
+ return defaults;
2258
+ }
2259
+ function computeAttrs(attrs, value) {
2260
+ let built = /* @__PURE__ */ Object.create(null);
2261
+ for (let name in attrs) {
2262
+ let given = value && value[name];
2263
+ if (given === void 0) {
2264
+ let attr = attrs[name];
2265
+ if (attr.hasDefault)
2266
+ given = attr.default;
2267
+ else
2268
+ throw new RangeError("No value supplied for attribute " + name);
2269
+ }
2270
+ built[name] = given;
2271
+ }
2272
+ return built;
2273
+ }
2274
+ function checkAttrs(attrs, values, type, name) {
2275
+ for (let name2 in values)
2276
+ if (!(name2 in attrs))
2277
+ throw new RangeError(`Unsupported attribute ${name2} for ${type} of type ${name2}`);
2278
+ for (let name2 in attrs) {
2279
+ let attr = attrs[name2];
2280
+ if (attr.validate)
2281
+ attr.validate(values[name2]);
2282
+ }
2283
+ }
2284
+ function initAttrs(typeName, attrs) {
2285
+ let result = /* @__PURE__ */ Object.create(null);
2286
+ if (attrs)
2287
+ for (let name in attrs)
2288
+ result[name] = new Attribute(typeName, name, attrs[name]);
2289
+ return result;
2290
+ }
2291
+ var NodeType = class _NodeType {
2292
+ /**
2293
+ @internal
2294
+ */
2295
+ constructor(name, schema2, spec) {
2296
+ this.name = name;
2297
+ this.schema = schema2;
2298
+ this.spec = spec;
2299
+ this.markSet = null;
2300
+ this.groups = spec.group ? spec.group.split(" ") : [];
2301
+ this.attrs = initAttrs(name, spec.attrs);
2302
+ this.defaultAttrs = defaultAttrs(this.attrs);
2303
+ this.contentMatch = null;
2304
+ this.inlineContent = null;
2305
+ this.isBlock = !(spec.inline || name == "text");
2306
+ this.isText = name == "text";
2307
+ }
2308
+ /**
2309
+ True if this is an inline type.
2310
+ */
2311
+ get isInline() {
2312
+ return !this.isBlock;
2313
+ }
2314
+ /**
2315
+ True if this is a textblock type, a block that contains inline
2316
+ content.
2317
+ */
2318
+ get isTextblock() {
2319
+ return this.isBlock && this.inlineContent;
2320
+ }
2321
+ /**
2322
+ True for node types that allow no content.
2323
+ */
2324
+ get isLeaf() {
2325
+ return this.contentMatch == ContentMatch.empty;
2326
+ }
2327
+ /**
2328
+ True when this node is an atom, i.e. when it does not have
2329
+ directly editable content.
2330
+ */
2331
+ get isAtom() {
2332
+ return this.isLeaf || !!this.spec.atom;
2333
+ }
2334
+ /**
2335
+ Return true when this node type is part of the given
2336
+ [group](https://prosemirror.net/docs/ref/#model.NodeSpec.group).
2337
+ */
2338
+ isInGroup(group) {
2339
+ return this.groups.indexOf(group) > -1;
2340
+ }
2341
+ /**
2342
+ The node type's [whitespace](https://prosemirror.net/docs/ref/#model.NodeSpec.whitespace) option.
2343
+ */
2344
+ get whitespace() {
2345
+ return this.spec.whitespace || (this.spec.code ? "pre" : "normal");
2346
+ }
2347
+ /**
2348
+ Tells you whether this node type has any required attributes.
2349
+ */
2350
+ hasRequiredAttrs() {
2351
+ for (let n in this.attrs)
2352
+ if (this.attrs[n].isRequired)
2353
+ return true;
2354
+ return false;
2355
+ }
2356
+ /**
2357
+ Indicates whether this node allows some of the same content as
2358
+ the given node type.
2359
+ */
2360
+ compatibleContent(other) {
2361
+ return this == other || this.contentMatch.compatible(other.contentMatch);
2362
+ }
2363
+ /**
2364
+ @internal
2365
+ */
2366
+ computeAttrs(attrs) {
2367
+ if (!attrs && this.defaultAttrs)
2368
+ return this.defaultAttrs;
2369
+ else
2370
+ return computeAttrs(this.attrs, attrs);
2371
+ }
2372
+ /**
2373
+ Create a `Node` of this type. The given attributes are
2374
+ checked and defaulted (you can pass `null` to use the type's
2375
+ defaults entirely, if no required attributes exist). `content`
2376
+ may be a `Fragment`, a node, an array of nodes, or
2377
+ `null`. Similarly `marks` may be `null` to default to the empty
2378
+ set of marks.
2379
+ */
2380
+ create(attrs = null, content, marks2) {
2381
+ if (this.isText)
2382
+ throw new Error("NodeType.create can't construct text nodes");
2383
+ return new Node(this, this.computeAttrs(attrs), Fragment.from(content), Mark.setFrom(marks2));
2384
+ }
2385
+ /**
2386
+ Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but check the given content
2387
+ against the node type's content restrictions, and throw an error
2388
+ if it doesn't match.
2389
+ */
2390
+ createChecked(attrs = null, content, marks2) {
2391
+ content = Fragment.from(content);
2392
+ this.checkContent(content);
2393
+ return new Node(this, this.computeAttrs(attrs), content, Mark.setFrom(marks2));
2394
+ }
2395
+ /**
2396
+ Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but see if it is
2397
+ necessary to add nodes to the start or end of the given fragment
2398
+ to make it fit the node. If no fitting wrapping can be found,
2399
+ return null. Note that, due to the fact that required nodes can
2400
+ always be created, this will always succeed if you pass null or
2401
+ `Fragment.empty` as content.
2402
+ */
2403
+ createAndFill(attrs = null, content, marks2) {
2404
+ attrs = this.computeAttrs(attrs);
2405
+ content = Fragment.from(content);
2406
+ if (content.size) {
2407
+ let before = this.contentMatch.fillBefore(content);
2408
+ if (!before)
2409
+ return null;
2410
+ content = before.append(content);
2411
+ }
2412
+ let matched = this.contentMatch.matchFragment(content);
2413
+ let after = matched && matched.fillBefore(Fragment.empty, true);
2414
+ if (!after)
2415
+ return null;
2416
+ return new Node(this, attrs, content.append(after), Mark.setFrom(marks2));
2417
+ }
2418
+ /**
2419
+ Returns true if the given fragment is valid content for this node
2420
+ type.
2421
+ */
2422
+ validContent(content) {
2423
+ let result = this.contentMatch.matchFragment(content);
2424
+ if (!result || !result.validEnd)
2425
+ return false;
2426
+ for (let i = 0; i < content.childCount; i++)
2427
+ if (!this.allowsMarks(content.child(i).marks))
2428
+ return false;
2429
+ return true;
2430
+ }
2431
+ /**
2432
+ Throws a RangeError if the given fragment is not valid content for this
2433
+ node type.
2434
+ @internal
2435
+ */
2436
+ checkContent(content) {
2437
+ if (!this.validContent(content))
2438
+ throw new RangeError(`Invalid content for node ${this.name}: ${content.toString().slice(0, 50)}`);
2439
+ }
2440
+ /**
2441
+ @internal
2442
+ */
2443
+ checkAttrs(attrs) {
2444
+ checkAttrs(this.attrs, attrs, "node", this.name);
2445
+ }
2446
+ /**
2447
+ Check whether the given mark type is allowed in this node.
2448
+ */
2449
+ allowsMarkType(markType) {
2450
+ return this.markSet == null || this.markSet.indexOf(markType) > -1;
2451
+ }
2452
+ /**
2453
+ Test whether the given set of marks are allowed in this node.
2454
+ */
2455
+ allowsMarks(marks2) {
2456
+ if (this.markSet == null)
2457
+ return true;
2458
+ for (let i = 0; i < marks2.length; i++)
2459
+ if (!this.allowsMarkType(marks2[i].type))
2460
+ return false;
2461
+ return true;
2462
+ }
2463
+ /**
2464
+ Removes the marks that are not allowed in this node from the given set.
2465
+ */
2466
+ allowedMarks(marks2) {
2467
+ if (this.markSet == null)
2468
+ return marks2;
2469
+ let copy;
2470
+ for (let i = 0; i < marks2.length; i++) {
2471
+ if (!this.allowsMarkType(marks2[i].type)) {
2472
+ if (!copy)
2473
+ copy = marks2.slice(0, i);
2474
+ } else if (copy) {
2475
+ copy.push(marks2[i]);
2476
+ }
2477
+ }
2478
+ return !copy ? marks2 : copy.length ? copy : Mark.none;
2479
+ }
2480
+ /**
2481
+ @internal
2482
+ */
2483
+ static compile(nodes2, schema2) {
2484
+ let result = /* @__PURE__ */ Object.create(null);
2485
+ nodes2.forEach((name, spec) => result[name] = new _NodeType(name, schema2, spec));
2486
+ let topType = schema2.spec.topNode || "doc";
2487
+ if (!result[topType])
2488
+ throw new RangeError("Schema is missing its top node type ('" + topType + "')");
2489
+ if (!result.text)
2490
+ throw new RangeError("Every schema needs a 'text' type");
2491
+ for (let _ in result.text.attrs)
2492
+ throw new RangeError("The text node type should not have attributes");
2493
+ return result;
2494
+ }
2495
+ };
2496
+ function validateType(typeName, attrName, type) {
2497
+ let types = type.split("|");
2498
+ return (value) => {
2499
+ let name = value === null ? "null" : typeof value;
2500
+ if (types.indexOf(name) < 0)
2501
+ throw new RangeError(`Expected value of type ${types} for attribute ${attrName} on type ${typeName}, got ${name}`);
2502
+ };
2503
+ }
2504
+ var Attribute = class {
2505
+ constructor(typeName, attrName, options) {
2506
+ this.hasDefault = Object.prototype.hasOwnProperty.call(options, "default");
2507
+ this.default = options.default;
2508
+ this.validate = typeof options.validate == "string" ? validateType(typeName, attrName, options.validate) : options.validate;
2509
+ }
2510
+ get isRequired() {
2511
+ return !this.hasDefault;
2512
+ }
2513
+ };
2514
+ var MarkType = class _MarkType {
2515
+ /**
2516
+ @internal
2517
+ */
2518
+ constructor(name, rank, schema2, spec) {
2519
+ this.name = name;
2520
+ this.rank = rank;
2521
+ this.schema = schema2;
2522
+ this.spec = spec;
2523
+ this.attrs = initAttrs(name, spec.attrs);
2524
+ this.excluded = null;
2525
+ let defaults = defaultAttrs(this.attrs);
2526
+ this.instance = defaults ? new Mark(this, defaults) : null;
2527
+ }
2528
+ /**
2529
+ Create a mark of this type. `attrs` may be `null` or an object
2530
+ containing only some of the mark's attributes. The others, if
2531
+ they have defaults, will be added.
2532
+ */
2533
+ create(attrs = null) {
2534
+ if (!attrs && this.instance)
2535
+ return this.instance;
2536
+ return new Mark(this, computeAttrs(this.attrs, attrs));
2537
+ }
2538
+ /**
2539
+ @internal
2540
+ */
2541
+ static compile(marks2, schema2) {
2542
+ let result = /* @__PURE__ */ Object.create(null), rank = 0;
2543
+ marks2.forEach((name, spec) => result[name] = new _MarkType(name, rank++, schema2, spec));
2544
+ return result;
2545
+ }
2546
+ /**
2547
+ When there is a mark of this type in the given set, a new set
2548
+ without it is returned. Otherwise, the input set is returned.
2549
+ */
2550
+ removeFromSet(set) {
2551
+ for (var i = 0; i < set.length; i++)
2552
+ if (set[i].type == this) {
2553
+ set = set.slice(0, i).concat(set.slice(i + 1));
2554
+ i--;
2555
+ }
2556
+ return set;
2557
+ }
2558
+ /**
2559
+ Tests whether there is a mark of this type in the given set.
2560
+ */
2561
+ isInSet(set) {
2562
+ for (let i = 0; i < set.length; i++)
2563
+ if (set[i].type == this)
2564
+ return set[i];
2565
+ }
2566
+ /**
2567
+ @internal
2568
+ */
2569
+ checkAttrs(attrs) {
2570
+ checkAttrs(this.attrs, attrs, "mark", this.name);
2571
+ }
2572
+ /**
2573
+ Queries whether a given mark type is
2574
+ [excluded](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) by this one.
2575
+ */
2576
+ excludes(other) {
2577
+ return this.excluded.indexOf(other) > -1;
2578
+ }
2579
+ };
2580
+ var Schema = class {
2581
+ /**
2582
+ Construct a schema from a schema [specification](https://prosemirror.net/docs/ref/#model.SchemaSpec).
2583
+ */
2584
+ constructor(spec) {
2585
+ this.linebreakReplacement = null;
2586
+ this.cached = /* @__PURE__ */ Object.create(null);
2587
+ let instanceSpec = this.spec = {};
2588
+ for (let prop in spec)
2589
+ instanceSpec[prop] = spec[prop];
2590
+ instanceSpec.nodes = dist_default.from(spec.nodes), instanceSpec.marks = dist_default.from(spec.marks || {}), this.nodes = NodeType.compile(this.spec.nodes, this);
2591
+ this.marks = MarkType.compile(this.spec.marks, this);
2592
+ let contentExprCache = /* @__PURE__ */ Object.create(null);
2593
+ for (let prop in this.nodes) {
2594
+ if (prop in this.marks)
2595
+ throw new RangeError(prop + " can not be both a node and a mark");
2596
+ let type = this.nodes[prop], contentExpr = type.spec.content || "", markExpr = type.spec.marks;
2597
+ type.contentMatch = contentExprCache[contentExpr] || (contentExprCache[contentExpr] = ContentMatch.parse(contentExpr, this.nodes));
2598
+ type.inlineContent = type.contentMatch.inlineContent;
2599
+ if (type.spec.linebreakReplacement) {
2600
+ if (this.linebreakReplacement)
2601
+ throw new RangeError("Multiple linebreak nodes defined");
2602
+ if (!type.isInline || !type.isLeaf)
2603
+ throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");
2604
+ this.linebreakReplacement = type;
2605
+ }
2606
+ type.markSet = markExpr == "_" ? null : markExpr ? gatherMarks(this, markExpr.split(" ")) : markExpr == "" || !type.inlineContent ? [] : null;
2607
+ }
2608
+ for (let prop in this.marks) {
2609
+ let type = this.marks[prop], excl = type.spec.excludes;
2610
+ type.excluded = excl == null ? [type] : excl == "" ? [] : gatherMarks(this, excl.split(" "));
2611
+ }
2612
+ this.nodeFromJSON = (json) => Node.fromJSON(this, json);
2613
+ this.markFromJSON = (json) => Mark.fromJSON(this, json);
2614
+ this.topNodeType = this.nodes[this.spec.topNode || "doc"];
2615
+ this.cached.wrappings = /* @__PURE__ */ Object.create(null);
2616
+ }
2617
+ /**
2618
+ Create a node in this schema. The `type` may be a string or a
2619
+ `NodeType` instance. Attributes will be extended with defaults,
2620
+ `content` may be a `Fragment`, `null`, a `Node`, or an array of
2621
+ nodes.
2622
+ */
2623
+ node(type, attrs = null, content, marks2) {
2624
+ if (typeof type == "string")
2625
+ type = this.nodeType(type);
2626
+ else if (!(type instanceof NodeType))
2627
+ throw new RangeError("Invalid node type: " + type);
2628
+ else if (type.schema != this)
2629
+ throw new RangeError("Node type from different schema used (" + type.name + ")");
2630
+ return type.createChecked(attrs, content, marks2);
2631
+ }
2632
+ /**
2633
+ Create a text node in the schema. Empty text nodes are not
2634
+ allowed.
2635
+ */
2636
+ text(text, marks2) {
2637
+ let type = this.nodes.text;
2638
+ return new TextNode(type, type.defaultAttrs, text, Mark.setFrom(marks2));
2639
+ }
2640
+ /**
2641
+ Create a mark with the given type and attributes.
2642
+ */
2643
+ mark(type, attrs) {
2644
+ if (typeof type == "string")
2645
+ type = this.marks[type];
2646
+ return type.create(attrs);
2647
+ }
2648
+ /**
2649
+ @internal
2650
+ */
2651
+ nodeType(name) {
2652
+ let found2 = this.nodes[name];
2653
+ if (!found2)
2654
+ throw new RangeError("Unknown node type: " + name);
2655
+ return found2;
2656
+ }
2657
+ };
2658
+ function gatherMarks(schema2, marks2) {
2659
+ let found2 = [];
2660
+ for (let i = 0; i < marks2.length; i++) {
2661
+ let name = marks2[i], mark = schema2.marks[name], ok = mark;
2662
+ if (mark) {
2663
+ found2.push(mark);
2664
+ } else {
2665
+ for (let prop in schema2.marks) {
2666
+ let mark2 = schema2.marks[prop];
2667
+ if (name == "_" || mark2.spec.group && mark2.spec.group.split(" ").indexOf(name) > -1)
2668
+ found2.push(ok = mark2);
2669
+ }
2670
+ }
2671
+ if (!ok)
2672
+ throw new SyntaxError("Unknown mark type: '" + marks2[i] + "'");
2673
+ }
2674
+ return found2;
2675
+ }
2676
+ var DOMSerializer = class _DOMSerializer {
2677
+ /**
2678
+ Create a serializer. `nodes` should map node names to functions
2679
+ that take a node and return a description of the corresponding
2680
+ DOM. `marks` does the same for mark names, but also gets an
2681
+ argument that tells it whether the mark's content is block or
2682
+ inline content (for typical use, it'll always be inline). A mark
2683
+ serializer may be `null` to indicate that marks of that type
2684
+ should not be serialized.
2685
+ */
2686
+ constructor(nodes2, marks2) {
2687
+ this.nodes = nodes2;
2688
+ this.marks = marks2;
2689
+ }
2690
+ /**
2691
+ Serialize the content of this fragment to a DOM fragment. When
2692
+ not in the browser, the `document` option, containing a DOM
2693
+ document, should be passed so that the serializer can create
2694
+ nodes.
2695
+ */
2696
+ serializeFragment(fragment, options = {}, target) {
2697
+ if (!target)
2698
+ target = doc(options).createDocumentFragment();
2699
+ let top = target, active = [];
2700
+ fragment.forEach((node) => {
2701
+ if (active.length || node.marks.length) {
2702
+ let keep = 0, rendered = 0;
2703
+ while (keep < active.length && rendered < node.marks.length) {
2704
+ let next = node.marks[rendered];
2705
+ if (!this.marks[next.type.name]) {
2706
+ rendered++;
2707
+ continue;
2708
+ }
2709
+ if (!next.eq(active[keep][0]) || next.type.spec.spanning === false)
2710
+ break;
2711
+ keep++;
2712
+ rendered++;
2713
+ }
2714
+ while (keep < active.length)
2715
+ top = active.pop()[1];
2716
+ while (rendered < node.marks.length) {
2717
+ let add2 = node.marks[rendered++];
2718
+ let markDOM = this.serializeMark(add2, node.isInline, options);
2719
+ if (markDOM) {
2720
+ active.push([add2, top]);
2721
+ top.appendChild(markDOM.dom);
2722
+ top = markDOM.contentDOM || markDOM.dom;
2723
+ }
2724
+ }
2725
+ }
2726
+ top.appendChild(this.serializeNodeInner(node, options));
2727
+ });
2728
+ return target;
2729
+ }
2730
+ /**
2731
+ @internal
2732
+ */
2733
+ serializeNodeInner(node, options) {
2734
+ let { dom, contentDOM } = renderSpec(doc(options), this.nodes[node.type.name](node), null, node.attrs);
2735
+ if (contentDOM) {
2736
+ if (node.isLeaf)
2737
+ throw new RangeError("Content hole not allowed in a leaf node spec");
2738
+ this.serializeFragment(node.content, options, contentDOM);
2739
+ }
2740
+ return dom;
2741
+ }
2742
+ /**
2743
+ Serialize this node to a DOM node. This can be useful when you
2744
+ need to serialize a part of a document, as opposed to the whole
2745
+ document. To serialize a whole document, use
2746
+ [`serializeFragment`](https://prosemirror.net/docs/ref/#model.DOMSerializer.serializeFragment) on
2747
+ its [content](https://prosemirror.net/docs/ref/#model.Node.content).
2748
+ */
2749
+ serializeNode(node, options = {}) {
2750
+ let dom = this.serializeNodeInner(node, options);
2751
+ for (let i = node.marks.length - 1; i >= 0; i--) {
2752
+ let wrap = this.serializeMark(node.marks[i], node.isInline, options);
2753
+ if (wrap) {
2754
+ (wrap.contentDOM || wrap.dom).appendChild(dom);
2755
+ dom = wrap.dom;
2756
+ }
2757
+ }
2758
+ return dom;
2759
+ }
2760
+ /**
2761
+ @internal
2762
+ */
2763
+ serializeMark(mark, inline, options = {}) {
2764
+ let toDOM = this.marks[mark.type.name];
2765
+ return toDOM && renderSpec(doc(options), toDOM(mark, inline), null, mark.attrs);
2766
+ }
2767
+ static renderSpec(doc2, structure, xmlNS = null, blockArraysIn) {
2768
+ return renderSpec(doc2, structure, xmlNS, blockArraysIn);
2769
+ }
2770
+ /**
2771
+ Build a serializer using the [`toDOM`](https://prosemirror.net/docs/ref/#model.NodeSpec.toDOM)
2772
+ properties in a schema's node and mark specs.
2773
+ */
2774
+ static fromSchema(schema2) {
2775
+ return schema2.cached.domSerializer || (schema2.cached.domSerializer = new _DOMSerializer(this.nodesFromSchema(schema2), this.marksFromSchema(schema2)));
2776
+ }
2777
+ /**
2778
+ Gather the serializers in a schema's node specs into an object.
2779
+ This can be useful as a base to build a custom serializer from.
2780
+ */
2781
+ static nodesFromSchema(schema2) {
2782
+ let result = gatherToDOM(schema2.nodes);
2783
+ if (!result.text)
2784
+ result.text = (node) => node.text;
2785
+ return result;
2786
+ }
2787
+ /**
2788
+ Gather the serializers in a schema's mark specs into an object.
2789
+ */
2790
+ static marksFromSchema(schema2) {
2791
+ return gatherToDOM(schema2.marks);
2792
+ }
2793
+ };
2794
+ function gatherToDOM(obj) {
2795
+ let result = {};
2796
+ for (let name in obj) {
2797
+ let toDOM = obj[name].spec.toDOM;
2798
+ if (toDOM)
2799
+ result[name] = toDOM;
2800
+ }
2801
+ return result;
2802
+ }
2803
+ function doc(options) {
2804
+ return options.document || window.document;
2805
+ }
2806
+ var suspiciousAttributeCache = /* @__PURE__ */ new WeakMap();
2807
+ function suspiciousAttributes(attrs) {
2808
+ let value = suspiciousAttributeCache.get(attrs);
2809
+ if (value === void 0)
2810
+ suspiciousAttributeCache.set(attrs, value = suspiciousAttributesInner(attrs));
2811
+ return value;
2812
+ }
2813
+ function suspiciousAttributesInner(attrs) {
2814
+ let result = null;
2815
+ function scan(value) {
2816
+ if (value && typeof value == "object") {
2817
+ if (Array.isArray(value)) {
2818
+ if (typeof value[0] == "string") {
2819
+ if (!result)
2820
+ result = [];
2821
+ result.push(value);
2822
+ } else {
2823
+ for (let i = 0; i < value.length; i++)
2824
+ scan(value[i]);
2825
+ }
2826
+ } else {
2827
+ for (let prop in value)
2828
+ scan(value[prop]);
2829
+ }
2830
+ }
2831
+ }
2832
+ scan(attrs);
2833
+ return result;
2834
+ }
2835
+ function renderSpec(doc2, structure, xmlNS, blockArraysIn) {
2836
+ if (typeof structure == "string")
2837
+ return { dom: doc2.createTextNode(structure) };
2838
+ if (structure.nodeType != null)
2839
+ return { dom: structure };
2840
+ if (structure.dom && structure.dom.nodeType != null)
2841
+ return structure;
2842
+ let tagName = structure[0], suspicious;
2843
+ if (typeof tagName != "string")
2844
+ throw new RangeError("Invalid array passed to renderSpec");
2845
+ if (blockArraysIn && (suspicious = suspiciousAttributes(blockArraysIn)) && suspicious.indexOf(structure) > -1)
2846
+ throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");
2847
+ let space = tagName.indexOf(" ");
2848
+ if (space > 0) {
2849
+ xmlNS = tagName.slice(0, space);
2850
+ tagName = tagName.slice(space + 1);
2851
+ }
2852
+ let contentDOM;
2853
+ let dom = xmlNS ? doc2.createElementNS(xmlNS, tagName) : doc2.createElement(tagName);
2854
+ let attrs = structure[1], start = 1;
2855
+ if (attrs && typeof attrs == "object" && attrs.nodeType == null && !Array.isArray(attrs)) {
2856
+ start = 2;
2857
+ for (let name in attrs)
2858
+ if (attrs[name] != null) {
2859
+ let space2 = name.indexOf(" ");
2860
+ if (space2 > 0)
2861
+ dom.setAttributeNS(name.slice(0, space2), name.slice(space2 + 1), attrs[name]);
2862
+ else if (name == "style" && dom.style)
2863
+ dom.style.cssText = attrs[name];
2864
+ else
2865
+ dom.setAttribute(name, attrs[name]);
2866
+ }
2867
+ }
2868
+ for (let i = start; i < structure.length; i++) {
2869
+ let child = structure[i];
2870
+ if (child === 0) {
2871
+ if (i < structure.length - 1 || i > start)
2872
+ throw new RangeError("Content hole must be the only child of its parent node");
2873
+ return { dom, contentDOM: dom };
2874
+ } else {
2875
+ let { dom: inner, contentDOM: innerContent } = renderSpec(doc2, child, xmlNS, blockArraysIn);
2876
+ dom.appendChild(inner);
2877
+ if (innerContent) {
2878
+ if (contentDOM)
2879
+ throw new RangeError("Multiple content holes");
2880
+ contentDOM = innerContent;
2881
+ }
2882
+ }
2883
+ }
2884
+ return { dom, contentDOM };
2885
+ }
2886
+
2887
+ // node_modules/prosemirror-schema-basic/dist/index.js
2888
+ var pDOM = ["p", 0];
2889
+ var blockquoteDOM = ["blockquote", 0];
2890
+ var hrDOM = ["hr"];
2891
+ var preDOM = ["pre", ["code", 0]];
2892
+ var brDOM = ["br"];
2893
+ var nodes = {
2894
+ /**
2895
+ NodeSpec The top level document node.
2896
+ */
2897
+ doc: {
2898
+ content: "block+"
2899
+ },
2900
+ /**
2901
+ A plain paragraph textblock. Represented in the DOM
2902
+ as a `<p>` element.
2903
+ */
2904
+ paragraph: {
2905
+ content: "inline*",
2906
+ group: "block",
2907
+ parseDOM: [{ tag: "p" }],
2908
+ toDOM() {
2909
+ return pDOM;
2910
+ }
2911
+ },
2912
+ /**
2913
+ A blockquote (`<blockquote>`) wrapping one or more blocks.
2914
+ */
2915
+ blockquote: {
2916
+ content: "block+",
2917
+ group: "block",
2918
+ defining: true,
2919
+ parseDOM: [{ tag: "blockquote" }],
2920
+ toDOM() {
2921
+ return blockquoteDOM;
2922
+ }
2923
+ },
2924
+ /**
2925
+ A horizontal rule (`<hr>`).
2926
+ */
2927
+ horizontal_rule: {
2928
+ group: "block",
2929
+ parseDOM: [{ tag: "hr" }],
2930
+ toDOM() {
2931
+ return hrDOM;
2932
+ }
2933
+ },
2934
+ /**
2935
+ A heading textblock, with a `level` attribute that
2936
+ should hold the number 1 to 6. Parsed and serialized as `<h1>` to
2937
+ `<h6>` elements.
2938
+ */
2939
+ heading: {
2940
+ attrs: { level: { default: 1, validate: "number" } },
2941
+ content: "inline*",
2942
+ group: "block",
2943
+ defining: true,
2944
+ parseDOM: [
2945
+ { tag: "h1", attrs: { level: 1 } },
2946
+ { tag: "h2", attrs: { level: 2 } },
2947
+ { tag: "h3", attrs: { level: 3 } },
2948
+ { tag: "h4", attrs: { level: 4 } },
2949
+ { tag: "h5", attrs: { level: 5 } },
2950
+ { tag: "h6", attrs: { level: 6 } }
2951
+ ],
2952
+ toDOM(node) {
2953
+ return ["h" + node.attrs.level, 0];
2954
+ }
2955
+ },
2956
+ /**
2957
+ A code listing. Disallows marks or non-text inline
2958
+ nodes by default. Represented as a `<pre>` element with a
2959
+ `<code>` element inside of it.
2960
+ */
2961
+ code_block: {
2962
+ content: "text*",
2963
+ marks: "",
2964
+ group: "block",
2965
+ code: true,
2966
+ defining: true,
2967
+ parseDOM: [{ tag: "pre", preserveWhitespace: "full" }],
2968
+ toDOM() {
2969
+ return preDOM;
2970
+ }
2971
+ },
2972
+ /**
2973
+ The text node.
2974
+ */
2975
+ text: {
2976
+ group: "inline"
2977
+ },
2978
+ /**
2979
+ An inline image (`<img>`) node. Supports `src`,
2980
+ `alt`, and `href` attributes. The latter two default to the empty
2981
+ string.
2982
+ */
2983
+ image: {
2984
+ inline: true,
2985
+ attrs: {
2986
+ src: { validate: "string" },
2987
+ alt: { default: null, validate: "string|null" },
2988
+ title: { default: null, validate: "string|null" }
2989
+ },
2990
+ group: "inline",
2991
+ draggable: true,
2992
+ parseDOM: [{ tag: "img[src]", getAttrs(dom) {
2993
+ return {
2994
+ src: dom.getAttribute("src"),
2995
+ title: dom.getAttribute("title"),
2996
+ alt: dom.getAttribute("alt")
2997
+ };
2998
+ } }],
2999
+ toDOM(node) {
3000
+ let { src, alt, title } = node.attrs;
3001
+ return ["img", { src, alt, title }];
3002
+ }
3003
+ },
3004
+ /**
3005
+ A hard line break, represented in the DOM as `<br>`.
3006
+ */
3007
+ hard_break: {
3008
+ inline: true,
3009
+ group: "inline",
3010
+ selectable: false,
3011
+ parseDOM: [{ tag: "br" }],
3012
+ toDOM() {
3013
+ return brDOM;
3014
+ }
3015
+ }
3016
+ };
3017
+ var emDOM = ["em", 0];
3018
+ var strongDOM = ["strong", 0];
3019
+ var codeDOM = ["code", 0];
3020
+ var marks = {
3021
+ /**
3022
+ A link. Has `href` and `title` attributes. `title`
3023
+ defaults to the empty string. Rendered and parsed as an `<a>`
3024
+ element.
3025
+ */
3026
+ link: {
3027
+ attrs: {
3028
+ href: { validate: "string" },
3029
+ title: { default: null, validate: "string|null" }
3030
+ },
3031
+ inclusive: false,
3032
+ parseDOM: [{ tag: "a[href]", getAttrs(dom) {
3033
+ return { href: dom.getAttribute("href"), title: dom.getAttribute("title") };
3034
+ } }],
3035
+ toDOM(node) {
3036
+ let { href, title } = node.attrs;
3037
+ return ["a", { href, title }, 0];
3038
+ }
3039
+ },
3040
+ /**
3041
+ An emphasis mark. Rendered as an `<em>` element. Has parse rules
3042
+ that also match `<i>` and `font-style: italic`.
3043
+ */
3044
+ em: {
3045
+ parseDOM: [
3046
+ { tag: "i" },
3047
+ { tag: "em" },
3048
+ { style: "font-style=italic" },
3049
+ { style: "font-style=normal", clearMark: (m) => m.type.name == "em" }
3050
+ ],
3051
+ toDOM() {
3052
+ return emDOM;
3053
+ }
3054
+ },
3055
+ /**
3056
+ A strong mark. Rendered as `<strong>`, parse rules also match
3057
+ `<b>` and `font-weight: bold`.
3058
+ */
3059
+ strong: {
3060
+ parseDOM: [
3061
+ { tag: "strong" },
3062
+ // This works around a Google Docs misbehavior where
3063
+ // pasted content will be inexplicably wrapped in `<b>`
3064
+ // tags with a font-weight normal.
3065
+ { tag: "b", getAttrs: (node) => node.style.fontWeight != "normal" && null },
3066
+ { style: "font-weight=400", clearMark: (m) => m.type.name == "strong" },
3067
+ { style: "font-weight", getAttrs: (value) => /^(bold(er)?|[5-9]\d{2,})$/.test(value) && null }
3068
+ ],
3069
+ toDOM() {
3070
+ return strongDOM;
3071
+ }
3072
+ },
3073
+ /**
3074
+ Code font mark. Represented as a `<code>` element.
3075
+ */
3076
+ code: {
3077
+ code: true,
3078
+ parseDOM: [{ tag: "code" }],
3079
+ toDOM() {
3080
+ return codeDOM;
3081
+ }
3082
+ }
3083
+ };
3084
+ var schema = new Schema({ nodes, marks });
3085
+
3086
+ // node_modules/prosemirror-schema-list/dist/index.js
3087
+ var olDOM = ["ol", 0];
3088
+ var ulDOM = ["ul", 0];
3089
+ var liDOM = ["li", 0];
3090
+ var orderedList = {
3091
+ attrs: { order: { default: 1, validate: "number" } },
3092
+ parseDOM: [{ tag: "ol", getAttrs(dom) {
3093
+ return { order: dom.hasAttribute("start") ? +dom.getAttribute("start") : 1 };
3094
+ } }],
3095
+ toDOM(node) {
3096
+ return node.attrs.order == 1 ? olDOM : ["ol", { start: node.attrs.order }, 0];
3097
+ }
3098
+ };
3099
+ var bulletList = {
3100
+ parseDOM: [{ tag: "ul" }],
3101
+ toDOM() {
3102
+ return ulDOM;
3103
+ }
3104
+ };
3105
+ var listItem = {
3106
+ parseDOM: [{ tag: "li" }],
3107
+ toDOM() {
3108
+ return liDOM;
3109
+ },
3110
+ defining: true
3111
+ };
3112
+ function add(obj, props) {
3113
+ let copy = {};
3114
+ for (let prop in obj)
3115
+ copy[prop] = obj[prop];
3116
+ for (let prop in props)
3117
+ copy[prop] = props[prop];
3118
+ return copy;
3119
+ }
3120
+ function addListNodes(nodes2, itemContent, listGroup) {
3121
+ return nodes2.append({
3122
+ ordered_list: add(orderedList, { content: "list_item+", group: listGroup }),
3123
+ bullet_list: add(bulletList, { content: "list_item+", group: listGroup }),
3124
+ list_item: add(listItem, { content: itemContent })
3125
+ });
3126
+ }
3127
+
3128
+ // src/objects/rich_text_object.ts
3129
+ function deepEqual(a, b) {
3130
+ if (a === b) {
3131
+ return true;
3132
+ }
3133
+ if (a === null || b === null || typeof a !== "object" || typeof b !== "object") {
3134
+ return false;
3135
+ }
3136
+ if (Array.isArray(a) !== Array.isArray(b)) {
3137
+ return false;
3138
+ }
3139
+ const objA = a;
3140
+ const objB = b;
3141
+ let countA = 0;
3142
+ for (const key in objA) {
3143
+ if (!Object.prototype.hasOwnProperty.call(objA, key)) {
3144
+ continue;
3145
+ }
3146
+ countA++;
3147
+ if (!Object.prototype.hasOwnProperty.call(objB, key)) {
3148
+ return false;
3149
+ }
3150
+ if (!deepEqual(objA[key], objB[key])) {
3151
+ return false;
3152
+ }
3153
+ }
3154
+ let countB = 0;
3155
+ for (const key in objB) {
3156
+ if (Object.prototype.hasOwnProperty.call(objB, key)) {
3157
+ countB++;
3158
+ }
3159
+ }
3160
+ return countA === countB;
3161
+ }
3162
+ var richTextSchema = new Schema({
3163
+ nodes: addListNodes(schema.spec.nodes, "paragraph block*", "block"),
3164
+ marks: schema.spec.marks.addToEnd("strike", {
3165
+ parseDOM: [{ tag: "s" }, { tag: "strike" }, { style: "text-decoration=line-through" }],
3166
+ toDOM() {
3167
+ return ["s", 0];
3168
+ }
3169
+ })
3170
+ });
3171
+ var _RSRichTextObject = class _RSRichTextObject {
3172
+ constructor(state) {
3173
+ this._innerNode = null;
3174
+ this._state = {
3175
+ doc: JSON.parse(JSON.stringify(state.doc))
3176
+ };
3177
+ }
3178
+ isStateEqual(state) {
3179
+ return deepEqual(this._state.doc, state.doc);
3180
+ }
3181
+ updateState(state) {
3182
+ this._state = {
3183
+ doc: JSON.parse(JSON.stringify(state.doc))
3184
+ };
3185
+ }
3186
+ getStateSFCT(state) {
3187
+ state.doc = this._state.doc;
3188
+ }
3189
+ renderSFCT(node) {
3190
+ const doc2 = Node.fromJSON(richTextSchema, this._state.doc);
3191
+ const fragment = _RSRichTextObject._DOM_SERIALIZER.serializeFragment(doc2.content);
3192
+ if (!this._innerNode) {
3193
+ this._innerNode = document.createElement("div");
3194
+ this._innerNode.className = "rs-rich-text";
3195
+ this._innerNode.style.cssText = "height:100%;width:100%;overflow:auto;box-sizing:border-box";
3196
+ node.replaceChildren(this._innerNode);
3197
+ }
3198
+ this._innerNode.replaceChildren(fragment);
3199
+ }
3200
+ destroy() {
3201
+ this._innerNode?.remove();
3202
+ this._innerNode = null;
3203
+ }
3204
+ };
3205
+ _RSRichTextObject._DOM_SERIALIZER = (() => {
3206
+ const nodes2 = { ...DOMSerializer.nodesFromSchema(richTextSchema) };
3207
+ const baseParagraph = nodes2.paragraph;
3208
+ nodes2.paragraph = (node) => {
3209
+ if (node.content.size === 0) {
3210
+ return ["p", ["br"]];
3211
+ }
3212
+ return baseParagraph(node);
3213
+ };
3214
+ return new DOMSerializer(nodes2, DOMSerializer.marksFromSchema(richTextSchema));
3215
+ })();
3216
+ var RSRichTextObject = _RSRichTextObject;
3217
+
3218
+ // src/controls/resize_control.ts
3219
+ var ResizeControl = class {
3220
+ constructor(canvas) {
3221
+ this._objectId = null;
3222
+ this._lastViewX = 0;
3223
+ this._lastViewY = 0;
3224
+ this._canvas = canvas;
3225
+ }
3226
+ handleEvent(event) {
3227
+ if (event.type === "mousedown") {
3228
+ const objectId = this._canvas.objectIdAtLowerRightCorner(event.viewX ?? 0, event.viewY ?? 0);
3229
+ if (!objectId) {
3230
+ return null;
3231
+ }
3232
+ this._objectId = objectId;
3233
+ this._lastViewX = event.viewX ?? 0;
3234
+ this._lastViewY = event.viewY ?? 0;
3235
+ this._canvas.changeCursor("se-resize");
3236
+ return this;
3237
+ }
3238
+ if (event.type === "mouseup" || event.type === "mouseleave") {
3239
+ this._objectId = null;
3240
+ this._canvas.changeCursor("default");
3241
+ return null;
3242
+ }
3243
+ if (event.type === "mousemove" && this._objectId) {
3244
+ const viewX = event.viewX ?? 0;
3245
+ const viewY = event.viewY ?? 0;
3246
+ const scale = this._canvas.getScale();
3247
+ const dw = (viewX - this._lastViewX) / scale;
3248
+ const dh = (viewY - this._lastViewY) / scale;
3249
+ this._lastViewX = viewX;
3250
+ this._lastViewY = viewY;
3251
+ this._canvas.resizeObject(this._objectId, dw, dh);
3252
+ this._canvas.changeCursor("se-resize");
3253
+ return this;
3254
+ }
3255
+ if (event.type === "mousemove") {
3256
+ const overHandle = this._canvas.objectIdAtLowerRightCorner(event.viewX ?? 0, event.viewY ?? 0);
3257
+ if (overHandle) {
3258
+ this._canvas.changeCursor("se-resize");
3259
+ }
3260
+ }
3261
+ return null;
3262
+ }
3263
+ render(_node) {
3264
+ }
3265
+ destroy() {
3266
+ }
3267
+ };
3268
+
3269
+ // src/controls/rotation_control.ts
3270
+ var ROTATION_HANDLE_SIZE = 14;
3271
+ var RotationControl = class {
3272
+ constructor(canvas) {
3273
+ this._cornerPosScratch = { worldX: 0, worldY: 0 };
3274
+ this._objectId = null;
3275
+ this._hoveredObjectId = null;
3276
+ this._lastAngle = 0;
3277
+ this._lastWorldX = 0;
3278
+ this._lastWorldY = 0;
3279
+ this._lineEl = null;
3280
+ this._handlePath = null;
3281
+ this._canvas = canvas;
3282
+ }
3283
+ handleEvent(event) {
3284
+ if (event.type === "mousedown") {
3285
+ const objectId = this._canvas.objectIdAtUpperRightCorner(event.viewX ?? 0, event.viewY ?? 0);
3286
+ if (!objectId) {
3287
+ return null;
3288
+ }
3289
+ this._objectId = objectId;
3290
+ this._canvas.highlightObject(objectId);
3291
+ const node = this._canvas.getObjectNode(objectId);
3292
+ if (!node) {
3293
+ return null;
3294
+ }
3295
+ const pivotX = node.getX() + node.getWidth() / 2;
3296
+ const pivotY = node.getY() + node.getHeight() / 2;
3297
+ const worldX = this._canvas.toWorldX(event.viewX ?? 0);
3298
+ const worldY = this._canvas.toWorldY(event.viewY ?? 0);
3299
+ this._lastAngle = Math.atan2(worldY - pivotY, worldX - pivotX);
3300
+ this._lastWorldX = worldX;
3301
+ this._lastWorldY = worldY;
3302
+ this._canvas.changeCursor("grabbing");
3303
+ return this;
3304
+ }
3305
+ if (event.type === "mouseup" || event.type === "mouseleave") {
3306
+ this._objectId = null;
3307
+ this._hoveredObjectId = null;
3308
+ this._canvas.changeCursor("default");
3309
+ return null;
3310
+ }
3311
+ if (event.type === "mousemove" && this._objectId) {
3312
+ const node = this._canvas.getObjectNode(this._objectId);
3313
+ if (!node) {
3314
+ return this;
3315
+ }
3316
+ const pivotX = node.getX() + node.getWidth() / 2;
3317
+ const pivotY = node.getY() + node.getHeight() / 2;
3318
+ const worldX = this._canvas.toWorldX(event.viewX ?? 0);
3319
+ const worldY = this._canvas.toWorldY(event.viewY ?? 0);
3320
+ const currentAngle = Math.atan2(worldY - pivotY, worldX - pivotX);
3321
+ let dAngle = currentAngle - this._lastAngle;
3322
+ if (dAngle > Math.PI) {
3323
+ dAngle -= 2 * Math.PI;
3324
+ }
3325
+ if (dAngle < -Math.PI) {
3326
+ dAngle += 2 * Math.PI;
3327
+ }
3328
+ this._lastAngle = currentAngle;
3329
+ this._lastWorldX = worldX;
3330
+ this._lastWorldY = worldY;
3331
+ this._canvas.rotateObject(this._objectId, dAngle);
3332
+ this._canvas.changeCursor("grabbing");
3333
+ return this;
3334
+ }
3335
+ if (event.type === "mousemove") {
3336
+ const overHandle = this._canvas.objectIdAtUpperRightCorner(event.viewX ?? 0, event.viewY ?? 0);
3337
+ if (overHandle !== this._hoveredObjectId) {
3338
+ this._hoveredObjectId = overHandle;
3339
+ }
3340
+ if (overHandle) {
3341
+ this._canvas.changeCursor("grab");
3342
+ }
3343
+ }
3344
+ return null;
3345
+ }
3346
+ render(node) {
3347
+ const objectId = this._objectId ?? this._hoveredObjectId;
3348
+ const isActive = this._objectId !== null;
3349
+ const fill = isActive ? "#4a90d9" : "#888";
3350
+ if (!objectId) {
3351
+ if (this._lineEl?.parentElement) {
3352
+ this._lineEl.parentElement.remove();
3353
+ this._lineEl = null;
3354
+ }
3355
+ if (this._handlePath?.parentElement) {
3356
+ this._handlePath.parentElement.remove();
3357
+ this._handlePath = null;
3358
+ }
3359
+ return;
3360
+ }
3361
+ this._canvas.getCornerWorldXYSFCT(objectId, "top-right", this._cornerPosScratch);
3362
+ const { worldX: x, worldY: y } = this._cornerPosScratch;
3363
+ const half = ROTATION_HANDLE_SIZE / 2;
3364
+ if (isActive) {
3365
+ if (!this._lineEl) {
3366
+ const lineSvg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
3367
+ lineSvg.setAttribute("width", "100%");
3368
+ lineSvg.setAttribute("height", "100%");
3369
+ lineSvg.setAttribute("viewBox", `0 0 ${this._canvas.getCanvasWidth()} ${this._canvas.getCanvasHeight()}`);
3370
+ lineSvg.style.position = "absolute";
3371
+ lineSvg.style.top = "0";
3372
+ lineSvg.style.left = "0";
3373
+ lineSvg.style.pointerEvents = "none";
3374
+ this._lineEl = document.createElementNS("http://www.w3.org/2000/svg", "line");
3375
+ this._lineEl.setAttribute("stroke", "#4a90d9");
3376
+ this._lineEl.setAttribute("stroke-width", "1.5");
3377
+ this._lineEl.setAttribute("stroke-linecap", "round");
3378
+ lineSvg.appendChild(this._lineEl);
3379
+ }
3380
+ this._lineEl.setAttribute("x1", String(x));
3381
+ this._lineEl.setAttribute("y1", String(y));
3382
+ this._lineEl.setAttribute("x2", String(this._lastWorldX));
3383
+ this._lineEl.setAttribute("y2", String(this._lastWorldY));
3384
+ node.appendChild(this._lineEl.parentElement);
3385
+ } else {
3386
+ if (this._lineEl?.parentElement) {
3387
+ this._lineEl.parentElement.remove();
3388
+ this._lineEl = null;
3389
+ }
3390
+ }
3391
+ if (!this._handlePath) {
3392
+ const handleSvg2 = document.createElementNS("http://www.w3.org/2000/svg", "svg");
3393
+ handleSvg2.setAttribute("width", String(ROTATION_HANDLE_SIZE));
3394
+ handleSvg2.setAttribute("height", String(ROTATION_HANDLE_SIZE));
3395
+ handleSvg2.setAttribute("viewBox", "0 0 24 24");
3396
+ handleSvg2.style.position = "absolute";
3397
+ handleSvg2.style.pointerEvents = "none";
3398
+ this._handlePath = document.createElementNS("http://www.w3.org/2000/svg", "path");
3399
+ this._handlePath.setAttribute("d", "M12 2v4l3-3-3-3v2c-4.4 0-8 3.6-8 8s3.6 8 8 8 8-3.6 8-8h2c0 5.5-4.5 10-10 10S2 17.5 2 12 6.5 2 12 2z");
3400
+ this._handlePath.setAttribute("stroke", "#fff");
3401
+ this._handlePath.setAttribute("stroke-width", "1.5");
3402
+ handleSvg2.appendChild(this._handlePath);
3403
+ }
3404
+ const handleSvg = this._handlePath.parentElement;
3405
+ handleSvg.style.left = `${x - half}px`;
3406
+ handleSvg.style.top = `${y - half}px`;
3407
+ this._handlePath.setAttribute("fill", fill);
3408
+ node.appendChild(handleSvg);
3409
+ }
3410
+ destroy() {
3411
+ this._objectId = null;
3412
+ this._hoveredObjectId = null;
3413
+ if (this._lineEl?.parentElement) {
3414
+ this._lineEl.parentElement.remove();
3415
+ }
3416
+ this._lineEl = null;
3417
+ if (this._handlePath?.parentElement) {
3418
+ this._handlePath.parentElement.remove();
3419
+ }
3420
+ this._handlePath = null;
3421
+ }
3422
+ };
3423
+
3424
+ // src/controls/zoom_control.ts
3425
+ var ZoomControl = class {
3426
+ constructor(canvas) {
3427
+ this._modifierHeld = false;
3428
+ this._canvas = canvas;
3429
+ }
3430
+ handleEvent(event) {
3431
+ if (event.type === "keydown" && (event.key === "Meta" || event.key === "Control")) {
3432
+ this._modifierHeld = true;
3433
+ this._canvas.changeCursor("zoom-in");
3434
+ return this;
3435
+ }
3436
+ if (event.type === "keyup" && (event.key === "Meta" || event.key === "Control")) {
3437
+ this._modifierHeld = false;
3438
+ this._canvas.changeCursor("default");
3439
+ return null;
3440
+ }
3441
+ if (this._modifierHeld && event.type === "scroll") {
3442
+ event.preventDefault?.();
3443
+ const scaleFactor = (event.deltaY ?? 0) > 0 ? 0.95 : 1.05;
3444
+ this._canvas.scaleAtXY(scaleFactor, event.viewX ?? 0, event.viewY ?? 0);
3445
+ return this;
3446
+ }
3447
+ return null;
3448
+ }
3449
+ render(_node) {
3450
+ }
3451
+ destroy() {
3452
+ }
3453
+ };
3454
+
3455
+ // src/controls/pan_control.ts
3456
+ var PanControl = class {
3457
+ constructor(canvas) {
3458
+ this._active = false;
3459
+ this._lastViewX = 0;
3460
+ this._lastViewY = 0;
3461
+ this._canvas = canvas;
3462
+ }
3463
+ handleEvent(event) {
3464
+ if (event.type === "mousedown") {
3465
+ const objectId = this._canvas.objectIdAtXY(event.viewX ?? 0, event.viewY ?? 0);
3466
+ if (objectId) {
3467
+ return null;
3468
+ }
3469
+ this._active = true;
3470
+ this._lastViewX = event.viewX ?? 0;
3471
+ this._lastViewY = event.viewY ?? 0;
3472
+ this._canvas.changeCursor("grabbing");
3473
+ return this;
3474
+ }
3475
+ if (event.type === "mouseup" || event.type === "mouseleave") {
3476
+ this._active = false;
3477
+ this._canvas.changeCursor("default");
3478
+ return null;
3479
+ }
3480
+ if (event.type === "mousemove" && this._active) {
3481
+ const viewX = event.viewX ?? 0;
3482
+ const viewY = event.viewY ?? 0;
3483
+ const dx = viewX - this._lastViewX;
3484
+ const dy = viewY - this._lastViewY;
3485
+ this._lastViewX = viewX;
3486
+ this._lastViewY = viewY;
3487
+ this._canvas.translate(dx, dy);
3488
+ this._canvas.changeCursor("grabbing");
3489
+ return this;
3490
+ }
3491
+ if (event.type === "mousemove") {
3492
+ const objectId = this._canvas.objectIdAtXY(event.viewX ?? 0, event.viewY ?? 0);
3493
+ if (!objectId) {
3494
+ this._canvas.changeCursor("grab");
3495
+ }
3496
+ }
3497
+ return null;
3498
+ }
3499
+ render(_node) {
3500
+ }
3501
+ destroy() {
3502
+ }
3503
+ };
3504
+
3505
+ // src/controls/drag_control.ts
3506
+ var DragControl = class {
3507
+ constructor(canvas) {
3508
+ this._objectId = null;
3509
+ this._lastViewX = 0;
3510
+ this._lastViewY = 0;
3511
+ this._canvas = canvas;
3512
+ }
3513
+ handleEvent(event) {
3514
+ if (event.type === "mousedown") {
3515
+ const objectId = this._canvas.objectIdAtXY(event.viewX ?? 0, event.viewY ?? 0);
3516
+ if (!objectId) {
3517
+ return null;
3518
+ }
3519
+ this._objectId = objectId;
3520
+ this._lastViewX = event.viewX ?? 0;
3521
+ this._lastViewY = event.viewY ?? 0;
3522
+ this._canvas.changeCursor("grabbing");
3523
+ return this;
3524
+ }
3525
+ if (event.type === "mouseup" || event.type === "mouseleave") {
3526
+ this._objectId = null;
3527
+ this._canvas.changeCursor("default");
3528
+ return null;
3529
+ }
3530
+ if (event.type === "mousemove" && this._objectId) {
3531
+ const viewX = event.viewX ?? 0;
3532
+ const viewY = event.viewY ?? 0;
3533
+ const scale = this._canvas.getScale();
3534
+ const dx = (viewX - this._lastViewX) / scale;
3535
+ const dy = (viewY - this._lastViewY) / scale;
3536
+ this._lastViewX = viewX;
3537
+ this._lastViewY = viewY;
3538
+ this._canvas.translateObject(this._objectId, dx, dy);
3539
+ this._canvas.changeCursor("grabbing");
3540
+ return this;
3541
+ }
3542
+ if (event.type === "mousemove") {
3543
+ if (this._canvas.objectIdAtLowerRightCorner(event.viewX ?? 0, event.viewY ?? 0) || this._canvas.objectIdAtUpperRightCorner(event.viewX ?? 0, event.viewY ?? 0)) {
3544
+ return null;
3545
+ }
3546
+ const objectId = this._canvas.objectIdAtXY(event.viewX ?? 0, event.viewY ?? 0);
3547
+ if (objectId) {
3548
+ this._canvas.changeCursor("grab");
3549
+ }
3550
+ }
3551
+ return null;
3552
+ }
3553
+ render(_node) {
3554
+ }
3555
+ destroy() {
3556
+ }
3557
+ };
3558
+
3559
+ // src/controls/highlight_control.ts
3560
+ var HighlightControl = class {
3561
+ constructor(canvas) {
3562
+ this._canvas = canvas;
3563
+ }
3564
+ handleEvent(event) {
3565
+ if (event.type === "mousemove") {
3566
+ const id = this._canvas.objectIdAtXY(event.viewX ?? 0, event.viewY ?? 0);
3567
+ if (id) {
3568
+ this._canvas.highlightObject(id);
3569
+ if (!this._canvas.objectIdAtLowerRightCorner(event.viewX ?? 0, event.viewY ?? 0) && !this._canvas.objectIdAtUpperRightCorner(event.viewX ?? 0, event.viewY ?? 0)) {
3570
+ this._canvas.changeCursor("pointer");
3571
+ }
3572
+ } else {
3573
+ this._canvas.clearHighlight();
3574
+ }
3575
+ return null;
3576
+ }
3577
+ if (event.type === "mouseleave") {
3578
+ this._canvas.clearHighlight();
3579
+ return null;
3580
+ }
3581
+ return null;
3582
+ }
3583
+ render(_node) {
3584
+ }
3585
+ destroy() {
3586
+ }
3587
+ };
3588
+
3589
+ // src/controls/edit_control.ts
3590
+ var DEFAULT_HIGHLIGHT_COLOR = "#00d4aa";
3591
+ var EditControl = class {
3592
+ constructor(canvas) {
3593
+ this._lockedObjectId = null;
3594
+ this._editingObjectId = null;
3595
+ this._canvas = canvas;
3596
+ }
3597
+ handleEvent(event) {
3598
+ if (this._editingObjectId) {
3599
+ return this;
3600
+ }
3601
+ if (event.type === "mouseleave") {
3602
+ if (this._lockedObjectId) {
3603
+ this._canvas.clearHighlight();
3604
+ this._canvas.setHighlightColor(DEFAULT_HIGHLIGHT_COLOR);
3605
+ this._canvas.changeCursor("default");
3606
+ this._lockedObjectId = null;
3607
+ }
3608
+ return null;
3609
+ }
3610
+ if (event.type === "dblclick") {
3611
+ if (this._lockedObjectId) {
3612
+ this._canvas.clearHighlight();
3613
+ this._canvas.setHighlightColor(DEFAULT_HIGHLIGHT_COLOR);
3614
+ this._canvas.changeCursor("default");
3615
+ this._lockedObjectId = null;
3616
+ return null;
3617
+ }
3618
+ const objectId = this._canvas.objectIdAtXY(event.viewX ?? 0, event.viewY ?? 0);
3619
+ if (objectId && this._canvas.canEditObject(objectId)) {
3620
+ this._canvas.setHighlightColor("#4a90d9");
3621
+ this._lockedObjectId = objectId;
3622
+ this._canvas.highlightObject(objectId);
3623
+ this._canvas.changeCursor("text");
3624
+ return this;
3625
+ }
3626
+ }
3627
+ if ((event.type === "click" || event.type === "keydown" && event.key === "Enter") && this._lockedObjectId) {
3628
+ const objectId = this._lockedObjectId;
3629
+ this._canvas.setHighlightColor("#4a90d9");
3630
+ this._canvas.highlightObject(objectId);
3631
+ const handle = {
3632
+ onEnd: () => {
3633
+ this._editingObjectId = null;
3634
+ this._canvas.setHighlightColor(DEFAULT_HIGHLIGHT_COLOR);
3635
+ }
3636
+ };
3637
+ const started = this._canvas.startEditSession(objectId, handle);
3638
+ if (started) {
3639
+ this._editingObjectId = objectId;
3640
+ this._lockedObjectId = null;
3641
+ return this;
3642
+ }
3643
+ this._canvas.clearHighlight();
3644
+ this._canvas.setHighlightColor(DEFAULT_HIGHLIGHT_COLOR);
3645
+ this._canvas.changeCursor("default");
3646
+ this._lockedObjectId = null;
3647
+ }
3648
+ if (this._lockedObjectId) {
3649
+ this._canvas.changeCursor("text");
3650
+ return this;
3651
+ }
3652
+ return null;
3653
+ }
3654
+ render(_node) {
3655
+ }
3656
+ destroy() {
3657
+ }
3658
+ };
3659
+
3660
+ // src/controls/delete_control.ts
3661
+ var DeleteControl = class {
3662
+ constructor(canvas) {
3663
+ this._canvas = canvas;
3664
+ }
3665
+ handleEvent(event) {
3666
+ if (event.type === "keydown" && event.key === "Backspace") {
3667
+ const id = this._canvas.getHighlightedObjectId();
3668
+ if (id) {
3669
+ this._canvas.deleteObject(id);
3670
+ event.preventDefault?.();
3671
+ }
3672
+ return null;
3673
+ }
3674
+ return null;
3675
+ }
3676
+ render(_node) {
3677
+ }
3678
+ destroy() {
3679
+ }
3680
+ };
3681
+
3682
+ // src/controls/keyboard_move_control.ts
3683
+ var ARROW_KEY_STEP = 8;
3684
+ var KeyboardMoveControl = class {
3685
+ constructor(canvas) {
3686
+ this._canvas = canvas;
3687
+ }
3688
+ handleEvent(event) {
3689
+ if (event.type !== "keydown") {
3690
+ return null;
3691
+ }
3692
+ const id = this._canvas.getHighlightedObjectId();
3693
+ if (!id) {
3694
+ return null;
3695
+ }
3696
+ let dx = 0;
3697
+ let dy = 0;
3698
+ if (event.key === "ArrowLeft") {
3699
+ dx = -ARROW_KEY_STEP;
3700
+ } else if (event.key === "ArrowRight") {
3701
+ dx = ARROW_KEY_STEP;
3702
+ } else if (event.key === "ArrowUp") {
3703
+ dy = -ARROW_KEY_STEP;
3704
+ } else if (event.key === "ArrowDown") {
3705
+ dy = ARROW_KEY_STEP;
3706
+ } else {
3707
+ return null;
3708
+ }
3709
+ this._canvas.translateObject(id, dx, dy);
3710
+ event.preventDefault?.();
3711
+ return null;
3712
+ }
3713
+ render(_node) {
3714
+ }
3715
+ destroy() {
3716
+ }
3717
+ };
3718
+
3719
+ // src/editors/text_object_editor.ts
3720
+ var RSTextObjectEditor = class {
3721
+ constructor(_canvas, state, container, handle) {
3722
+ this._editContainer = null;
3723
+ this._destroyed = false;
3724
+ this._state = state;
3725
+ const editable = container;
3726
+ this._editContainer = editable;
3727
+ editable.contentEditable = "true";
3728
+ editable.focus({ preventScroll: true });
3729
+ const sel = window.getSelection();
3730
+ if (sel) {
3731
+ sel.selectAllChildren(editable);
3732
+ sel.collapseToEnd();
3733
+ }
3734
+ const finish = (commit) => {
3735
+ editable.contentEditable = "false";
3736
+ if (commit) {
3737
+ const text = editable.textContent ?? "";
3738
+ this._state = { text };
3739
+ handle.onCommit(this._state);
3740
+ } else {
3741
+ editable.textContent = state.text;
3742
+ }
3743
+ handle.onEnd();
3744
+ this._editContainer = null;
3745
+ };
3746
+ const keyHandler = (e) => {
3747
+ if (e.key === "Enter") {
3748
+ e.preventDefault();
3749
+ editable.blur();
3750
+ } else if (e.key === "Escape") {
3751
+ e.preventDefault();
3752
+ finish(false);
3753
+ }
3754
+ };
3755
+ editable.addEventListener("blur", () => finish(true), { once: true });
3756
+ editable.addEventListener("keydown", keyHandler);
3757
+ }
3758
+ destroy() {
3759
+ if (this._destroyed) {
3760
+ return;
3761
+ }
3762
+ this._destroyed = true;
3763
+ if (this._editContainer) {
3764
+ this._editContainer.blur();
3765
+ }
3766
+ }
3767
+ };
3768
+
3769
+ // src/canvas.ts
3770
+ import html2canvas from "html2canvas";
3771
+ var RESIZE_HANDLE_SIZE = 12;
3772
+ var ROTATION_HANDLE_SIZE2 = 14;
3773
+ var RSCanvas = class {
3774
+ constructor(container, options) {
3775
+ this._scale = 1;
3776
+ this._translateX = 0;
3777
+ this._translateY = 0;
3778
+ this._objects = {};
3779
+ this._objectConstructors = /* @__PURE__ */ new Map();
3780
+ this._objectEditorConstructors = /* @__PURE__ */ new Map();
3781
+ this._editingObjectId = null;
3782
+ this._highlightedObjectId = null;
3783
+ this._highlightColor = "#00d4aa";
3784
+ this._activeControl = null;
3785
+ this._rafId = null;
3786
+ this._listeners = /* @__PURE__ */ new Map();
3787
+ this._destroyed = false;
3788
+ this._dirtyTransform = true;
3789
+ this._pendingState = null;
3790
+ this._internalStateVersion = 0;
3791
+ this._pendingStateVersion = -1;
3792
+ this._cornerPosScratch = { worldX: 0, worldY: 0 };
3793
+ this._boundingClientRect = { left: 0, top: 0 };
3794
+ this._controls = [];
3795
+ this._onMouseDown = (e) => {
3796
+ if (this._destroyed || this._editingObjectId) {
3797
+ return;
3798
+ }
3799
+ const event = this._createPointerEvent("mousedown", e);
3800
+ this._dispatchToControls(event);
3801
+ if (this._activeControl && !this._editingObjectId) {
3802
+ this._containerNode.focus();
3803
+ e.preventDefault();
3804
+ e.stopPropagation();
3805
+ }
3806
+ };
3807
+ this._onMouseUp = (e) => {
3808
+ if (this._destroyed || this._editingObjectId) {
3809
+ return;
3810
+ }
3811
+ const hadActive = !!this._activeControl;
3812
+ const event = this._createPointerEvent("mouseup", e);
3813
+ this._dispatchToControls(event);
3814
+ if (hadActive || this._activeControl) {
3815
+ e.preventDefault();
3816
+ e.stopPropagation();
3817
+ }
3818
+ };
3819
+ this._onMouseEnter = (e) => {
3820
+ if (this._destroyed || this._editingObjectId) {
3821
+ return;
3822
+ }
3823
+ const event = this._createPointerEvent("mouseenter", e);
3824
+ this._emit("mouseenter", event);
3825
+ };
3826
+ this._onMouseLeave = (e) => {
3827
+ if (this._destroyed || this._editingObjectId) {
3828
+ return;
3829
+ }
3830
+ const hadActive = !!this._activeControl;
3831
+ const event = this._createPointerEvent("mouseleave", e);
3832
+ this._dispatchToControls(event);
3833
+ if (hadActive || this._activeControl) {
3834
+ e.preventDefault();
3835
+ e.stopPropagation();
3836
+ }
3837
+ };
3838
+ this._onMouseMove = (e) => {
3839
+ if (this._destroyed || this._editingObjectId) {
3840
+ return;
3841
+ }
3842
+ const hadActive = !!this._activeControl;
3843
+ const event = this._createPointerEvent("mousemove", e);
3844
+ this._dispatchToControls(event);
3845
+ if (hadActive || this._activeControl) {
3846
+ e.preventDefault();
3847
+ e.stopPropagation();
3848
+ }
3849
+ };
3850
+ this._onClick = (e) => {
3851
+ if (this._destroyed || this._editingObjectId) {
3852
+ return;
3853
+ }
3854
+ const event = this._createPointerEvent("click", e);
3855
+ this._dispatchToControls(event);
3856
+ this._emit("click", event);
3857
+ };
3858
+ this._onDblClick = (e) => {
3859
+ if (this._destroyed || this._editingObjectId) {
3860
+ return;
3861
+ }
3862
+ const event = this._createPointerEvent("dblclick", e);
3863
+ this._dispatchToControls(event);
3864
+ };
3865
+ this._onScroll = (e) => {
3866
+ if (this._destroyed || this._editingObjectId) {
3867
+ return;
3868
+ }
3869
+ const event = this._createPointerEvent("scroll", e);
3870
+ this._dispatchToControls(event);
3871
+ };
3872
+ this._onKeyDown = (e) => {
3873
+ if (this._destroyed || this._editingObjectId) {
3874
+ return;
3875
+ }
3876
+ const event = {
3877
+ type: "keydown",
3878
+ viewX: 0,
3879
+ viewY: 0,
3880
+ deltaY: null,
3881
+ preventDefault: () => e.preventDefault(),
3882
+ key: e.key
3883
+ };
3884
+ this._dispatchToControls(event);
3885
+ };
3886
+ this._onKeyUp = (e) => {
3887
+ if (this._destroyed || this._editingObjectId) {
3888
+ return;
3889
+ }
3890
+ const event = {
3891
+ type: "keyup",
3892
+ viewX: 0,
3893
+ viewY: 0,
3894
+ deltaY: null,
3895
+ preventDefault: () => e.preventDefault(),
3896
+ key: e.key
3897
+ };
3898
+ this._dispatchToControls(event);
3899
+ };
3900
+ this._localInvalidate = () => this._invalidate();
3901
+ this._onPaint = () => this._paint();
3902
+ this._containerNode = container;
3903
+ this._width = options?.width ?? 1200;
3904
+ this._height = options?.height ?? 800;
3905
+ this._containerNode.style.overflow = "hidden";
3906
+ this._containerNode.tabIndex = 0;
3907
+ this._containerNode.style.userSelect = "none";
3908
+ this._containerNode.style.webkitUserSelect = "none";
3909
+ this._containerNode.style.background = "#e0e0e0";
3910
+ this._innerContainerNode = document.createElement("div");
3911
+ this._innerContainerNode.style.position = "relative";
3912
+ this._innerContainerNode.style.userSelect = "none";
3913
+ this._innerContainerNode.style.webkitUserSelect = "none";
3914
+ this._innerContainerNode.style.width = `${this._width}px`;
3915
+ this._innerContainerNode.style.height = `${this._height}px`;
3916
+ this._innerContainerNode.style.transformOrigin = "0 0";
3917
+ this._innerContainerNode.style.background = "#ffffff";
3918
+ this._containerNode.appendChild(this._innerContainerNode);
3919
+ this._overlayNode = document.createElement("div");
3920
+ this._overlayNode.style.position = "absolute";
3921
+ this._overlayNode.style.top = "0";
3922
+ this._overlayNode.style.left = "0";
3923
+ this._overlayNode.style.width = "100%";
3924
+ this._overlayNode.style.height = "100%";
3925
+ this._overlayNode.style.pointerEvents = "none";
3926
+ this._overlayNode.style.zIndex = "10";
3927
+ this._innerContainerNode.appendChild(this._overlayNode);
3928
+ this._updateBoundingClientRect();
3929
+ this._resizeObserver = new ResizeObserver(() => {
3930
+ this._updateBoundingClientRect();
3931
+ this._invalidate();
3932
+ });
3933
+ this._resizeObserver.observe(this._containerNode);
3934
+ this.center();
3935
+ this._setupEventListeners();
3936
+ this._controls.push(
3937
+ new ResizeControl(this),
3938
+ new RotationControl(this),
3939
+ new DragControl(this),
3940
+ new PanControl(this),
3941
+ new ZoomControl(this),
3942
+ new EditControl(this),
3943
+ new HighlightControl(this),
3944
+ new KeyboardMoveControl(this),
3945
+ new DeleteControl(this)
3946
+ );
3947
+ this.registerObjectType(
3948
+ "text",
3949
+ (state) => new RSTextObject(state)
3950
+ );
3951
+ this.registerObjectType(
3952
+ "image",
3953
+ (state) => new RSImageObject(state)
3954
+ );
3955
+ this.registerObjectType(
3956
+ "rich-text",
3957
+ (state) => new RSRichTextObject(state)
3958
+ );
3959
+ this.registerObjectTypeEditor(
3960
+ "text",
3961
+ RSTextObjectEditor
3962
+ );
3963
+ }
3964
+ _setupEventListeners() {
3965
+ this._containerNode.addEventListener("mousedown", this._onMouseDown);
3966
+ this._containerNode.addEventListener("mouseup", this._onMouseUp);
3967
+ this._containerNode.addEventListener("mouseenter", this._onMouseEnter);
3968
+ this._containerNode.addEventListener("mouseleave", this._onMouseLeave);
3969
+ this._containerNode.addEventListener("mousemove", this._onMouseMove);
3970
+ this._containerNode.addEventListener("click", this._onClick);
3971
+ this._containerNode.addEventListener("dblclick", this._onDblClick);
3972
+ this._containerNode.addEventListener("wheel", this._onScroll, {
3973
+ passive: false
3974
+ });
3975
+ this._containerNode.addEventListener("keydown", this._onKeyDown);
3976
+ this._containerNode.addEventListener("keyup", this._onKeyUp);
3977
+ }
3978
+ _updateBoundingClientRect() {
3979
+ const rect = this._containerNode.getBoundingClientRect();
3980
+ this._boundingClientRect.left = rect.left;
3981
+ this._boundingClientRect.top = rect.top;
3982
+ }
3983
+ _viewXFromEvent(e) {
3984
+ return e.clientX - this._boundingClientRect.left;
3985
+ }
3986
+ _viewYFromEvent(e) {
3987
+ return e.clientY - this._boundingClientRect.top;
3988
+ }
3989
+ _emit(type, event) {
3990
+ const listeners = this._listeners.get(type);
3991
+ if (listeners) {
3992
+ const fullEvent = { type, ...event };
3993
+ for (const fn of listeners) {
3994
+ fn(fullEvent);
3995
+ }
3996
+ }
3997
+ }
3998
+ _paint() {
3999
+ this._rafId = null;
4000
+ if (this._pendingState) {
4001
+ if (this._pendingStateVersion >= this._internalStateVersion) {
4002
+ this._updateObjectTree(this._pendingState);
4003
+ }
4004
+ this._pendingState = null;
4005
+ }
4006
+ if (this._dirtyTransform) {
4007
+ this._dirtyTransform = false;
4008
+ this._innerContainerNode.style.transform = `translate(${this._translateX}px, ${this._translateY}px) scale(${this._scale})`;
4009
+ }
4010
+ for (const id in this._objects) {
4011
+ this._objects[id].render();
4012
+ }
4013
+ for (const ctrl of this._controls) {
4014
+ ctrl.render(this._overlayNode);
4015
+ }
4016
+ }
4017
+ _invalidate() {
4018
+ if (this._rafId != null) {
4019
+ return;
4020
+ }
4021
+ this._rafId = requestAnimationFrame(this._onPaint);
4022
+ }
4023
+ _cornerWorldPosSFCT(node, corner, out) {
4024
+ const sx = corner === "top-left" || corner === "bottom-left" ? 0 : 1;
4025
+ const sy = corner === "top-left" || corner === "top-right" ? 0 : 1;
4026
+ const x = node.getX();
4027
+ const y = node.getY();
4028
+ const w = node.getWidth();
4029
+ const h = node.getHeight();
4030
+ const r = node.getRotation();
4031
+ const cx = x + w / 2;
4032
+ const cy = y + h / 2;
4033
+ const lx = (sx - 0.5) * w;
4034
+ const ly = (sy - 0.5) * h;
4035
+ const c = Math.cos(r);
4036
+ const s = Math.sin(r);
4037
+ out.worldX = cx + lx * c - ly * s;
4038
+ out.worldY = cy + lx * s + ly * c;
4039
+ }
4040
+ _emitStateChanged() {
4041
+ this._internalStateVersion++;
4042
+ this._emit("stateChanged", {});
4043
+ }
4044
+ _dispatchToControls(event) {
4045
+ if (event.type === "mouseleave") {
4046
+ if (this._activeControl) {
4047
+ this._activeControl.handleEvent(event);
4048
+ this._activeControl = null;
4049
+ } else {
4050
+ for (const ctrl of this._controls) {
4051
+ ctrl.handleEvent(event);
4052
+ }
4053
+ }
4054
+ this.changeCursor("default");
4055
+ this._emit(event.type, event);
4056
+ return;
4057
+ }
4058
+ if (this._activeControl) {
4059
+ const next = this._activeControl.handleEvent(event);
4060
+ if (next !== null) {
4061
+ this._activeControl = next;
4062
+ this._emit(event.type, event);
4063
+ return;
4064
+ }
4065
+ this._activeControl = null;
4066
+ }
4067
+ if (event.type === "mousemove") {
4068
+ this.changeCursor("default");
4069
+ }
4070
+ for (const ctrl of this._controls) {
4071
+ const next = ctrl.handleEvent(event);
4072
+ if (next !== null) {
4073
+ this._activeControl = next;
4074
+ break;
4075
+ }
4076
+ }
4077
+ this._emit(event.type, event);
4078
+ }
4079
+ _createPointerEvent(type, e) {
4080
+ const viewX = this._viewXFromEvent(e);
4081
+ const viewY = this._viewYFromEvent(e);
4082
+ const we = type === "scroll" ? e : null;
4083
+ return {
4084
+ type,
4085
+ viewX,
4086
+ viewY,
4087
+ deltaY: we ? we.deltaY : null,
4088
+ preventDefault: () => e.preventDefault(),
4089
+ metaKey: we?.metaKey,
4090
+ ctrlKey: we?.ctrlKey
4091
+ };
4092
+ }
4093
+ _on(type, fn) {
4094
+ let list = this._listeners.get(type);
4095
+ if (!list) {
4096
+ list = [];
4097
+ this._listeners.set(type, list);
4098
+ }
4099
+ list.push(fn);
4100
+ }
4101
+ _getObjectEditorConstructor(objectType) {
4102
+ return this._objectEditorConstructors.get(objectType) ?? null;
4103
+ }
4104
+ _updateObjectTree(objects) {
4105
+ for (const id in this._objects) {
4106
+ if (!(id in objects)) {
4107
+ this._objects[id].destroy();
4108
+ if (id === this._highlightedObjectId) {
4109
+ this._highlightedObjectId = null;
4110
+ }
4111
+ delete this._objects[id];
4112
+ }
4113
+ }
4114
+ for (const id in objects) {
4115
+ const cfg = objects[id];
4116
+ const existing = this._objects[id];
4117
+ if (existing) {
4118
+ if (existing.getType() !== cfg.type) {
4119
+ throw new Error(`Object "${id}" type changed from "${existing.getType()}" to "${cfg.type}". Type changes are not allowed.`);
4120
+ }
4121
+ existing.move(cfg.x, cfg.y);
4122
+ existing.resize(cfg.width, cfg.height);
4123
+ existing.rotate(cfg.rotation ?? 0);
4124
+ existing.updateState(cfg.options);
4125
+ continue;
4126
+ }
4127
+ const ctor = this._objectConstructors.get(cfg.type);
4128
+ if (!ctor) {
4129
+ console.warn(`No constructor registered for object type "${cfg.type}"`);
4130
+ continue;
4131
+ }
4132
+ const obj = ctor(cfg.options, this._localInvalidate);
4133
+ const node = new RSObjectNode(this._innerContainerNode, obj, cfg.x, cfg.y, cfg.width, cfg.height, cfg.type, id, (oid) => this._editingObjectId === oid, cfg.rotation ?? 0);
4134
+ this._objects[id] = node;
4135
+ }
4136
+ }
4137
+ onHighlight(fn) {
4138
+ this._on("highlight", (e) => fn(e.objectId ?? null));
4139
+ }
4140
+ onStateChanged(fn) {
4141
+ this._on("stateChanged", () => fn(this));
4142
+ }
4143
+ registerObjectType(objectType, constructor) {
4144
+ this._objectConstructors.set(objectType, constructor);
4145
+ }
4146
+ registerObjectTypeEditor(objectType, constructor) {
4147
+ this._objectEditorConstructors.set(objectType, constructor);
4148
+ }
4149
+ setState(state) {
4150
+ this._pendingState = state.objects ?? {};
4151
+ this._pendingStateVersion = this._internalStateVersion;
4152
+ this._invalidate();
4153
+ }
4154
+ getStateSFCT(state) {
4155
+ if (!state.objects) {
4156
+ state.objects = {};
4157
+ }
4158
+ for (const id in this._objects) {
4159
+ const node = this._objects[id];
4160
+ const cfg = state.objects[id];
4161
+ if (cfg) {
4162
+ cfg.type = node.getType();
4163
+ cfg.x = node.getX();
4164
+ cfg.y = node.getY();
4165
+ cfg.width = node.getWidth();
4166
+ cfg.height = node.getHeight();
4167
+ cfg.rotation = node.getRotation();
4168
+ if (!cfg.options) {
4169
+ cfg.options = {};
4170
+ }
4171
+ node.getOptionsSFCT(cfg.options);
4172
+ } else {
4173
+ const options = {};
4174
+ node.getOptionsSFCT(options);
4175
+ state.objects[id] = {
4176
+ type: node.getType(),
4177
+ x: node.getX(),
4178
+ y: node.getY(),
4179
+ width: node.getWidth(),
4180
+ height: node.getHeight(),
4181
+ rotation: node.getRotation(),
4182
+ options
4183
+ };
4184
+ }
4185
+ }
4186
+ for (const id in state.objects) {
4187
+ if (!(id in this._objects)) {
4188
+ delete state.objects[id];
4189
+ }
4190
+ }
4191
+ }
4192
+ changeCursor(cursor) {
4193
+ this._containerNode.style.cursor = cursor;
4194
+ }
4195
+ addControlToFront(ControlCtor) {
4196
+ const control = new ControlCtor(this);
4197
+ this._controls.unshift(control);
4198
+ return control;
4199
+ }
4200
+ getScale() {
4201
+ return this._scale;
4202
+ }
4203
+ toWorldX(viewX) {
4204
+ return (viewX - this._translateX) / this._scale;
4205
+ }
4206
+ toWorldY(viewY) {
4207
+ return (viewY - this._translateY) / this._scale;
4208
+ }
4209
+ toViewX(worldX) {
4210
+ return this._translateX + worldX * this._scale;
4211
+ }
4212
+ toViewY(worldY) {
4213
+ return this._translateY + worldY * this._scale;
4214
+ }
4215
+ objectIdAtXY(viewX, viewY) {
4216
+ const worldX = this.toWorldX(viewX);
4217
+ const worldY = this.toWorldY(viewY);
4218
+ for (const id in this._objects) {
4219
+ if (this._objects[id].interacts(worldX, worldY)) {
4220
+ return id;
4221
+ }
4222
+ }
4223
+ return null;
4224
+ }
4225
+ objectIdAtLowerRightCorner(viewX, viewY) {
4226
+ const worldX = this.toWorldX(viewX);
4227
+ const worldY = this.toWorldY(viewY);
4228
+ const threshold = RESIZE_HANDLE_SIZE / this._scale;
4229
+ const out = this._cornerPosScratch;
4230
+ for (const id in this._objects) {
4231
+ this._cornerWorldPosSFCT(this._objects[id], "bottom-right", out);
4232
+ if (Math.abs(worldX - out.worldX) <= threshold && Math.abs(worldY - out.worldY) <= threshold) {
4233
+ return this._objects[id].getId();
4234
+ }
4235
+ }
4236
+ return null;
4237
+ }
4238
+ objectIdAtUpperRightCorner(viewX, viewY) {
4239
+ const worldX = this.toWorldX(viewX);
4240
+ const worldY = this.toWorldY(viewY);
4241
+ const threshold = ROTATION_HANDLE_SIZE2 / this._scale;
4242
+ const out = this._cornerPosScratch;
4243
+ for (const id in this._objects) {
4244
+ this._cornerWorldPosSFCT(this._objects[id], "top-right", out);
4245
+ if (Math.abs(worldX - out.worldX) <= threshold && Math.abs(worldY - out.worldY) <= threshold) {
4246
+ return this._objects[id].getId();
4247
+ }
4248
+ }
4249
+ return null;
4250
+ }
4251
+ getCornerWorldXYSFCT(objectId, corner, out) {
4252
+ const node = this._objects[objectId];
4253
+ if (!node) {
4254
+ return false;
4255
+ }
4256
+ this._cornerWorldPosSFCT(node, corner, out);
4257
+ return true;
4258
+ }
4259
+ getCanvasWidth() {
4260
+ return this._width;
4261
+ }
4262
+ getCanvasHeight() {
4263
+ return this._height;
4264
+ }
4265
+ getObjectNode(objectId) {
4266
+ return this._objects[objectId] ?? null;
4267
+ }
4268
+ resizeObject(objectId, dw, dh) {
4269
+ const node = this._objects[objectId];
4270
+ if (!node) {
4271
+ return;
4272
+ }
4273
+ const w = node.getWidth();
4274
+ const h = node.getHeight();
4275
+ node.resize(Math.max(1, w + dw), Math.max(1, h + dh));
4276
+ this._emitStateChanged();
4277
+ this._invalidate();
4278
+ }
4279
+ rotateObject(objectId, dAngle) {
4280
+ const node = this._objects[objectId];
4281
+ if (!node) {
4282
+ return;
4283
+ }
4284
+ node.rotate(node.getRotation() + dAngle);
4285
+ this._emitStateChanged();
4286
+ this._invalidate();
4287
+ }
4288
+ translateObject(objectId, dx, dy) {
4289
+ const node = this._objects[objectId];
4290
+ if (!node) {
4291
+ return;
4292
+ }
4293
+ node.translate(dx, dy);
4294
+ this._emitStateChanged();
4295
+ this._invalidate();
4296
+ }
4297
+ translate(dx, dy) {
4298
+ this._translateX += dx;
4299
+ this._translateY += dy;
4300
+ this._dirtyTransform = true;
4301
+ this._invalidate();
4302
+ }
4303
+ scaleAtXY(scaleFactor, viewX, viewY) {
4304
+ const worldX = this.toWorldX(viewX);
4305
+ const worldY = this.toWorldY(viewY);
4306
+ this._scale *= scaleFactor;
4307
+ this._translateX = viewX - worldX * this._scale;
4308
+ this._translateY = viewY - worldY * this._scale;
4309
+ this._dirtyTransform = true;
4310
+ this._invalidate();
4311
+ }
4312
+ center() {
4313
+ const padding = 8;
4314
+ const cw = this._containerNode.clientWidth - padding * 2;
4315
+ const ch = this._containerNode.clientHeight - padding * 2;
4316
+ this._scale = Math.min(cw / this._width, ch / this._height);
4317
+ this._translateX = (this._containerNode.clientWidth - this._width * this._scale) / 2;
4318
+ this._translateY = (this._containerNode.clientHeight - this._height * this._scale) / 2;
4319
+ this._dirtyTransform = true;
4320
+ this._invalidate();
4321
+ }
4322
+ highlightObject(id) {
4323
+ if (!(id in this._objects)) {
4324
+ return;
4325
+ }
4326
+ if (this._highlightedObjectId && this._highlightedObjectId !== id) {
4327
+ this._objects[this._highlightedObjectId]?.unhighlight();
4328
+ this._invalidate();
4329
+ }
4330
+ if (id !== this._highlightedObjectId) {
4331
+ this._highlightedObjectId = id;
4332
+ this._objects[id]?.highlight(this._highlightColor);
4333
+ this._containerNode.focus();
4334
+ this._invalidate();
4335
+ this._emit("highlight", { objectId: id });
4336
+ }
4337
+ }
4338
+ clearHighlight() {
4339
+ if (!this._highlightedObjectId) {
4340
+ return;
4341
+ }
4342
+ this._objects[this._highlightedObjectId]?.unhighlight();
4343
+ this._emit("highlight", { objectId: null });
4344
+ this._highlightedObjectId = null;
4345
+ this._invalidate();
4346
+ }
4347
+ setHighlightColor(color) {
4348
+ this._highlightColor = color;
4349
+ if (this._highlightedObjectId) {
4350
+ this._objects[this._highlightedObjectId]?.highlight(color);
4351
+ this._invalidate();
4352
+ }
4353
+ }
4354
+ getHighlightedObjectId() {
4355
+ return this._highlightedObjectId;
4356
+ }
4357
+ canEditObject(objectId) {
4358
+ const node = this._objects[objectId];
4359
+ return node ? this._objectEditorConstructors.has(node.getType()) : false;
4360
+ }
4361
+ startEditSession(objectId, hostHandle) {
4362
+ const node = this._objects[objectId];
4363
+ if (!node) {
4364
+ return false;
4365
+ }
4366
+ const EditorCtor = this._getObjectEditorConstructor(node.getType());
4367
+ if (!EditorCtor) {
4368
+ return false;
4369
+ }
4370
+ this._editingObjectId = objectId;
4371
+ const container = node.getContainerNode();
4372
+ const options = {};
4373
+ node.getOptionsSFCT(options);
4374
+ const editorHandle = {
4375
+ onCommit: (newState) => {
4376
+ node.updateState(newState);
4377
+ this._emitStateChanged();
4378
+ this._invalidate();
4379
+ },
4380
+ onEnd: () => {
4381
+ this._editingObjectId = null;
4382
+ hostHandle.onEnd();
4383
+ this._invalidate();
4384
+ }
4385
+ };
4386
+ const editor = new EditorCtor(this, options, container, editorHandle);
4387
+ editor._sessionHandle = hostHandle;
4388
+ return true;
4389
+ }
4390
+ deleteObject(objectId) {
4391
+ const node = this._objects[objectId];
4392
+ if (!node) {
4393
+ return;
4394
+ }
4395
+ node.destroy();
4396
+ delete this._objects[objectId];
4397
+ if (this._highlightedObjectId === objectId) {
4398
+ this._highlightedObjectId = null;
4399
+ }
4400
+ this._emitStateChanged();
4401
+ this._invalidate();
4402
+ }
4403
+ async saveToImage(callback) {
4404
+ const clone = this._innerContainerNode.cloneNode(true);
4405
+ clone.style.transform = "none";
4406
+ clone.style.position = "fixed";
4407
+ clone.style.left = "-9999px";
4408
+ clone.style.top = "0";
4409
+ clone.style.zIndex = "-1";
4410
+ const overlayClone = clone.lastElementChild;
4411
+ if (overlayClone) {
4412
+ overlayClone.style.visibility = "hidden";
4413
+ }
4414
+ document.body.appendChild(clone);
4415
+ const imgs = clone.querySelectorAll("img");
4416
+ await Promise.all(
4417
+ Array.from(imgs).map(async (img) => {
4418
+ const src = img.getAttribute("src") ?? "";
4419
+ if (src.startsWith("blob:")) {
4420
+ try {
4421
+ const blob = await fetch(src).then((r) => r.blob());
4422
+ const dataUrl = await new Promise((resolve, reject) => {
4423
+ const r = new FileReader();
4424
+ r.onload = () => resolve(r.result);
4425
+ r.onerror = reject;
4426
+ r.readAsDataURL(blob);
4427
+ });
4428
+ img.src = dataUrl;
4429
+ } catch {
4430
+ }
4431
+ } else if (src.startsWith("http://") || src.startsWith("https://")) {
4432
+ img.setAttribute("crossorigin", "anonymous");
4433
+ }
4434
+ })
4435
+ );
4436
+ await Promise.all(
4437
+ Array.from(clone.querySelectorAll("img")).map(
4438
+ (img) => new Promise((resolve) => {
4439
+ if (img.complete) {
4440
+ resolve();
4441
+ return;
4442
+ }
4443
+ img.onload = () => resolve();
4444
+ img.onerror = () => resolve();
4445
+ setTimeout(resolve, 5e3);
4446
+ })
4447
+ )
4448
+ );
4449
+ try {
4450
+ const canvas = await html2canvas(clone, {
4451
+ scale: 1,
4452
+ useCORS: true
4453
+ });
4454
+ const blob = await new Promise((resolve) => {
4455
+ canvas.toBlob((b) => resolve(b), "image/png");
4456
+ });
4457
+ if (blob) {
4458
+ callback(blob);
4459
+ }
4460
+ } finally {
4461
+ clone.remove();
4462
+ }
4463
+ }
4464
+ destroy() {
4465
+ if (this._destroyed) {
4466
+ return;
4467
+ }
4468
+ this._destroyed = true;
4469
+ this._resizeObserver.disconnect();
4470
+ if (this._rafId != null) {
4471
+ cancelAnimationFrame(this._rafId);
4472
+ this._rafId = null;
4473
+ }
4474
+ this._activeControl = null;
4475
+ this._dispatchToControls({
4476
+ type: "mouseleave",
4477
+ viewX: 0,
4478
+ viewY: 0,
4479
+ deltaY: null,
4480
+ preventDefault: () => {
4481
+ }
4482
+ });
4483
+ this._containerNode.removeEventListener("mousedown", this._onMouseDown);
4484
+ this._containerNode.removeEventListener("mouseup", this._onMouseUp);
4485
+ this._containerNode.removeEventListener("mouseenter", this._onMouseEnter);
4486
+ this._containerNode.removeEventListener("mouseleave", this._onMouseLeave);
4487
+ this._containerNode.removeEventListener("mousemove", this._onMouseMove);
4488
+ this._containerNode.removeEventListener("click", this._onClick);
4489
+ this._containerNode.removeEventListener("dblclick", this._onDblClick);
4490
+ this._containerNode.removeEventListener("wheel", this._onScroll);
4491
+ this._containerNode.removeEventListener("keydown", this._onKeyDown);
4492
+ this._containerNode.removeEventListener("keyup", this._onKeyUp);
4493
+ for (const ctrl of this._controls) {
4494
+ ctrl.destroy();
4495
+ }
4496
+ for (const id in this._objects) {
4497
+ this._objects[id].destroy();
4498
+ }
4499
+ this._objects = {};
4500
+ this._innerContainerNode.remove();
4501
+ }
4502
+ };
4503
+ export {
4504
+ RSCanvas,
4505
+ richTextSchema
4506
+ };
4507
+ //# sourceMappingURL=index.mjs.map