@tiptap/extension-link 2.0.0-beta.214 → 2.0.0-beta.216

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.cjs CHANGED
@@ -4,3447 +4,11 @@ Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var core = require('@tiptap/core');
6
6
  var linkifyjs = require('linkifyjs');
7
-
8
- function findDiffStart(a, b, pos) {
9
- for (let i = 0;; i++) {
10
- if (i == a.childCount || i == b.childCount)
11
- return a.childCount == b.childCount ? null : pos;
12
- let childA = a.child(i), childB = b.child(i);
13
- if (childA == childB) {
14
- pos += childA.nodeSize;
15
- continue;
16
- }
17
- if (!childA.sameMarkup(childB))
18
- return pos;
19
- if (childA.isText && childA.text != childB.text) {
20
- for (let j = 0; childA.text[j] == childB.text[j]; j++)
21
- pos++;
22
- return pos;
23
- }
24
- if (childA.content.size || childB.content.size) {
25
- let inner = findDiffStart(childA.content, childB.content, pos + 1);
26
- if (inner != null)
27
- return inner;
28
- }
29
- pos += childA.nodeSize;
30
- }
31
- }
32
- function findDiffEnd(a, b, posA, posB) {
33
- for (let iA = a.childCount, iB = b.childCount;;) {
34
- if (iA == 0 || iB == 0)
35
- return iA == iB ? null : { a: posA, b: posB };
36
- let childA = a.child(--iA), childB = b.child(--iB), size = childA.nodeSize;
37
- if (childA == childB) {
38
- posA -= size;
39
- posB -= size;
40
- continue;
41
- }
42
- if (!childA.sameMarkup(childB))
43
- return { a: posA, b: posB };
44
- if (childA.isText && childA.text != childB.text) {
45
- let same = 0, minSize = Math.min(childA.text.length, childB.text.length);
46
- while (same < minSize && childA.text[childA.text.length - same - 1] == childB.text[childB.text.length - same - 1]) {
47
- same++;
48
- posA--;
49
- posB--;
50
- }
51
- return { a: posA, b: posB };
52
- }
53
- if (childA.content.size || childB.content.size) {
54
- let inner = findDiffEnd(childA.content, childB.content, posA - 1, posB - 1);
55
- if (inner)
56
- return inner;
57
- }
58
- posA -= size;
59
- posB -= size;
60
- }
61
- }
62
-
63
- /**
64
- A fragment represents a node's collection of child nodes.
65
-
66
- Like nodes, fragments are persistent data structures, and you
67
- should not mutate them or their content. Rather, you create new
68
- instances whenever needed. The API tries to make this easy.
69
- */
70
- class Fragment {
71
- /**
72
- @internal
73
- */
74
- constructor(
75
- /**
76
- @internal
77
- */
78
- content, size) {
79
- this.content = content;
80
- this.size = size || 0;
81
- if (size == null)
82
- for (let i = 0; i < content.length; i++)
83
- this.size += content[i].nodeSize;
84
- }
85
- /**
86
- Invoke a callback for all descendant nodes between the given two
87
- positions (relative to start of this fragment). Doesn't descend
88
- into a node when the callback returns `false`.
89
- */
90
- nodesBetween(from, to, f, nodeStart = 0, parent) {
91
- for (let i = 0, pos = 0; pos < to; i++) {
92
- let child = this.content[i], end = pos + child.nodeSize;
93
- if (end > from && f(child, nodeStart + pos, parent || null, i) !== false && child.content.size) {
94
- let start = pos + 1;
95
- child.nodesBetween(Math.max(0, from - start), Math.min(child.content.size, to - start), f, nodeStart + start);
96
- }
97
- pos = end;
98
- }
99
- }
100
- /**
101
- Call the given callback for every descendant node. `pos` will be
102
- relative to the start of the fragment. The callback may return
103
- `false` to prevent traversal of a given node's children.
104
- */
105
- descendants(f) {
106
- this.nodesBetween(0, this.size, f);
107
- }
108
- /**
109
- Extract the text between `from` and `to`. See the same method on
110
- [`Node`](https://prosemirror.net/docs/ref/#model.Node.textBetween).
111
- */
112
- textBetween(from, to, blockSeparator, leafText) {
113
- let text = "", separated = true;
114
- this.nodesBetween(from, to, (node, pos) => {
115
- if (node.isText) {
116
- text += node.text.slice(Math.max(from, pos) - pos, to - pos);
117
- separated = !blockSeparator;
118
- }
119
- else if (node.isLeaf) {
120
- if (leafText) {
121
- text += typeof leafText === "function" ? leafText(node) : leafText;
122
- }
123
- else if (node.type.spec.leafText) {
124
- text += node.type.spec.leafText(node);
125
- }
126
- separated = !blockSeparator;
127
- }
128
- else if (!separated && node.isBlock) {
129
- text += blockSeparator;
130
- separated = true;
131
- }
132
- }, 0);
133
- return text;
134
- }
135
- /**
136
- Create a new fragment containing the combined content of this
137
- fragment and the other.
138
- */
139
- append(other) {
140
- if (!other.size)
141
- return this;
142
- if (!this.size)
143
- return other;
144
- let last = this.lastChild, first = other.firstChild, content = this.content.slice(), i = 0;
145
- if (last.isText && last.sameMarkup(first)) {
146
- content[content.length - 1] = last.withText(last.text + first.text);
147
- i = 1;
148
- }
149
- for (; i < other.content.length; i++)
150
- content.push(other.content[i]);
151
- return new Fragment(content, this.size + other.size);
152
- }
153
- /**
154
- Cut out the sub-fragment between the two given positions.
155
- */
156
- cut(from, to = this.size) {
157
- if (from == 0 && to == this.size)
158
- return this;
159
- let result = [], size = 0;
160
- if (to > from)
161
- for (let i = 0, pos = 0; pos < to; i++) {
162
- let child = this.content[i], end = pos + child.nodeSize;
163
- if (end > from) {
164
- if (pos < from || end > to) {
165
- if (child.isText)
166
- child = child.cut(Math.max(0, from - pos), Math.min(child.text.length, to - pos));
167
- else
168
- child = child.cut(Math.max(0, from - pos - 1), Math.min(child.content.size, to - pos - 1));
169
- }
170
- result.push(child);
171
- size += child.nodeSize;
172
- }
173
- pos = end;
174
- }
175
- return new Fragment(result, size);
176
- }
177
- /**
178
- @internal
179
- */
180
- cutByIndex(from, to) {
181
- if (from == to)
182
- return Fragment.empty;
183
- if (from == 0 && to == this.content.length)
184
- return this;
185
- return new Fragment(this.content.slice(from, to));
186
- }
187
- /**
188
- Create a new fragment in which the node at the given index is
189
- replaced by the given node.
190
- */
191
- replaceChild(index, node) {
192
- let current = this.content[index];
193
- if (current == node)
194
- return this;
195
- let copy = this.content.slice();
196
- let size = this.size + node.nodeSize - current.nodeSize;
197
- copy[index] = node;
198
- return new Fragment(copy, size);
199
- }
200
- /**
201
- Create a new fragment by prepending the given node to this
202
- fragment.
203
- */
204
- addToStart(node) {
205
- return new Fragment([node].concat(this.content), this.size + node.nodeSize);
206
- }
207
- /**
208
- Create a new fragment by appending the given node to this
209
- fragment.
210
- */
211
- addToEnd(node) {
212
- return new Fragment(this.content.concat(node), this.size + node.nodeSize);
213
- }
214
- /**
215
- Compare this fragment to another one.
216
- */
217
- eq(other) {
218
- if (this.content.length != other.content.length)
219
- return false;
220
- for (let i = 0; i < this.content.length; i++)
221
- if (!this.content[i].eq(other.content[i]))
222
- return false;
223
- return true;
224
- }
225
- /**
226
- The first child of the fragment, or `null` if it is empty.
227
- */
228
- get firstChild() { return this.content.length ? this.content[0] : null; }
229
- /**
230
- The last child of the fragment, or `null` if it is empty.
231
- */
232
- get lastChild() { return this.content.length ? this.content[this.content.length - 1] : null; }
233
- /**
234
- The number of child nodes in this fragment.
235
- */
236
- get childCount() { return this.content.length; }
237
- /**
238
- Get the child node at the given index. Raise an error when the
239
- index is out of range.
240
- */
241
- child(index) {
242
- let found = this.content[index];
243
- if (!found)
244
- throw new RangeError("Index " + index + " out of range for " + this);
245
- return found;
246
- }
247
- /**
248
- Get the child node at the given index, if it exists.
249
- */
250
- maybeChild(index) {
251
- return this.content[index] || null;
252
- }
253
- /**
254
- Call `f` for every child node, passing the node, its offset
255
- into this parent node, and its index.
256
- */
257
- forEach(f) {
258
- for (let i = 0, p = 0; i < this.content.length; i++) {
259
- let child = this.content[i];
260
- f(child, p, i);
261
- p += child.nodeSize;
262
- }
263
- }
264
- /**
265
- Find the first position at which this fragment and another
266
- fragment differ, or `null` if they are the same.
267
- */
268
- findDiffStart(other, pos = 0) {
269
- return findDiffStart(this, other, pos);
270
- }
271
- /**
272
- Find the first position, searching from the end, at which this
273
- fragment and the given fragment differ, or `null` if they are
274
- the same. Since this position will not be the same in both
275
- nodes, an object with two separate positions is returned.
276
- */
277
- findDiffEnd(other, pos = this.size, otherPos = other.size) {
278
- return findDiffEnd(this, other, pos, otherPos);
279
- }
280
- /**
281
- Find the index and inner offset corresponding to a given relative
282
- position in this fragment. The result object will be reused
283
- (overwritten) the next time the function is called. (Not public.)
284
- */
285
- findIndex(pos, round = -1) {
286
- if (pos == 0)
287
- return retIndex(0, pos);
288
- if (pos == this.size)
289
- return retIndex(this.content.length, pos);
290
- if (pos > this.size || pos < 0)
291
- throw new RangeError(`Position ${pos} outside of fragment (${this})`);
292
- for (let i = 0, curPos = 0;; i++) {
293
- let cur = this.child(i), end = curPos + cur.nodeSize;
294
- if (end >= pos) {
295
- if (end == pos || round > 0)
296
- return retIndex(i + 1, end);
297
- return retIndex(i, curPos);
298
- }
299
- curPos = end;
300
- }
301
- }
302
- /**
303
- Return a debugging string that describes this fragment.
304
- */
305
- toString() { return "<" + this.toStringInner() + ">"; }
306
- /**
307
- @internal
308
- */
309
- toStringInner() { return this.content.join(", "); }
310
- /**
311
- Create a JSON-serializeable representation of this fragment.
312
- */
313
- toJSON() {
314
- return this.content.length ? this.content.map(n => n.toJSON()) : null;
315
- }
316
- /**
317
- Deserialize a fragment from its JSON representation.
318
- */
319
- static fromJSON(schema, value) {
320
- if (!value)
321
- return Fragment.empty;
322
- if (!Array.isArray(value))
323
- throw new RangeError("Invalid input for Fragment.fromJSON");
324
- return new Fragment(value.map(schema.nodeFromJSON));
325
- }
326
- /**
327
- Build a fragment from an array of nodes. Ensures that adjacent
328
- text nodes with the same marks are joined together.
329
- */
330
- static fromArray(array) {
331
- if (!array.length)
332
- return Fragment.empty;
333
- let joined, size = 0;
334
- for (let i = 0; i < array.length; i++) {
335
- let node = array[i];
336
- size += node.nodeSize;
337
- if (i && node.isText && array[i - 1].sameMarkup(node)) {
338
- if (!joined)
339
- joined = array.slice(0, i);
340
- joined[joined.length - 1] = node
341
- .withText(joined[joined.length - 1].text + node.text);
342
- }
343
- else if (joined) {
344
- joined.push(node);
345
- }
346
- }
347
- return new Fragment(joined || array, size);
348
- }
349
- /**
350
- Create a fragment from something that can be interpreted as a
351
- set of nodes. For `null`, it returns the empty fragment. For a
352
- fragment, the fragment itself. For a node or array of nodes, a
353
- fragment containing those nodes.
354
- */
355
- static from(nodes) {
356
- if (!nodes)
357
- return Fragment.empty;
358
- if (nodes instanceof Fragment)
359
- return nodes;
360
- if (Array.isArray(nodes))
361
- return this.fromArray(nodes);
362
- if (nodes.attrs)
363
- return new Fragment([nodes], nodes.nodeSize);
364
- throw new RangeError("Can not convert " + nodes + " to a Fragment" +
365
- (nodes.nodesBetween ? " (looks like multiple versions of prosemirror-model were loaded)" : ""));
366
- }
367
- }
368
- /**
369
- An empty fragment. Intended to be reused whenever a node doesn't
370
- contain anything (rather than allocating a new empty fragment for
371
- each leaf node).
372
- */
373
- Fragment.empty = new Fragment([], 0);
374
- const found = { index: 0, offset: 0 };
375
- function retIndex(index, offset) {
376
- found.index = index;
377
- found.offset = offset;
378
- return found;
379
- }
380
-
381
- function compareDeep(a, b) {
382
- if (a === b)
383
- return true;
384
- if (!(a && typeof a == "object") ||
385
- !(b && typeof b == "object"))
386
- return false;
387
- let array = Array.isArray(a);
388
- if (Array.isArray(b) != array)
389
- return false;
390
- if (array) {
391
- if (a.length != b.length)
392
- return false;
393
- for (let i = 0; i < a.length; i++)
394
- if (!compareDeep(a[i], b[i]))
395
- return false;
396
- }
397
- else {
398
- for (let p in a)
399
- if (!(p in b) || !compareDeep(a[p], b[p]))
400
- return false;
401
- for (let p in b)
402
- if (!(p in a))
403
- return false;
404
- }
405
- return true;
406
- }
407
-
408
- /**
409
- A mark is a piece of information that can be attached to a node,
410
- such as it being emphasized, in code font, or a link. It has a
411
- type and optionally a set of attributes that provide further
412
- information (such as the target of the link). Marks are created
413
- through a `Schema`, which controls which types exist and which
414
- attributes they have.
415
- */
416
- class Mark {
417
- /**
418
- @internal
419
- */
420
- constructor(
421
- /**
422
- The type of this mark.
423
- */
424
- type,
425
- /**
426
- The attributes associated with this mark.
427
- */
428
- attrs) {
429
- this.type = type;
430
- this.attrs = attrs;
431
- }
432
- /**
433
- Given a set of marks, create a new set which contains this one as
434
- well, in the right position. If this mark is already in the set,
435
- the set itself is returned. If any marks that are set to be
436
- [exclusive](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) with this mark are present,
437
- those are replaced by this one.
438
- */
439
- addToSet(set) {
440
- let copy, placed = false;
441
- for (let i = 0; i < set.length; i++) {
442
- let other = set[i];
443
- if (this.eq(other))
444
- return set;
445
- if (this.type.excludes(other.type)) {
446
- if (!copy)
447
- copy = set.slice(0, i);
448
- }
449
- else if (other.type.excludes(this.type)) {
450
- return set;
451
- }
452
- else {
453
- if (!placed && other.type.rank > this.type.rank) {
454
- if (!copy)
455
- copy = set.slice(0, i);
456
- copy.push(this);
457
- placed = true;
458
- }
459
- if (copy)
460
- copy.push(other);
461
- }
462
- }
463
- if (!copy)
464
- copy = set.slice();
465
- if (!placed)
466
- copy.push(this);
467
- return copy;
468
- }
469
- /**
470
- Remove this mark from the given set, returning a new set. If this
471
- mark is not in the set, the set itself is returned.
472
- */
473
- removeFromSet(set) {
474
- for (let i = 0; i < set.length; i++)
475
- if (this.eq(set[i]))
476
- return set.slice(0, i).concat(set.slice(i + 1));
477
- return set;
478
- }
479
- /**
480
- Test whether this mark is in the given set of marks.
481
- */
482
- isInSet(set) {
483
- for (let i = 0; i < set.length; i++)
484
- if (this.eq(set[i]))
485
- return true;
486
- return false;
487
- }
488
- /**
489
- Test whether this mark has the same type and attributes as
490
- another mark.
491
- */
492
- eq(other) {
493
- return this == other ||
494
- (this.type == other.type && compareDeep(this.attrs, other.attrs));
495
- }
496
- /**
497
- Convert this mark to a JSON-serializeable representation.
498
- */
499
- toJSON() {
500
- let obj = { type: this.type.name };
501
- for (let _ in this.attrs) {
502
- obj.attrs = this.attrs;
503
- break;
504
- }
505
- return obj;
506
- }
507
- /**
508
- Deserialize a mark from JSON.
509
- */
510
- static fromJSON(schema, json) {
511
- if (!json)
512
- throw new RangeError("Invalid input for Mark.fromJSON");
513
- let type = schema.marks[json.type];
514
- if (!type)
515
- throw new RangeError(`There is no mark type ${json.type} in this schema`);
516
- return type.create(json.attrs);
517
- }
518
- /**
519
- Test whether two sets of marks are identical.
520
- */
521
- static sameSet(a, b) {
522
- if (a == b)
523
- return true;
524
- if (a.length != b.length)
525
- return false;
526
- for (let i = 0; i < a.length; i++)
527
- if (!a[i].eq(b[i]))
528
- return false;
529
- return true;
530
- }
531
- /**
532
- Create a properly sorted mark set from null, a single mark, or an
533
- unsorted array of marks.
534
- */
535
- static setFrom(marks) {
536
- if (!marks || Array.isArray(marks) && marks.length == 0)
537
- return Mark.none;
538
- if (marks instanceof Mark)
539
- return [marks];
540
- let copy = marks.slice();
541
- copy.sort((a, b) => a.type.rank - b.type.rank);
542
- return copy;
543
- }
544
- }
545
- /**
546
- The empty set of marks.
547
- */
548
- Mark.none = [];
549
-
550
- /**
551
- Error type raised by [`Node.replace`](https://prosemirror.net/docs/ref/#model.Node.replace) when
552
- given an invalid replacement.
553
- */
554
- class ReplaceError extends Error {
555
- }
556
- /*
557
- ReplaceError = function(this: any, message: string) {
558
- let err = Error.call(this, message)
559
- ;(err as any).__proto__ = ReplaceError.prototype
560
- return err
561
- } as any
562
-
563
- ReplaceError.prototype = Object.create(Error.prototype)
564
- ReplaceError.prototype.constructor = ReplaceError
565
- ReplaceError.prototype.name = "ReplaceError"
566
- */
567
- /**
568
- A slice represents a piece cut out of a larger document. It
569
- stores not only a fragment, but also the depth up to which nodes on
570
- both side are ‘open’ (cut through).
571
- */
572
- class Slice {
573
- /**
574
- Create a slice. When specifying a non-zero open depth, you must
575
- make sure that there are nodes of at least that depth at the
576
- appropriate side of the fragment—i.e. if the fragment is an
577
- empty paragraph node, `openStart` and `openEnd` can't be greater
578
- than 1.
579
-
580
- It is not necessary for the content of open nodes to conform to
581
- the schema's content constraints, though it should be a valid
582
- start/end/middle for such a node, depending on which sides are
583
- open.
584
- */
585
- constructor(
586
- /**
587
- The slice's content.
588
- */
589
- content,
590
- /**
591
- The open depth at the start of the fragment.
592
- */
593
- openStart,
594
- /**
595
- The open depth at the end.
596
- */
597
- openEnd) {
598
- this.content = content;
599
- this.openStart = openStart;
600
- this.openEnd = openEnd;
601
- }
602
- /**
603
- The size this slice would add when inserted into a document.
604
- */
605
- get size() {
606
- return this.content.size - this.openStart - this.openEnd;
607
- }
608
- /**
609
- @internal
610
- */
611
- insertAt(pos, fragment) {
612
- let content = insertInto(this.content, pos + this.openStart, fragment);
613
- return content && new Slice(content, this.openStart, this.openEnd);
614
- }
615
- /**
616
- @internal
617
- */
618
- removeBetween(from, to) {
619
- return new Slice(removeRange(this.content, from + this.openStart, to + this.openStart), this.openStart, this.openEnd);
620
- }
621
- /**
622
- Tests whether this slice is equal to another slice.
623
- */
624
- eq(other) {
625
- return this.content.eq(other.content) && this.openStart == other.openStart && this.openEnd == other.openEnd;
626
- }
627
- /**
628
- @internal
629
- */
630
- toString() {
631
- return this.content + "(" + this.openStart + "," + this.openEnd + ")";
632
- }
633
- /**
634
- Convert a slice to a JSON-serializable representation.
635
- */
636
- toJSON() {
637
- if (!this.content.size)
638
- return null;
639
- let json = { content: this.content.toJSON() };
640
- if (this.openStart > 0)
641
- json.openStart = this.openStart;
642
- if (this.openEnd > 0)
643
- json.openEnd = this.openEnd;
644
- return json;
645
- }
646
- /**
647
- Deserialize a slice from its JSON representation.
648
- */
649
- static fromJSON(schema, json) {
650
- if (!json)
651
- return Slice.empty;
652
- let openStart = json.openStart || 0, openEnd = json.openEnd || 0;
653
- if (typeof openStart != "number" || typeof openEnd != "number")
654
- throw new RangeError("Invalid input for Slice.fromJSON");
655
- return new Slice(Fragment.fromJSON(schema, json.content), openStart, openEnd);
656
- }
657
- /**
658
- Create a slice from a fragment by taking the maximum possible
659
- open value on both side of the fragment.
660
- */
661
- static maxOpen(fragment, openIsolating = true) {
662
- let openStart = 0, openEnd = 0;
663
- for (let n = fragment.firstChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.firstChild)
664
- openStart++;
665
- for (let n = fragment.lastChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.lastChild)
666
- openEnd++;
667
- return new Slice(fragment, openStart, openEnd);
668
- }
669
- }
670
- /**
671
- The empty slice.
672
- */
673
- Slice.empty = new Slice(Fragment.empty, 0, 0);
674
- function removeRange(content, from, to) {
675
- let { index, offset } = content.findIndex(from), child = content.maybeChild(index);
676
- let { index: indexTo, offset: offsetTo } = content.findIndex(to);
677
- if (offset == from || child.isText) {
678
- if (offsetTo != to && !content.child(indexTo).isText)
679
- throw new RangeError("Removing non-flat range");
680
- return content.cut(0, from).append(content.cut(to));
681
- }
682
- if (index != indexTo)
683
- throw new RangeError("Removing non-flat range");
684
- return content.replaceChild(index, child.copy(removeRange(child.content, from - offset - 1, to - offset - 1)));
685
- }
686
- function insertInto(content, dist, insert, parent) {
687
- let { index, offset } = content.findIndex(dist), child = content.maybeChild(index);
688
- if (offset == dist || child.isText) {
689
- if (parent && !parent.canReplace(index, index, insert))
690
- return null;
691
- return content.cut(0, dist).append(insert).append(content.cut(dist));
692
- }
693
- let inner = insertInto(child.content, dist - offset - 1, insert);
694
- return inner && content.replaceChild(index, child.copy(inner));
695
- }
696
-
697
- // For node types where all attrs have a default value (or which don't
698
- // have any attributes), build up a single reusable default attribute
699
- // object, and use it for all nodes that don't specify specific
700
- // attributes.
701
- function defaultAttrs(attrs) {
702
- let defaults = Object.create(null);
703
- for (let attrName in attrs) {
704
- let attr = attrs[attrName];
705
- if (!attr.hasDefault)
706
- return null;
707
- defaults[attrName] = attr.default;
708
- }
709
- return defaults;
710
- }
711
- function computeAttrs(attrs, value) {
712
- let built = Object.create(null);
713
- for (let name in attrs) {
714
- let given = value && value[name];
715
- if (given === undefined) {
716
- let attr = attrs[name];
717
- if (attr.hasDefault)
718
- given = attr.default;
719
- else
720
- throw new RangeError("No value supplied for attribute " + name);
721
- }
722
- built[name] = given;
723
- }
724
- return built;
725
- }
726
- function initAttrs(attrs) {
727
- let result = Object.create(null);
728
- if (attrs)
729
- for (let name in attrs)
730
- result[name] = new Attribute(attrs[name]);
731
- return result;
732
- }
733
- // Attribute descriptors
734
- class Attribute {
735
- constructor(options) {
736
- this.hasDefault = Object.prototype.hasOwnProperty.call(options, "default");
737
- this.default = options.default;
738
- }
739
- get isRequired() {
740
- return !this.hasDefault;
741
- }
742
- }
743
- // Marks
744
- /**
745
- Like nodes, marks (which are associated with nodes to signify
746
- things like emphasis or being part of a link) are
747
- [tagged](https://prosemirror.net/docs/ref/#model.Mark.type) with type objects, which are
748
- instantiated once per `Schema`.
749
- */
750
- class MarkType {
751
- /**
752
- @internal
753
- */
754
- constructor(
755
- /**
756
- The name of the mark type.
757
- */
758
- name,
759
- /**
760
- @internal
761
- */
762
- rank,
763
- /**
764
- The schema that this mark type instance is part of.
765
- */
766
- schema,
767
- /**
768
- The spec on which the type is based.
769
- */
770
- spec) {
771
- this.name = name;
772
- this.rank = rank;
773
- this.schema = schema;
774
- this.spec = spec;
775
- this.attrs = initAttrs(spec.attrs);
776
- this.excluded = null;
777
- let defaults = defaultAttrs(this.attrs);
778
- this.instance = defaults ? new Mark(this, defaults) : null;
779
- }
780
- /**
781
- Create a mark of this type. `attrs` may be `null` or an object
782
- containing only some of the mark's attributes. The others, if
783
- they have defaults, will be added.
784
- */
785
- create(attrs = null) {
786
- if (!attrs && this.instance)
787
- return this.instance;
788
- return new Mark(this, computeAttrs(this.attrs, attrs));
789
- }
790
- /**
791
- @internal
792
- */
793
- static compile(marks, schema) {
794
- let result = Object.create(null), rank = 0;
795
- marks.forEach((name, spec) => result[name] = new MarkType(name, rank++, schema, spec));
796
- return result;
797
- }
798
- /**
799
- When there is a mark of this type in the given set, a new set
800
- without it is returned. Otherwise, the input set is returned.
801
- */
802
- removeFromSet(set) {
803
- for (var i = 0; i < set.length; i++)
804
- if (set[i].type == this) {
805
- set = set.slice(0, i).concat(set.slice(i + 1));
806
- i--;
807
- }
808
- return set;
809
- }
810
- /**
811
- Tests whether there is a mark of this type in the given set.
812
- */
813
- isInSet(set) {
814
- for (let i = 0; i < set.length; i++)
815
- if (set[i].type == this)
816
- return set[i];
817
- }
818
- /**
819
- Queries whether a given mark type is
820
- [excluded](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) by this one.
821
- */
822
- excludes(other) {
823
- return this.excluded.indexOf(other) > -1;
824
- }
825
- }
826
-
827
- // Recovery values encode a range index and an offset. They are
828
- // represented as numbers, because tons of them will be created when
829
- // mapping, for example, a large number of decorations. The number's
830
- // lower 16 bits provide the index, the remaining bits the offset.
831
- //
832
- // Note: We intentionally don't use bit shift operators to en- and
833
- // decode these, since those clip to 32 bits, which we might in rare
834
- // cases want to overflow. A 64-bit float can represent 48-bit
835
- // integers precisely.
836
- const lower16 = 0xffff;
837
- const factor16 = Math.pow(2, 16);
838
- function makeRecover(index, offset) { return index + offset * factor16; }
839
- function recoverIndex(value) { return value & lower16; }
840
- function recoverOffset(value) { return (value - (value & lower16)) / factor16; }
841
- const DEL_BEFORE = 1, DEL_AFTER = 2, DEL_ACROSS = 4, DEL_SIDE = 8;
842
- /**
843
- An object representing a mapped position with extra
844
- information.
845
- */
846
- class MapResult {
847
- /**
848
- @internal
849
- */
850
- constructor(
851
- /**
852
- The mapped version of the position.
853
- */
854
- pos,
855
- /**
856
- @internal
857
- */
858
- delInfo,
859
- /**
860
- @internal
861
- */
862
- recover) {
863
- this.pos = pos;
864
- this.delInfo = delInfo;
865
- this.recover = recover;
866
- }
867
- /**
868
- Tells you whether the position was deleted, that is, whether the
869
- step removed the token on the side queried (via the `assoc`)
870
- argument from the document.
871
- */
872
- get deleted() { return (this.delInfo & DEL_SIDE) > 0; }
873
- /**
874
- Tells you whether the token before the mapped position was deleted.
875
- */
876
- get deletedBefore() { return (this.delInfo & (DEL_BEFORE | DEL_ACROSS)) > 0; }
877
- /**
878
- True when the token after the mapped position was deleted.
879
- */
880
- get deletedAfter() { return (this.delInfo & (DEL_AFTER | DEL_ACROSS)) > 0; }
881
- /**
882
- Tells whether any of the steps mapped through deletes across the
883
- position (including both the token before and after the
884
- position).
885
- */
886
- get deletedAcross() { return (this.delInfo & DEL_ACROSS) > 0; }
887
- }
888
- /**
889
- A map describing the deletions and insertions made by a step, which
890
- can be used to find the correspondence between positions in the
891
- pre-step version of a document and the same position in the
892
- post-step version.
893
- */
894
- class StepMap {
895
- /**
896
- Create a position map. The modifications to the document are
897
- represented as an array of numbers, in which each group of three
898
- represents a modified chunk as `[start, oldSize, newSize]`.
899
- */
900
- constructor(
901
- /**
902
- @internal
903
- */
904
- ranges,
905
- /**
906
- @internal
907
- */
908
- inverted = false) {
909
- this.ranges = ranges;
910
- this.inverted = inverted;
911
- if (!ranges.length && StepMap.empty)
912
- return StepMap.empty;
913
- }
914
- /**
915
- @internal
916
- */
917
- recover(value) {
918
- let diff = 0, index = recoverIndex(value);
919
- if (!this.inverted)
920
- for (let i = 0; i < index; i++)
921
- diff += this.ranges[i * 3 + 2] - this.ranges[i * 3 + 1];
922
- return this.ranges[index * 3] + diff + recoverOffset(value);
923
- }
924
- mapResult(pos, assoc = 1) { return this._map(pos, assoc, false); }
925
- map(pos, assoc = 1) { return this._map(pos, assoc, true); }
926
- /**
927
- @internal
928
- */
929
- _map(pos, assoc, simple) {
930
- let diff = 0, oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;
931
- for (let i = 0; i < this.ranges.length; i += 3) {
932
- let start = this.ranges[i] - (this.inverted ? diff : 0);
933
- if (start > pos)
934
- break;
935
- let oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex], end = start + oldSize;
936
- if (pos <= end) {
937
- let side = !oldSize ? assoc : pos == start ? -1 : pos == end ? 1 : assoc;
938
- let result = start + diff + (side < 0 ? 0 : newSize);
939
- if (simple)
940
- return result;
941
- let recover = pos == (assoc < 0 ? start : end) ? null : makeRecover(i / 3, pos - start);
942
- let del = pos == start ? DEL_AFTER : pos == end ? DEL_BEFORE : DEL_ACROSS;
943
- if (assoc < 0 ? pos != start : pos != end)
944
- del |= DEL_SIDE;
945
- return new MapResult(result, del, recover);
946
- }
947
- diff += newSize - oldSize;
948
- }
949
- return simple ? pos + diff : new MapResult(pos + diff, 0, null);
950
- }
951
- /**
952
- @internal
953
- */
954
- touches(pos, recover) {
955
- let diff = 0, index = recoverIndex(recover);
956
- let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;
957
- for (let i = 0; i < this.ranges.length; i += 3) {
958
- let start = this.ranges[i] - (this.inverted ? diff : 0);
959
- if (start > pos)
960
- break;
961
- let oldSize = this.ranges[i + oldIndex], end = start + oldSize;
962
- if (pos <= end && i == index * 3)
963
- return true;
964
- diff += this.ranges[i + newIndex] - oldSize;
965
- }
966
- return false;
967
- }
968
- /**
969
- Calls the given function on each of the changed ranges included in
970
- this map.
971
- */
972
- forEach(f) {
973
- let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;
974
- for (let i = 0, diff = 0; i < this.ranges.length; i += 3) {
975
- let start = this.ranges[i], oldStart = start - (this.inverted ? diff : 0), newStart = start + (this.inverted ? 0 : diff);
976
- let oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex];
977
- f(oldStart, oldStart + oldSize, newStart, newStart + newSize);
978
- diff += newSize - oldSize;
979
- }
980
- }
981
- /**
982
- Create an inverted version of this map. The result can be used to
983
- map positions in the post-step document to the pre-step document.
984
- */
985
- invert() {
986
- return new StepMap(this.ranges, !this.inverted);
987
- }
988
- /**
989
- @internal
990
- */
991
- toString() {
992
- return (this.inverted ? "-" : "") + JSON.stringify(this.ranges);
993
- }
994
- /**
995
- Create a map that moves all positions by offset `n` (which may be
996
- negative). This can be useful when applying steps meant for a
997
- sub-document to a larger document, or vice-versa.
998
- */
999
- static offset(n) {
1000
- return n == 0 ? StepMap.empty : new StepMap(n < 0 ? [0, -n, 0] : [0, 0, n]);
1001
- }
1002
- }
1003
- /**
1004
- A StepMap that contains no changed ranges.
1005
- */
1006
- StepMap.empty = new StepMap([]);
1007
- /**
1008
- A mapping represents a pipeline of zero or more [step
1009
- maps](https://prosemirror.net/docs/ref/#transform.StepMap). It has special provisions for losslessly
1010
- handling mapping positions through a series of steps in which some
1011
- steps are inverted versions of earlier steps. (This comes up when
1012
- ‘[rebasing](/docs/guide/#transform.rebasing)’ steps for
1013
- collaboration or history management.)
1014
- */
1015
- class Mapping {
1016
- /**
1017
- Create a new mapping with the given position maps.
1018
- */
1019
- constructor(
1020
- /**
1021
- The step maps in this mapping.
1022
- */
1023
- maps = [],
1024
- /**
1025
- @internal
1026
- */
1027
- mirror,
1028
- /**
1029
- The starting position in the `maps` array, used when `map` or
1030
- `mapResult` is called.
1031
- */
1032
- from = 0,
1033
- /**
1034
- The end position in the `maps` array.
1035
- */
1036
- to = maps.length) {
1037
- this.maps = maps;
1038
- this.mirror = mirror;
1039
- this.from = from;
1040
- this.to = to;
1041
- }
1042
- /**
1043
- Create a mapping that maps only through a part of this one.
1044
- */
1045
- slice(from = 0, to = this.maps.length) {
1046
- return new Mapping(this.maps, this.mirror, from, to);
1047
- }
1048
- /**
1049
- @internal
1050
- */
1051
- copy() {
1052
- return new Mapping(this.maps.slice(), this.mirror && this.mirror.slice(), this.from, this.to);
1053
- }
1054
- /**
1055
- Add a step map to the end of this mapping. If `mirrors` is
1056
- given, it should be the index of the step map that is the mirror
1057
- image of this one.
1058
- */
1059
- appendMap(map, mirrors) {
1060
- this.to = this.maps.push(map);
1061
- if (mirrors != null)
1062
- this.setMirror(this.maps.length - 1, mirrors);
1063
- }
1064
- /**
1065
- Add all the step maps in a given mapping to this one (preserving
1066
- mirroring information).
1067
- */
1068
- appendMapping(mapping) {
1069
- for (let i = 0, startSize = this.maps.length; i < mapping.maps.length; i++) {
1070
- let mirr = mapping.getMirror(i);
1071
- this.appendMap(mapping.maps[i], mirr != null && mirr < i ? startSize + mirr : undefined);
1072
- }
1073
- }
1074
- /**
1075
- Finds the offset of the step map that mirrors the map at the
1076
- given offset, in this mapping (as per the second argument to
1077
- `appendMap`).
1078
- */
1079
- getMirror(n) {
1080
- if (this.mirror)
1081
- for (let i = 0; i < this.mirror.length; i++)
1082
- if (this.mirror[i] == n)
1083
- return this.mirror[i + (i % 2 ? -1 : 1)];
1084
- }
1085
- /**
1086
- @internal
1087
- */
1088
- setMirror(n, m) {
1089
- if (!this.mirror)
1090
- this.mirror = [];
1091
- this.mirror.push(n, m);
1092
- }
1093
- /**
1094
- Append the inverse of the given mapping to this one.
1095
- */
1096
- appendMappingInverted(mapping) {
1097
- for (let i = mapping.maps.length - 1, totalSize = this.maps.length + mapping.maps.length; i >= 0; i--) {
1098
- let mirr = mapping.getMirror(i);
1099
- this.appendMap(mapping.maps[i].invert(), mirr != null && mirr > i ? totalSize - mirr - 1 : undefined);
1100
- }
1101
- }
1102
- /**
1103
- Create an inverted version of this mapping.
1104
- */
1105
- invert() {
1106
- let inverse = new Mapping;
1107
- inverse.appendMappingInverted(this);
1108
- return inverse;
1109
- }
1110
- /**
1111
- Map a position through this mapping.
1112
- */
1113
- map(pos, assoc = 1) {
1114
- if (this.mirror)
1115
- return this._map(pos, assoc, true);
1116
- for (let i = this.from; i < this.to; i++)
1117
- pos = this.maps[i].map(pos, assoc);
1118
- return pos;
1119
- }
1120
- /**
1121
- Map a position through this mapping, returning a mapping
1122
- result.
1123
- */
1124
- mapResult(pos, assoc = 1) { return this._map(pos, assoc, false); }
1125
- /**
1126
- @internal
1127
- */
1128
- _map(pos, assoc, simple) {
1129
- let delInfo = 0;
1130
- for (let i = this.from; i < this.to; i++) {
1131
- let map = this.maps[i], result = map.mapResult(pos, assoc);
1132
- if (result.recover != null) {
1133
- let corr = this.getMirror(i);
1134
- if (corr != null && corr > i && corr < this.to) {
1135
- i = corr;
1136
- pos = this.maps[corr].recover(result.recover);
1137
- continue;
1138
- }
1139
- }
1140
- delInfo |= result.delInfo;
1141
- pos = result.pos;
1142
- }
1143
- return simple ? pos : new MapResult(pos, delInfo, null);
1144
- }
1145
- }
1146
-
1147
- const stepsByID = Object.create(null);
1148
- /**
1149
- A step object represents an atomic change. It generally applies
1150
- only to the document it was created for, since the positions
1151
- stored in it will only make sense for that document.
1152
-
1153
- New steps are defined by creating classes that extend `Step`,
1154
- overriding the `apply`, `invert`, `map`, `getMap` and `fromJSON`
1155
- methods, and registering your class with a unique
1156
- JSON-serialization identifier using
1157
- [`Step.jsonID`](https://prosemirror.net/docs/ref/#transform.Step^jsonID).
1158
- */
1159
- class Step {
1160
- /**
1161
- Get the step map that represents the changes made by this step,
1162
- and which can be used to transform between positions in the old
1163
- and the new document.
1164
- */
1165
- getMap() { return StepMap.empty; }
1166
- /**
1167
- Try to merge this step with another one, to be applied directly
1168
- after it. Returns the merged step when possible, null if the
1169
- steps can't be merged.
1170
- */
1171
- merge(other) { return null; }
1172
- /**
1173
- Deserialize a step from its JSON representation. Will call
1174
- through to the step class' own implementation of this method.
1175
- */
1176
- static fromJSON(schema, json) {
1177
- if (!json || !json.stepType)
1178
- throw new RangeError("Invalid input for Step.fromJSON");
1179
- let type = stepsByID[json.stepType];
1180
- if (!type)
1181
- throw new RangeError(`No step type ${json.stepType} defined`);
1182
- return type.fromJSON(schema, json);
1183
- }
1184
- /**
1185
- To be able to serialize steps to JSON, each step needs a string
1186
- ID to attach to its JSON representation. Use this method to
1187
- register an ID for your step classes. Try to pick something
1188
- that's unlikely to clash with steps from other modules.
1189
- */
1190
- static jsonID(id, stepClass) {
1191
- if (id in stepsByID)
1192
- throw new RangeError("Duplicate use of step JSON ID " + id);
1193
- stepsByID[id] = stepClass;
1194
- stepClass.prototype.jsonID = id;
1195
- return stepClass;
1196
- }
1197
- }
1198
- /**
1199
- The result of [applying](https://prosemirror.net/docs/ref/#transform.Step.apply) a step. Contains either a
1200
- new document or a failure value.
1201
- */
1202
- class StepResult {
1203
- /**
1204
- @internal
1205
- */
1206
- constructor(
1207
- /**
1208
- The transformed document, if successful.
1209
- */
1210
- doc,
1211
- /**
1212
- The failure message, if unsuccessful.
1213
- */
1214
- failed) {
1215
- this.doc = doc;
1216
- this.failed = failed;
1217
- }
1218
- /**
1219
- Create a successful step result.
1220
- */
1221
- static ok(doc) { return new StepResult(doc, null); }
1222
- /**
1223
- Create a failed step result.
1224
- */
1225
- static fail(message) { return new StepResult(null, message); }
1226
- /**
1227
- Call [`Node.replace`](https://prosemirror.net/docs/ref/#model.Node.replace) with the given
1228
- arguments. Create a successful result if it succeeds, and a
1229
- failed one if it throws a `ReplaceError`.
1230
- */
1231
- static fromReplace(doc, from, to, slice) {
1232
- try {
1233
- return StepResult.ok(doc.replace(from, to, slice));
1234
- }
1235
- catch (e) {
1236
- if (e instanceof ReplaceError)
1237
- return StepResult.fail(e.message);
1238
- throw e;
1239
- }
1240
- }
1241
- }
1242
-
1243
- function mapFragment(fragment, f, parent) {
1244
- let mapped = [];
1245
- for (let i = 0; i < fragment.childCount; i++) {
1246
- let child = fragment.child(i);
1247
- if (child.content.size)
1248
- child = child.copy(mapFragment(child.content, f, child));
1249
- if (child.isInline)
1250
- child = f(child, parent, i);
1251
- mapped.push(child);
1252
- }
1253
- return Fragment.fromArray(mapped);
1254
- }
1255
- /**
1256
- Add a mark to all inline content between two positions.
1257
- */
1258
- class AddMarkStep extends Step {
1259
- /**
1260
- Create a mark step.
1261
- */
1262
- constructor(
1263
- /**
1264
- The start of the marked range.
1265
- */
1266
- from,
1267
- /**
1268
- The end of the marked range.
1269
- */
1270
- to,
1271
- /**
1272
- The mark to add.
1273
- */
1274
- mark) {
1275
- super();
1276
- this.from = from;
1277
- this.to = to;
1278
- this.mark = mark;
1279
- }
1280
- apply(doc) {
1281
- let oldSlice = doc.slice(this.from, this.to), $from = doc.resolve(this.from);
1282
- let parent = $from.node($from.sharedDepth(this.to));
1283
- let slice = new Slice(mapFragment(oldSlice.content, (node, parent) => {
1284
- if (!node.isAtom || !parent.type.allowsMarkType(this.mark.type))
1285
- return node;
1286
- return node.mark(this.mark.addToSet(node.marks));
1287
- }, parent), oldSlice.openStart, oldSlice.openEnd);
1288
- return StepResult.fromReplace(doc, this.from, this.to, slice);
1289
- }
1290
- invert() {
1291
- return new RemoveMarkStep(this.from, this.to, this.mark);
1292
- }
1293
- map(mapping) {
1294
- let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);
1295
- if (from.deleted && to.deleted || from.pos >= to.pos)
1296
- return null;
1297
- return new AddMarkStep(from.pos, to.pos, this.mark);
1298
- }
1299
- merge(other) {
1300
- if (other instanceof AddMarkStep &&
1301
- other.mark.eq(this.mark) &&
1302
- this.from <= other.to && this.to >= other.from)
1303
- return new AddMarkStep(Math.min(this.from, other.from), Math.max(this.to, other.to), this.mark);
1304
- return null;
1305
- }
1306
- toJSON() {
1307
- return { stepType: "addMark", mark: this.mark.toJSON(),
1308
- from: this.from, to: this.to };
1309
- }
1310
- /**
1311
- @internal
1312
- */
1313
- static fromJSON(schema, json) {
1314
- if (typeof json.from != "number" || typeof json.to != "number")
1315
- throw new RangeError("Invalid input for AddMarkStep.fromJSON");
1316
- return new AddMarkStep(json.from, json.to, schema.markFromJSON(json.mark));
1317
- }
1318
- }
1319
- Step.jsonID("addMark", AddMarkStep);
1320
- /**
1321
- Remove a mark from all inline content between two positions.
1322
- */
1323
- class RemoveMarkStep extends Step {
1324
- /**
1325
- Create a mark-removing step.
1326
- */
1327
- constructor(
1328
- /**
1329
- The start of the unmarked range.
1330
- */
1331
- from,
1332
- /**
1333
- The end of the unmarked range.
1334
- */
1335
- to,
1336
- /**
1337
- The mark to remove.
1338
- */
1339
- mark) {
1340
- super();
1341
- this.from = from;
1342
- this.to = to;
1343
- this.mark = mark;
1344
- }
1345
- apply(doc) {
1346
- let oldSlice = doc.slice(this.from, this.to);
1347
- let slice = new Slice(mapFragment(oldSlice.content, node => {
1348
- return node.mark(this.mark.removeFromSet(node.marks));
1349
- }, doc), oldSlice.openStart, oldSlice.openEnd);
1350
- return StepResult.fromReplace(doc, this.from, this.to, slice);
1351
- }
1352
- invert() {
1353
- return new AddMarkStep(this.from, this.to, this.mark);
1354
- }
1355
- map(mapping) {
1356
- let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);
1357
- if (from.deleted && to.deleted || from.pos >= to.pos)
1358
- return null;
1359
- return new RemoveMarkStep(from.pos, to.pos, this.mark);
1360
- }
1361
- merge(other) {
1362
- if (other instanceof RemoveMarkStep &&
1363
- other.mark.eq(this.mark) &&
1364
- this.from <= other.to && this.to >= other.from)
1365
- return new RemoveMarkStep(Math.min(this.from, other.from), Math.max(this.to, other.to), this.mark);
1366
- return null;
1367
- }
1368
- toJSON() {
1369
- return { stepType: "removeMark", mark: this.mark.toJSON(),
1370
- from: this.from, to: this.to };
1371
- }
1372
- /**
1373
- @internal
1374
- */
1375
- static fromJSON(schema, json) {
1376
- if (typeof json.from != "number" || typeof json.to != "number")
1377
- throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");
1378
- return new RemoveMarkStep(json.from, json.to, schema.markFromJSON(json.mark));
1379
- }
1380
- }
1381
- Step.jsonID("removeMark", RemoveMarkStep);
1382
- /**
1383
- Add a mark to a specific node.
1384
- */
1385
- class AddNodeMarkStep extends Step {
1386
- /**
1387
- Create a node mark step.
1388
- */
1389
- constructor(
1390
- /**
1391
- The position of the target node.
1392
- */
1393
- pos,
1394
- /**
1395
- The mark to add.
1396
- */
1397
- mark) {
1398
- super();
1399
- this.pos = pos;
1400
- this.mark = mark;
1401
- }
1402
- apply(doc) {
1403
- let node = doc.nodeAt(this.pos);
1404
- if (!node)
1405
- return StepResult.fail("No node at mark step's position");
1406
- let updated = node.type.create(node.attrs, null, this.mark.addToSet(node.marks));
1407
- return StepResult.fromReplace(doc, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));
1408
- }
1409
- invert(doc) {
1410
- let node = doc.nodeAt(this.pos);
1411
- if (node) {
1412
- let newSet = this.mark.addToSet(node.marks);
1413
- if (newSet.length == node.marks.length) {
1414
- for (let i = 0; i < node.marks.length; i++)
1415
- if (!node.marks[i].isInSet(newSet))
1416
- return new AddNodeMarkStep(this.pos, node.marks[i]);
1417
- return new AddNodeMarkStep(this.pos, this.mark);
1418
- }
1419
- }
1420
- return new RemoveNodeMarkStep(this.pos, this.mark);
1421
- }
1422
- map(mapping) {
1423
- let pos = mapping.mapResult(this.pos, 1);
1424
- return pos.deletedAfter ? null : new AddNodeMarkStep(pos.pos, this.mark);
1425
- }
1426
- toJSON() {
1427
- return { stepType: "addNodeMark", pos: this.pos, mark: this.mark.toJSON() };
1428
- }
1429
- /**
1430
- @internal
1431
- */
1432
- static fromJSON(schema, json) {
1433
- if (typeof json.pos != "number")
1434
- throw new RangeError("Invalid input for AddNodeMarkStep.fromJSON");
1435
- return new AddNodeMarkStep(json.pos, schema.markFromJSON(json.mark));
1436
- }
1437
- }
1438
- Step.jsonID("addNodeMark", AddNodeMarkStep);
1439
- /**
1440
- Remove a mark from a specific node.
1441
- */
1442
- class RemoveNodeMarkStep extends Step {
1443
- /**
1444
- Create a mark-removing step.
1445
- */
1446
- constructor(
1447
- /**
1448
- The position of the target node.
1449
- */
1450
- pos,
1451
- /**
1452
- The mark to remove.
1453
- */
1454
- mark) {
1455
- super();
1456
- this.pos = pos;
1457
- this.mark = mark;
1458
- }
1459
- apply(doc) {
1460
- let node = doc.nodeAt(this.pos);
1461
- if (!node)
1462
- return StepResult.fail("No node at mark step's position");
1463
- let updated = node.type.create(node.attrs, null, this.mark.removeFromSet(node.marks));
1464
- return StepResult.fromReplace(doc, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));
1465
- }
1466
- invert(doc) {
1467
- let node = doc.nodeAt(this.pos);
1468
- if (!node || !this.mark.isInSet(node.marks))
1469
- return this;
1470
- return new AddNodeMarkStep(this.pos, this.mark);
1471
- }
1472
- map(mapping) {
1473
- let pos = mapping.mapResult(this.pos, 1);
1474
- return pos.deletedAfter ? null : new RemoveNodeMarkStep(pos.pos, this.mark);
1475
- }
1476
- toJSON() {
1477
- return { stepType: "removeNodeMark", pos: this.pos, mark: this.mark.toJSON() };
1478
- }
1479
- /**
1480
- @internal
1481
- */
1482
- static fromJSON(schema, json) {
1483
- if (typeof json.pos != "number")
1484
- throw new RangeError("Invalid input for RemoveNodeMarkStep.fromJSON");
1485
- return new RemoveNodeMarkStep(json.pos, schema.markFromJSON(json.mark));
1486
- }
1487
- }
1488
- Step.jsonID("removeNodeMark", RemoveNodeMarkStep);
1489
-
1490
- /**
1491
- Replace a part of the document with a slice of new content.
1492
- */
1493
- class ReplaceStep extends Step {
1494
- /**
1495
- The given `slice` should fit the 'gap' between `from` and
1496
- `to`—the depths must line up, and the surrounding nodes must be
1497
- able to be joined with the open sides of the slice. When
1498
- `structure` is true, the step will fail if the content between
1499
- from and to is not just a sequence of closing and then opening
1500
- tokens (this is to guard against rebased replace steps
1501
- overwriting something they weren't supposed to).
1502
- */
1503
- constructor(
1504
- /**
1505
- The start position of the replaced range.
1506
- */
1507
- from,
1508
- /**
1509
- The end position of the replaced range.
1510
- */
1511
- to,
1512
- /**
1513
- The slice to insert.
1514
- */
1515
- slice,
1516
- /**
1517
- @internal
1518
- */
1519
- structure = false) {
1520
- super();
1521
- this.from = from;
1522
- this.to = to;
1523
- this.slice = slice;
1524
- this.structure = structure;
1525
- }
1526
- apply(doc) {
1527
- if (this.structure && contentBetween(doc, this.from, this.to))
1528
- return StepResult.fail("Structure replace would overwrite content");
1529
- return StepResult.fromReplace(doc, this.from, this.to, this.slice);
1530
- }
1531
- getMap() {
1532
- return new StepMap([this.from, this.to - this.from, this.slice.size]);
1533
- }
1534
- invert(doc) {
1535
- return new ReplaceStep(this.from, this.from + this.slice.size, doc.slice(this.from, this.to));
1536
- }
1537
- map(mapping) {
1538
- let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);
1539
- if (from.deletedAcross && to.deletedAcross)
1540
- return null;
1541
- return new ReplaceStep(from.pos, Math.max(from.pos, to.pos), this.slice);
1542
- }
1543
- merge(other) {
1544
- if (!(other instanceof ReplaceStep) || other.structure || this.structure)
1545
- return null;
1546
- if (this.from + this.slice.size == other.from && !this.slice.openEnd && !other.slice.openStart) {
1547
- let slice = this.slice.size + other.slice.size == 0 ? Slice.empty
1548
- : new Slice(this.slice.content.append(other.slice.content), this.slice.openStart, other.slice.openEnd);
1549
- return new ReplaceStep(this.from, this.to + (other.to - other.from), slice, this.structure);
1550
- }
1551
- else if (other.to == this.from && !this.slice.openStart && !other.slice.openEnd) {
1552
- let slice = this.slice.size + other.slice.size == 0 ? Slice.empty
1553
- : new Slice(other.slice.content.append(this.slice.content), other.slice.openStart, this.slice.openEnd);
1554
- return new ReplaceStep(other.from, this.to, slice, this.structure);
1555
- }
1556
- else {
1557
- return null;
1558
- }
1559
- }
1560
- toJSON() {
1561
- let json = { stepType: "replace", from: this.from, to: this.to };
1562
- if (this.slice.size)
1563
- json.slice = this.slice.toJSON();
1564
- if (this.structure)
1565
- json.structure = true;
1566
- return json;
1567
- }
1568
- /**
1569
- @internal
1570
- */
1571
- static fromJSON(schema, json) {
1572
- if (typeof json.from != "number" || typeof json.to != "number")
1573
- throw new RangeError("Invalid input for ReplaceStep.fromJSON");
1574
- return new ReplaceStep(json.from, json.to, Slice.fromJSON(schema, json.slice), !!json.structure);
1575
- }
1576
- }
1577
- Step.jsonID("replace", ReplaceStep);
1578
- /**
1579
- Replace a part of the document with a slice of content, but
1580
- preserve a range of the replaced content by moving it into the
1581
- slice.
1582
- */
1583
- class ReplaceAroundStep extends Step {
1584
- /**
1585
- Create a replace-around step with the given range and gap.
1586
- `insert` should be the point in the slice into which the content
1587
- of the gap should be moved. `structure` has the same meaning as
1588
- it has in the [`ReplaceStep`](https://prosemirror.net/docs/ref/#transform.ReplaceStep) class.
1589
- */
1590
- constructor(
1591
- /**
1592
- The start position of the replaced range.
1593
- */
1594
- from,
1595
- /**
1596
- The end position of the replaced range.
1597
- */
1598
- to,
1599
- /**
1600
- The start of preserved range.
1601
- */
1602
- gapFrom,
1603
- /**
1604
- The end of preserved range.
1605
- */
1606
- gapTo,
1607
- /**
1608
- The slice to insert.
1609
- */
1610
- slice,
1611
- /**
1612
- The position in the slice where the preserved range should be
1613
- inserted.
1614
- */
1615
- insert,
1616
- /**
1617
- @internal
1618
- */
1619
- structure = false) {
1620
- super();
1621
- this.from = from;
1622
- this.to = to;
1623
- this.gapFrom = gapFrom;
1624
- this.gapTo = gapTo;
1625
- this.slice = slice;
1626
- this.insert = insert;
1627
- this.structure = structure;
1628
- }
1629
- apply(doc) {
1630
- if (this.structure && (contentBetween(doc, this.from, this.gapFrom) ||
1631
- contentBetween(doc, this.gapTo, this.to)))
1632
- return StepResult.fail("Structure gap-replace would overwrite content");
1633
- let gap = doc.slice(this.gapFrom, this.gapTo);
1634
- if (gap.openStart || gap.openEnd)
1635
- return StepResult.fail("Gap is not a flat range");
1636
- let inserted = this.slice.insertAt(this.insert, gap.content);
1637
- if (!inserted)
1638
- return StepResult.fail("Content does not fit in gap");
1639
- return StepResult.fromReplace(doc, this.from, this.to, inserted);
1640
- }
1641
- getMap() {
1642
- return new StepMap([this.from, this.gapFrom - this.from, this.insert,
1643
- this.gapTo, this.to - this.gapTo, this.slice.size - this.insert]);
1644
- }
1645
- invert(doc) {
1646
- let gap = this.gapTo - this.gapFrom;
1647
- return new ReplaceAroundStep(this.from, this.from + this.slice.size + gap, this.from + this.insert, this.from + this.insert + gap, doc.slice(this.from, this.to).removeBetween(this.gapFrom - this.from, this.gapTo - this.from), this.gapFrom - this.from, this.structure);
1648
- }
1649
- map(mapping) {
1650
- let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);
1651
- let gapFrom = mapping.map(this.gapFrom, -1), gapTo = mapping.map(this.gapTo, 1);
1652
- if ((from.deletedAcross && to.deletedAcross) || gapFrom < from.pos || gapTo > to.pos)
1653
- return null;
1654
- return new ReplaceAroundStep(from.pos, to.pos, gapFrom, gapTo, this.slice, this.insert, this.structure);
1655
- }
1656
- toJSON() {
1657
- let json = { stepType: "replaceAround", from: this.from, to: this.to,
1658
- gapFrom: this.gapFrom, gapTo: this.gapTo, insert: this.insert };
1659
- if (this.slice.size)
1660
- json.slice = this.slice.toJSON();
1661
- if (this.structure)
1662
- json.structure = true;
1663
- return json;
1664
- }
1665
- /**
1666
- @internal
1667
- */
1668
- static fromJSON(schema, json) {
1669
- if (typeof json.from != "number" || typeof json.to != "number" ||
1670
- typeof json.gapFrom != "number" || typeof json.gapTo != "number" || typeof json.insert != "number")
1671
- throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");
1672
- return new ReplaceAroundStep(json.from, json.to, json.gapFrom, json.gapTo, Slice.fromJSON(schema, json.slice), json.insert, !!json.structure);
1673
- }
1674
- }
1675
- Step.jsonID("replaceAround", ReplaceAroundStep);
1676
- function contentBetween(doc, from, to) {
1677
- let $from = doc.resolve(from), dist = to - from, depth = $from.depth;
1678
- while (dist > 0 && depth > 0 && $from.indexAfter(depth) == $from.node(depth).childCount) {
1679
- depth--;
1680
- dist--;
1681
- }
1682
- if (dist > 0) {
1683
- let next = $from.node(depth).maybeChild($from.indexAfter(depth));
1684
- while (dist > 0) {
1685
- if (!next || next.isLeaf)
1686
- return true;
1687
- next = next.firstChild;
1688
- dist--;
1689
- }
1690
- }
1691
- return false;
1692
- }
1693
-
1694
- function addMark(tr, from, to, mark) {
1695
- let removed = [], added = [];
1696
- let removing, adding;
1697
- tr.doc.nodesBetween(from, to, (node, pos, parent) => {
1698
- if (!node.isInline)
1699
- return;
1700
- let marks = node.marks;
1701
- if (!mark.isInSet(marks) && parent.type.allowsMarkType(mark.type)) {
1702
- let start = Math.max(pos, from), end = Math.min(pos + node.nodeSize, to);
1703
- let newSet = mark.addToSet(marks);
1704
- for (let i = 0; i < marks.length; i++) {
1705
- if (!marks[i].isInSet(newSet)) {
1706
- if (removing && removing.to == start && removing.mark.eq(marks[i]))
1707
- removing.to = end;
1708
- else
1709
- removed.push(removing = new RemoveMarkStep(start, end, marks[i]));
1710
- }
1711
- }
1712
- if (adding && adding.to == start)
1713
- adding.to = end;
1714
- else
1715
- added.push(adding = new AddMarkStep(start, end, mark));
1716
- }
1717
- });
1718
- removed.forEach(s => tr.step(s));
1719
- added.forEach(s => tr.step(s));
1720
- }
1721
- function removeMark(tr, from, to, mark) {
1722
- let matched = [], step = 0;
1723
- tr.doc.nodesBetween(from, to, (node, pos) => {
1724
- if (!node.isInline)
1725
- return;
1726
- step++;
1727
- let toRemove = null;
1728
- if (mark instanceof MarkType) {
1729
- let set = node.marks, found;
1730
- while (found = mark.isInSet(set)) {
1731
- (toRemove || (toRemove = [])).push(found);
1732
- set = found.removeFromSet(set);
1733
- }
1734
- }
1735
- else if (mark) {
1736
- if (mark.isInSet(node.marks))
1737
- toRemove = [mark];
1738
- }
1739
- else {
1740
- toRemove = node.marks;
1741
- }
1742
- if (toRemove && toRemove.length) {
1743
- let end = Math.min(pos + node.nodeSize, to);
1744
- for (let i = 0; i < toRemove.length; i++) {
1745
- let style = toRemove[i], found;
1746
- for (let j = 0; j < matched.length; j++) {
1747
- let m = matched[j];
1748
- if (m.step == step - 1 && style.eq(matched[j].style))
1749
- found = m;
1750
- }
1751
- if (found) {
1752
- found.to = end;
1753
- found.step = step;
1754
- }
1755
- else {
1756
- matched.push({ style, from: Math.max(pos, from), to: end, step });
1757
- }
1758
- }
1759
- }
1760
- });
1761
- matched.forEach(m => tr.step(new RemoveMarkStep(m.from, m.to, m.style)));
1762
- }
1763
- function clearIncompatible(tr, pos, parentType, match = parentType.contentMatch) {
1764
- let node = tr.doc.nodeAt(pos);
1765
- let delSteps = [], cur = pos + 1;
1766
- for (let i = 0; i < node.childCount; i++) {
1767
- let child = node.child(i), end = cur + child.nodeSize;
1768
- let allowed = match.matchType(child.type);
1769
- if (!allowed) {
1770
- delSteps.push(new ReplaceStep(cur, end, Slice.empty));
1771
- }
1772
- else {
1773
- match = allowed;
1774
- for (let j = 0; j < child.marks.length; j++)
1775
- if (!parentType.allowsMarkType(child.marks[j].type))
1776
- tr.step(new RemoveMarkStep(cur, end, child.marks[j]));
1777
- }
1778
- cur = end;
1779
- }
1780
- if (!match.validEnd) {
1781
- let fill = match.fillBefore(Fragment.empty, true);
1782
- tr.replace(cur, cur, new Slice(fill, 0, 0));
1783
- }
1784
- for (let i = delSteps.length - 1; i >= 0; i--)
1785
- tr.step(delSteps[i]);
1786
- }
1787
- function lift(tr, range, target) {
1788
- let { $from, $to, depth } = range;
1789
- let gapStart = $from.before(depth + 1), gapEnd = $to.after(depth + 1);
1790
- let start = gapStart, end = gapEnd;
1791
- let before = Fragment.empty, openStart = 0;
1792
- for (let d = depth, splitting = false; d > target; d--)
1793
- if (splitting || $from.index(d) > 0) {
1794
- splitting = true;
1795
- before = Fragment.from($from.node(d).copy(before));
1796
- openStart++;
1797
- }
1798
- else {
1799
- start--;
1800
- }
1801
- let after = Fragment.empty, openEnd = 0;
1802
- for (let d = depth, splitting = false; d > target; d--)
1803
- if (splitting || $to.after(d + 1) < $to.end(d)) {
1804
- splitting = true;
1805
- after = Fragment.from($to.node(d).copy(after));
1806
- openEnd++;
1807
- }
1808
- else {
1809
- end++;
1810
- }
1811
- tr.step(new ReplaceAroundStep(start, end, gapStart, gapEnd, new Slice(before.append(after), openStart, openEnd), before.size - openStart, true));
1812
- }
1813
- function wrap(tr, range, wrappers) {
1814
- let content = Fragment.empty;
1815
- for (let i = wrappers.length - 1; i >= 0; i--) {
1816
- if (content.size) {
1817
- let match = wrappers[i].type.contentMatch.matchFragment(content);
1818
- if (!match || !match.validEnd)
1819
- throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper");
1820
- }
1821
- content = Fragment.from(wrappers[i].type.create(wrappers[i].attrs, content));
1822
- }
1823
- let start = range.start, end = range.end;
1824
- tr.step(new ReplaceAroundStep(start, end, start, end, new Slice(content, 0, 0), wrappers.length, true));
1825
- }
1826
- function setBlockType(tr, from, to, type, attrs) {
1827
- if (!type.isTextblock)
1828
- throw new RangeError("Type given to setBlockType should be a textblock");
1829
- let mapFrom = tr.steps.length;
1830
- tr.doc.nodesBetween(from, to, (node, pos) => {
1831
- if (node.isTextblock && !node.hasMarkup(type, attrs) && canChangeType(tr.doc, tr.mapping.slice(mapFrom).map(pos), type)) {
1832
- // Ensure all markup that isn't allowed in the new node type is cleared
1833
- tr.clearIncompatible(tr.mapping.slice(mapFrom).map(pos, 1), type);
1834
- let mapping = tr.mapping.slice(mapFrom);
1835
- let startM = mapping.map(pos, 1), endM = mapping.map(pos + node.nodeSize, 1);
1836
- tr.step(new ReplaceAroundStep(startM, endM, startM + 1, endM - 1, new Slice(Fragment.from(type.create(attrs, null, node.marks)), 0, 0), 1, true));
1837
- return false;
1838
- }
1839
- });
1840
- }
1841
- function canChangeType(doc, pos, type) {
1842
- let $pos = doc.resolve(pos), index = $pos.index();
1843
- return $pos.parent.canReplaceWith(index, index + 1, type);
1844
- }
1845
- /**
1846
- Change the type, attributes, and/or marks of the node at `pos`.
1847
- When `type` isn't given, the existing node type is preserved,
1848
- */
1849
- function setNodeMarkup(tr, pos, type, attrs, marks) {
1850
- let node = tr.doc.nodeAt(pos);
1851
- if (!node)
1852
- throw new RangeError("No node at given position");
1853
- if (!type)
1854
- type = node.type;
1855
- let newNode = type.create(attrs, null, marks || node.marks);
1856
- if (node.isLeaf)
1857
- return tr.replaceWith(pos, pos + node.nodeSize, newNode);
1858
- if (!type.validContent(node.content))
1859
- throw new RangeError("Invalid content for node type " + type.name);
1860
- tr.step(new ReplaceAroundStep(pos, pos + node.nodeSize, pos + 1, pos + node.nodeSize - 1, new Slice(Fragment.from(newNode), 0, 0), 1, true));
1861
- }
1862
- function split(tr, pos, depth = 1, typesAfter) {
1863
- let $pos = tr.doc.resolve(pos), before = Fragment.empty, after = Fragment.empty;
1864
- for (let d = $pos.depth, e = $pos.depth - depth, i = depth - 1; d > e; d--, i--) {
1865
- before = Fragment.from($pos.node(d).copy(before));
1866
- let typeAfter = typesAfter && typesAfter[i];
1867
- after = Fragment.from(typeAfter ? typeAfter.type.create(typeAfter.attrs, after) : $pos.node(d).copy(after));
1868
- }
1869
- tr.step(new ReplaceStep(pos, pos, new Slice(before.append(after), depth, depth), true));
1870
- }
1871
- function join(tr, pos, depth) {
1872
- let step = new ReplaceStep(pos - depth, pos + depth, Slice.empty, true);
1873
- tr.step(step);
1874
- }
1875
- /**
1876
- Try to find a point where a node of the given type can be inserted
1877
- near `pos`, by searching up the node hierarchy when `pos` itself
1878
- isn't a valid place but is at the start or end of a node. Return
1879
- null if no position was found.
1880
- */
1881
- function insertPoint(doc, pos, nodeType) {
1882
- let $pos = doc.resolve(pos);
1883
- if ($pos.parent.canReplaceWith($pos.index(), $pos.index(), nodeType))
1884
- return pos;
1885
- if ($pos.parentOffset == 0)
1886
- for (let d = $pos.depth - 1; d >= 0; d--) {
1887
- let index = $pos.index(d);
1888
- if ($pos.node(d).canReplaceWith(index, index, nodeType))
1889
- return $pos.before(d + 1);
1890
- if (index > 0)
1891
- return null;
1892
- }
1893
- if ($pos.parentOffset == $pos.parent.content.size)
1894
- for (let d = $pos.depth - 1; d >= 0; d--) {
1895
- let index = $pos.indexAfter(d);
1896
- if ($pos.node(d).canReplaceWith(index, index, nodeType))
1897
- return $pos.after(d + 1);
1898
- if (index < $pos.node(d).childCount)
1899
- return null;
1900
- }
1901
- return null;
1902
- }
1903
-
1904
- /**
1905
- ‘Fit’ a slice into a given position in the document, producing a
1906
- [step](https://prosemirror.net/docs/ref/#transform.Step) that inserts it. Will return null if
1907
- there's no meaningful way to insert the slice here, or inserting it
1908
- would be a no-op (an empty slice over an empty range).
1909
- */
1910
- function replaceStep(doc, from, to = from, slice = Slice.empty) {
1911
- if (from == to && !slice.size)
1912
- return null;
1913
- let $from = doc.resolve(from), $to = doc.resolve(to);
1914
- // Optimization -- avoid work if it's obvious that it's not needed.
1915
- if (fitsTrivially($from, $to, slice))
1916
- return new ReplaceStep(from, to, slice);
1917
- return new Fitter($from, $to, slice).fit();
1918
- }
1919
- function fitsTrivially($from, $to, slice) {
1920
- return !slice.openStart && !slice.openEnd && $from.start() == $to.start() &&
1921
- $from.parent.canReplace($from.index(), $to.index(), slice.content);
1922
- }
1923
- // Algorithm for 'placing' the elements of a slice into a gap:
1924
- //
1925
- // We consider the content of each node that is open to the left to be
1926
- // independently placeable. I.e. in <p("foo"), p("bar")>, when the
1927
- // paragraph on the left is open, "foo" can be placed (somewhere on
1928
- // the left side of the replacement gap) independently from p("bar").
1929
- //
1930
- // This class tracks the state of the placement progress in the
1931
- // following properties:
1932
- //
1933
- // - `frontier` holds a stack of `{type, match}` objects that
1934
- // represent the open side of the replacement. It starts at
1935
- // `$from`, then moves forward as content is placed, and is finally
1936
- // reconciled with `$to`.
1937
- //
1938
- // - `unplaced` is a slice that represents the content that hasn't
1939
- // been placed yet.
1940
- //
1941
- // - `placed` is a fragment of placed content. Its open-start value
1942
- // is implicit in `$from`, and its open-end value in `frontier`.
1943
- class Fitter {
1944
- constructor($from, $to, unplaced) {
1945
- this.$from = $from;
1946
- this.$to = $to;
1947
- this.unplaced = unplaced;
1948
- this.frontier = [];
1949
- this.placed = Fragment.empty;
1950
- for (let i = 0; i <= $from.depth; i++) {
1951
- let node = $from.node(i);
1952
- this.frontier.push({
1953
- type: node.type,
1954
- match: node.contentMatchAt($from.indexAfter(i))
1955
- });
1956
- }
1957
- for (let i = $from.depth; i > 0; i--)
1958
- this.placed = Fragment.from($from.node(i).copy(this.placed));
1959
- }
1960
- get depth() { return this.frontier.length - 1; }
1961
- fit() {
1962
- // As long as there's unplaced content, try to place some of it.
1963
- // If that fails, either increase the open score of the unplaced
1964
- // slice, or drop nodes from it, and then try again.
1965
- while (this.unplaced.size) {
1966
- let fit = this.findFittable();
1967
- if (fit)
1968
- this.placeNodes(fit);
1969
- else
1970
- this.openMore() || this.dropNode();
1971
- }
1972
- // When there's inline content directly after the frontier _and_
1973
- // directly after `this.$to`, we must generate a `ReplaceAround`
1974
- // step that pulls that content into the node after the frontier.
1975
- // That means the fitting must be done to the end of the textblock
1976
- // node after `this.$to`, not `this.$to` itself.
1977
- let moveInline = this.mustMoveInline(), placedSize = this.placed.size - this.depth - this.$from.depth;
1978
- let $from = this.$from, $to = this.close(moveInline < 0 ? this.$to : $from.doc.resolve(moveInline));
1979
- if (!$to)
1980
- return null;
1981
- // If closing to `$to` succeeded, create a step
1982
- let content = this.placed, openStart = $from.depth, openEnd = $to.depth;
1983
- while (openStart && openEnd && content.childCount == 1) { // Normalize by dropping open parent nodes
1984
- content = content.firstChild.content;
1985
- openStart--;
1986
- openEnd--;
1987
- }
1988
- let slice = new Slice(content, openStart, openEnd);
1989
- if (moveInline > -1)
1990
- return new ReplaceAroundStep($from.pos, moveInline, this.$to.pos, this.$to.end(), slice, placedSize);
1991
- if (slice.size || $from.pos != this.$to.pos) // Don't generate no-op steps
1992
- return new ReplaceStep($from.pos, $to.pos, slice);
1993
- return null;
1994
- }
1995
- // Find a position on the start spine of `this.unplaced` that has
1996
- // content that can be moved somewhere on the frontier. Returns two
1997
- // depths, one for the slice and one for the frontier.
1998
- findFittable() {
1999
- // Only try wrapping nodes (pass 2) after finding a place without
2000
- // wrapping failed.
2001
- for (let pass = 1; pass <= 2; pass++) {
2002
- for (let sliceDepth = this.unplaced.openStart; sliceDepth >= 0; sliceDepth--) {
2003
- let fragment, parent = null;
2004
- if (sliceDepth) {
2005
- parent = contentAt(this.unplaced.content, sliceDepth - 1).firstChild;
2006
- fragment = parent.content;
2007
- }
2008
- else {
2009
- fragment = this.unplaced.content;
2010
- }
2011
- let first = fragment.firstChild;
2012
- for (let frontierDepth = this.depth; frontierDepth >= 0; frontierDepth--) {
2013
- let { type, match } = this.frontier[frontierDepth], wrap, inject = null;
2014
- // In pass 1, if the next node matches, or there is no next
2015
- // node but the parents look compatible, we've found a
2016
- // place.
2017
- if (pass == 1 && (first ? match.matchType(first.type) || (inject = match.fillBefore(Fragment.from(first), false))
2018
- : parent && type.compatibleContent(parent.type)))
2019
- return { sliceDepth, frontierDepth, parent, inject };
2020
- // In pass 2, look for a set of wrapping nodes that make
2021
- // `first` fit here.
2022
- else if (pass == 2 && first && (wrap = match.findWrapping(first.type)))
2023
- return { sliceDepth, frontierDepth, parent, wrap };
2024
- // Don't continue looking further up if the parent node
2025
- // would fit here.
2026
- if (parent && match.matchType(parent.type))
2027
- break;
2028
- }
2029
- }
2030
- }
2031
- }
2032
- openMore() {
2033
- let { content, openStart, openEnd } = this.unplaced;
2034
- let inner = contentAt(content, openStart);
2035
- if (!inner.childCount || inner.firstChild.isLeaf)
2036
- return false;
2037
- this.unplaced = new Slice(content, openStart + 1, Math.max(openEnd, inner.size + openStart >= content.size - openEnd ? openStart + 1 : 0));
2038
- return true;
2039
- }
2040
- dropNode() {
2041
- let { content, openStart, openEnd } = this.unplaced;
2042
- let inner = contentAt(content, openStart);
2043
- if (inner.childCount <= 1 && openStart > 0) {
2044
- let openAtEnd = content.size - openStart <= openStart + inner.size;
2045
- this.unplaced = new Slice(dropFromFragment(content, openStart - 1, 1), openStart - 1, openAtEnd ? openStart - 1 : openEnd);
2046
- }
2047
- else {
2048
- this.unplaced = new Slice(dropFromFragment(content, openStart, 1), openStart, openEnd);
2049
- }
2050
- }
2051
- // Move content from the unplaced slice at `sliceDepth` to the
2052
- // frontier node at `frontierDepth`. Close that frontier node when
2053
- // applicable.
2054
- placeNodes({ sliceDepth, frontierDepth, parent, inject, wrap }) {
2055
- while (this.depth > frontierDepth)
2056
- this.closeFrontierNode();
2057
- if (wrap)
2058
- for (let i = 0; i < wrap.length; i++)
2059
- this.openFrontierNode(wrap[i]);
2060
- let slice = this.unplaced, fragment = parent ? parent.content : slice.content;
2061
- let openStart = slice.openStart - sliceDepth;
2062
- let taken = 0, add = [];
2063
- let { match, type } = this.frontier[frontierDepth];
2064
- if (inject) {
2065
- for (let i = 0; i < inject.childCount; i++)
2066
- add.push(inject.child(i));
2067
- match = match.matchFragment(inject);
2068
- }
2069
- // Computes the amount of (end) open nodes at the end of the
2070
- // fragment. When 0, the parent is open, but no more. When
2071
- // negative, nothing is open.
2072
- let openEndCount = (fragment.size + sliceDepth) - (slice.content.size - slice.openEnd);
2073
- // Scan over the fragment, fitting as many child nodes as
2074
- // possible.
2075
- while (taken < fragment.childCount) {
2076
- let next = fragment.child(taken), matches = match.matchType(next.type);
2077
- if (!matches)
2078
- break;
2079
- taken++;
2080
- if (taken > 1 || openStart == 0 || next.content.size) { // Drop empty open nodes
2081
- match = matches;
2082
- add.push(closeNodeStart(next.mark(type.allowedMarks(next.marks)), taken == 1 ? openStart : 0, taken == fragment.childCount ? openEndCount : -1));
2083
- }
2084
- }
2085
- let toEnd = taken == fragment.childCount;
2086
- if (!toEnd)
2087
- openEndCount = -1;
2088
- this.placed = addToFragment(this.placed, frontierDepth, Fragment.from(add));
2089
- this.frontier[frontierDepth].match = match;
2090
- // If the parent types match, and the entire node was moved, and
2091
- // it's not open, close this frontier node right away.
2092
- if (toEnd && openEndCount < 0 && parent && parent.type == this.frontier[this.depth].type && this.frontier.length > 1)
2093
- this.closeFrontierNode();
2094
- // Add new frontier nodes for any open nodes at the end.
2095
- for (let i = 0, cur = fragment; i < openEndCount; i++) {
2096
- let node = cur.lastChild;
2097
- this.frontier.push({ type: node.type, match: node.contentMatchAt(node.childCount) });
2098
- cur = node.content;
2099
- }
2100
- // Update `this.unplaced`. Drop the entire node from which we
2101
- // placed it we got to its end, otherwise just drop the placed
2102
- // nodes.
2103
- this.unplaced = !toEnd ? new Slice(dropFromFragment(slice.content, sliceDepth, taken), slice.openStart, slice.openEnd)
2104
- : sliceDepth == 0 ? Slice.empty
2105
- : new Slice(dropFromFragment(slice.content, sliceDepth - 1, 1), sliceDepth - 1, openEndCount < 0 ? slice.openEnd : sliceDepth - 1);
2106
- }
2107
- mustMoveInline() {
2108
- if (!this.$to.parent.isTextblock)
2109
- return -1;
2110
- let top = this.frontier[this.depth], level;
2111
- if (!top.type.isTextblock || !contentAfterFits(this.$to, this.$to.depth, top.type, top.match, false) ||
2112
- (this.$to.depth == this.depth && (level = this.findCloseLevel(this.$to)) && level.depth == this.depth))
2113
- return -1;
2114
- let { depth } = this.$to, after = this.$to.after(depth);
2115
- while (depth > 1 && after == this.$to.end(--depth))
2116
- ++after;
2117
- return after;
2118
- }
2119
- findCloseLevel($to) {
2120
- scan: for (let i = Math.min(this.depth, $to.depth); i >= 0; i--) {
2121
- let { match, type } = this.frontier[i];
2122
- let dropInner = i < $to.depth && $to.end(i + 1) == $to.pos + ($to.depth - (i + 1));
2123
- let fit = contentAfterFits($to, i, type, match, dropInner);
2124
- if (!fit)
2125
- continue;
2126
- for (let d = i - 1; d >= 0; d--) {
2127
- let { match, type } = this.frontier[d];
2128
- let matches = contentAfterFits($to, d, type, match, true);
2129
- if (!matches || matches.childCount)
2130
- continue scan;
2131
- }
2132
- return { depth: i, fit, move: dropInner ? $to.doc.resolve($to.after(i + 1)) : $to };
2133
- }
2134
- }
2135
- close($to) {
2136
- let close = this.findCloseLevel($to);
2137
- if (!close)
2138
- return null;
2139
- while (this.depth > close.depth)
2140
- this.closeFrontierNode();
2141
- if (close.fit.childCount)
2142
- this.placed = addToFragment(this.placed, close.depth, close.fit);
2143
- $to = close.move;
2144
- for (let d = close.depth + 1; d <= $to.depth; d++) {
2145
- let node = $to.node(d), add = node.type.contentMatch.fillBefore(node.content, true, $to.index(d));
2146
- this.openFrontierNode(node.type, node.attrs, add);
2147
- }
2148
- return $to;
2149
- }
2150
- openFrontierNode(type, attrs = null, content) {
2151
- let top = this.frontier[this.depth];
2152
- top.match = top.match.matchType(type);
2153
- this.placed = addToFragment(this.placed, this.depth, Fragment.from(type.create(attrs, content)));
2154
- this.frontier.push({ type, match: type.contentMatch });
2155
- }
2156
- closeFrontierNode() {
2157
- let open = this.frontier.pop();
2158
- let add = open.match.fillBefore(Fragment.empty, true);
2159
- if (add.childCount)
2160
- this.placed = addToFragment(this.placed, this.frontier.length, add);
2161
- }
2162
- }
2163
- function dropFromFragment(fragment, depth, count) {
2164
- if (depth == 0)
2165
- return fragment.cutByIndex(count, fragment.childCount);
2166
- return fragment.replaceChild(0, fragment.firstChild.copy(dropFromFragment(fragment.firstChild.content, depth - 1, count)));
2167
- }
2168
- function addToFragment(fragment, depth, content) {
2169
- if (depth == 0)
2170
- return fragment.append(content);
2171
- return fragment.replaceChild(fragment.childCount - 1, fragment.lastChild.copy(addToFragment(fragment.lastChild.content, depth - 1, content)));
2172
- }
2173
- function contentAt(fragment, depth) {
2174
- for (let i = 0; i < depth; i++)
2175
- fragment = fragment.firstChild.content;
2176
- return fragment;
2177
- }
2178
- function closeNodeStart(node, openStart, openEnd) {
2179
- if (openStart <= 0)
2180
- return node;
2181
- let frag = node.content;
2182
- if (openStart > 1)
2183
- frag = frag.replaceChild(0, closeNodeStart(frag.firstChild, openStart - 1, frag.childCount == 1 ? openEnd - 1 : 0));
2184
- if (openStart > 0) {
2185
- frag = node.type.contentMatch.fillBefore(frag).append(frag);
2186
- if (openEnd <= 0)
2187
- frag = frag.append(node.type.contentMatch.matchFragment(frag).fillBefore(Fragment.empty, true));
2188
- }
2189
- return node.copy(frag);
2190
- }
2191
- function contentAfterFits($to, depth, type, match, open) {
2192
- let node = $to.node(depth), index = open ? $to.indexAfter(depth) : $to.index(depth);
2193
- if (index == node.childCount && !type.compatibleContent(node.type))
2194
- return null;
2195
- let fit = match.fillBefore(node.content, true, index);
2196
- return fit && !invalidMarks(type, node.content, index) ? fit : null;
2197
- }
2198
- function invalidMarks(type, fragment, start) {
2199
- for (let i = start; i < fragment.childCount; i++)
2200
- if (!type.allowsMarks(fragment.child(i).marks))
2201
- return true;
2202
- return false;
2203
- }
2204
- function definesContent(type) {
2205
- return type.spec.defining || type.spec.definingForContent;
2206
- }
2207
- function replaceRange(tr, from, to, slice) {
2208
- if (!slice.size)
2209
- return tr.deleteRange(from, to);
2210
- let $from = tr.doc.resolve(from), $to = tr.doc.resolve(to);
2211
- if (fitsTrivially($from, $to, slice))
2212
- return tr.step(new ReplaceStep(from, to, slice));
2213
- let targetDepths = coveredDepths($from, tr.doc.resolve(to));
2214
- // Can't replace the whole document, so remove 0 if it's present
2215
- if (targetDepths[targetDepths.length - 1] == 0)
2216
- targetDepths.pop();
2217
- // Negative numbers represent not expansion over the whole node at
2218
- // that depth, but replacing from $from.before(-D) to $to.pos.
2219
- let preferredTarget = -($from.depth + 1);
2220
- targetDepths.unshift(preferredTarget);
2221
- // This loop picks a preferred target depth, if one of the covering
2222
- // depths is not outside of a defining node, and adds negative
2223
- // depths for any depth that has $from at its start and does not
2224
- // cross a defining node.
2225
- for (let d = $from.depth, pos = $from.pos - 1; d > 0; d--, pos--) {
2226
- let spec = $from.node(d).type.spec;
2227
- if (spec.defining || spec.definingAsContext || spec.isolating)
2228
- break;
2229
- if (targetDepths.indexOf(d) > -1)
2230
- preferredTarget = d;
2231
- else if ($from.before(d) == pos)
2232
- targetDepths.splice(1, 0, -d);
2233
- }
2234
- // Try to fit each possible depth of the slice into each possible
2235
- // target depth, starting with the preferred depths.
2236
- let preferredTargetIndex = targetDepths.indexOf(preferredTarget);
2237
- let leftNodes = [], preferredDepth = slice.openStart;
2238
- for (let content = slice.content, i = 0;; i++) {
2239
- let node = content.firstChild;
2240
- leftNodes.push(node);
2241
- if (i == slice.openStart)
2242
- break;
2243
- content = node.content;
2244
- }
2245
- // Back up preferredDepth to cover defining textblocks directly
2246
- // above it, possibly skipping a non-defining textblock.
2247
- for (let d = preferredDepth - 1; d >= 0; d--) {
2248
- let type = leftNodes[d].type, def = definesContent(type);
2249
- if (def && $from.node(preferredTargetIndex).type != type)
2250
- preferredDepth = d;
2251
- else if (def || !type.isTextblock)
2252
- break;
2253
- }
2254
- for (let j = slice.openStart; j >= 0; j--) {
2255
- let openDepth = (j + preferredDepth + 1) % (slice.openStart + 1);
2256
- let insert = leftNodes[openDepth];
2257
- if (!insert)
2258
- continue;
2259
- for (let i = 0; i < targetDepths.length; i++) {
2260
- // Loop over possible expansion levels, starting with the
2261
- // preferred one
2262
- let targetDepth = targetDepths[(i + preferredTargetIndex) % targetDepths.length], expand = true;
2263
- if (targetDepth < 0) {
2264
- expand = false;
2265
- targetDepth = -targetDepth;
2266
- }
2267
- let parent = $from.node(targetDepth - 1), index = $from.index(targetDepth - 1);
2268
- if (parent.canReplaceWith(index, index, insert.type, insert.marks))
2269
- return tr.replace($from.before(targetDepth), expand ? $to.after(targetDepth) : to, new Slice(closeFragment(slice.content, 0, slice.openStart, openDepth), openDepth, slice.openEnd));
2270
- }
2271
- }
2272
- let startSteps = tr.steps.length;
2273
- for (let i = targetDepths.length - 1; i >= 0; i--) {
2274
- tr.replace(from, to, slice);
2275
- if (tr.steps.length > startSteps)
2276
- break;
2277
- let depth = targetDepths[i];
2278
- if (depth < 0)
2279
- continue;
2280
- from = $from.before(depth);
2281
- to = $to.after(depth);
2282
- }
2283
- }
2284
- function closeFragment(fragment, depth, oldOpen, newOpen, parent) {
2285
- if (depth < oldOpen) {
2286
- let first = fragment.firstChild;
2287
- fragment = fragment.replaceChild(0, first.copy(closeFragment(first.content, depth + 1, oldOpen, newOpen, first)));
2288
- }
2289
- if (depth > newOpen) {
2290
- let match = parent.contentMatchAt(0);
2291
- let start = match.fillBefore(fragment).append(fragment);
2292
- fragment = start.append(match.matchFragment(start).fillBefore(Fragment.empty, true));
2293
- }
2294
- return fragment;
2295
- }
2296
- function replaceRangeWith(tr, from, to, node) {
2297
- if (!node.isInline && from == to && tr.doc.resolve(from).parent.content.size) {
2298
- let point = insertPoint(tr.doc, from, node.type);
2299
- if (point != null)
2300
- from = to = point;
2301
- }
2302
- tr.replaceRange(from, to, new Slice(Fragment.from(node), 0, 0));
2303
- }
2304
- function deleteRange(tr, from, to) {
2305
- let $from = tr.doc.resolve(from), $to = tr.doc.resolve(to);
2306
- let covered = coveredDepths($from, $to);
2307
- for (let i = 0; i < covered.length; i++) {
2308
- let depth = covered[i], last = i == covered.length - 1;
2309
- if ((last && depth == 0) || $from.node(depth).type.contentMatch.validEnd)
2310
- return tr.delete($from.start(depth), $to.end(depth));
2311
- if (depth > 0 && (last || $from.node(depth - 1).canReplace($from.index(depth - 1), $to.indexAfter(depth - 1))))
2312
- return tr.delete($from.before(depth), $to.after(depth));
2313
- }
2314
- for (let d = 1; d <= $from.depth && d <= $to.depth; d++) {
2315
- if (from - $from.start(d) == $from.depth - d && to > $from.end(d) && $to.end(d) - to != $to.depth - d)
2316
- return tr.delete($from.before(d), to);
2317
- }
2318
- tr.delete(from, to);
2319
- }
2320
- // Returns an array of all depths for which $from - $to spans the
2321
- // whole content of the nodes at that depth.
2322
- function coveredDepths($from, $to) {
2323
- let result = [], minDepth = Math.min($from.depth, $to.depth);
2324
- for (let d = minDepth; d >= 0; d--) {
2325
- let start = $from.start(d);
2326
- if (start < $from.pos - ($from.depth - d) ||
2327
- $to.end(d) > $to.pos + ($to.depth - d) ||
2328
- $from.node(d).type.spec.isolating ||
2329
- $to.node(d).type.spec.isolating)
2330
- break;
2331
- if (start == $to.start(d) ||
2332
- (d == $from.depth && d == $to.depth && $from.parent.inlineContent && $to.parent.inlineContent &&
2333
- d && $to.start(d - 1) == start - 1))
2334
- result.push(d);
2335
- }
2336
- return result;
2337
- }
2338
-
2339
- /**
2340
- Update an attribute in a specific node.
2341
- */
2342
- class AttrStep extends Step {
2343
- /**
2344
- Construct an attribute step.
2345
- */
2346
- constructor(
2347
- /**
2348
- The position of the target node.
2349
- */
2350
- pos,
2351
- /**
2352
- The attribute to set.
2353
- */
2354
- attr,
2355
- // The attribute's new value.
2356
- value) {
2357
- super();
2358
- this.pos = pos;
2359
- this.attr = attr;
2360
- this.value = value;
2361
- }
2362
- apply(doc) {
2363
- let node = doc.nodeAt(this.pos);
2364
- if (!node)
2365
- return StepResult.fail("No node at attribute step's position");
2366
- let attrs = Object.create(null);
2367
- for (let name in node.attrs)
2368
- attrs[name] = node.attrs[name];
2369
- attrs[this.attr] = this.value;
2370
- let updated = node.type.create(attrs, null, node.marks);
2371
- return StepResult.fromReplace(doc, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));
2372
- }
2373
- getMap() {
2374
- return StepMap.empty;
2375
- }
2376
- invert(doc) {
2377
- return new AttrStep(this.pos, this.attr, doc.nodeAt(this.pos).attrs[this.attr]);
2378
- }
2379
- map(mapping) {
2380
- let pos = mapping.mapResult(this.pos, 1);
2381
- return pos.deletedAfter ? null : new AttrStep(pos.pos, this.attr, this.value);
2382
- }
2383
- toJSON() {
2384
- return { stepType: "attr", pos: this.pos, attr: this.attr, value: this.value };
2385
- }
2386
- static fromJSON(schema, json) {
2387
- if (typeof json.pos != "number" || typeof json.attr != "string")
2388
- throw new RangeError("Invalid input for AttrStep.fromJSON");
2389
- return new AttrStep(json.pos, json.attr, json.value);
2390
- }
2391
- }
2392
- Step.jsonID("attr", AttrStep);
2393
-
2394
- /**
2395
- @internal
2396
- */
2397
- let TransformError = class extends Error {
2398
- };
2399
- TransformError = function TransformError(message) {
2400
- let err = Error.call(this, message);
2401
- err.__proto__ = TransformError.prototype;
2402
- return err;
2403
- };
2404
- TransformError.prototype = Object.create(Error.prototype);
2405
- TransformError.prototype.constructor = TransformError;
2406
- TransformError.prototype.name = "TransformError";
2407
- /**
2408
- Abstraction to build up and track an array of
2409
- [steps](https://prosemirror.net/docs/ref/#transform.Step) representing a document transformation.
2410
-
2411
- Most transforming methods return the `Transform` object itself, so
2412
- that they can be chained.
2413
- */
2414
- class Transform {
2415
- /**
2416
- Create a transform that starts with the given document.
2417
- */
2418
- constructor(
2419
- /**
2420
- The current document (the result of applying the steps in the
2421
- transform).
2422
- */
2423
- doc) {
2424
- this.doc = doc;
2425
- /**
2426
- The steps in this transform.
2427
- */
2428
- this.steps = [];
2429
- /**
2430
- The documents before each of the steps.
2431
- */
2432
- this.docs = [];
2433
- /**
2434
- A mapping with the maps for each of the steps in this transform.
2435
- */
2436
- this.mapping = new Mapping;
2437
- }
2438
- /**
2439
- The starting document.
2440
- */
2441
- get before() { return this.docs.length ? this.docs[0] : this.doc; }
2442
- /**
2443
- Apply a new step in this transform, saving the result. Throws an
2444
- error when the step fails.
2445
- */
2446
- step(step) {
2447
- let result = this.maybeStep(step);
2448
- if (result.failed)
2449
- throw new TransformError(result.failed);
2450
- return this;
2451
- }
2452
- /**
2453
- Try to apply a step in this transformation, ignoring it if it
2454
- fails. Returns the step result.
2455
- */
2456
- maybeStep(step) {
2457
- let result = step.apply(this.doc);
2458
- if (!result.failed)
2459
- this.addStep(step, result.doc);
2460
- return result;
2461
- }
2462
- /**
2463
- True when the document has been changed (when there are any
2464
- steps).
2465
- */
2466
- get docChanged() {
2467
- return this.steps.length > 0;
2468
- }
2469
- /**
2470
- @internal
2471
- */
2472
- addStep(step, doc) {
2473
- this.docs.push(this.doc);
2474
- this.steps.push(step);
2475
- this.mapping.appendMap(step.getMap());
2476
- this.doc = doc;
2477
- }
2478
- /**
2479
- Replace the part of the document between `from` and `to` with the
2480
- given `slice`.
2481
- */
2482
- replace(from, to = from, slice = Slice.empty) {
2483
- let step = replaceStep(this.doc, from, to, slice);
2484
- if (step)
2485
- this.step(step);
2486
- return this;
2487
- }
2488
- /**
2489
- Replace the given range with the given content, which may be a
2490
- fragment, node, or array of nodes.
2491
- */
2492
- replaceWith(from, to, content) {
2493
- return this.replace(from, to, new Slice(Fragment.from(content), 0, 0));
2494
- }
2495
- /**
2496
- Delete the content between the given positions.
2497
- */
2498
- delete(from, to) {
2499
- return this.replace(from, to, Slice.empty);
2500
- }
2501
- /**
2502
- Insert the given content at the given position.
2503
- */
2504
- insert(pos, content) {
2505
- return this.replaceWith(pos, pos, content);
2506
- }
2507
- /**
2508
- Replace a range of the document with a given slice, using
2509
- `from`, `to`, and the slice's
2510
- [`openStart`](https://prosemirror.net/docs/ref/#model.Slice.openStart) property as hints, rather
2511
- than fixed start and end points. This method may grow the
2512
- replaced area or close open nodes in the slice in order to get a
2513
- fit that is more in line with WYSIWYG expectations, by dropping
2514
- fully covered parent nodes of the replaced region when they are
2515
- marked [non-defining as
2516
- context](https://prosemirror.net/docs/ref/#model.NodeSpec.definingAsContext), or including an
2517
- open parent node from the slice that _is_ marked as [defining
2518
- its content](https://prosemirror.net/docs/ref/#model.NodeSpec.definingForContent).
2519
-
2520
- This is the method, for example, to handle paste. The similar
2521
- [`replace`](https://prosemirror.net/docs/ref/#transform.Transform.replace) method is a more
2522
- primitive tool which will _not_ move the start and end of its given
2523
- range, and is useful in situations where you need more precise
2524
- control over what happens.
2525
- */
2526
- replaceRange(from, to, slice) {
2527
- replaceRange(this, from, to, slice);
2528
- return this;
2529
- }
2530
- /**
2531
- Replace the given range with a node, but use `from` and `to` as
2532
- hints, rather than precise positions. When from and to are the same
2533
- and are at the start or end of a parent node in which the given
2534
- node doesn't fit, this method may _move_ them out towards a parent
2535
- that does allow the given node to be placed. When the given range
2536
- completely covers a parent node, this method may completely replace
2537
- that parent node.
2538
- */
2539
- replaceRangeWith(from, to, node) {
2540
- replaceRangeWith(this, from, to, node);
2541
- return this;
2542
- }
2543
- /**
2544
- Delete the given range, expanding it to cover fully covered
2545
- parent nodes until a valid replace is found.
2546
- */
2547
- deleteRange(from, to) {
2548
- deleteRange(this, from, to);
2549
- return this;
2550
- }
2551
- /**
2552
- Split the content in the given range off from its parent, if there
2553
- is sibling content before or after it, and move it up the tree to
2554
- the depth specified by `target`. You'll probably want to use
2555
- [`liftTarget`](https://prosemirror.net/docs/ref/#transform.liftTarget) to compute `target`, to make
2556
- sure the lift is valid.
2557
- */
2558
- lift(range, target) {
2559
- lift(this, range, target);
2560
- return this;
2561
- }
2562
- /**
2563
- Join the blocks around the given position. If depth is 2, their
2564
- last and first siblings are also joined, and so on.
2565
- */
2566
- join(pos, depth = 1) {
2567
- join(this, pos, depth);
2568
- return this;
2569
- }
2570
- /**
2571
- Wrap the given [range](https://prosemirror.net/docs/ref/#model.NodeRange) in the given set of wrappers.
2572
- The wrappers are assumed to be valid in this position, and should
2573
- probably be computed with [`findWrapping`](https://prosemirror.net/docs/ref/#transform.findWrapping).
2574
- */
2575
- wrap(range, wrappers) {
2576
- wrap(this, range, wrappers);
2577
- return this;
2578
- }
2579
- /**
2580
- Set the type of all textblocks (partly) between `from` and `to` to
2581
- the given node type with the given attributes.
2582
- */
2583
- setBlockType(from, to = from, type, attrs = null) {
2584
- setBlockType(this, from, to, type, attrs);
2585
- return this;
2586
- }
2587
- /**
2588
- Change the type, attributes, and/or marks of the node at `pos`.
2589
- When `type` isn't given, the existing node type is preserved,
2590
- */
2591
- setNodeMarkup(pos, type, attrs = null, marks = []) {
2592
- setNodeMarkup(this, pos, type, attrs, marks);
2593
- return this;
2594
- }
2595
- /**
2596
- Set a single attribute on a given node to a new value.
2597
- */
2598
- setNodeAttribute(pos, attr, value) {
2599
- this.step(new AttrStep(pos, attr, value));
2600
- return this;
2601
- }
2602
- /**
2603
- Add a mark to the node at position `pos`.
2604
- */
2605
- addNodeMark(pos, mark) {
2606
- this.step(new AddNodeMarkStep(pos, mark));
2607
- return this;
2608
- }
2609
- /**
2610
- Remove a mark (or a mark of the given type) from the node at
2611
- position `pos`.
2612
- */
2613
- removeNodeMark(pos, mark) {
2614
- if (!(mark instanceof Mark)) {
2615
- let node = this.doc.nodeAt(pos);
2616
- if (!node)
2617
- throw new RangeError("No node at position " + pos);
2618
- mark = mark.isInSet(node.marks);
2619
- if (!mark)
2620
- return this;
2621
- }
2622
- this.step(new RemoveNodeMarkStep(pos, mark));
2623
- return this;
2624
- }
2625
- /**
2626
- Split the node at the given position, and optionally, if `depth` is
2627
- greater than one, any number of nodes above that. By default, the
2628
- parts split off will inherit the node type of the original node.
2629
- This can be changed by passing an array of types and attributes to
2630
- use after the split.
2631
- */
2632
- split(pos, depth = 1, typesAfter) {
2633
- split(this, pos, depth, typesAfter);
2634
- return this;
2635
- }
2636
- /**
2637
- Add the given mark to the inline content between `from` and `to`.
2638
- */
2639
- addMark(from, to, mark) {
2640
- addMark(this, from, to, mark);
2641
- return this;
2642
- }
2643
- /**
2644
- Remove marks from inline nodes between `from` and `to`. When
2645
- `mark` is a single mark, remove precisely that mark. When it is
2646
- a mark type, remove all marks of that type. When it is null,
2647
- remove all marks of any type.
2648
- */
2649
- removeMark(from, to, mark) {
2650
- removeMark(this, from, to, mark);
2651
- return this;
2652
- }
2653
- /**
2654
- Removes all marks and nodes from the content of the node at
2655
- `pos` that don't match the given new parent node type. Accepts
2656
- an optional starting [content match](https://prosemirror.net/docs/ref/#model.ContentMatch) as
2657
- third argument.
2658
- */
2659
- clearIncompatible(pos, parentType, match) {
2660
- clearIncompatible(this, pos, parentType, match);
2661
- return this;
2662
- }
2663
- }
2664
-
2665
- const classesById = Object.create(null);
2666
- /**
2667
- Superclass for editor selections. Every selection type should
2668
- extend this. Should not be instantiated directly.
2669
- */
2670
- class Selection {
2671
- /**
2672
- Initialize a selection with the head and anchor and ranges. If no
2673
- ranges are given, constructs a single range across `$anchor` and
2674
- `$head`.
2675
- */
2676
- constructor(
2677
- /**
2678
- The resolved anchor of the selection (the side that stays in
2679
- place when the selection is modified).
2680
- */
2681
- $anchor,
2682
- /**
2683
- The resolved head of the selection (the side that moves when
2684
- the selection is modified).
2685
- */
2686
- $head, ranges) {
2687
- this.$anchor = $anchor;
2688
- this.$head = $head;
2689
- this.ranges = ranges || [new SelectionRange($anchor.min($head), $anchor.max($head))];
2690
- }
2691
- /**
2692
- The selection's anchor, as an unresolved position.
2693
- */
2694
- get anchor() { return this.$anchor.pos; }
2695
- /**
2696
- The selection's head.
2697
- */
2698
- get head() { return this.$head.pos; }
2699
- /**
2700
- The lower bound of the selection's main range.
2701
- */
2702
- get from() { return this.$from.pos; }
2703
- /**
2704
- The upper bound of the selection's main range.
2705
- */
2706
- get to() { return this.$to.pos; }
2707
- /**
2708
- The resolved lower bound of the selection's main range.
2709
- */
2710
- get $from() {
2711
- return this.ranges[0].$from;
2712
- }
2713
- /**
2714
- The resolved upper bound of the selection's main range.
2715
- */
2716
- get $to() {
2717
- return this.ranges[0].$to;
2718
- }
2719
- /**
2720
- Indicates whether the selection contains any content.
2721
- */
2722
- get empty() {
2723
- let ranges = this.ranges;
2724
- for (let i = 0; i < ranges.length; i++)
2725
- if (ranges[i].$from.pos != ranges[i].$to.pos)
2726
- return false;
2727
- return true;
2728
- }
2729
- /**
2730
- Get the content of this selection as a slice.
2731
- */
2732
- content() {
2733
- return this.$from.doc.slice(this.from, this.to, true);
2734
- }
2735
- /**
2736
- Replace the selection with a slice or, if no slice is given,
2737
- delete the selection. Will append to the given transaction.
2738
- */
2739
- replace(tr, content = Slice.empty) {
2740
- // Put the new selection at the position after the inserted
2741
- // content. When that ended in an inline node, search backwards,
2742
- // to get the position after that node. If not, search forward.
2743
- let lastNode = content.content.lastChild, lastParent = null;
2744
- for (let i = 0; i < content.openEnd; i++) {
2745
- lastParent = lastNode;
2746
- lastNode = lastNode.lastChild;
2747
- }
2748
- let mapFrom = tr.steps.length, ranges = this.ranges;
2749
- for (let i = 0; i < ranges.length; i++) {
2750
- let { $from, $to } = ranges[i], mapping = tr.mapping.slice(mapFrom);
2751
- tr.replaceRange(mapping.map($from.pos), mapping.map($to.pos), i ? Slice.empty : content);
2752
- if (i == 0)
2753
- selectionToInsertionEnd(tr, mapFrom, (lastNode ? lastNode.isInline : lastParent && lastParent.isTextblock) ? -1 : 1);
2754
- }
2755
- }
2756
- /**
2757
- Replace the selection with the given node, appending the changes
2758
- to the given transaction.
2759
- */
2760
- replaceWith(tr, node) {
2761
- let mapFrom = tr.steps.length, ranges = this.ranges;
2762
- for (let i = 0; i < ranges.length; i++) {
2763
- let { $from, $to } = ranges[i], mapping = tr.mapping.slice(mapFrom);
2764
- let from = mapping.map($from.pos), to = mapping.map($to.pos);
2765
- if (i) {
2766
- tr.deleteRange(from, to);
2767
- }
2768
- else {
2769
- tr.replaceRangeWith(from, to, node);
2770
- selectionToInsertionEnd(tr, mapFrom, node.isInline ? -1 : 1);
2771
- }
2772
- }
2773
- }
2774
- /**
2775
- Find a valid cursor or leaf node selection starting at the given
2776
- position and searching back if `dir` is negative, and forward if
2777
- positive. When `textOnly` is true, only consider cursor
2778
- selections. Will return null when no valid selection position is
2779
- found.
2780
- */
2781
- static findFrom($pos, dir, textOnly = false) {
2782
- let inner = $pos.parent.inlineContent ? new TextSelection($pos)
2783
- : findSelectionIn($pos.node(0), $pos.parent, $pos.pos, $pos.index(), dir, textOnly);
2784
- if (inner)
2785
- return inner;
2786
- for (let depth = $pos.depth - 1; depth >= 0; depth--) {
2787
- let found = dir < 0
2788
- ? findSelectionIn($pos.node(0), $pos.node(depth), $pos.before(depth + 1), $pos.index(depth), dir, textOnly)
2789
- : findSelectionIn($pos.node(0), $pos.node(depth), $pos.after(depth + 1), $pos.index(depth) + 1, dir, textOnly);
2790
- if (found)
2791
- return found;
2792
- }
2793
- return null;
2794
- }
2795
- /**
2796
- Find a valid cursor or leaf node selection near the given
2797
- position. Searches forward first by default, but if `bias` is
2798
- negative, it will search backwards first.
2799
- */
2800
- static near($pos, bias = 1) {
2801
- return this.findFrom($pos, bias) || this.findFrom($pos, -bias) || new AllSelection($pos.node(0));
2802
- }
2803
- /**
2804
- Find the cursor or leaf node selection closest to the start of
2805
- the given document. Will return an
2806
- [`AllSelection`](https://prosemirror.net/docs/ref/#state.AllSelection) if no valid position
2807
- exists.
2808
- */
2809
- static atStart(doc) {
2810
- return findSelectionIn(doc, doc, 0, 0, 1) || new AllSelection(doc);
2811
- }
2812
- /**
2813
- Find the cursor or leaf node selection closest to the end of the
2814
- given document.
2815
- */
2816
- static atEnd(doc) {
2817
- return findSelectionIn(doc, doc, doc.content.size, doc.childCount, -1) || new AllSelection(doc);
2818
- }
2819
- /**
2820
- Deserialize the JSON representation of a selection. Must be
2821
- implemented for custom classes (as a static class method).
2822
- */
2823
- static fromJSON(doc, json) {
2824
- if (!json || !json.type)
2825
- throw new RangeError("Invalid input for Selection.fromJSON");
2826
- let cls = classesById[json.type];
2827
- if (!cls)
2828
- throw new RangeError(`No selection type ${json.type} defined`);
2829
- return cls.fromJSON(doc, json);
2830
- }
2831
- /**
2832
- To be able to deserialize selections from JSON, custom selection
2833
- classes must register themselves with an ID string, so that they
2834
- can be disambiguated. Try to pick something that's unlikely to
2835
- clash with classes from other modules.
2836
- */
2837
- static jsonID(id, selectionClass) {
2838
- if (id in classesById)
2839
- throw new RangeError("Duplicate use of selection JSON ID " + id);
2840
- classesById[id] = selectionClass;
2841
- selectionClass.prototype.jsonID = id;
2842
- return selectionClass;
2843
- }
2844
- /**
2845
- Get a [bookmark](https://prosemirror.net/docs/ref/#state.SelectionBookmark) for this selection,
2846
- which is a value that can be mapped without having access to a
2847
- current document, and later resolved to a real selection for a
2848
- given document again. (This is used mostly by the history to
2849
- track and restore old selections.) The default implementation of
2850
- this method just converts the selection to a text selection and
2851
- returns the bookmark for that.
2852
- */
2853
- getBookmark() {
2854
- return TextSelection.between(this.$anchor, this.$head).getBookmark();
2855
- }
2856
- }
2857
- Selection.prototype.visible = true;
2858
- /**
2859
- Represents a selected range in a document.
2860
- */
2861
- class SelectionRange {
2862
- /**
2863
- Create a range.
2864
- */
2865
- constructor(
2866
- /**
2867
- The lower bound of the range.
2868
- */
2869
- $from,
2870
- /**
2871
- The upper bound of the range.
2872
- */
2873
- $to) {
2874
- this.$from = $from;
2875
- this.$to = $to;
2876
- }
2877
- }
2878
- let warnedAboutTextSelection = false;
2879
- function checkTextSelection($pos) {
2880
- if (!warnedAboutTextSelection && !$pos.parent.inlineContent) {
2881
- warnedAboutTextSelection = true;
2882
- console["warn"]("TextSelection endpoint not pointing into a node with inline content (" + $pos.parent.type.name + ")");
2883
- }
2884
- }
2885
- /**
2886
- A text selection represents a classical editor selection, with a
2887
- head (the moving side) and anchor (immobile side), both of which
2888
- point into textblock nodes. It can be empty (a regular cursor
2889
- position).
2890
- */
2891
- class TextSelection extends Selection {
2892
- /**
2893
- Construct a text selection between the given points.
2894
- */
2895
- constructor($anchor, $head = $anchor) {
2896
- checkTextSelection($anchor);
2897
- checkTextSelection($head);
2898
- super($anchor, $head);
2899
- }
2900
- /**
2901
- Returns a resolved position if this is a cursor selection (an
2902
- empty text selection), and null otherwise.
2903
- */
2904
- get $cursor() { return this.$anchor.pos == this.$head.pos ? this.$head : null; }
2905
- map(doc, mapping) {
2906
- let $head = doc.resolve(mapping.map(this.head));
2907
- if (!$head.parent.inlineContent)
2908
- return Selection.near($head);
2909
- let $anchor = doc.resolve(mapping.map(this.anchor));
2910
- return new TextSelection($anchor.parent.inlineContent ? $anchor : $head, $head);
2911
- }
2912
- replace(tr, content = Slice.empty) {
2913
- super.replace(tr, content);
2914
- if (content == Slice.empty) {
2915
- let marks = this.$from.marksAcross(this.$to);
2916
- if (marks)
2917
- tr.ensureMarks(marks);
2918
- }
2919
- }
2920
- eq(other) {
2921
- return other instanceof TextSelection && other.anchor == this.anchor && other.head == this.head;
2922
- }
2923
- getBookmark() {
2924
- return new TextBookmark(this.anchor, this.head);
2925
- }
2926
- toJSON() {
2927
- return { type: "text", anchor: this.anchor, head: this.head };
2928
- }
2929
- /**
2930
- @internal
2931
- */
2932
- static fromJSON(doc, json) {
2933
- if (typeof json.anchor != "number" || typeof json.head != "number")
2934
- throw new RangeError("Invalid input for TextSelection.fromJSON");
2935
- return new TextSelection(doc.resolve(json.anchor), doc.resolve(json.head));
2936
- }
2937
- /**
2938
- Create a text selection from non-resolved positions.
2939
- */
2940
- static create(doc, anchor, head = anchor) {
2941
- let $anchor = doc.resolve(anchor);
2942
- return new this($anchor, head == anchor ? $anchor : doc.resolve(head));
2943
- }
2944
- /**
2945
- Return a text selection that spans the given positions or, if
2946
- they aren't text positions, find a text selection near them.
2947
- `bias` determines whether the method searches forward (default)
2948
- or backwards (negative number) first. Will fall back to calling
2949
- [`Selection.near`](https://prosemirror.net/docs/ref/#state.Selection^near) when the document
2950
- doesn't contain a valid text position.
2951
- */
2952
- static between($anchor, $head, bias) {
2953
- let dPos = $anchor.pos - $head.pos;
2954
- if (!bias || dPos)
2955
- bias = dPos >= 0 ? 1 : -1;
2956
- if (!$head.parent.inlineContent) {
2957
- let found = Selection.findFrom($head, bias, true) || Selection.findFrom($head, -bias, true);
2958
- if (found)
2959
- $head = found.$head;
2960
- else
2961
- return Selection.near($head, bias);
2962
- }
2963
- if (!$anchor.parent.inlineContent) {
2964
- if (dPos == 0) {
2965
- $anchor = $head;
2966
- }
2967
- else {
2968
- $anchor = (Selection.findFrom($anchor, -bias, true) || Selection.findFrom($anchor, bias, true)).$anchor;
2969
- if (($anchor.pos < $head.pos) != (dPos < 0))
2970
- $anchor = $head;
2971
- }
2972
- }
2973
- return new TextSelection($anchor, $head);
2974
- }
2975
- }
2976
- Selection.jsonID("text", TextSelection);
2977
- class TextBookmark {
2978
- constructor(anchor, head) {
2979
- this.anchor = anchor;
2980
- this.head = head;
2981
- }
2982
- map(mapping) {
2983
- return new TextBookmark(mapping.map(this.anchor), mapping.map(this.head));
2984
- }
2985
- resolve(doc) {
2986
- return TextSelection.between(doc.resolve(this.anchor), doc.resolve(this.head));
2987
- }
2988
- }
2989
- /**
2990
- A node selection is a selection that points at a single node. All
2991
- nodes marked [selectable](https://prosemirror.net/docs/ref/#model.NodeSpec.selectable) can be the
2992
- target of a node selection. In such a selection, `from` and `to`
2993
- point directly before and after the selected node, `anchor` equals
2994
- `from`, and `head` equals `to`..
2995
- */
2996
- class NodeSelection extends Selection {
2997
- /**
2998
- Create a node selection. Does not verify the validity of its
2999
- argument.
3000
- */
3001
- constructor($pos) {
3002
- let node = $pos.nodeAfter;
3003
- let $end = $pos.node(0).resolve($pos.pos + node.nodeSize);
3004
- super($pos, $end);
3005
- this.node = node;
3006
- }
3007
- map(doc, mapping) {
3008
- let { deleted, pos } = mapping.mapResult(this.anchor);
3009
- let $pos = doc.resolve(pos);
3010
- if (deleted)
3011
- return Selection.near($pos);
3012
- return new NodeSelection($pos);
3013
- }
3014
- content() {
3015
- return new Slice(Fragment.from(this.node), 0, 0);
3016
- }
3017
- eq(other) {
3018
- return other instanceof NodeSelection && other.anchor == this.anchor;
3019
- }
3020
- toJSON() {
3021
- return { type: "node", anchor: this.anchor };
3022
- }
3023
- getBookmark() { return new NodeBookmark(this.anchor); }
3024
- /**
3025
- @internal
3026
- */
3027
- static fromJSON(doc, json) {
3028
- if (typeof json.anchor != "number")
3029
- throw new RangeError("Invalid input for NodeSelection.fromJSON");
3030
- return new NodeSelection(doc.resolve(json.anchor));
3031
- }
3032
- /**
3033
- Create a node selection from non-resolved positions.
3034
- */
3035
- static create(doc, from) {
3036
- return new NodeSelection(doc.resolve(from));
3037
- }
3038
- /**
3039
- Determines whether the given node may be selected as a node
3040
- selection.
3041
- */
3042
- static isSelectable(node) {
3043
- return !node.isText && node.type.spec.selectable !== false;
3044
- }
3045
- }
3046
- NodeSelection.prototype.visible = false;
3047
- Selection.jsonID("node", NodeSelection);
3048
- class NodeBookmark {
3049
- constructor(anchor) {
3050
- this.anchor = anchor;
3051
- }
3052
- map(mapping) {
3053
- let { deleted, pos } = mapping.mapResult(this.anchor);
3054
- return deleted ? new TextBookmark(pos, pos) : new NodeBookmark(pos);
3055
- }
3056
- resolve(doc) {
3057
- let $pos = doc.resolve(this.anchor), node = $pos.nodeAfter;
3058
- if (node && NodeSelection.isSelectable(node))
3059
- return new NodeSelection($pos);
3060
- return Selection.near($pos);
3061
- }
3062
- }
3063
- /**
3064
- A selection type that represents selecting the whole document
3065
- (which can not necessarily be expressed with a text selection, when
3066
- there are for example leaf block nodes at the start or end of the
3067
- document).
3068
- */
3069
- class AllSelection extends Selection {
3070
- /**
3071
- Create an all-selection over the given document.
3072
- */
3073
- constructor(doc) {
3074
- super(doc.resolve(0), doc.resolve(doc.content.size));
3075
- }
3076
- replace(tr, content = Slice.empty) {
3077
- if (content == Slice.empty) {
3078
- tr.delete(0, tr.doc.content.size);
3079
- let sel = Selection.atStart(tr.doc);
3080
- if (!sel.eq(tr.selection))
3081
- tr.setSelection(sel);
3082
- }
3083
- else {
3084
- super.replace(tr, content);
3085
- }
3086
- }
3087
- toJSON() { return { type: "all" }; }
3088
- /**
3089
- @internal
3090
- */
3091
- static fromJSON(doc) { return new AllSelection(doc); }
3092
- map(doc) { return new AllSelection(doc); }
3093
- eq(other) { return other instanceof AllSelection; }
3094
- getBookmark() { return AllBookmark; }
3095
- }
3096
- Selection.jsonID("all", AllSelection);
3097
- const AllBookmark = {
3098
- map() { return this; },
3099
- resolve(doc) { return new AllSelection(doc); }
3100
- };
3101
- // FIXME we'll need some awareness of text direction when scanning for selections
3102
- // Try to find a selection inside the given node. `pos` points at the
3103
- // position where the search starts. When `text` is true, only return
3104
- // text selections.
3105
- function findSelectionIn(doc, node, pos, index, dir, text = false) {
3106
- if (node.inlineContent)
3107
- return TextSelection.create(doc, pos);
3108
- for (let i = index - (dir > 0 ? 0 : 1); dir > 0 ? i < node.childCount : i >= 0; i += dir) {
3109
- let child = node.child(i);
3110
- if (!child.isAtom) {
3111
- let inner = findSelectionIn(doc, child, pos + dir, dir < 0 ? child.childCount : 0, dir, text);
3112
- if (inner)
3113
- return inner;
3114
- }
3115
- else if (!text && NodeSelection.isSelectable(child)) {
3116
- return NodeSelection.create(doc, pos - (dir < 0 ? child.nodeSize : 0));
3117
- }
3118
- pos += child.nodeSize * dir;
3119
- }
3120
- return null;
3121
- }
3122
- function selectionToInsertionEnd(tr, startLen, bias) {
3123
- let last = tr.steps.length - 1;
3124
- if (last < startLen)
3125
- return;
3126
- let step = tr.steps[last];
3127
- if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep))
3128
- return;
3129
- let map = tr.mapping.maps[last], end;
3130
- map.forEach((_from, _to, _newFrom, newTo) => { if (end == null)
3131
- end = newTo; });
3132
- tr.setSelection(Selection.near(tr.doc.resolve(end), bias));
3133
- }
3134
-
3135
- const UPDATED_SEL = 1, UPDATED_MARKS = 2, UPDATED_SCROLL = 4;
3136
- /**
3137
- An editor state transaction, which can be applied to a state to
3138
- create an updated state. Use
3139
- [`EditorState.tr`](https://prosemirror.net/docs/ref/#state.EditorState.tr) to create an instance.
3140
-
3141
- Transactions track changes to the document (they are a subclass of
3142
- [`Transform`](https://prosemirror.net/docs/ref/#transform.Transform)), but also other state changes,
3143
- like selection updates and adjustments of the set of [stored
3144
- marks](https://prosemirror.net/docs/ref/#state.EditorState.storedMarks). In addition, you can store
3145
- metadata properties in a transaction, which are extra pieces of
3146
- information that client code or plugins can use to describe what a
3147
- transaction represents, so that they can update their [own
3148
- state](https://prosemirror.net/docs/ref/#state.StateField) accordingly.
3149
-
3150
- The [editor view](https://prosemirror.net/docs/ref/#view.EditorView) uses a few metadata properties:
3151
- it will attach a property `"pointer"` with the value `true` to
3152
- selection transactions directly caused by mouse or touch input, and
3153
- a `"uiEvent"` property of that may be `"paste"`, `"cut"`, or `"drop"`.
3154
- */
3155
- class Transaction extends Transform {
3156
- /**
3157
- @internal
3158
- */
3159
- constructor(state) {
3160
- super(state.doc);
3161
- // The step count for which the current selection is valid.
3162
- this.curSelectionFor = 0;
3163
- // Bitfield to track which aspects of the state were updated by
3164
- // this transaction.
3165
- this.updated = 0;
3166
- // Object used to store metadata properties for the transaction.
3167
- this.meta = Object.create(null);
3168
- this.time = Date.now();
3169
- this.curSelection = state.selection;
3170
- this.storedMarks = state.storedMarks;
3171
- }
3172
- /**
3173
- The transaction's current selection. This defaults to the editor
3174
- selection [mapped](https://prosemirror.net/docs/ref/#state.Selection.map) through the steps in the
3175
- transaction, but can be overwritten with
3176
- [`setSelection`](https://prosemirror.net/docs/ref/#state.Transaction.setSelection).
3177
- */
3178
- get selection() {
3179
- if (this.curSelectionFor < this.steps.length) {
3180
- this.curSelection = this.curSelection.map(this.doc, this.mapping.slice(this.curSelectionFor));
3181
- this.curSelectionFor = this.steps.length;
3182
- }
3183
- return this.curSelection;
3184
- }
3185
- /**
3186
- Update the transaction's current selection. Will determine the
3187
- selection that the editor gets when the transaction is applied.
3188
- */
3189
- setSelection(selection) {
3190
- if (selection.$from.doc != this.doc)
3191
- throw new RangeError("Selection passed to setSelection must point at the current document");
3192
- this.curSelection = selection;
3193
- this.curSelectionFor = this.steps.length;
3194
- this.updated = (this.updated | UPDATED_SEL) & ~UPDATED_MARKS;
3195
- this.storedMarks = null;
3196
- return this;
3197
- }
3198
- /**
3199
- Whether the selection was explicitly updated by this transaction.
3200
- */
3201
- get selectionSet() {
3202
- return (this.updated & UPDATED_SEL) > 0;
3203
- }
3204
- /**
3205
- Set the current stored marks.
3206
- */
3207
- setStoredMarks(marks) {
3208
- this.storedMarks = marks;
3209
- this.updated |= UPDATED_MARKS;
3210
- return this;
3211
- }
3212
- /**
3213
- Make sure the current stored marks or, if that is null, the marks
3214
- at the selection, match the given set of marks. Does nothing if
3215
- this is already the case.
3216
- */
3217
- ensureMarks(marks) {
3218
- if (!Mark.sameSet(this.storedMarks || this.selection.$from.marks(), marks))
3219
- this.setStoredMarks(marks);
3220
- return this;
3221
- }
3222
- /**
3223
- Add a mark to the set of stored marks.
3224
- */
3225
- addStoredMark(mark) {
3226
- return this.ensureMarks(mark.addToSet(this.storedMarks || this.selection.$head.marks()));
3227
- }
3228
- /**
3229
- Remove a mark or mark type from the set of stored marks.
3230
- */
3231
- removeStoredMark(mark) {
3232
- return this.ensureMarks(mark.removeFromSet(this.storedMarks || this.selection.$head.marks()));
3233
- }
3234
- /**
3235
- Whether the stored marks were explicitly set for this transaction.
3236
- */
3237
- get storedMarksSet() {
3238
- return (this.updated & UPDATED_MARKS) > 0;
3239
- }
3240
- /**
3241
- @internal
3242
- */
3243
- addStep(step, doc) {
3244
- super.addStep(step, doc);
3245
- this.updated = this.updated & ~UPDATED_MARKS;
3246
- this.storedMarks = null;
3247
- }
3248
- /**
3249
- Update the timestamp for the transaction.
3250
- */
3251
- setTime(time) {
3252
- this.time = time;
3253
- return this;
3254
- }
3255
- /**
3256
- Replace the current selection with the given slice.
3257
- */
3258
- replaceSelection(slice) {
3259
- this.selection.replace(this, slice);
3260
- return this;
3261
- }
3262
- /**
3263
- Replace the selection with the given node. When `inheritMarks` is
3264
- true and the content is inline, it inherits the marks from the
3265
- place where it is inserted.
3266
- */
3267
- replaceSelectionWith(node, inheritMarks = true) {
3268
- let selection = this.selection;
3269
- if (inheritMarks)
3270
- node = node.mark(this.storedMarks || (selection.empty ? selection.$from.marks() : (selection.$from.marksAcross(selection.$to) || Mark.none)));
3271
- selection.replaceWith(this, node);
3272
- return this;
3273
- }
3274
- /**
3275
- Delete the selection.
3276
- */
3277
- deleteSelection() {
3278
- this.selection.replace(this);
3279
- return this;
3280
- }
3281
- /**
3282
- Replace the given range, or the selection if no range is given,
3283
- with a text node containing the given string.
3284
- */
3285
- insertText(text, from, to) {
3286
- let schema = this.doc.type.schema;
3287
- if (from == null) {
3288
- if (!text)
3289
- return this.deleteSelection();
3290
- return this.replaceSelectionWith(schema.text(text), true);
3291
- }
3292
- else {
3293
- if (to == null)
3294
- to = from;
3295
- to = to == null ? from : to;
3296
- if (!text)
3297
- return this.deleteRange(from, to);
3298
- let marks = this.storedMarks;
3299
- if (!marks) {
3300
- let $from = this.doc.resolve(from);
3301
- marks = to == from ? $from.marks() : $from.marksAcross(this.doc.resolve(to));
3302
- }
3303
- this.replaceRangeWith(from, to, schema.text(text, marks));
3304
- if (!this.selection.empty)
3305
- this.setSelection(Selection.near(this.selection.$to));
3306
- return this;
3307
- }
3308
- }
3309
- /**
3310
- Store a metadata property in this transaction, keyed either by
3311
- name or by plugin.
3312
- */
3313
- setMeta(key, value) {
3314
- this.meta[typeof key == "string" ? key : key.key] = value;
3315
- return this;
3316
- }
3317
- /**
3318
- Retrieve a metadata property for a given name or plugin.
3319
- */
3320
- getMeta(key) {
3321
- return this.meta[typeof key == "string" ? key : key.key];
3322
- }
3323
- /**
3324
- Returns true if this transaction doesn't contain any metadata,
3325
- and can thus safely be extended.
3326
- */
3327
- get isGeneric() {
3328
- for (let _ in this.meta)
3329
- return false;
3330
- return true;
3331
- }
3332
- /**
3333
- Indicate that the editor should scroll the selection into view
3334
- when updated to the state produced by this transaction.
3335
- */
3336
- scrollIntoView() {
3337
- this.updated |= UPDATED_SCROLL;
3338
- return this;
3339
- }
3340
- /**
3341
- True when this transaction has had `scrollIntoView` called on it.
3342
- */
3343
- get scrolledIntoView() {
3344
- return (this.updated & UPDATED_SCROLL) > 0;
3345
- }
3346
- }
3347
-
3348
- function bind(f, self) {
3349
- return !self || !f ? f : f.bind(self);
3350
- }
3351
- class FieldDesc {
3352
- constructor(name, desc, self) {
3353
- this.name = name;
3354
- this.init = bind(desc.init, self);
3355
- this.apply = bind(desc.apply, self);
3356
- }
3357
- }
3358
- [
3359
- new FieldDesc("doc", {
3360
- init(config) { return config.doc || config.schema.topNodeType.createAndFill(); },
3361
- apply(tr) { return tr.doc; }
3362
- }),
3363
- new FieldDesc("selection", {
3364
- init(config, instance) { return config.selection || Selection.atStart(instance.doc); },
3365
- apply(tr) { return tr.selection; }
3366
- }),
3367
- new FieldDesc("storedMarks", {
3368
- init(config) { return config.storedMarks || null; },
3369
- apply(tr, _marks, _old, state) { return state.selection.$cursor ? tr.storedMarks : null; }
3370
- }),
3371
- new FieldDesc("scrollToSelection", {
3372
- init() { return 0; },
3373
- apply(tr, prev) { return tr.scrolledIntoView ? prev + 1 : prev; }
3374
- })
3375
- ];
3376
-
3377
- function bindProps(obj, self, target) {
3378
- for (let prop in obj) {
3379
- let val = obj[prop];
3380
- if (val instanceof Function)
3381
- val = val.bind(self);
3382
- else if (prop == "handleDOMEvents")
3383
- val = bindProps(val, self, {});
3384
- target[prop] = val;
3385
- }
3386
- return target;
3387
- }
3388
- /**
3389
- Plugins bundle functionality that can be added to an editor.
3390
- They are part of the [editor state](https://prosemirror.net/docs/ref/#state.EditorState) and
3391
- may influence that state and the view that contains it.
3392
- */
3393
- class Plugin {
3394
- /**
3395
- Create a plugin.
3396
- */
3397
- constructor(
3398
- /**
3399
- The plugin's [spec object](https://prosemirror.net/docs/ref/#state.PluginSpec).
3400
- */
3401
- spec) {
3402
- this.spec = spec;
3403
- /**
3404
- The [props](https://prosemirror.net/docs/ref/#view.EditorProps) exported by this plugin.
3405
- */
3406
- this.props = {};
3407
- if (spec.props)
3408
- bindProps(spec.props, this, this.props);
3409
- this.key = spec.key ? spec.key.key : createKey("plugin");
3410
- }
3411
- /**
3412
- Extract the plugin's state field from an editor state.
3413
- */
3414
- getState(state) { return state[this.key]; }
3415
- }
3416
- const keys = Object.create(null);
3417
- function createKey(name) {
3418
- if (name in keys)
3419
- return name + "$" + ++keys[name];
3420
- keys[name] = 0;
3421
- return name + "$";
3422
- }
3423
- /**
3424
- A key is used to [tag](https://prosemirror.net/docs/ref/#state.PluginSpec.key) plugins in a way
3425
- that makes it possible to find them, given an editor state.
3426
- Assigning a key does mean only one plugin of that type can be
3427
- active in a state.
3428
- */
3429
- class PluginKey {
3430
- /**
3431
- Create a plugin key.
3432
- */
3433
- constructor(name = "key") { this.key = createKey(name); }
3434
- /**
3435
- Get the active plugin with this key, if any, from an editor
3436
- state.
3437
- */
3438
- get(state) { return state.config.pluginsByKey[this.key]; }
3439
- /**
3440
- Get the plugin's state from an editor state.
3441
- */
3442
- getState(state) { return state[this.key]; }
3443
- }
7
+ var state = require('@tiptap/pm/state');
3444
8
 
