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