@tiptap/extension-code-block 2.0.0-beta.214 → 2.0.0-beta.215

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