3445
9
  function autolink(options) {
3446
- return new Plugin({
3447
- key: new PluginKey('autolink'),
10
+ return new state.Plugin({
11
+ key: new state.PluginKey('autolink'),
3448
12
  appendTransaction: (transactions, oldState, newState) => {
3449
13
  const docChanges = transactions.some(transaction => transaction.docChanged) && !oldState.doc.eq(newState.doc);
3450
14
  const preventAutolink = transactions.some(transaction => transaction.getMeta('preventAutolink'));
@@ -3533,8 +97,8 @@ function autolink(options) {
3533
97
  }
3534
98
 
3535
99
  function clickHandler(options) {
3536
- return new Plugin({
3537
- key: new PluginKey('handleClickLink'),
100
+ return new state.Plugin({
101
+ key: new state.PluginKey('handleClickLink'),
3538
102
  props: {
3539
103
  handleClick: (view, pos, event) => {
3540
104
  var _a;
@@ -3551,8 +115,8 @@ function clickHandler(options) {
3551
115
  }
3552
116
 
3553
117
  function pasteHandler(options) {
3554
- return new Plugin({
3555
- key: new PluginKey('handlePasteLink'),
118
+ return new state.Plugin({
119
+ key: new state.PluginKey('handlePasteLink'),
3556
120
  props: {
3557
121
  handlePaste: (view, event, slice) => {
3558
122
  const { state } = view;