@vonage/vivid 5.7.0 → 5.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/bundled/data-grid.options.cjs +1 -0
  2. package/bundled/data-grid.options.js +29 -0
  3. package/bundled/definition19.cjs +3 -4
  4. package/bundled/definition19.js +35 -52
  5. package/bundled/definition2.cjs +1 -1
  6. package/bundled/definition2.js +1 -1
  7. package/bundled/definition3.cjs +1 -1
  8. package/bundled/definition3.js +1 -1
  9. package/bundled/definition8.cjs +1 -1
  10. package/bundled/definition8.js +1 -1
  11. package/bundled/definition9.cjs +9 -9
  12. package/bundled/definition9.js +113 -1342
  13. package/bundled/feature.cjs +4 -0
  14. package/bundled/feature.js +2886 -0
  15. package/bundled/floating-ui.dom.cjs +1 -0
  16. package/bundled/floating-ui.dom.js +1242 -0
  17. package/bundled/listbox.cjs +1 -1
  18. package/bundled/listbox.js +49 -22
  19. package/bundled/localized.cjs +1 -1
  20. package/bundled/localized.js +15 -13
  21. package/bundled/vivid-element.cjs +3 -3
  22. package/bundled/vivid-element.js +89 -69
  23. package/checkbox/definition.cjs +1 -1
  24. package/checkbox/definition.js +1 -1
  25. package/combobox/definition.cjs +14 -15
  26. package/combobox/definition.js +15 -16
  27. package/combobox/index.cjs +4 -4
  28. package/combobox/index.js +82 -87
  29. package/contextual-help/definition.cjs +1 -0
  30. package/contextual-help/definition.js +1 -1
  31. package/custom-elements.json +5145 -3781
  32. package/data-grid/definition.cjs +23 -49
  33. package/data-grid/definition.js +1 -27
  34. package/data-grid/index.cjs +27 -27
  35. package/data-grid/index.js +44 -64
  36. package/data-table/definition.cjs +204 -0
  37. package/data-table/definition.js +188 -0
  38. package/data-table/index.cjs +37 -0
  39. package/data-table/index.js +143 -0
  40. package/file-picker/definition.cjs +10 -8
  41. package/file-picker/definition.js +10 -8
  42. package/file-picker/index.cjs +5 -5
  43. package/file-picker/index.js +12 -12
  44. package/icon/definition.cjs +1 -1
  45. package/icon/definition.js +1 -1
  46. package/index.cjs +26 -0
  47. package/index.js +4 -0
  48. package/lib/components.d.ts +4 -0
  49. package/lib/contextual-help/definition.d.ts +2 -0
  50. package/lib/data-table/definition.d.ts +8 -0
  51. package/lib/data-table/table-body.d.ts +3 -0
  52. package/lib/data-table/table-body.template.d.ts +3 -0
  53. package/lib/data-table/table-cell.d.ts +381 -0
  54. package/lib/data-table/table-cell.template.d.ts +3 -0
  55. package/lib/data-table/table-head.d.ts +3 -0
  56. package/lib/data-table/table-head.template.d.ts +3 -0
  57. package/lib/data-table/table-header-cell.d.ts +381 -0
  58. package/lib/data-table/table-header-cell.template.d.ts +3 -0
  59. package/lib/data-table/table-row.d.ts +381 -0
  60. package/lib/data-table/table-row.template.d.ts +3 -0
  61. package/lib/data-table/table.d.ts +3 -0
  62. package/lib/data-table/table.template.d.ts +3 -0
  63. package/lib/popover/definition.d.ts +4 -0
  64. package/lib/popover/locale.d.ts +3 -0
  65. package/lib/popover/popover.d.ts +781 -0
  66. package/lib/popover/popover.template.d.ts +3 -0
  67. package/lib/rich-text-editor/locale.d.ts +0 -1
  68. package/lib/rich-text-editor/rte/config.d.ts +3 -0
  69. package/lib/rich-text-editor/rte/document.d.ts +2 -0
  70. package/lib/rich-text-editor/rte/exports.d.ts +1 -0
  71. package/lib/rich-text-editor/rte/view.d.ts +30 -0
  72. package/lib/rich-text-view/definition.d.ts +4 -0
  73. package/lib/rich-text-view/rich-text-view.d.ts +15 -0
  74. package/lib/rich-text-view/rich-text-view.template.d.ts +3 -0
  75. package/lib/tag-name-map.d.ts +10 -1
  76. package/locales/de-DE.cjs +3 -1
  77. package/locales/de-DE.js +3 -1
  78. package/locales/en-GB.cjs +3 -1
  79. package/locales/en-GB.js +3 -1
  80. package/locales/en-US.cjs +3 -1
  81. package/locales/en-US.js +3 -1
  82. package/locales/ja-JP.cjs +3 -1
  83. package/locales/ja-JP.js +3 -1
  84. package/locales/zh-CN.cjs +3 -1
  85. package/locales/zh-CN.js +3 -1
  86. package/package.json +8 -12
  87. package/popover/definition.cjs +363 -0
  88. package/popover/definition.js +357 -0
  89. package/popover/index.cjs +27 -0
  90. package/popover/index.js +263 -0
  91. package/rich-text-editor/definition.cjs +328 -3882
  92. package/rich-text-editor/definition.js +143 -3697
  93. package/rich-text-editor/index.cjs +12 -15
  94. package/rich-text-editor/index.js +3489 -6291
  95. package/rich-text-view/definition.cjs +159 -0
  96. package/rich-text-view/definition.js +153 -0
  97. package/rich-text-view/index.cjs +1 -0
  98. package/rich-text-view/index.js +95 -0
  99. package/select/definition.cjs +27 -15
  100. package/select/definition.js +27 -15
  101. package/shared/foundation/listbox/listbox.d.ts +0 -1
  102. package/shared/localization/Locale.d.ts +2 -0
  103. package/tag/definition.cjs +1 -1
  104. package/tag/definition.js +1 -1
  105. package/tag/index.cjs +1 -1
  106. package/tag/index.js +1 -1
  107. package/unbundled/_commonjsHelpers.cjs +26 -0
  108. package/unbundled/_commonjsHelpers.js +26 -1
  109. package/unbundled/data-grid.options.cjs +34 -0
  110. package/unbundled/data-grid.options.js +28 -0
  111. package/unbundled/definition.cjs +1 -1
  112. package/unbundled/definition.js +1 -1
  113. package/unbundled/feature.cjs +3678 -0
  114. package/unbundled/feature.js +3662 -0
  115. package/unbundled/listbox.cjs +29 -2
  116. package/unbundled/listbox.js +29 -2
  117. package/unbundled/vivid-element.cjs +1 -1
  118. package/unbundled/vivid-element.js +1 -1
  119. package/video-player/definition.cjs +11 -1
  120. package/video-player/definition.js +12 -2
  121. package/video-player/index.cjs +30 -30
  122. package/video-player/index.js +705 -702
  123. package/vivid.api.json +1478 -39
@@ -0,0 +1,3678 @@
1
+ 'use strict';
2
+
3
+ // ::- Persistent data structure representing an ordered mapping from
4
+ // strings to values, with some convenient update methods.
5
+ function OrderedMap(content) {
6
+ this.content = content;
7
+ }
8
+
9
+ OrderedMap.prototype = {
10
+ constructor: OrderedMap,
11
+
12
+ find: function(key) {
13
+ for (var i = 0; i < this.content.length; i += 2)
14
+ if (this.content[i] === key) return i
15
+ return -1
16
+ },
17
+
18
+ // :: (string) → ?any
19
+ // Retrieve the value stored under `key`, or return undefined when
20
+ // no such key exists.
21
+ get: function(key) {
22
+ var found = this.find(key);
23
+ return found == -1 ? undefined : this.content[found + 1]
24
+ },
25
+
26
+ // :: (string, any, ?string) → OrderedMap
27
+ // Create a new map by replacing the value of `key` with a new
28
+ // value, or adding a binding to the end of the map. If `newKey` is
29
+ // given, the key of the binding will be replaced with that key.
30
+ update: function(key, value, newKey) {
31
+ var self = newKey && newKey != key ? this.remove(newKey) : this;
32
+ var found = self.find(key), content = self.content.slice();
33
+ if (found == -1) {
34
+ content.push(newKey || key, value);
35
+ } else {
36
+ content[found + 1] = value;
37
+ if (newKey) content[found] = newKey;
38
+ }
39
+ return new OrderedMap(content)
40
+ },
41
+
42
+ // :: (string) → OrderedMap
43
+ // Return a map with the given key removed, if it existed.
44
+ remove: function(key) {
45
+ var found = this.find(key);
46
+ if (found == -1) return this
47
+ var content = this.content.slice();
48
+ content.splice(found, 2);
49
+ return new OrderedMap(content)
50
+ },
51
+
52
+ // :: (string, any) → OrderedMap
53
+ // Add a new key to the start of the map.
54
+ addToStart: function(key, value) {
55
+ return new OrderedMap([key, value].concat(this.remove(key).content))
56
+ },
57
+
58
+ // :: (string, any) → OrderedMap
59
+ // Add a new key to the end of the map.
60
+ addToEnd: function(key, value) {
61
+ var content = this.remove(key).content.slice();
62
+ content.push(key, value);
63
+ return new OrderedMap(content)
64
+ },
65
+
66
+ // :: (string, string, any) → OrderedMap
67
+ // Add a key after the given key. If `place` is not found, the new
68
+ // key is added to the end.
69
+ addBefore: function(place, key, value) {
70
+ var without = this.remove(key), content = without.content.slice();
71
+ var found = without.find(place);
72
+ content.splice(found == -1 ? content.length : found, 0, key, value);
73
+ return new OrderedMap(content)
74
+ },
75
+
76
+ // :: ((key: string, value: any))
77
+ // Call the given function for each key/value pair in the map, in
78
+ // order.
79
+ forEach: function(f) {
80
+ for (var i = 0; i < this.content.length; i += 2)
81
+ f(this.content[i], this.content[i + 1]);
82
+ },
83
+
84
+ // :: (union<Object, OrderedMap>) → OrderedMap
85
+ // Create a new map by prepending the keys in this map that don't
86
+ // appear in `map` before the keys in `map`.
87
+ prepend: function(map) {
88
+ map = OrderedMap.from(map);
89
+ if (!map.size) return this
90
+ return new OrderedMap(map.content.concat(this.subtract(map).content))
91
+ },
92
+
93
+ // :: (union<Object, OrderedMap>) → OrderedMap
94
+ // Create a new map by appending the keys in this map that don't
95
+ // appear in `map` after the keys in `map`.
96
+ append: function(map) {
97
+ map = OrderedMap.from(map);
98
+ if (!map.size) return this
99
+ return new OrderedMap(this.subtract(map).content.concat(map.content))
100
+ },
101
+
102
+ // :: (union<Object, OrderedMap>) → OrderedMap
103
+ // Create a map containing all the keys in this map that don't
104
+ // appear in `map`.
105
+ subtract: function(map) {
106
+ var result = this;
107
+ map = OrderedMap.from(map);
108
+ for (var i = 0; i < map.content.length; i += 2)
109
+ result = result.remove(map.content[i]);
110
+ return result
111
+ },
112
+
113
+ // :: () → Object
114
+ // Turn ordered map into a plain object.
115
+ toObject: function() {
116
+ var result = {};
117
+ this.forEach(function(key, value) { result[key] = value; });
118
+ return result
119
+ },
120
+
121
+ // :: number
122
+ // The amount of keys in this map.
123
+ get size() {
124
+ return this.content.length >> 1
125
+ }
126
+ };
127
+
128
+ // :: (?union<Object, OrderedMap>) → OrderedMap
129
+ // Return a map with the given content. If null, create an empty
130
+ // map. If given an ordered map, return that map itself. If given an
131
+ // object, create a map from the object's properties.
132
+ OrderedMap.from = function(value) {
133
+ if (value instanceof OrderedMap) return value
134
+ var content = [];
135
+ if (value) for (var prop in value) content.push(prop, value[prop]);
136
+ return new OrderedMap(content)
137
+ };
138
+
139
+ function findDiffStart(a, b, pos) {
140
+ for (let i = 0;; i++) {
141
+ if (i == a.childCount || i == b.childCount)
142
+ return a.childCount == b.childCount ? null : pos;
143
+ let childA = a.child(i), childB = b.child(i);
144
+ if (childA == childB) {
145
+ pos += childA.nodeSize;
146
+ continue;
147
+ }
148
+ if (!childA.sameMarkup(childB))
149
+ return pos;
150
+ if (childA.isText && childA.text != childB.text) {
151
+ for (let j = 0; childA.text[j] == childB.text[j]; j++)
152
+ pos++;
153
+ return pos;
154
+ }
155
+ if (childA.content.size || childB.content.size) {
156
+ let inner = findDiffStart(childA.content, childB.content, pos + 1);
157
+ if (inner != null)
158
+ return inner;
159
+ }
160
+ pos += childA.nodeSize;
161
+ }
162
+ }
163
+ function findDiffEnd(a, b, posA, posB) {
164
+ for (let iA = a.childCount, iB = b.childCount;;) {
165
+ if (iA == 0 || iB == 0)
166
+ return iA == iB ? null : { a: posA, b: posB };
167
+ let childA = a.child(--iA), childB = b.child(--iB), size = childA.nodeSize;
168
+ if (childA == childB) {
169
+ posA -= size;
170
+ posB -= size;
171
+ continue;
172
+ }
173
+ if (!childA.sameMarkup(childB))
174
+ return { a: posA, b: posB };
175
+ if (childA.isText && childA.text != childB.text) {
176
+ let same = 0, minSize = Math.min(childA.text.length, childB.text.length);
177
+ while (same < minSize && childA.text[childA.text.length - same - 1] == childB.text[childB.text.length - same - 1]) {
178
+ same++;
179
+ posA--;
180
+ posB--;
181
+ }
182
+ return { a: posA, b: posB };
183
+ }
184
+ if (childA.content.size || childB.content.size) {
185
+ let inner = findDiffEnd(childA.content, childB.content, posA - 1, posB - 1);
186
+ if (inner)
187
+ return inner;
188
+ }
189
+ posA -= size;
190
+ posB -= size;
191
+ }
192
+ }
193
+
194
+ /**
195
+ A fragment represents a node's collection of child nodes.
196
+
197
+ Like nodes, fragments are persistent data structures, and you
198
+ should not mutate them or their content. Rather, you create new
199
+ instances whenever needed. The API tries to make this easy.
200
+ */
201
+ class Fragment {
202
+ /**
203
+ @internal
204
+ */
205
+ constructor(
206
+ /**
207
+ The child nodes in this fragment.
208
+ */
209
+ content, size) {
210
+ this.content = content;
211
+ this.size = size || 0;
212
+ if (size == null)
213
+ for (let i = 0; i < content.length; i++)
214
+ this.size += content[i].nodeSize;
215
+ }
216
+ /**
217
+ Invoke a callback for all descendant nodes between the given two
218
+ positions (relative to start of this fragment). Doesn't descend
219
+ into a node when the callback returns `false`.
220
+ */
221
+ nodesBetween(from, to, f, nodeStart = 0, parent) {
222
+ for (let i = 0, pos = 0; pos < to; i++) {
223
+ let child = this.content[i], end = pos + child.nodeSize;
224
+ if (end > from && f(child, nodeStart + pos, parent || null, i) !== false && child.content.size) {
225
+ let start = pos + 1;
226
+ child.nodesBetween(Math.max(0, from - start), Math.min(child.content.size, to - start), f, nodeStart + start);
227
+ }
228
+ pos = end;
229
+ }
230
+ }
231
+ /**
232
+ Call the given callback for every descendant node. `pos` will be
233
+ relative to the start of the fragment. The callback may return
234
+ `false` to prevent traversal of a given node's children.
235
+ */
236
+ descendants(f) {
237
+ this.nodesBetween(0, this.size, f);
238
+ }
239
+ /**
240
+ Extract the text between `from` and `to`. See the same method on
241
+ [`Node`](https://prosemirror.net/docs/ref/#model.Node.textBetween).
242
+ */
243
+ textBetween(from, to, blockSeparator, leafText) {
244
+ let text = "", first = true;
245
+ this.nodesBetween(from, to, (node, pos) => {
246
+ let nodeText = node.isText ? node.text.slice(Math.max(from, pos) - pos, to - pos)
247
+ : !node.isLeaf ? ""
248
+ : leafText ? (typeof leafText === "function" ? leafText(node) : leafText)
249
+ : node.type.spec.leafText ? node.type.spec.leafText(node)
250
+ : "";
251
+ if (node.isBlock && (node.isLeaf && nodeText || node.isTextblock) && blockSeparator) {
252
+ if (first)
253
+ first = false;
254
+ else
255
+ text += blockSeparator;
256
+ }
257
+ text += nodeText;
258
+ }, 0);
259
+ return text;
260
+ }
261
+ /**
262
+ Create a new fragment containing the combined content of this
263
+ fragment and the other.
264
+ */
265
+ append(other) {
266
+ if (!other.size)
267
+ return this;
268
+ if (!this.size)
269
+ return other;
270
+ let last = this.lastChild, first = other.firstChild, content = this.content.slice(), i = 0;
271
+ if (last.isText && last.sameMarkup(first)) {
272
+ content[content.length - 1] = last.withText(last.text + first.text);
273
+ i = 1;
274
+ }
275
+ for (; i < other.content.length; i++)
276
+ content.push(other.content[i]);
277
+ return new Fragment(content, this.size + other.size);
278
+ }
279
+ /**
280
+ Cut out the sub-fragment between the two given positions.
281
+ */
282
+ cut(from, to = this.size) {
283
+ if (from == 0 && to == this.size)
284
+ return this;
285
+ let result = [], size = 0;
286
+ if (to > from)
287
+ for (let i = 0, pos = 0; pos < to; i++) {
288
+ let child = this.content[i], end = pos + child.nodeSize;
289
+ if (end > from) {
290
+ if (pos < from || end > to) {
291
+ if (child.isText)
292
+ child = child.cut(Math.max(0, from - pos), Math.min(child.text.length, to - pos));
293
+ else
294
+ child = child.cut(Math.max(0, from - pos - 1), Math.min(child.content.size, to - pos - 1));
295
+ }
296
+ result.push(child);
297
+ size += child.nodeSize;
298
+ }
299
+ pos = end;
300
+ }
301
+ return new Fragment(result, size);
302
+ }
303
+ /**
304
+ @internal
305
+ */
306
+ cutByIndex(from, to) {
307
+ if (from == to)
308
+ return Fragment.empty;
309
+ if (from == 0 && to == this.content.length)
310
+ return this;
311
+ return new Fragment(this.content.slice(from, to));
312
+ }
313
+ /**
314
+ Create a new fragment in which the node at the given index is
315
+ replaced by the given node.
316
+ */
317
+ replaceChild(index, node) {
318
+ let current = this.content[index];
319
+ if (current == node)
320
+ return this;
321
+ let copy = this.content.slice();
322
+ let size = this.size + node.nodeSize - current.nodeSize;
323
+ copy[index] = node;
324
+ return new Fragment(copy, size);
325
+ }
326
+ /**
327
+ Create a new fragment by prepending the given node to this
328
+ fragment.
329
+ */
330
+ addToStart(node) {
331
+ return new Fragment([node].concat(this.content), this.size + node.nodeSize);
332
+ }
333
+ /**
334
+ Create a new fragment by appending the given node to this
335
+ fragment.
336
+ */
337
+ addToEnd(node) {
338
+ return new Fragment(this.content.concat(node), this.size + node.nodeSize);
339
+ }
340
+ /**
341
+ Compare this fragment to another one.
342
+ */
343
+ eq(other) {
344
+ if (this.content.length != other.content.length)
345
+ return false;
346
+ for (let i = 0; i < this.content.length; i++)
347
+ if (!this.content[i].eq(other.content[i]))
348
+ return false;
349
+ return true;
350
+ }
351
+ /**
352
+ The first child of the fragment, or `null` if it is empty.
353
+ */
354
+ get firstChild() { return this.content.length ? this.content[0] : null; }
355
+ /**
356
+ The last child of the fragment, or `null` if it is empty.
357
+ */
358
+ get lastChild() { return this.content.length ? this.content[this.content.length - 1] : null; }
359
+ /**
360
+ The number of child nodes in this fragment.
361
+ */
362
+ get childCount() { return this.content.length; }
363
+ /**
364
+ Get the child node at the given index. Raise an error when the
365
+ index is out of range.
366
+ */
367
+ child(index) {
368
+ let found = this.content[index];
369
+ if (!found)
370
+ throw new RangeError("Index " + index + " out of range for " + this);
371
+ return found;
372
+ }
373
+ /**
374
+ Get the child node at the given index, if it exists.
375
+ */
376
+ maybeChild(index) {
377
+ return this.content[index] || null;
378
+ }
379
+ /**
380
+ Call `f` for every child node, passing the node, its offset
381
+ into this parent node, and its index.
382
+ */
383
+ forEach(f) {
384
+ for (let i = 0, p = 0; i < this.content.length; i++) {
385
+ let child = this.content[i];
386
+ f(child, p, i);
387
+ p += child.nodeSize;
388
+ }
389
+ }
390
+ /**
391
+ Find the first position at which this fragment and another
392
+ fragment differ, or `null` if they are the same.
393
+ */
394
+ findDiffStart(other, pos = 0) {
395
+ return findDiffStart(this, other, pos);
396
+ }
397
+ /**
398
+ Find the first position, searching from the end, at which this
399
+ fragment and the given fragment differ, or `null` if they are
400
+ the same. Since this position will not be the same in both
401
+ nodes, an object with two separate positions is returned.
402
+ */
403
+ findDiffEnd(other, pos = this.size, otherPos = other.size) {
404
+ return findDiffEnd(this, other, pos, otherPos);
405
+ }
406
+ /**
407
+ Find the index and inner offset corresponding to a given relative
408
+ position in this fragment. The result object will be reused
409
+ (overwritten) the next time the function is called. @internal
410
+ */
411
+ findIndex(pos) {
412
+ if (pos == 0)
413
+ return retIndex(0, pos);
414
+ if (pos == this.size)
415
+ return retIndex(this.content.length, pos);
416
+ if (pos > this.size || pos < 0)
417
+ throw new RangeError(`Position ${pos} outside of fragment (${this})`);
418
+ for (let i = 0, curPos = 0;; i++) {
419
+ let cur = this.child(i), end = curPos + cur.nodeSize;
420
+ if (end >= pos) {
421
+ if (end == pos)
422
+ return retIndex(i + 1, end);
423
+ return retIndex(i, curPos);
424
+ }
425
+ curPos = end;
426
+ }
427
+ }
428
+ /**
429
+ Return a debugging string that describes this fragment.
430
+ */
431
+ toString() { return "<" + this.toStringInner() + ">"; }
432
+ /**
433
+ @internal
434
+ */
435
+ toStringInner() { return this.content.join(", "); }
436
+ /**
437
+ Create a JSON-serializeable representation of this fragment.
438
+ */
439
+ toJSON() {
440
+ return this.content.length ? this.content.map(n => n.toJSON()) : null;
441
+ }
442
+ /**
443
+ Deserialize a fragment from its JSON representation.
444
+ */
445
+ static fromJSON(schema, value) {
446
+ if (!value)
447
+ return Fragment.empty;
448
+ if (!Array.isArray(value))
449
+ throw new RangeError("Invalid input for Fragment.fromJSON");
450
+ return new Fragment(value.map(schema.nodeFromJSON));
451
+ }
452
+ /**
453
+ Build a fragment from an array of nodes. Ensures that adjacent
454
+ text nodes with the same marks are joined together.
455
+ */
456
+ static fromArray(array) {
457
+ if (!array.length)
458
+ return Fragment.empty;
459
+ let joined, size = 0;
460
+ for (let i = 0; i < array.length; i++) {
461
+ let node = array[i];
462
+ size += node.nodeSize;
463
+ if (i && node.isText && array[i - 1].sameMarkup(node)) {
464
+ if (!joined)
465
+ joined = array.slice(0, i);
466
+ joined[joined.length - 1] = node
467
+ .withText(joined[joined.length - 1].text + node.text);
468
+ }
469
+ else if (joined) {
470
+ joined.push(node);
471
+ }
472
+ }
473
+ return new Fragment(joined || array, size);
474
+ }
475
+ /**
476
+ Create a fragment from something that can be interpreted as a
477
+ set of nodes. For `null`, it returns the empty fragment. For a
478
+ fragment, the fragment itself. For a node or array of nodes, a
479
+ fragment containing those nodes.
480
+ */
481
+ static from(nodes) {
482
+ if (!nodes)
483
+ return Fragment.empty;
484
+ if (nodes instanceof Fragment)
485
+ return nodes;
486
+ if (Array.isArray(nodes))
487
+ return this.fromArray(nodes);
488
+ if (nodes.attrs)
489
+ return new Fragment([nodes], nodes.nodeSize);
490
+ throw new RangeError("Can not convert " + nodes + " to a Fragment" +
491
+ (nodes.nodesBetween ? " (looks like multiple versions of prosemirror-model were loaded)" : ""));
492
+ }
493
+ }
494
+ /**
495
+ An empty fragment. Intended to be reused whenever a node doesn't
496
+ contain anything (rather than allocating a new empty fragment for
497
+ each leaf node).
498
+ */
499
+ Fragment.empty = new Fragment([], 0);
500
+ const found = { index: 0, offset: 0 };
501
+ function retIndex(index, offset) {
502
+ found.index = index;
503
+ found.offset = offset;
504
+ return found;
505
+ }
506
+
507
+ function compareDeep(a, b) {
508
+ if (a === b)
509
+ return true;
510
+ if (!(a && typeof a == "object") ||
511
+ !(b && typeof b == "object"))
512
+ return false;
513
+ let array = Array.isArray(a);
514
+ if (Array.isArray(b) != array)
515
+ return false;
516
+ if (array) {
517
+ if (a.length != b.length)
518
+ return false;
519
+ for (let i = 0; i < a.length; i++)
520
+ if (!compareDeep(a[i], b[i]))
521
+ return false;
522
+ }
523
+ else {
524
+ for (let p in a)
525
+ if (!(p in b) || !compareDeep(a[p], b[p]))
526
+ return false;
527
+ for (let p in b)
528
+ if (!(p in a))
529
+ return false;
530
+ }
531
+ return true;
532
+ }
533
+
534
+ /**
535
+ A mark is a piece of information that can be attached to a node,
536
+ such as it being emphasized, in code font, or a link. It has a
537
+ type and optionally a set of attributes that provide further
538
+ information (such as the target of the link). Marks are created
539
+ through a `Schema`, which controls which types exist and which
540
+ attributes they have.
541
+ */
542
+ class Mark {
543
+ /**
544
+ @internal
545
+ */
546
+ constructor(
547
+ /**
548
+ The type of this mark.
549
+ */
550
+ type,
551
+ /**
552
+ The attributes associated with this mark.
553
+ */
554
+ attrs) {
555
+ this.type = type;
556
+ this.attrs = attrs;
557
+ }
558
+ /**
559
+ Given a set of marks, create a new set which contains this one as
560
+ well, in the right position. If this mark is already in the set,
561
+ the set itself is returned. If any marks that are set to be
562
+ [exclusive](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) with this mark are present,
563
+ those are replaced by this one.
564
+ */
565
+ addToSet(set) {
566
+ let copy, placed = false;
567
+ for (let i = 0; i < set.length; i++) {
568
+ let other = set[i];
569
+ if (this.eq(other))
570
+ return set;
571
+ if (this.type.excludes(other.type)) {
572
+ if (!copy)
573
+ copy = set.slice(0, i);
574
+ }
575
+ else if (other.type.excludes(this.type)) {
576
+ return set;
577
+ }
578
+ else {
579
+ if (!placed && other.type.rank > this.type.rank) {
580
+ if (!copy)
581
+ copy = set.slice(0, i);
582
+ copy.push(this);
583
+ placed = true;
584
+ }
585
+ if (copy)
586
+ copy.push(other);
587
+ }
588
+ }
589
+ if (!copy)
590
+ copy = set.slice();
591
+ if (!placed)
592
+ copy.push(this);
593
+ return copy;
594
+ }
595
+ /**
596
+ Remove this mark from the given set, returning a new set. If this
597
+ mark is not in the set, the set itself is returned.
598
+ */
599
+ removeFromSet(set) {
600
+ for (let i = 0; i < set.length; i++)
601
+ if (this.eq(set[i]))
602
+ return set.slice(0, i).concat(set.slice(i + 1));
603
+ return set;
604
+ }
605
+ /**
606
+ Test whether this mark is in the given set of marks.
607
+ */
608
+ isInSet(set) {
609
+ for (let i = 0; i < set.length; i++)
610
+ if (this.eq(set[i]))
611
+ return true;
612
+ return false;
613
+ }
614
+ /**
615
+ Test whether this mark has the same type and attributes as
616
+ another mark.
617
+ */
618
+ eq(other) {
619
+ return this == other ||
620
+ (this.type == other.type && compareDeep(this.attrs, other.attrs));
621
+ }
622
+ /**
623
+ Convert this mark to a JSON-serializeable representation.
624
+ */
625
+ toJSON() {
626
+ let obj = { type: this.type.name };
627
+ for (let _ in this.attrs) {
628
+ obj.attrs = this.attrs;
629
+ break;
630
+ }
631
+ return obj;
632
+ }
633
+ /**
634
+ Deserialize a mark from JSON.
635
+ */
636
+ static fromJSON(schema, json) {
637
+ if (!json)
638
+ throw new RangeError("Invalid input for Mark.fromJSON");
639
+ let type = schema.marks[json.type];
640
+ if (!type)
641
+ throw new RangeError(`There is no mark type ${json.type} in this schema`);
642
+ let mark = type.create(json.attrs);
643
+ type.checkAttrs(mark.attrs);
644
+ return mark;
645
+ }
646
+ /**
647
+ Test whether two sets of marks are identical.
648
+ */
649
+ static sameSet(a, b) {
650
+ if (a == b)
651
+ return true;
652
+ if (a.length != b.length)
653
+ return false;
654
+ for (let i = 0; i < a.length; i++)
655
+ if (!a[i].eq(b[i]))
656
+ return false;
657
+ return true;
658
+ }
659
+ /**
660
+ Create a properly sorted mark set from null, a single mark, or an
661
+ unsorted array of marks.
662
+ */
663
+ static setFrom(marks) {
664
+ if (!marks || Array.isArray(marks) && marks.length == 0)
665
+ return Mark.none;
666
+ if (marks instanceof Mark)
667
+ return [marks];
668
+ let copy = marks.slice();
669
+ copy.sort((a, b) => a.type.rank - b.type.rank);
670
+ return copy;
671
+ }
672
+ }
673
+ /**
674
+ The empty set of marks.
675
+ */
676
+ Mark.none = [];
677
+
678
+ /**
679
+ Error type raised by [`Node.replace`](https://prosemirror.net/docs/ref/#model.Node.replace) when
680
+ given an invalid replacement.
681
+ */
682
+ class ReplaceError extends Error {
683
+ }
684
+ /*
685
+ ReplaceError = function(this: any, message: string) {
686
+ let err = Error.call(this, message)
687
+ ;(err as any).__proto__ = ReplaceError.prototype
688
+ return err
689
+ } as any
690
+
691
+ ReplaceError.prototype = Object.create(Error.prototype)
692
+ ReplaceError.prototype.constructor = ReplaceError
693
+ ReplaceError.prototype.name = "ReplaceError"
694
+ */
695
+ /**
696
+ A slice represents a piece cut out of a larger document. It
697
+ stores not only a fragment, but also the depth up to which nodes on
698
+ both side are ‘open’ (cut through).
699
+ */
700
+ class Slice {
701
+ /**
702
+ Create a slice. When specifying a non-zero open depth, you must
703
+ make sure that there are nodes of at least that depth at the
704
+ appropriate side of the fragment—i.e. if the fragment is an
705
+ empty paragraph node, `openStart` and `openEnd` can't be greater
706
+ than 1.
707
+
708
+ It is not necessary for the content of open nodes to conform to
709
+ the schema's content constraints, though it should be a valid
710
+ start/end/middle for such a node, depending on which sides are
711
+ open.
712
+ */
713
+ constructor(
714
+ /**
715
+ The slice's content.
716
+ */
717
+ content,
718
+ /**
719
+ The open depth at the start of the fragment.
720
+ */
721
+ openStart,
722
+ /**
723
+ The open depth at the end.
724
+ */
725
+ openEnd) {
726
+ this.content = content;
727
+ this.openStart = openStart;
728
+ this.openEnd = openEnd;
729
+ }
730
+ /**
731
+ The size this slice would add when inserted into a document.
732
+ */
733
+ get size() {
734
+ return this.content.size - this.openStart - this.openEnd;
735
+ }
736
+ /**
737
+ @internal
738
+ */
739
+ insertAt(pos, fragment) {
740
+ let content = insertInto(this.content, pos + this.openStart, fragment);
741
+ return content && new Slice(content, this.openStart, this.openEnd);
742
+ }
743
+ /**
744
+ @internal
745
+ */
746
+ removeBetween(from, to) {
747
+ return new Slice(removeRange(this.content, from + this.openStart, to + this.openStart), this.openStart, this.openEnd);
748
+ }
749
+ /**
750
+ Tests whether this slice is equal to another slice.
751
+ */
752
+ eq(other) {
753
+ return this.content.eq(other.content) && this.openStart == other.openStart && this.openEnd == other.openEnd;
754
+ }
755
+ /**
756
+ @internal
757
+ */
758
+ toString() {
759
+ return this.content + "(" + this.openStart + "," + this.openEnd + ")";
760
+ }
761
+ /**
762
+ Convert a slice to a JSON-serializable representation.
763
+ */
764
+ toJSON() {
765
+ if (!this.content.size)
766
+ return null;
767
+ let json = { content: this.content.toJSON() };
768
+ if (this.openStart > 0)
769
+ json.openStart = this.openStart;
770
+ if (this.openEnd > 0)
771
+ json.openEnd = this.openEnd;
772
+ return json;
773
+ }
774
+ /**
775
+ Deserialize a slice from its JSON representation.
776
+ */
777
+ static fromJSON(schema, json) {
778
+ if (!json)
779
+ return Slice.empty;
780
+ let openStart = json.openStart || 0, openEnd = json.openEnd || 0;
781
+ if (typeof openStart != "number" || typeof openEnd != "number")
782
+ throw new RangeError("Invalid input for Slice.fromJSON");
783
+ return new Slice(Fragment.fromJSON(schema, json.content), openStart, openEnd);
784
+ }
785
+ /**
786
+ Create a slice from a fragment by taking the maximum possible
787
+ open value on both side of the fragment.
788
+ */
789
+ static maxOpen(fragment, openIsolating = true) {
790
+ let openStart = 0, openEnd = 0;
791
+ for (let n = fragment.firstChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.firstChild)
792
+ openStart++;
793
+ for (let n = fragment.lastChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.lastChild)
794
+ openEnd++;
795
+ return new Slice(fragment, openStart, openEnd);
796
+ }
797
+ }
798
+ /**
799
+ The empty slice.
800
+ */
801
+ Slice.empty = new Slice(Fragment.empty, 0, 0);
802
+ function removeRange(content, from, to) {
803
+ let { index, offset } = content.findIndex(from), child = content.maybeChild(index);
804
+ let { index: indexTo, offset: offsetTo } = content.findIndex(to);
805
+ if (offset == from || child.isText) {
806
+ if (offsetTo != to && !content.child(indexTo).isText)
807
+ throw new RangeError("Removing non-flat range");
808
+ return content.cut(0, from).append(content.cut(to));
809
+ }
810
+ if (index != indexTo)
811
+ throw new RangeError("Removing non-flat range");
812
+ return content.replaceChild(index, child.copy(removeRange(child.content, from - offset - 1, to - offset - 1)));
813
+ }
814
+ function insertInto(content, dist, insert, parent) {
815
+ let { index, offset } = content.findIndex(dist), child = content.maybeChild(index);
816
+ if (offset == dist || child.isText) {
817
+ if (parent && !parent.canReplace(index, index, insert))
818
+ return null;
819
+ return content.cut(0, dist).append(insert).append(content.cut(dist));
820
+ }
821
+ let inner = insertInto(child.content, dist - offset - 1, insert, child);
822
+ return inner && content.replaceChild(index, child.copy(inner));
823
+ }
824
+ function replace($from, $to, slice) {
825
+ if (slice.openStart > $from.depth)
826
+ throw new ReplaceError("Inserted content deeper than insertion position");
827
+ if ($from.depth - slice.openStart != $to.depth - slice.openEnd)
828
+ throw new ReplaceError("Inconsistent open depths");
829
+ return replaceOuter($from, $to, slice, 0);
830
+ }
831
+ function replaceOuter($from, $to, slice, depth) {
832
+ let index = $from.index(depth), node = $from.node(depth);
833
+ if (index == $to.index(depth) && depth < $from.depth - slice.openStart) {
834
+ let inner = replaceOuter($from, $to, slice, depth + 1);
835
+ return node.copy(node.content.replaceChild(index, inner));
836
+ }
837
+ else if (!slice.content.size) {
838
+ return close(node, replaceTwoWay($from, $to, depth));
839
+ }
840
+ else if (!slice.openStart && !slice.openEnd && $from.depth == depth && $to.depth == depth) { // Simple, flat case
841
+ let parent = $from.parent, content = parent.content;
842
+ return close(parent, content.cut(0, $from.parentOffset).append(slice.content).append(content.cut($to.parentOffset)));
843
+ }
844
+ else {
845
+ let { start, end } = prepareSliceForReplace(slice, $from);
846
+ return close(node, replaceThreeWay($from, start, end, $to, depth));
847
+ }
848
+ }
849
+ function checkJoin(main, sub) {
850
+ if (!sub.type.compatibleContent(main.type))
851
+ throw new ReplaceError("Cannot join " + sub.type.name + " onto " + main.type.name);
852
+ }
853
+ function joinable($before, $after, depth) {
854
+ let node = $before.node(depth);
855
+ checkJoin(node, $after.node(depth));
856
+ return node;
857
+ }
858
+ function addNode(child, target) {
859
+ let last = target.length - 1;
860
+ if (last >= 0 && child.isText && child.sameMarkup(target[last]))
861
+ target[last] = child.withText(target[last].text + child.text);
862
+ else
863
+ target.push(child);
864
+ }
865
+ function addRange($start, $end, depth, target) {
866
+ let node = ($end || $start).node(depth);
867
+ let startIndex = 0, endIndex = $end ? $end.index(depth) : node.childCount;
868
+ if ($start) {
869
+ startIndex = $start.index(depth);
870
+ if ($start.depth > depth) {
871
+ startIndex++;
872
+ }
873
+ else if ($start.textOffset) {
874
+ addNode($start.nodeAfter, target);
875
+ startIndex++;
876
+ }
877
+ }
878
+ for (let i = startIndex; i < endIndex; i++)
879
+ addNode(node.child(i), target);
880
+ if ($end && $end.depth == depth && $end.textOffset)
881
+ addNode($end.nodeBefore, target);
882
+ }
883
+ function close(node, content) {
884
+ node.type.checkContent(content);
885
+ return node.copy(content);
886
+ }
887
+ function replaceThreeWay($from, $start, $end, $to, depth) {
888
+ let openStart = $from.depth > depth && joinable($from, $start, depth + 1);
889
+ let openEnd = $to.depth > depth && joinable($end, $to, depth + 1);
890
+ let content = [];
891
+ addRange(null, $from, depth, content);
892
+ if (openStart && openEnd && $start.index(depth) == $end.index(depth)) {
893
+ checkJoin(openStart, openEnd);
894
+ addNode(close(openStart, replaceThreeWay($from, $start, $end, $to, depth + 1)), content);
895
+ }
896
+ else {
897
+ if (openStart)
898
+ addNode(close(openStart, replaceTwoWay($from, $start, depth + 1)), content);
899
+ addRange($start, $end, depth, content);
900
+ if (openEnd)
901
+ addNode(close(openEnd, replaceTwoWay($end, $to, depth + 1)), content);
902
+ }
903
+ addRange($to, null, depth, content);
904
+ return new Fragment(content);
905
+ }
906
+ function replaceTwoWay($from, $to, depth) {
907
+ let content = [];
908
+ addRange(null, $from, depth, content);
909
+ if ($from.depth > depth) {
910
+ let type = joinable($from, $to, depth + 1);
911
+ addNode(close(type, replaceTwoWay($from, $to, depth + 1)), content);
912
+ }
913
+ addRange($to, null, depth, content);
914
+ return new Fragment(content);
915
+ }
916
+ function prepareSliceForReplace(slice, $along) {
917
+ let extra = $along.depth - slice.openStart, parent = $along.node(extra);
918
+ let node = parent.copy(slice.content);
919
+ for (let i = extra - 1; i >= 0; i--)
920
+ node = $along.node(i).copy(Fragment.from(node));
921
+ return { start: node.resolveNoCache(slice.openStart + extra),
922
+ end: node.resolveNoCache(node.content.size - slice.openEnd - extra) };
923
+ }
924
+
925
+ /**
926
+ You can [_resolve_](https://prosemirror.net/docs/ref/#model.Node.resolve) a position to get more
927
+ information about it. Objects of this class represent such a
928
+ resolved position, providing various pieces of context
929
+ information, and some helper methods.
930
+
931
+ Throughout this interface, methods that take an optional `depth`
932
+ parameter will interpret undefined as `this.depth` and negative
933
+ numbers as `this.depth + value`.
934
+ */
935
+ class ResolvedPos {
936
+ /**
937
+ @internal
938
+ */
939
+ constructor(
940
+ /**
941
+ The position that was resolved.
942
+ */
943
+ pos,
944
+ /**
945
+ @internal
946
+ */
947
+ path,
948
+ /**
949
+ The offset this position has into its parent node.
950
+ */
951
+ parentOffset) {
952
+ this.pos = pos;
953
+ this.path = path;
954
+ this.parentOffset = parentOffset;
955
+ this.depth = path.length / 3 - 1;
956
+ }
957
+ /**
958
+ @internal
959
+ */
960
+ resolveDepth(val) {
961
+ if (val == null)
962
+ return this.depth;
963
+ if (val < 0)
964
+ return this.depth + val;
965
+ return val;
966
+ }
967
+ /**
968
+ The parent node that the position points into. Note that even if
969
+ a position points into a text node, that node is not considered
970
+ the parent—text nodes are ‘flat’ in this model, and have no content.
971
+ */
972
+ get parent() { return this.node(this.depth); }
973
+ /**
974
+ The root node in which the position was resolved.
975
+ */
976
+ get doc() { return this.node(0); }
977
+ /**
978
+ The ancestor node at the given level. `p.node(p.depth)` is the
979
+ same as `p.parent`.
980
+ */
981
+ node(depth) { return this.path[this.resolveDepth(depth) * 3]; }
982
+ /**
983
+ The index into the ancestor at the given level. If this points
984
+ at the 3rd node in the 2nd paragraph on the top level, for
985
+ example, `p.index(0)` is 1 and `p.index(1)` is 2.
986
+ */
987
+ index(depth) { return this.path[this.resolveDepth(depth) * 3 + 1]; }
988
+ /**
989
+ The index pointing after this position into the ancestor at the
990
+ given level.
991
+ */
992
+ indexAfter(depth) {
993
+ depth = this.resolveDepth(depth);
994
+ return this.index(depth) + (depth == this.depth && !this.textOffset ? 0 : 1);
995
+ }
996
+ /**
997
+ The (absolute) position at the start of the node at the given
998
+ level.
999
+ */
1000
+ start(depth) {
1001
+ depth = this.resolveDepth(depth);
1002
+ return depth == 0 ? 0 : this.path[depth * 3 - 1] + 1;
1003
+ }
1004
+ /**
1005
+ The (absolute) position at the end of the node at the given
1006
+ level.
1007
+ */
1008
+ end(depth) {
1009
+ depth = this.resolveDepth(depth);
1010
+ return this.start(depth) + this.node(depth).content.size;
1011
+ }
1012
+ /**
1013
+ The (absolute) position directly before the wrapping node at the
1014
+ given level, or, when `depth` is `this.depth + 1`, the original
1015
+ position.
1016
+ */
1017
+ before(depth) {
1018
+ depth = this.resolveDepth(depth);
1019
+ if (!depth)
1020
+ throw new RangeError("There is no position before the top-level node");
1021
+ return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1];
1022
+ }
1023
+ /**
1024
+ The (absolute) position directly after the wrapping node at the
1025
+ given level, or the original position when `depth` is `this.depth + 1`.
1026
+ */
1027
+ after(depth) {
1028
+ depth = this.resolveDepth(depth);
1029
+ if (!depth)
1030
+ throw new RangeError("There is no position after the top-level node");
1031
+ return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1] + this.path[depth * 3].nodeSize;
1032
+ }
1033
+ /**
1034
+ When this position points into a text node, this returns the
1035
+ distance between the position and the start of the text node.
1036
+ Will be zero for positions that point between nodes.
1037
+ */
1038
+ get textOffset() { return this.pos - this.path[this.path.length - 1]; }
1039
+ /**
1040
+ Get the node directly after the position, if any. If the position
1041
+ points into a text node, only the part of that node after the
1042
+ position is returned.
1043
+ */
1044
+ get nodeAfter() {
1045
+ let parent = this.parent, index = this.index(this.depth);
1046
+ if (index == parent.childCount)
1047
+ return null;
1048
+ let dOff = this.pos - this.path[this.path.length - 1], child = parent.child(index);
1049
+ return dOff ? parent.child(index).cut(dOff) : child;
1050
+ }
1051
+ /**
1052
+ Get the node directly before the position, if any. If the
1053
+ position points into a text node, only the part of that node
1054
+ before the position is returned.
1055
+ */
1056
+ get nodeBefore() {
1057
+ let index = this.index(this.depth);
1058
+ let dOff = this.pos - this.path[this.path.length - 1];
1059
+ if (dOff)
1060
+ return this.parent.child(index).cut(0, dOff);
1061
+ return index == 0 ? null : this.parent.child(index - 1);
1062
+ }
1063
+ /**
1064
+ Get the position at the given index in the parent node at the
1065
+ given depth (which defaults to `this.depth`).
1066
+ */
1067
+ posAtIndex(index, depth) {
1068
+ depth = this.resolveDepth(depth);
1069
+ let node = this.path[depth * 3], pos = depth == 0 ? 0 : this.path[depth * 3 - 1] + 1;
1070
+ for (let i = 0; i < index; i++)
1071
+ pos += node.child(i).nodeSize;
1072
+ return pos;
1073
+ }
1074
+ /**
1075
+ Get the marks at this position, factoring in the surrounding
1076
+ marks' [`inclusive`](https://prosemirror.net/docs/ref/#model.MarkSpec.inclusive) property. If the
1077
+ position is at the start of a non-empty node, the marks of the
1078
+ node after it (if any) are returned.
1079
+ */
1080
+ marks() {
1081
+ let parent = this.parent, index = this.index();
1082
+ // In an empty parent, return the empty array
1083
+ if (parent.content.size == 0)
1084
+ return Mark.none;
1085
+ // When inside a text node, just return the text node's marks
1086
+ if (this.textOffset)
1087
+ return parent.child(index).marks;
1088
+ let main = parent.maybeChild(index - 1), other = parent.maybeChild(index);
1089
+ // If the `after` flag is true of there is no node before, make
1090
+ // the node after this position the main reference.
1091
+ if (!main) {
1092
+ let tmp = main;
1093
+ main = other;
1094
+ other = tmp;
1095
+ }
1096
+ // Use all marks in the main node, except those that have
1097
+ // `inclusive` set to false and are not present in the other node.
1098
+ let marks = main.marks;
1099
+ for (var i = 0; i < marks.length; i++)
1100
+ if (marks[i].type.spec.inclusive === false && (!other || !marks[i].isInSet(other.marks)))
1101
+ marks = marks[i--].removeFromSet(marks);
1102
+ return marks;
1103
+ }
1104
+ /**
1105
+ Get the marks after the current position, if any, except those
1106
+ that are non-inclusive and not present at position `$end`. This
1107
+ is mostly useful for getting the set of marks to preserve after a
1108
+ deletion. Will return `null` if this position is at the end of
1109
+ its parent node or its parent node isn't a textblock (in which
1110
+ case no marks should be preserved).
1111
+ */
1112
+ marksAcross($end) {
1113
+ let after = this.parent.maybeChild(this.index());
1114
+ if (!after || !after.isInline)
1115
+ return null;
1116
+ let marks = after.marks, next = $end.parent.maybeChild($end.index());
1117
+ for (var i = 0; i < marks.length; i++)
1118
+ if (marks[i].type.spec.inclusive === false && (!next || !marks[i].isInSet(next.marks)))
1119
+ marks = marks[i--].removeFromSet(marks);
1120
+ return marks;
1121
+ }
1122
+ /**
1123
+ The depth up to which this position and the given (non-resolved)
1124
+ position share the same parent nodes.
1125
+ */
1126
+ sharedDepth(pos) {
1127
+ for (let depth = this.depth; depth > 0; depth--)
1128
+ if (this.start(depth) <= pos && this.end(depth) >= pos)
1129
+ return depth;
1130
+ return 0;
1131
+ }
1132
+ /**
1133
+ Returns a range based on the place where this position and the
1134
+ given position diverge around block content. If both point into
1135
+ the same textblock, for example, a range around that textblock
1136
+ will be returned. If they point into different blocks, the range
1137
+ around those blocks in their shared ancestor is returned. You can
1138
+ pass in an optional predicate that will be called with a parent
1139
+ node to see if a range into that parent is acceptable.
1140
+ */
1141
+ blockRange(other = this, pred) {
1142
+ if (other.pos < this.pos)
1143
+ return other.blockRange(this);
1144
+ for (let d = this.depth - (this.parent.inlineContent || this.pos == other.pos ? 1 : 0); d >= 0; d--)
1145
+ if (other.pos <= this.end(d) && (!pred || pred(this.node(d))))
1146
+ return new NodeRange(this, other, d);
1147
+ return null;
1148
+ }
1149
+ /**
1150
+ Query whether the given position shares the same parent node.
1151
+ */
1152
+ sameParent(other) {
1153
+ return this.pos - this.parentOffset == other.pos - other.parentOffset;
1154
+ }
1155
+ /**
1156
+ Return the greater of this and the given position.
1157
+ */
1158
+ max(other) {
1159
+ return other.pos > this.pos ? other : this;
1160
+ }
1161
+ /**
1162
+ Return the smaller of this and the given position.
1163
+ */
1164
+ min(other) {
1165
+ return other.pos < this.pos ? other : this;
1166
+ }
1167
+ /**
1168
+ @internal
1169
+ */
1170
+ toString() {
1171
+ let str = "";
1172
+ for (let i = 1; i <= this.depth; i++)
1173
+ str += (str ? "/" : "") + this.node(i).type.name + "_" + this.index(i - 1);
1174
+ return str + ":" + this.parentOffset;
1175
+ }
1176
+ /**
1177
+ @internal
1178
+ */
1179
+ static resolve(doc, pos) {
1180
+ if (!(pos >= 0 && pos <= doc.content.size))
1181
+ throw new RangeError("Position " + pos + " out of range");
1182
+ let path = [];
1183
+ let start = 0, parentOffset = pos;
1184
+ for (let node = doc;;) {
1185
+ let { index, offset } = node.content.findIndex(parentOffset);
1186
+ let rem = parentOffset - offset;
1187
+ path.push(node, index, start + offset);
1188
+ if (!rem)
1189
+ break;
1190
+ node = node.child(index);
1191
+ if (node.isText)
1192
+ break;
1193
+ parentOffset = rem - 1;
1194
+ start += offset + 1;
1195
+ }
1196
+ return new ResolvedPos(pos, path, parentOffset);
1197
+ }
1198
+ /**
1199
+ @internal
1200
+ */
1201
+ static resolveCached(doc, pos) {
1202
+ let cache = resolveCache.get(doc);
1203
+ if (cache) {
1204
+ for (let i = 0; i < cache.elts.length; i++) {
1205
+ let elt = cache.elts[i];
1206
+ if (elt.pos == pos)
1207
+ return elt;
1208
+ }
1209
+ }
1210
+ else {
1211
+ resolveCache.set(doc, cache = new ResolveCache);
1212
+ }
1213
+ let result = cache.elts[cache.i] = ResolvedPos.resolve(doc, pos);
1214
+ cache.i = (cache.i + 1) % resolveCacheSize;
1215
+ return result;
1216
+ }
1217
+ }
1218
+ class ResolveCache {
1219
+ constructor() {
1220
+ this.elts = [];
1221
+ this.i = 0;
1222
+ }
1223
+ }
1224
+ const resolveCacheSize = 12, resolveCache = new WeakMap();
1225
+ /**
1226
+ Represents a flat range of content, i.e. one that starts and
1227
+ ends in the same node.
1228
+ */
1229
+ class NodeRange {
1230
+ /**
1231
+ Construct a node range. `$from` and `$to` should point into the
1232
+ same node until at least the given `depth`, since a node range
1233
+ denotes an adjacent set of nodes in a single parent node.
1234
+ */
1235
+ constructor(
1236
+ /**
1237
+ A resolved position along the start of the content. May have a
1238
+ `depth` greater than this object's `depth` property, since
1239
+ these are the positions that were used to compute the range,
1240
+ not re-resolved positions directly at its boundaries.
1241
+ */
1242
+ $from,
1243
+ /**
1244
+ A position along the end of the content. See
1245
+ caveat for [`$from`](https://prosemirror.net/docs/ref/#model.NodeRange.$from).
1246
+ */
1247
+ $to,
1248
+ /**
1249
+ The depth of the node that this range points into.
1250
+ */
1251
+ depth) {
1252
+ this.$from = $from;
1253
+ this.$to = $to;
1254
+ this.depth = depth;
1255
+ }
1256
+ /**
1257
+ The position at the start of the range.
1258
+ */
1259
+ get start() { return this.$from.before(this.depth + 1); }
1260
+ /**
1261
+ The position at the end of the range.
1262
+ */
1263
+ get end() { return this.$to.after(this.depth + 1); }
1264
+ /**
1265
+ The parent node that the range points into.
1266
+ */
1267
+ get parent() { return this.$from.node(this.depth); }
1268
+ /**
1269
+ The start index of the range in the parent node.
1270
+ */
1271
+ get startIndex() { return this.$from.index(this.depth); }
1272
+ /**
1273
+ The end index of the range in the parent node.
1274
+ */
1275
+ get endIndex() { return this.$to.indexAfter(this.depth); }
1276
+ }
1277
+
1278
+ const emptyAttrs = Object.create(null);
1279
+ /**
1280
+ This class represents a node in the tree that makes up a
1281
+ ProseMirror document. So a document is an instance of `Node`, with
1282
+ children that are also instances of `Node`.
1283
+
1284
+ Nodes are persistent data structures. Instead of changing them, you
1285
+ create new ones with the content you want. Old ones keep pointing
1286
+ at the old document shape. This is made cheaper by sharing
1287
+ structure between the old and new data as much as possible, which a
1288
+ tree shape like this (without back pointers) makes easy.
1289
+
1290
+ **Do not** directly mutate the properties of a `Node` object. See
1291
+ [the guide](https://prosemirror.net/docs/guide/#doc) for more information.
1292
+ */
1293
+ class Node {
1294
+ /**
1295
+ @internal
1296
+ */
1297
+ constructor(
1298
+ /**
1299
+ The type of node that this is.
1300
+ */
1301
+ type,
1302
+ /**
1303
+ An object mapping attribute names to values. The kind of
1304
+ attributes allowed and required are
1305
+ [determined](https://prosemirror.net/docs/ref/#model.NodeSpec.attrs) by the node type.
1306
+ */
1307
+ attrs,
1308
+ // A fragment holding the node's children.
1309
+ content,
1310
+ /**
1311
+ The marks (things like whether it is emphasized or part of a
1312
+ link) applied to this node.
1313
+ */
1314
+ marks = Mark.none) {
1315
+ this.type = type;
1316
+ this.attrs = attrs;
1317
+ this.marks = marks;
1318
+ this.content = content || Fragment.empty;
1319
+ }
1320
+ /**
1321
+ The array of this node's child nodes.
1322
+ */
1323
+ get children() { return this.content.content; }
1324
+ /**
1325
+ The size of this node, as defined by the integer-based [indexing
1326
+ scheme](https://prosemirror.net/docs/guide/#doc.indexing). For text nodes, this is the
1327
+ amount of characters. For other leaf nodes, it is one. For
1328
+ non-leaf nodes, it is the size of the content plus two (the
1329
+ start and end token).
1330
+ */
1331
+ get nodeSize() { return this.isLeaf ? 1 : 2 + this.content.size; }
1332
+ /**
1333
+ The number of children that the node has.
1334
+ */
1335
+ get childCount() { return this.content.childCount; }
1336
+ /**
1337
+ Get the child node at the given index. Raises an error when the
1338
+ index is out of range.
1339
+ */
1340
+ child(index) { return this.content.child(index); }
1341
+ /**
1342
+ Get the child node at the given index, if it exists.
1343
+ */
1344
+ maybeChild(index) { return this.content.maybeChild(index); }
1345
+ /**
1346
+ Call `f` for every child node, passing the node, its offset
1347
+ into this parent node, and its index.
1348
+ */
1349
+ forEach(f) { this.content.forEach(f); }
1350
+ /**
1351
+ Invoke a callback for all descendant nodes recursively between
1352
+ the given two positions that are relative to start of this
1353
+ node's content. The callback is invoked with the node, its
1354
+ position relative to the original node (method receiver),
1355
+ its parent node, and its child index. When the callback returns
1356
+ false for a given node, that node's children will not be
1357
+ recursed over. The last parameter can be used to specify a
1358
+ starting position to count from.
1359
+ */
1360
+ nodesBetween(from, to, f, startPos = 0) {
1361
+ this.content.nodesBetween(from, to, f, startPos, this);
1362
+ }
1363
+ /**
1364
+ Call the given callback for every descendant node. Doesn't
1365
+ descend into a node when the callback returns `false`.
1366
+ */
1367
+ descendants(f) {
1368
+ this.nodesBetween(0, this.content.size, f);
1369
+ }
1370
+ /**
1371
+ Concatenates all the text nodes found in this fragment and its
1372
+ children.
1373
+ */
1374
+ get textContent() {
1375
+ return (this.isLeaf && this.type.spec.leafText)
1376
+ ? this.type.spec.leafText(this)
1377
+ : this.textBetween(0, this.content.size, "");
1378
+ }
1379
+ /**
1380
+ Get all text between positions `from` and `to`. When
1381
+ `blockSeparator` is given, it will be inserted to separate text
1382
+ from different block nodes. If `leafText` is given, it'll be
1383
+ inserted for every non-text leaf node encountered, otherwise
1384
+ [`leafText`](https://prosemirror.net/docs/ref/#model.NodeSpec.leafText) will be used.
1385
+ */
1386
+ textBetween(from, to, blockSeparator, leafText) {
1387
+ return this.content.textBetween(from, to, blockSeparator, leafText);
1388
+ }
1389
+ /**
1390
+ Returns this node's first child, or `null` if there are no
1391
+ children.
1392
+ */
1393
+ get firstChild() { return this.content.firstChild; }
1394
+ /**
1395
+ Returns this node's last child, or `null` if there are no
1396
+ children.
1397
+ */
1398
+ get lastChild() { return this.content.lastChild; }
1399
+ /**
1400
+ Test whether two nodes represent the same piece of document.
1401
+ */
1402
+ eq(other) {
1403
+ return this == other || (this.sameMarkup(other) && this.content.eq(other.content));
1404
+ }
1405
+ /**
1406
+ Compare the markup (type, attributes, and marks) of this node to
1407
+ those of another. Returns `true` if both have the same markup.
1408
+ */
1409
+ sameMarkup(other) {
1410
+ return this.hasMarkup(other.type, other.attrs, other.marks);
1411
+ }
1412
+ /**
1413
+ Check whether this node's markup correspond to the given type,
1414
+ attributes, and marks.
1415
+ */
1416
+ hasMarkup(type, attrs, marks) {
1417
+ return this.type == type &&
1418
+ compareDeep(this.attrs, attrs || type.defaultAttrs || emptyAttrs) &&
1419
+ Mark.sameSet(this.marks, marks || Mark.none);
1420
+ }
1421
+ /**
1422
+ Create a new node with the same markup as this node, containing
1423
+ the given content (or empty, if no content is given).
1424
+ */
1425
+ copy(content = null) {
1426
+ if (content == this.content)
1427
+ return this;
1428
+ return new Node(this.type, this.attrs, content, this.marks);
1429
+ }
1430
+ /**
1431
+ Create a copy of this node, with the given set of marks instead
1432
+ of the node's own marks.
1433
+ */
1434
+ mark(marks) {
1435
+ return marks == this.marks ? this : new Node(this.type, this.attrs, this.content, marks);
1436
+ }
1437
+ /**
1438
+ Create a copy of this node with only the content between the
1439
+ given positions. If `to` is not given, it defaults to the end of
1440
+ the node.
1441
+ */
1442
+ cut(from, to = this.content.size) {
1443
+ if (from == 0 && to == this.content.size)
1444
+ return this;
1445
+ return this.copy(this.content.cut(from, to));
1446
+ }
1447
+ /**
1448
+ Cut out the part of the document between the given positions, and
1449
+ return it as a `Slice` object.
1450
+ */
1451
+ slice(from, to = this.content.size, includeParents = false) {
1452
+ if (from == to)
1453
+ return Slice.empty;
1454
+ let $from = this.resolve(from), $to = this.resolve(to);
1455
+ let depth = includeParents ? 0 : $from.sharedDepth(to);
1456
+ let start = $from.start(depth), node = $from.node(depth);
1457
+ let content = node.content.cut($from.pos - start, $to.pos - start);
1458
+ return new Slice(content, $from.depth - depth, $to.depth - depth);
1459
+ }
1460
+ /**
1461
+ Replace the part of the document between the given positions with
1462
+ the given slice. The slice must 'fit', meaning its open sides
1463
+ must be able to connect to the surrounding content, and its
1464
+ content nodes must be valid children for the node they are placed
1465
+ into. If any of this is violated, an error of type
1466
+ [`ReplaceError`](https://prosemirror.net/docs/ref/#model.ReplaceError) is thrown.
1467
+ */
1468
+ replace(from, to, slice) {
1469
+ return replace(this.resolve(from), this.resolve(to), slice);
1470
+ }
1471
+ /**
1472
+ Find the node directly after the given position.
1473
+ */
1474
+ nodeAt(pos) {
1475
+ for (let node = this;;) {
1476
+ let { index, offset } = node.content.findIndex(pos);
1477
+ node = node.maybeChild(index);
1478
+ if (!node)
1479
+ return null;
1480
+ if (offset == pos || node.isText)
1481
+ return node;
1482
+ pos -= offset + 1;
1483
+ }
1484
+ }
1485
+ /**
1486
+ Find the (direct) child node after the given offset, if any,
1487
+ and return it along with its index and offset relative to this
1488
+ node.
1489
+ */
1490
+ childAfter(pos) {
1491
+ let { index, offset } = this.content.findIndex(pos);
1492
+ return { node: this.content.maybeChild(index), index, offset };
1493
+ }
1494
+ /**
1495
+ Find the (direct) child node before the given offset, if any,
1496
+ and return it along with its index and offset relative to this
1497
+ node.
1498
+ */
1499
+ childBefore(pos) {
1500
+ if (pos == 0)
1501
+ return { node: null, index: 0, offset: 0 };
1502
+ let { index, offset } = this.content.findIndex(pos);
1503
+ if (offset < pos)
1504
+ return { node: this.content.child(index), index, offset };
1505
+ let node = this.content.child(index - 1);
1506
+ return { node, index: index - 1, offset: offset - node.nodeSize };
1507
+ }
1508
+ /**
1509
+ Resolve the given position in the document, returning an
1510
+ [object](https://prosemirror.net/docs/ref/#model.ResolvedPos) with information about its context.
1511
+ */
1512
+ resolve(pos) { return ResolvedPos.resolveCached(this, pos); }
1513
+ /**
1514
+ @internal
1515
+ */
1516
+ resolveNoCache(pos) { return ResolvedPos.resolve(this, pos); }
1517
+ /**
1518
+ Test whether a given mark or mark type occurs in this document
1519
+ between the two given positions.
1520
+ */
1521
+ rangeHasMark(from, to, type) {
1522
+ let found = false;
1523
+ if (to > from)
1524
+ this.nodesBetween(from, to, node => {
1525
+ if (type.isInSet(node.marks))
1526
+ found = true;
1527
+ return !found;
1528
+ });
1529
+ return found;
1530
+ }
1531
+ /**
1532
+ True when this is a block (non-inline node)
1533
+ */
1534
+ get isBlock() { return this.type.isBlock; }
1535
+ /**
1536
+ True when this is a textblock node, a block node with inline
1537
+ content.
1538
+ */
1539
+ get isTextblock() { return this.type.isTextblock; }
1540
+ /**
1541
+ True when this node allows inline content.
1542
+ */
1543
+ get inlineContent() { return this.type.inlineContent; }
1544
+ /**
1545
+ True when this is an inline node (a text node or a node that can
1546
+ appear among text).
1547
+ */
1548
+ get isInline() { return this.type.isInline; }
1549
+ /**
1550
+ True when this is a text node.
1551
+ */
1552
+ get isText() { return this.type.isText; }
1553
+ /**
1554
+ True when this is a leaf node.
1555
+ */
1556
+ get isLeaf() { return this.type.isLeaf; }
1557
+ /**
1558
+ True when this is an atom, i.e. when it does not have directly
1559
+ editable content. This is usually the same as `isLeaf`, but can
1560
+ be configured with the [`atom` property](https://prosemirror.net/docs/ref/#model.NodeSpec.atom)
1561
+ on a node's spec (typically used when the node is displayed as
1562
+ an uneditable [node view](https://prosemirror.net/docs/ref/#view.NodeView)).
1563
+ */
1564
+ get isAtom() { return this.type.isAtom; }
1565
+ /**
1566
+ Return a string representation of this node for debugging
1567
+ purposes.
1568
+ */
1569
+ toString() {
1570
+ if (this.type.spec.toDebugString)
1571
+ return this.type.spec.toDebugString(this);
1572
+ let name = this.type.name;
1573
+ if (this.content.size)
1574
+ name += "(" + this.content.toStringInner() + ")";
1575
+ return wrapMarks(this.marks, name);
1576
+ }
1577
+ /**
1578
+ Get the content match in this node at the given index.
1579
+ */
1580
+ contentMatchAt(index) {
1581
+ let match = this.type.contentMatch.matchFragment(this.content, 0, index);
1582
+ if (!match)
1583
+ throw new Error("Called contentMatchAt on a node with invalid content");
1584
+ return match;
1585
+ }
1586
+ /**
1587
+ Test whether replacing the range between `from` and `to` (by
1588
+ child index) with the given replacement fragment (which defaults
1589
+ to the empty fragment) would leave the node's content valid. You
1590
+ can optionally pass `start` and `end` indices into the
1591
+ replacement fragment.
1592
+ */
1593
+ canReplace(from, to, replacement = Fragment.empty, start = 0, end = replacement.childCount) {
1594
+ let one = this.contentMatchAt(from).matchFragment(replacement, start, end);
1595
+ let two = one && one.matchFragment(this.content, to);
1596
+ if (!two || !two.validEnd)
1597
+ return false;
1598
+ for (let i = start; i < end; i++)
1599
+ if (!this.type.allowsMarks(replacement.child(i).marks))
1600
+ return false;
1601
+ return true;
1602
+ }
1603
+ /**
1604
+ Test whether replacing the range `from` to `to` (by index) with
1605
+ a node of the given type would leave the node's content valid.
1606
+ */
1607
+ canReplaceWith(from, to, type, marks) {
1608
+ if (marks && !this.type.allowsMarks(marks))
1609
+ return false;
1610
+ let start = this.contentMatchAt(from).matchType(type);
1611
+ let end = start && start.matchFragment(this.content, to);
1612
+ return end ? end.validEnd : false;
1613
+ }
1614
+ /**
1615
+ Test whether the given node's content could be appended to this
1616
+ node. If that node is empty, this will only return true if there
1617
+ is at least one node type that can appear in both nodes (to avoid
1618
+ merging completely incompatible nodes).
1619
+ */
1620
+ canAppend(other) {
1621
+ if (other.content.size)
1622
+ return this.canReplace(this.childCount, this.childCount, other.content);
1623
+ else
1624
+ return this.type.compatibleContent(other.type);
1625
+ }
1626
+ /**
1627
+ Check whether this node and its descendants conform to the
1628
+ schema, and raise an exception when they do not.
1629
+ */
1630
+ check() {
1631
+ this.type.checkContent(this.content);
1632
+ this.type.checkAttrs(this.attrs);
1633
+ let copy = Mark.none;
1634
+ for (let i = 0; i < this.marks.length; i++) {
1635
+ let mark = this.marks[i];
1636
+ mark.type.checkAttrs(mark.attrs);
1637
+ copy = mark.addToSet(copy);
1638
+ }
1639
+ if (!Mark.sameSet(copy, this.marks))
1640
+ throw new RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map(m => m.type.name)}`);
1641
+ this.content.forEach(node => node.check());
1642
+ }
1643
+ /**
1644
+ Return a JSON-serializeable representation of this node.
1645
+ */
1646
+ toJSON() {
1647
+ let obj = { type: this.type.name };
1648
+ for (let _ in this.attrs) {
1649
+ obj.attrs = this.attrs;
1650
+ break;
1651
+ }
1652
+ if (this.content.size)
1653
+ obj.content = this.content.toJSON();
1654
+ if (this.marks.length)
1655
+ obj.marks = this.marks.map(n => n.toJSON());
1656
+ return obj;
1657
+ }
1658
+ /**
1659
+ Deserialize a node from its JSON representation.
1660
+ */
1661
+ static fromJSON(schema, json) {
1662
+ if (!json)
1663
+ throw new RangeError("Invalid input for Node.fromJSON");
1664
+ let marks = undefined;
1665
+ if (json.marks) {
1666
+ if (!Array.isArray(json.marks))
1667
+ throw new RangeError("Invalid mark data for Node.fromJSON");
1668
+ marks = json.marks.map(schema.markFromJSON);
1669
+ }
1670
+ if (json.type == "text") {
1671
+ if (typeof json.text != "string")
1672
+ throw new RangeError("Invalid text node in JSON");
1673
+ return schema.text(json.text, marks);
1674
+ }
1675
+ let content = Fragment.fromJSON(schema, json.content);
1676
+ let node = schema.nodeType(json.type).create(json.attrs, content, marks);
1677
+ node.type.checkAttrs(node.attrs);
1678
+ return node;
1679
+ }
1680
+ }
1681
+ Node.prototype.text = undefined;
1682
+ class TextNode extends Node {
1683
+ /**
1684
+ @internal
1685
+ */
1686
+ constructor(type, attrs, content, marks) {
1687
+ super(type, attrs, null, marks);
1688
+ if (!content)
1689
+ throw new RangeError("Empty text nodes are not allowed");
1690
+ this.text = content;
1691
+ }
1692
+ toString() {
1693
+ if (this.type.spec.toDebugString)
1694
+ return this.type.spec.toDebugString(this);
1695
+ return wrapMarks(this.marks, JSON.stringify(this.text));
1696
+ }
1697
+ get textContent() { return this.text; }
1698
+ textBetween(from, to) { return this.text.slice(from, to); }
1699
+ get nodeSize() { return this.text.length; }
1700
+ mark(marks) {
1701
+ return marks == this.marks ? this : new TextNode(this.type, this.attrs, this.text, marks);
1702
+ }
1703
+ withText(text) {
1704
+ if (text == this.text)
1705
+ return this;
1706
+ return new TextNode(this.type, this.attrs, text, this.marks);
1707
+ }
1708
+ cut(from = 0, to = this.text.length) {
1709
+ if (from == 0 && to == this.text.length)
1710
+ return this;
1711
+ return this.withText(this.text.slice(from, to));
1712
+ }
1713
+ eq(other) {
1714
+ return this.sameMarkup(other) && this.text == other.text;
1715
+ }
1716
+ toJSON() {
1717
+ let base = super.toJSON();
1718
+ base.text = this.text;
1719
+ return base;
1720
+ }
1721
+ }
1722
+ function wrapMarks(marks, str) {
1723
+ for (let i = marks.length - 1; i >= 0; i--)
1724
+ str = marks[i].type.name + "(" + str + ")";
1725
+ return str;
1726
+ }
1727
+
1728
+ /**
1729
+ Instances of this class represent a match state of a node type's
1730
+ [content expression](https://prosemirror.net/docs/ref/#model.NodeSpec.content), and can be used to
1731
+ find out whether further content matches here, and whether a given
1732
+ position is a valid end of the node.
1733
+ */
1734
+ class ContentMatch {
1735
+ /**
1736
+ @internal
1737
+ */
1738
+ constructor(
1739
+ /**
1740
+ True when this match state represents a valid end of the node.
1741
+ */
1742
+ validEnd) {
1743
+ this.validEnd = validEnd;
1744
+ /**
1745
+ @internal
1746
+ */
1747
+ this.next = [];
1748
+ /**
1749
+ @internal
1750
+ */
1751
+ this.wrapCache = [];
1752
+ }
1753
+ /**
1754
+ @internal
1755
+ */
1756
+ static parse(string, nodeTypes) {
1757
+ let stream = new TokenStream(string, nodeTypes);
1758
+ if (stream.next == null)
1759
+ return ContentMatch.empty;
1760
+ let expr = parseExpr(stream);
1761
+ if (stream.next)
1762
+ stream.err("Unexpected trailing text");
1763
+ let match = dfa(nfa(expr));
1764
+ checkForDeadEnds(match, stream);
1765
+ return match;
1766
+ }
1767
+ /**
1768
+ Match a node type, returning a match after that node if
1769
+ successful.
1770
+ */
1771
+ matchType(type) {
1772
+ for (let i = 0; i < this.next.length; i++)
1773
+ if (this.next[i].type == type)
1774
+ return this.next[i].next;
1775
+ return null;
1776
+ }
1777
+ /**
1778
+ Try to match a fragment. Returns the resulting match when
1779
+ successful.
1780
+ */
1781
+ matchFragment(frag, start = 0, end = frag.childCount) {
1782
+ let cur = this;
1783
+ for (let i = start; cur && i < end; i++)
1784
+ cur = cur.matchType(frag.child(i).type);
1785
+ return cur;
1786
+ }
1787
+ /**
1788
+ @internal
1789
+ */
1790
+ get inlineContent() {
1791
+ return this.next.length != 0 && this.next[0].type.isInline;
1792
+ }
1793
+ /**
1794
+ Get the first matching node type at this match position that can
1795
+ be generated.
1796
+ */
1797
+ get defaultType() {
1798
+ for (let i = 0; i < this.next.length; i++) {
1799
+ let { type } = this.next[i];
1800
+ if (!(type.isText || type.hasRequiredAttrs()))
1801
+ return type;
1802
+ }
1803
+ return null;
1804
+ }
1805
+ /**
1806
+ @internal
1807
+ */
1808
+ compatible(other) {
1809
+ for (let i = 0; i < this.next.length; i++)
1810
+ for (let j = 0; j < other.next.length; j++)
1811
+ if (this.next[i].type == other.next[j].type)
1812
+ return true;
1813
+ return false;
1814
+ }
1815
+ /**
1816
+ Try to match the given fragment, and if that fails, see if it can
1817
+ be made to match by inserting nodes in front of it. When
1818
+ successful, return a fragment of inserted nodes (which may be
1819
+ empty if nothing had to be inserted). When `toEnd` is true, only
1820
+ return a fragment if the resulting match goes to the end of the
1821
+ content expression.
1822
+ */
1823
+ fillBefore(after, toEnd = false, startIndex = 0) {
1824
+ let seen = [this];
1825
+ function search(match, types) {
1826
+ let finished = match.matchFragment(after, startIndex);
1827
+ if (finished && (!toEnd || finished.validEnd))
1828
+ return Fragment.from(types.map(tp => tp.createAndFill()));
1829
+ for (let i = 0; i < match.next.length; i++) {
1830
+ let { type, next } = match.next[i];
1831
+ if (!(type.isText || type.hasRequiredAttrs()) && seen.indexOf(next) == -1) {
1832
+ seen.push(next);
1833
+ let found = search(next, types.concat(type));
1834
+ if (found)
1835
+ return found;
1836
+ }
1837
+ }
1838
+ return null;
1839
+ }
1840
+ return search(this, []);
1841
+ }
1842
+ /**
1843
+ Find a set of wrapping node types that would allow a node of the
1844
+ given type to appear at this position. The result may be empty
1845
+ (when it fits directly) and will be null when no such wrapping
1846
+ exists.
1847
+ */
1848
+ findWrapping(target) {
1849
+ for (let i = 0; i < this.wrapCache.length; i += 2)
1850
+ if (this.wrapCache[i] == target)
1851
+ return this.wrapCache[i + 1];
1852
+ let computed = this.computeWrapping(target);
1853
+ this.wrapCache.push(target, computed);
1854
+ return computed;
1855
+ }
1856
+ /**
1857
+ @internal
1858
+ */
1859
+ computeWrapping(target) {
1860
+ let seen = Object.create(null), active = [{ match: this, type: null, via: null }];
1861
+ while (active.length) {
1862
+ let current = active.shift(), match = current.match;
1863
+ if (match.matchType(target)) {
1864
+ let result = [];
1865
+ for (let obj = current; obj.type; obj = obj.via)
1866
+ result.push(obj.type);
1867
+ return result.reverse();
1868
+ }
1869
+ for (let i = 0; i < match.next.length; i++) {
1870
+ let { type, next } = match.next[i];
1871
+ if (!type.isLeaf && !type.hasRequiredAttrs() && !(type.name in seen) && (!current.type || next.validEnd)) {
1872
+ active.push({ match: type.contentMatch, type, via: current });
1873
+ seen[type.name] = true;
1874
+ }
1875
+ }
1876
+ }
1877
+ return null;
1878
+ }
1879
+ /**
1880
+ The number of outgoing edges this node has in the finite
1881
+ automaton that describes the content expression.
1882
+ */
1883
+ get edgeCount() {
1884
+ return this.next.length;
1885
+ }
1886
+ /**
1887
+ Get the _n_​th outgoing edge from this node in the finite
1888
+ automaton that describes the content expression.
1889
+ */
1890
+ edge(n) {
1891
+ if (n >= this.next.length)
1892
+ throw new RangeError(`There's no ${n}th edge in this content match`);
1893
+ return this.next[n];
1894
+ }
1895
+ /**
1896
+ @internal
1897
+ */
1898
+ toString() {
1899
+ let seen = [];
1900
+ function scan(m) {
1901
+ seen.push(m);
1902
+ for (let i = 0; i < m.next.length; i++)
1903
+ if (seen.indexOf(m.next[i].next) == -1)
1904
+ scan(m.next[i].next);
1905
+ }
1906
+ scan(this);
1907
+ return seen.map((m, i) => {
1908
+ let out = i + (m.validEnd ? "*" : " ") + " ";
1909
+ for (let i = 0; i < m.next.length; i++)
1910
+ out += (i ? ", " : "") + m.next[i].type.name + "->" + seen.indexOf(m.next[i].next);
1911
+ return out;
1912
+ }).join("\n");
1913
+ }
1914
+ }
1915
+ /**
1916
+ @internal
1917
+ */
1918
+ ContentMatch.empty = new ContentMatch(true);
1919
+ class TokenStream {
1920
+ constructor(string, nodeTypes) {
1921
+ this.string = string;
1922
+ this.nodeTypes = nodeTypes;
1923
+ this.inline = null;
1924
+ this.pos = 0;
1925
+ this.tokens = string.split(/\s*(?=\b|\W|$)/);
1926
+ if (this.tokens[this.tokens.length - 1] == "")
1927
+ this.tokens.pop();
1928
+ if (this.tokens[0] == "")
1929
+ this.tokens.shift();
1930
+ }
1931
+ get next() { return this.tokens[this.pos]; }
1932
+ eat(tok) { return this.next == tok && (this.pos++ || true); }
1933
+ err(str) { throw new SyntaxError(str + " (in content expression '" + this.string + "')"); }
1934
+ }
1935
+ function parseExpr(stream) {
1936
+ let exprs = [];
1937
+ do {
1938
+ exprs.push(parseExprSeq(stream));
1939
+ } while (stream.eat("|"));
1940
+ return exprs.length == 1 ? exprs[0] : { type: "choice", exprs };
1941
+ }
1942
+ function parseExprSeq(stream) {
1943
+ let exprs = [];
1944
+ do {
1945
+ exprs.push(parseExprSubscript(stream));
1946
+ } while (stream.next && stream.next != ")" && stream.next != "|");
1947
+ return exprs.length == 1 ? exprs[0] : { type: "seq", exprs };
1948
+ }
1949
+ function parseExprSubscript(stream) {
1950
+ let expr = parseExprAtom(stream);
1951
+ for (;;) {
1952
+ if (stream.eat("+"))
1953
+ expr = { type: "plus", expr };
1954
+ else if (stream.eat("*"))
1955
+ expr = { type: "star", expr };
1956
+ else if (stream.eat("?"))
1957
+ expr = { type: "opt", expr };
1958
+ else if (stream.eat("{"))
1959
+ expr = parseExprRange(stream, expr);
1960
+ else
1961
+ break;
1962
+ }
1963
+ return expr;
1964
+ }
1965
+ function parseNum(stream) {
1966
+ if (/\D/.test(stream.next))
1967
+ stream.err("Expected number, got '" + stream.next + "'");
1968
+ let result = Number(stream.next);
1969
+ stream.pos++;
1970
+ return result;
1971
+ }
1972
+ function parseExprRange(stream, expr) {
1973
+ let min = parseNum(stream), max = min;
1974
+ if (stream.eat(",")) {
1975
+ if (stream.next != "}")
1976
+ max = parseNum(stream);
1977
+ else
1978
+ max = -1;
1979
+ }
1980
+ if (!stream.eat("}"))
1981
+ stream.err("Unclosed braced range");
1982
+ return { type: "range", min, max, expr };
1983
+ }
1984
+ function resolveName(stream, name) {
1985
+ let types = stream.nodeTypes, type = types[name];
1986
+ if (type)
1987
+ return [type];
1988
+ let result = [];
1989
+ for (let typeName in types) {
1990
+ let type = types[typeName];
1991
+ if (type.isInGroup(name))
1992
+ result.push(type);
1993
+ }
1994
+ if (result.length == 0)
1995
+ stream.err("No node type or group '" + name + "' found");
1996
+ return result;
1997
+ }
1998
+ function parseExprAtom(stream) {
1999
+ if (stream.eat("(")) {
2000
+ let expr = parseExpr(stream);
2001
+ if (!stream.eat(")"))
2002
+ stream.err("Missing closing paren");
2003
+ return expr;
2004
+ }
2005
+ else if (!/\W/.test(stream.next)) {
2006
+ let exprs = resolveName(stream, stream.next).map(type => {
2007
+ if (stream.inline == null)
2008
+ stream.inline = type.isInline;
2009
+ else if (stream.inline != type.isInline)
2010
+ stream.err("Mixing inline and block content");
2011
+ return { type: "name", value: type };
2012
+ });
2013
+ stream.pos++;
2014
+ return exprs.length == 1 ? exprs[0] : { type: "choice", exprs };
2015
+ }
2016
+ else {
2017
+ stream.err("Unexpected token '" + stream.next + "'");
2018
+ }
2019
+ }
2020
+ // Construct an NFA from an expression as returned by the parser. The
2021
+ // NFA is represented as an array of states, which are themselves
2022
+ // arrays of edges, which are `{term, to}` objects. The first state is
2023
+ // the entry state and the last node is the success state.
2024
+ //
2025
+ // Note that unlike typical NFAs, the edge ordering in this one is
2026
+ // significant, in that it is used to contruct filler content when
2027
+ // necessary.
2028
+ function nfa(expr) {
2029
+ let nfa = [[]];
2030
+ connect(compile(expr, 0), node());
2031
+ return nfa;
2032
+ function node() { return nfa.push([]) - 1; }
2033
+ function edge(from, to, term) {
2034
+ let edge = { term, to };
2035
+ nfa[from].push(edge);
2036
+ return edge;
2037
+ }
2038
+ function connect(edges, to) {
2039
+ edges.forEach(edge => edge.to = to);
2040
+ }
2041
+ function compile(expr, from) {
2042
+ if (expr.type == "choice") {
2043
+ return expr.exprs.reduce((out, expr) => out.concat(compile(expr, from)), []);
2044
+ }
2045
+ else if (expr.type == "seq") {
2046
+ for (let i = 0;; i++) {
2047
+ let next = compile(expr.exprs[i], from);
2048
+ if (i == expr.exprs.length - 1)
2049
+ return next;
2050
+ connect(next, from = node());
2051
+ }
2052
+ }
2053
+ else if (expr.type == "star") {
2054
+ let loop = node();
2055
+ edge(from, loop);
2056
+ connect(compile(expr.expr, loop), loop);
2057
+ return [edge(loop)];
2058
+ }
2059
+ else if (expr.type == "plus") {
2060
+ let loop = node();
2061
+ connect(compile(expr.expr, from), loop);
2062
+ connect(compile(expr.expr, loop), loop);
2063
+ return [edge(loop)];
2064
+ }
2065
+ else if (expr.type == "opt") {
2066
+ return [edge(from)].concat(compile(expr.expr, from));
2067
+ }
2068
+ else if (expr.type == "range") {
2069
+ let cur = from;
2070
+ for (let i = 0; i < expr.min; i++) {
2071
+ let next = node();
2072
+ connect(compile(expr.expr, cur), next);
2073
+ cur = next;
2074
+ }
2075
+ if (expr.max == -1) {
2076
+ connect(compile(expr.expr, cur), cur);
2077
+ }
2078
+ else {
2079
+ for (let i = expr.min; i < expr.max; i++) {
2080
+ let next = node();
2081
+ edge(cur, next);
2082
+ connect(compile(expr.expr, cur), next);
2083
+ cur = next;
2084
+ }
2085
+ }
2086
+ return [edge(cur)];
2087
+ }
2088
+ else if (expr.type == "name") {
2089
+ return [edge(from, undefined, expr.value)];
2090
+ }
2091
+ else {
2092
+ throw new Error("Unknown expr type");
2093
+ }
2094
+ }
2095
+ }
2096
+ function cmp(a, b) { return b - a; }
2097
+ // Get the set of nodes reachable by null edges from `node`. Omit
2098
+ // nodes with only a single null-out-edge, since they may lead to
2099
+ // needless duplicated nodes.
2100
+ function nullFrom(nfa, node) {
2101
+ let result = [];
2102
+ scan(node);
2103
+ return result.sort(cmp);
2104
+ function scan(node) {
2105
+ let edges = nfa[node];
2106
+ if (edges.length == 1 && !edges[0].term)
2107
+ return scan(edges[0].to);
2108
+ result.push(node);
2109
+ for (let i = 0; i < edges.length; i++) {
2110
+ let { term, to } = edges[i];
2111
+ if (!term && result.indexOf(to) == -1)
2112
+ scan(to);
2113
+ }
2114
+ }
2115
+ }
2116
+ // Compiles an NFA as produced by `nfa` into a DFA, modeled as a set
2117
+ // of state objects (`ContentMatch` instances) with transitions
2118
+ // between them.
2119
+ function dfa(nfa) {
2120
+ let labeled = Object.create(null);
2121
+ return explore(nullFrom(nfa, 0));
2122
+ function explore(states) {
2123
+ let out = [];
2124
+ states.forEach(node => {
2125
+ nfa[node].forEach(({ term, to }) => {
2126
+ if (!term)
2127
+ return;
2128
+ let set;
2129
+ for (let i = 0; i < out.length; i++)
2130
+ if (out[i][0] == term)
2131
+ set = out[i][1];
2132
+ nullFrom(nfa, to).forEach(node => {
2133
+ if (!set)
2134
+ out.push([term, set = []]);
2135
+ if (set.indexOf(node) == -1)
2136
+ set.push(node);
2137
+ });
2138
+ });
2139
+ });
2140
+ let state = labeled[states.join(",")] = new ContentMatch(states.indexOf(nfa.length - 1) > -1);
2141
+ for (let i = 0; i < out.length; i++) {
2142
+ let states = out[i][1].sort(cmp);
2143
+ state.next.push({ type: out[i][0], next: labeled[states.join(",")] || explore(states) });
2144
+ }
2145
+ return state;
2146
+ }
2147
+ }
2148
+ function checkForDeadEnds(match, stream) {
2149
+ for (let i = 0, work = [match]; i < work.length; i++) {
2150
+ let state = work[i], dead = !state.validEnd, nodes = [];
2151
+ for (let j = 0; j < state.next.length; j++) {
2152
+ let { type, next } = state.next[j];
2153
+ nodes.push(type.name);
2154
+ if (dead && !(type.isText || type.hasRequiredAttrs()))
2155
+ dead = false;
2156
+ if (work.indexOf(next) == -1)
2157
+ work.push(next);
2158
+ }
2159
+ if (dead)
2160
+ stream.err("Only non-generatable nodes (" + nodes.join(", ") + ") in a required position (see https://prosemirror.net/docs/guide/#generatable)");
2161
+ }
2162
+ }
2163
+
2164
+ // For node types where all attrs have a default value (or which don't
2165
+ // have any attributes), build up a single reusable default attribute
2166
+ // object, and use it for all nodes that don't specify specific
2167
+ // attributes.
2168
+ function defaultAttrs(attrs) {
2169
+ let defaults = Object.create(null);
2170
+ for (let attrName in attrs) {
2171
+ let attr = attrs[attrName];
2172
+ if (!attr.hasDefault)
2173
+ return null;
2174
+ defaults[attrName] = attr.default;
2175
+ }
2176
+ return defaults;
2177
+ }
2178
+ function computeAttrs(attrs, value) {
2179
+ let built = Object.create(null);
2180
+ for (let name in attrs) {
2181
+ let given = value && value[name];
2182
+ if (given === undefined) {
2183
+ let attr = attrs[name];
2184
+ if (attr.hasDefault)
2185
+ given = attr.default;
2186
+ else
2187
+ throw new RangeError("No value supplied for attribute " + name);
2188
+ }
2189
+ built[name] = given;
2190
+ }
2191
+ return built;
2192
+ }
2193
+ function checkAttrs(attrs, values, type, name) {
2194
+ for (let name in values)
2195
+ if (!(name in attrs))
2196
+ throw new RangeError(`Unsupported attribute ${name} for ${type} of type ${name}`);
2197
+ for (let name in attrs) {
2198
+ let attr = attrs[name];
2199
+ if (attr.validate)
2200
+ attr.validate(values[name]);
2201
+ }
2202
+ }
2203
+ function initAttrs(typeName, attrs) {
2204
+ let result = Object.create(null);
2205
+ if (attrs)
2206
+ for (let name in attrs)
2207
+ result[name] = new Attribute(typeName, name, attrs[name]);
2208
+ return result;
2209
+ }
2210
+ /**
2211
+ Node types are objects allocated once per `Schema` and used to
2212
+ [tag](https://prosemirror.net/docs/ref/#model.Node.type) `Node` instances. They contain information
2213
+ about the node type, such as its name and what kind of node it
2214
+ represents.
2215
+ */
2216
+ class NodeType {
2217
+ /**
2218
+ @internal
2219
+ */
2220
+ constructor(
2221
+ /**
2222
+ The name the node type has in this schema.
2223
+ */
2224
+ name,
2225
+ /**
2226
+ A link back to the `Schema` the node type belongs to.
2227
+ */
2228
+ schema,
2229
+ /**
2230
+ The spec that this type is based on
2231
+ */
2232
+ spec) {
2233
+ this.name = name;
2234
+ this.schema = schema;
2235
+ this.spec = spec;
2236
+ /**
2237
+ The set of marks allowed in this node. `null` means all marks
2238
+ are allowed.
2239
+ */
2240
+ this.markSet = null;
2241
+ this.groups = spec.group ? spec.group.split(" ") : [];
2242
+ this.attrs = initAttrs(name, spec.attrs);
2243
+ this.defaultAttrs = defaultAttrs(this.attrs);
2244
+ this.contentMatch = null;
2245
+ this.inlineContent = null;
2246
+ this.isBlock = !(spec.inline || name == "text");
2247
+ this.isText = name == "text";
2248
+ }
2249
+ /**
2250
+ True if this is an inline type.
2251
+ */
2252
+ get isInline() { return !this.isBlock; }
2253
+ /**
2254
+ True if this is a textblock type, a block that contains inline
2255
+ content.
2256
+ */
2257
+ get isTextblock() { return this.isBlock && this.inlineContent; }
2258
+ /**
2259
+ True for node types that allow no content.
2260
+ */
2261
+ get isLeaf() { return this.contentMatch == ContentMatch.empty; }
2262
+ /**
2263
+ True when this node is an atom, i.e. when it does not have
2264
+ directly editable content.
2265
+ */
2266
+ get isAtom() { return this.isLeaf || !!this.spec.atom; }
2267
+ /**
2268
+ Return true when this node type is part of the given
2269
+ [group](https://prosemirror.net/docs/ref/#model.NodeSpec.group).
2270
+ */
2271
+ isInGroup(group) {
2272
+ return this.groups.indexOf(group) > -1;
2273
+ }
2274
+ /**
2275
+ The node type's [whitespace](https://prosemirror.net/docs/ref/#model.NodeSpec.whitespace) option.
2276
+ */
2277
+ get whitespace() {
2278
+ return this.spec.whitespace || (this.spec.code ? "pre" : "normal");
2279
+ }
2280
+ /**
2281
+ Tells you whether this node type has any required attributes.
2282
+ */
2283
+ hasRequiredAttrs() {
2284
+ for (let n in this.attrs)
2285
+ if (this.attrs[n].isRequired)
2286
+ return true;
2287
+ return false;
2288
+ }
2289
+ /**
2290
+ Indicates whether this node allows some of the same content as
2291
+ the given node type.
2292
+ */
2293
+ compatibleContent(other) {
2294
+ return this == other || this.contentMatch.compatible(other.contentMatch);
2295
+ }
2296
+ /**
2297
+ @internal
2298
+ */
2299
+ computeAttrs(attrs) {
2300
+ if (!attrs && this.defaultAttrs)
2301
+ return this.defaultAttrs;
2302
+ else
2303
+ return computeAttrs(this.attrs, attrs);
2304
+ }
2305
+ /**
2306
+ Create a `Node` of this type. The given attributes are
2307
+ checked and defaulted (you can pass `null` to use the type's
2308
+ defaults entirely, if no required attributes exist). `content`
2309
+ may be a `Fragment`, a node, an array of nodes, or
2310
+ `null`. Similarly `marks` may be `null` to default to the empty
2311
+ set of marks.
2312
+ */
2313
+ create(attrs = null, content, marks) {
2314
+ if (this.isText)
2315
+ throw new Error("NodeType.create can't construct text nodes");
2316
+ return new Node(this, this.computeAttrs(attrs), Fragment.from(content), Mark.setFrom(marks));
2317
+ }
2318
+ /**
2319
+ Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but check the given content
2320
+ against the node type's content restrictions, and throw an error
2321
+ if it doesn't match.
2322
+ */
2323
+ createChecked(attrs = null, content, marks) {
2324
+ content = Fragment.from(content);
2325
+ this.checkContent(content);
2326
+ return new Node(this, this.computeAttrs(attrs), content, Mark.setFrom(marks));
2327
+ }
2328
+ /**
2329
+ Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but see if it is
2330
+ necessary to add nodes to the start or end of the given fragment
2331
+ to make it fit the node. If no fitting wrapping can be found,
2332
+ return null. Note that, due to the fact that required nodes can
2333
+ always be created, this will always succeed if you pass null or
2334
+ `Fragment.empty` as content.
2335
+ */
2336
+ createAndFill(attrs = null, content, marks) {
2337
+ attrs = this.computeAttrs(attrs);
2338
+ content = Fragment.from(content);
2339
+ if (content.size) {
2340
+ let before = this.contentMatch.fillBefore(content);
2341
+ if (!before)
2342
+ return null;
2343
+ content = before.append(content);
2344
+ }
2345
+ let matched = this.contentMatch.matchFragment(content);
2346
+ let after = matched && matched.fillBefore(Fragment.empty, true);
2347
+ if (!after)
2348
+ return null;
2349
+ return new Node(this, attrs, content.append(after), Mark.setFrom(marks));
2350
+ }
2351
+ /**
2352
+ Returns true if the given fragment is valid content for this node
2353
+ type.
2354
+ */
2355
+ validContent(content) {
2356
+ let result = this.contentMatch.matchFragment(content);
2357
+ if (!result || !result.validEnd)
2358
+ return false;
2359
+ for (let i = 0; i < content.childCount; i++)
2360
+ if (!this.allowsMarks(content.child(i).marks))
2361
+ return false;
2362
+ return true;
2363
+ }
2364
+ /**
2365
+ Throws a RangeError if the given fragment is not valid content for this
2366
+ node type.
2367
+ @internal
2368
+ */
2369
+ checkContent(content) {
2370
+ if (!this.validContent(content))
2371
+ throw new RangeError(`Invalid content for node ${this.name}: ${content.toString().slice(0, 50)}`);
2372
+ }
2373
+ /**
2374
+ @internal
2375
+ */
2376
+ checkAttrs(attrs) {
2377
+ checkAttrs(this.attrs, attrs, "node", this.name);
2378
+ }
2379
+ /**
2380
+ Check whether the given mark type is allowed in this node.
2381
+ */
2382
+ allowsMarkType(markType) {
2383
+ return this.markSet == null || this.markSet.indexOf(markType) > -1;
2384
+ }
2385
+ /**
2386
+ Test whether the given set of marks are allowed in this node.
2387
+ */
2388
+ allowsMarks(marks) {
2389
+ if (this.markSet == null)
2390
+ return true;
2391
+ for (let i = 0; i < marks.length; i++)
2392
+ if (!this.allowsMarkType(marks[i].type))
2393
+ return false;
2394
+ return true;
2395
+ }
2396
+ /**
2397
+ Removes the marks that are not allowed in this node from the given set.
2398
+ */
2399
+ allowedMarks(marks) {
2400
+ if (this.markSet == null)
2401
+ return marks;
2402
+ let copy;
2403
+ for (let i = 0; i < marks.length; i++) {
2404
+ if (!this.allowsMarkType(marks[i].type)) {
2405
+ if (!copy)
2406
+ copy = marks.slice(0, i);
2407
+ }
2408
+ else if (copy) {
2409
+ copy.push(marks[i]);
2410
+ }
2411
+ }
2412
+ return !copy ? marks : copy.length ? copy : Mark.none;
2413
+ }
2414
+ /**
2415
+ @internal
2416
+ */
2417
+ static compile(nodes, schema) {
2418
+ let result = Object.create(null);
2419
+ nodes.forEach((name, spec) => result[name] = new NodeType(name, schema, spec));
2420
+ let topType = schema.spec.topNode || "doc";
2421
+ if (!result[topType])
2422
+ throw new RangeError("Schema is missing its top node type ('" + topType + "')");
2423
+ if (!result.text)
2424
+ throw new RangeError("Every schema needs a 'text' type");
2425
+ for (let _ in result.text.attrs)
2426
+ throw new RangeError("The text node type should not have attributes");
2427
+ return result;
2428
+ }
2429
+ }
2430
+ function validateType(typeName, attrName, type) {
2431
+ let types = type.split("|");
2432
+ return (value) => {
2433
+ let name = value === null ? "null" : typeof value;
2434
+ if (types.indexOf(name) < 0)
2435
+ throw new RangeError(`Expected value of type ${types} for attribute ${attrName} on type ${typeName}, got ${name}`);
2436
+ };
2437
+ }
2438
+ // Attribute descriptors
2439
+ class Attribute {
2440
+ constructor(typeName, attrName, options) {
2441
+ this.hasDefault = Object.prototype.hasOwnProperty.call(options, "default");
2442
+ this.default = options.default;
2443
+ this.validate = typeof options.validate == "string" ? validateType(typeName, attrName, options.validate) : options.validate;
2444
+ }
2445
+ get isRequired() {
2446
+ return !this.hasDefault;
2447
+ }
2448
+ }
2449
+ // Marks
2450
+ /**
2451
+ Like nodes, marks (which are associated with nodes to signify
2452
+ things like emphasis or being part of a link) are
2453
+ [tagged](https://prosemirror.net/docs/ref/#model.Mark.type) with type objects, which are
2454
+ instantiated once per `Schema`.
2455
+ */
2456
+ class MarkType {
2457
+ /**
2458
+ @internal
2459
+ */
2460
+ constructor(
2461
+ /**
2462
+ The name of the mark type.
2463
+ */
2464
+ name,
2465
+ /**
2466
+ @internal
2467
+ */
2468
+ rank,
2469
+ /**
2470
+ The schema that this mark type instance is part of.
2471
+ */
2472
+ schema,
2473
+ /**
2474
+ The spec on which the type is based.
2475
+ */
2476
+ spec) {
2477
+ this.name = name;
2478
+ this.rank = rank;
2479
+ this.schema = schema;
2480
+ this.spec = spec;
2481
+ this.attrs = initAttrs(name, spec.attrs);
2482
+ this.excluded = null;
2483
+ let defaults = defaultAttrs(this.attrs);
2484
+ this.instance = defaults ? new Mark(this, defaults) : null;
2485
+ }
2486
+ /**
2487
+ Create a mark of this type. `attrs` may be `null` or an object
2488
+ containing only some of the mark's attributes. The others, if
2489
+ they have defaults, will be added.
2490
+ */
2491
+ create(attrs = null) {
2492
+ if (!attrs && this.instance)
2493
+ return this.instance;
2494
+ return new Mark(this, computeAttrs(this.attrs, attrs));
2495
+ }
2496
+ /**
2497
+ @internal
2498
+ */
2499
+ static compile(marks, schema) {
2500
+ let result = Object.create(null), rank = 0;
2501
+ marks.forEach((name, spec) => result[name] = new MarkType(name, rank++, schema, spec));
2502
+ return result;
2503
+ }
2504
+ /**
2505
+ When there is a mark of this type in the given set, a new set
2506
+ without it is returned. Otherwise, the input set is returned.
2507
+ */
2508
+ removeFromSet(set) {
2509
+ for (var i = 0; i < set.length; i++)
2510
+ if (set[i].type == this) {
2511
+ set = set.slice(0, i).concat(set.slice(i + 1));
2512
+ i--;
2513
+ }
2514
+ return set;
2515
+ }
2516
+ /**
2517
+ Tests whether there is a mark of this type in the given set.
2518
+ */
2519
+ isInSet(set) {
2520
+ for (let i = 0; i < set.length; i++)
2521
+ if (set[i].type == this)
2522
+ return set[i];
2523
+ }
2524
+ /**
2525
+ @internal
2526
+ */
2527
+ checkAttrs(attrs) {
2528
+ checkAttrs(this.attrs, attrs, "mark", this.name);
2529
+ }
2530
+ /**
2531
+ Queries whether a given mark type is
2532
+ [excluded](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) by this one.
2533
+ */
2534
+ excludes(other) {
2535
+ return this.excluded.indexOf(other) > -1;
2536
+ }
2537
+ }
2538
+ /**
2539
+ A document schema. Holds [node](https://prosemirror.net/docs/ref/#model.NodeType) and [mark
2540
+ type](https://prosemirror.net/docs/ref/#model.MarkType) objects for the nodes and marks that may
2541
+ occur in conforming documents, and provides functionality for
2542
+ creating and deserializing such documents.
2543
+
2544
+ When given, the type parameters provide the names of the nodes and
2545
+ marks in this schema.
2546
+ */
2547
+ class Schema {
2548
+ /**
2549
+ Construct a schema from a schema [specification](https://prosemirror.net/docs/ref/#model.SchemaSpec).
2550
+ */
2551
+ constructor(spec) {
2552
+ /**
2553
+ The [linebreak
2554
+ replacement](https://prosemirror.net/docs/ref/#model.NodeSpec.linebreakReplacement) node defined
2555
+ in this schema, if any.
2556
+ */
2557
+ this.linebreakReplacement = null;
2558
+ /**
2559
+ An object for storing whatever values modules may want to
2560
+ compute and cache per schema. (If you want to store something
2561
+ in it, try to use property names unlikely to clash.)
2562
+ */
2563
+ this.cached = Object.create(null);
2564
+ let instanceSpec = this.spec = {};
2565
+ for (let prop in spec)
2566
+ instanceSpec[prop] = spec[prop];
2567
+ instanceSpec.nodes = OrderedMap.from(spec.nodes),
2568
+ instanceSpec.marks = OrderedMap.from(spec.marks || {}),
2569
+ this.nodes = NodeType.compile(this.spec.nodes, this);
2570
+ this.marks = MarkType.compile(this.spec.marks, this);
2571
+ let contentExprCache = Object.create(null);
2572
+ for (let prop in this.nodes) {
2573
+ if (prop in this.marks)
2574
+ throw new RangeError(prop + " can not be both a node and a mark");
2575
+ let type = this.nodes[prop], contentExpr = type.spec.content || "", markExpr = type.spec.marks;
2576
+ type.contentMatch = contentExprCache[contentExpr] ||
2577
+ (contentExprCache[contentExpr] = ContentMatch.parse(contentExpr, this.nodes));
2578
+ type.inlineContent = type.contentMatch.inlineContent;
2579
+ if (type.spec.linebreakReplacement) {
2580
+ if (this.linebreakReplacement)
2581
+ throw new RangeError("Multiple linebreak nodes defined");
2582
+ if (!type.isInline || !type.isLeaf)
2583
+ throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");
2584
+ this.linebreakReplacement = type;
2585
+ }
2586
+ type.markSet = markExpr == "_" ? null :
2587
+ markExpr ? gatherMarks(this, markExpr.split(" ")) :
2588
+ markExpr == "" || !type.inlineContent ? [] : null;
2589
+ }
2590
+ for (let prop in this.marks) {
2591
+ let type = this.marks[prop], excl = type.spec.excludes;
2592
+ type.excluded = excl == null ? [type] : excl == "" ? [] : gatherMarks(this, excl.split(" "));
2593
+ }
2594
+ this.nodeFromJSON = json => Node.fromJSON(this, json);
2595
+ this.markFromJSON = json => Mark.fromJSON(this, json);
2596
+ this.topNodeType = this.nodes[this.spec.topNode || "doc"];
2597
+ this.cached.wrappings = Object.create(null);
2598
+ }
2599
+ /**
2600
+ Create a node in this schema. The `type` may be a string or a
2601
+ `NodeType` instance. Attributes will be extended with defaults,
2602
+ `content` may be a `Fragment`, `null`, a `Node`, or an array of
2603
+ nodes.
2604
+ */
2605
+ node(type, attrs = null, content, marks) {
2606
+ if (typeof type == "string")
2607
+ type = this.nodeType(type);
2608
+ else if (!(type instanceof NodeType))
2609
+ throw new RangeError("Invalid node type: " + type);
2610
+ else if (type.schema != this)
2611
+ throw new RangeError("Node type from different schema used (" + type.name + ")");
2612
+ return type.createChecked(attrs, content, marks);
2613
+ }
2614
+ /**
2615
+ Create a text node in the schema. Empty text nodes are not
2616
+ allowed.
2617
+ */
2618
+ text(text, marks) {
2619
+ let type = this.nodes.text;
2620
+ return new TextNode(type, type.defaultAttrs, text, Mark.setFrom(marks));
2621
+ }
2622
+ /**
2623
+ Create a mark with the given type and attributes.
2624
+ */
2625
+ mark(type, attrs) {
2626
+ if (typeof type == "string")
2627
+ type = this.marks[type];
2628
+ return type.create(attrs);
2629
+ }
2630
+ /**
2631
+ @internal
2632
+ */
2633
+ nodeType(name) {
2634
+ let found = this.nodes[name];
2635
+ if (!found)
2636
+ throw new RangeError("Unknown node type: " + name);
2637
+ return found;
2638
+ }
2639
+ }
2640
+ function gatherMarks(schema, marks) {
2641
+ let found = [];
2642
+ for (let i = 0; i < marks.length; i++) {
2643
+ let name = marks[i], mark = schema.marks[name], ok = mark;
2644
+ if (mark) {
2645
+ found.push(mark);
2646
+ }
2647
+ else {
2648
+ for (let prop in schema.marks) {
2649
+ let mark = schema.marks[prop];
2650
+ if (name == "_" || (mark.spec.group && mark.spec.group.split(" ").indexOf(name) > -1))
2651
+ found.push(ok = mark);
2652
+ }
2653
+ }
2654
+ if (!ok)
2655
+ throw new SyntaxError("Unknown mark type: '" + marks[i] + "'");
2656
+ }
2657
+ return found;
2658
+ }
2659
+
2660
+ function isTagRule(rule) { return rule.tag != null; }
2661
+ function isStyleRule(rule) { return rule.style != null; }
2662
+ /**
2663
+ A DOM parser represents a strategy for parsing DOM content into a
2664
+ ProseMirror document conforming to a given schema. Its behavior is
2665
+ defined by an array of [rules](https://prosemirror.net/docs/ref/#model.ParseRule).
2666
+ */
2667
+ class DOMParser {
2668
+ /**
2669
+ Create a parser that targets the given schema, using the given
2670
+ parsing rules.
2671
+ */
2672
+ constructor(
2673
+ /**
2674
+ The schema into which the parser parses.
2675
+ */
2676
+ schema,
2677
+ /**
2678
+ The set of [parse rules](https://prosemirror.net/docs/ref/#model.ParseRule) that the parser
2679
+ uses, in order of precedence.
2680
+ */
2681
+ rules) {
2682
+ this.schema = schema;
2683
+ this.rules = rules;
2684
+ /**
2685
+ @internal
2686
+ */
2687
+ this.tags = [];
2688
+ /**
2689
+ @internal
2690
+ */
2691
+ this.styles = [];
2692
+ let matchedStyles = this.matchedStyles = [];
2693
+ rules.forEach(rule => {
2694
+ if (isTagRule(rule)) {
2695
+ this.tags.push(rule);
2696
+ }
2697
+ else if (isStyleRule(rule)) {
2698
+ let prop = /[^=]*/.exec(rule.style)[0];
2699
+ if (matchedStyles.indexOf(prop) < 0)
2700
+ matchedStyles.push(prop);
2701
+ this.styles.push(rule);
2702
+ }
2703
+ });
2704
+ // Only normalize list elements when lists in the schema can't directly contain themselves
2705
+ this.normalizeLists = !this.tags.some(r => {
2706
+ if (!/^(ul|ol)\b/.test(r.tag) || !r.node)
2707
+ return false;
2708
+ let node = schema.nodes[r.node];
2709
+ return node.contentMatch.matchType(node);
2710
+ });
2711
+ }
2712
+ /**
2713
+ Parse a document from the content of a DOM node.
2714
+ */
2715
+ parse(dom, options = {}) {
2716
+ let context = new ParseContext(this, options, false);
2717
+ context.addAll(dom, Mark.none, options.from, options.to);
2718
+ return context.finish();
2719
+ }
2720
+ /**
2721
+ Parses the content of the given DOM node, like
2722
+ [`parse`](https://prosemirror.net/docs/ref/#model.DOMParser.parse), and takes the same set of
2723
+ options. But unlike that method, which produces a whole node,
2724
+ this one returns a slice that is open at the sides, meaning that
2725
+ the schema constraints aren't applied to the start of nodes to
2726
+ the left of the input and the end of nodes at the end.
2727
+ */
2728
+ parseSlice(dom, options = {}) {
2729
+ let context = new ParseContext(this, options, true);
2730
+ context.addAll(dom, Mark.none, options.from, options.to);
2731
+ return Slice.maxOpen(context.finish());
2732
+ }
2733
+ /**
2734
+ @internal
2735
+ */
2736
+ matchTag(dom, context, after) {
2737
+ for (let i = after ? this.tags.indexOf(after) + 1 : 0; i < this.tags.length; i++) {
2738
+ let rule = this.tags[i];
2739
+ if (matches(dom, rule.tag) &&
2740
+ (rule.namespace === undefined || dom.namespaceURI == rule.namespace) &&
2741
+ (!rule.context || context.matchesContext(rule.context))) {
2742
+ if (rule.getAttrs) {
2743
+ let result = rule.getAttrs(dom);
2744
+ if (result === false)
2745
+ continue;
2746
+ rule.attrs = result || undefined;
2747
+ }
2748
+ return rule;
2749
+ }
2750
+ }
2751
+ }
2752
+ /**
2753
+ @internal
2754
+ */
2755
+ matchStyle(prop, value, context, after) {
2756
+ for (let i = after ? this.styles.indexOf(after) + 1 : 0; i < this.styles.length; i++) {
2757
+ let rule = this.styles[i], style = rule.style;
2758
+ if (style.indexOf(prop) != 0 ||
2759
+ rule.context && !context.matchesContext(rule.context) ||
2760
+ // Test that the style string either precisely matches the prop,
2761
+ // or has an '=' sign after the prop, followed by the given
2762
+ // value.
2763
+ style.length > prop.length &&
2764
+ (style.charCodeAt(prop.length) != 61 || style.slice(prop.length + 1) != value))
2765
+ continue;
2766
+ if (rule.getAttrs) {
2767
+ let result = rule.getAttrs(value);
2768
+ if (result === false)
2769
+ continue;
2770
+ rule.attrs = result || undefined;
2771
+ }
2772
+ return rule;
2773
+ }
2774
+ }
2775
+ /**
2776
+ @internal
2777
+ */
2778
+ static schemaRules(schema) {
2779
+ let result = [];
2780
+ function insert(rule) {
2781
+ let priority = rule.priority == null ? 50 : rule.priority, i = 0;
2782
+ for (; i < result.length; i++) {
2783
+ let next = result[i], nextPriority = next.priority == null ? 50 : next.priority;
2784
+ if (nextPriority < priority)
2785
+ break;
2786
+ }
2787
+ result.splice(i, 0, rule);
2788
+ }
2789
+ for (let name in schema.marks) {
2790
+ let rules = schema.marks[name].spec.parseDOM;
2791
+ if (rules)
2792
+ rules.forEach(rule => {
2793
+ insert(rule = copy(rule));
2794
+ if (!(rule.mark || rule.ignore || rule.clearMark))
2795
+ rule.mark = name;
2796
+ });
2797
+ }
2798
+ for (let name in schema.nodes) {
2799
+ let rules = schema.nodes[name].spec.parseDOM;
2800
+ if (rules)
2801
+ rules.forEach(rule => {
2802
+ insert(rule = copy(rule));
2803
+ if (!(rule.node || rule.ignore || rule.mark))
2804
+ rule.node = name;
2805
+ });
2806
+ }
2807
+ return result;
2808
+ }
2809
+ /**
2810
+ Construct a DOM parser using the parsing rules listed in a
2811
+ schema's [node specs](https://prosemirror.net/docs/ref/#model.NodeSpec.parseDOM), reordered by
2812
+ [priority](https://prosemirror.net/docs/ref/#model.GenericParseRule.priority).
2813
+ */
2814
+ static fromSchema(schema) {
2815
+ return schema.cached.domParser ||
2816
+ (schema.cached.domParser = new DOMParser(schema, DOMParser.schemaRules(schema)));
2817
+ }
2818
+ }
2819
+ const blockTags = {
2820
+ address: true, article: true, aside: true, blockquote: true, canvas: true,
2821
+ dd: true, div: true, dl: true, fieldset: true, figcaption: true, figure: true,
2822
+ footer: true, form: true, h1: true, h2: true, h3: true, h4: true, h5: true,
2823
+ h6: true, header: true, hgroup: true, hr: true, li: true, noscript: true, ol: true,
2824
+ output: true, p: true, pre: true, section: true, table: true, tfoot: true, ul: true
2825
+ };
2826
+ const ignoreTags = {
2827
+ head: true, noscript: true, object: true, script: true, style: true, title: true
2828
+ };
2829
+ const listTags = { ol: true, ul: true };
2830
+ // Using a bitfield for node context options
2831
+ const OPT_PRESERVE_WS = 1, OPT_PRESERVE_WS_FULL = 2, OPT_OPEN_LEFT = 4;
2832
+ function wsOptionsFor(type, preserveWhitespace, base) {
2833
+ if (preserveWhitespace != null)
2834
+ return (preserveWhitespace ? OPT_PRESERVE_WS : 0) |
2835
+ (preserveWhitespace === "full" ? OPT_PRESERVE_WS_FULL : 0);
2836
+ return type && type.whitespace == "pre" ? OPT_PRESERVE_WS | OPT_PRESERVE_WS_FULL : base & ~OPT_OPEN_LEFT;
2837
+ }
2838
+ class NodeContext {
2839
+ constructor(type, attrs, marks, solid, match, options) {
2840
+ this.type = type;
2841
+ this.attrs = attrs;
2842
+ this.marks = marks;
2843
+ this.solid = solid;
2844
+ this.options = options;
2845
+ this.content = [];
2846
+ // Marks applied to the node's children
2847
+ this.activeMarks = Mark.none;
2848
+ this.match = match || (options & OPT_OPEN_LEFT ? null : type.contentMatch);
2849
+ }
2850
+ findWrapping(node) {
2851
+ if (!this.match) {
2852
+ if (!this.type)
2853
+ return [];
2854
+ let fill = this.type.contentMatch.fillBefore(Fragment.from(node));
2855
+ if (fill) {
2856
+ this.match = this.type.contentMatch.matchFragment(fill);
2857
+ }
2858
+ else {
2859
+ let start = this.type.contentMatch, wrap;
2860
+ if (wrap = start.findWrapping(node.type)) {
2861
+ this.match = start;
2862
+ return wrap;
2863
+ }
2864
+ else {
2865
+ return null;
2866
+ }
2867
+ }
2868
+ }
2869
+ return this.match.findWrapping(node.type);
2870
+ }
2871
+ finish(openEnd) {
2872
+ if (!(this.options & OPT_PRESERVE_WS)) { // Strip trailing whitespace
2873
+ let last = this.content[this.content.length - 1], m;
2874
+ if (last && last.isText && (m = /[ \t\r\n\u000c]+$/.exec(last.text))) {
2875
+ let text = last;
2876
+ if (last.text.length == m[0].length)
2877
+ this.content.pop();
2878
+ else
2879
+ this.content[this.content.length - 1] = text.withText(text.text.slice(0, text.text.length - m[0].length));
2880
+ }
2881
+ }
2882
+ let content = Fragment.from(this.content);
2883
+ if (!openEnd && this.match)
2884
+ content = content.append(this.match.fillBefore(Fragment.empty, true));
2885
+ return this.type ? this.type.create(this.attrs, content, this.marks) : content;
2886
+ }
2887
+ inlineContext(node) {
2888
+ if (this.type)
2889
+ return this.type.inlineContent;
2890
+ if (this.content.length)
2891
+ return this.content[0].isInline;
2892
+ return node.parentNode && !blockTags.hasOwnProperty(node.parentNode.nodeName.toLowerCase());
2893
+ }
2894
+ }
2895
+ class ParseContext {
2896
+ constructor(
2897
+ // The parser we are using.
2898
+ parser,
2899
+ // The options passed to this parse.
2900
+ options, isOpen) {
2901
+ this.parser = parser;
2902
+ this.options = options;
2903
+ this.isOpen = isOpen;
2904
+ this.open = 0;
2905
+ this.localPreserveWS = false;
2906
+ let topNode = options.topNode, topContext;
2907
+ let topOptions = wsOptionsFor(null, options.preserveWhitespace, 0) | (isOpen ? OPT_OPEN_LEFT : 0);
2908
+ if (topNode)
2909
+ topContext = new NodeContext(topNode.type, topNode.attrs, Mark.none, true, options.topMatch || topNode.type.contentMatch, topOptions);
2910
+ else if (isOpen)
2911
+ topContext = new NodeContext(null, null, Mark.none, true, null, topOptions);
2912
+ else
2913
+ topContext = new NodeContext(parser.schema.topNodeType, null, Mark.none, true, null, topOptions);
2914
+ this.nodes = [topContext];
2915
+ this.find = options.findPositions;
2916
+ this.needsBlock = false;
2917
+ }
2918
+ get top() {
2919
+ return this.nodes[this.open];
2920
+ }
2921
+ // Add a DOM node to the content. Text is inserted as text node,
2922
+ // otherwise, the node is passed to `addElement` or, if it has a
2923
+ // `style` attribute, `addElementWithStyles`.
2924
+ addDOM(dom, marks) {
2925
+ if (dom.nodeType == 3)
2926
+ this.addTextNode(dom, marks);
2927
+ else if (dom.nodeType == 1)
2928
+ this.addElement(dom, marks);
2929
+ }
2930
+ addTextNode(dom, marks) {
2931
+ let value = dom.nodeValue;
2932
+ let top = this.top, preserveWS = (top.options & OPT_PRESERVE_WS_FULL) ? "full"
2933
+ : this.localPreserveWS || (top.options & OPT_PRESERVE_WS) > 0;
2934
+ let { schema } = this.parser;
2935
+ if (preserveWS === "full" ||
2936
+ top.inlineContext(dom) ||
2937
+ /[^ \t\r\n\u000c]/.test(value)) {
2938
+ if (!preserveWS) {
2939
+ value = value.replace(/[ \t\r\n\u000c]+/g, " ");
2940
+ // If this starts with whitespace, and there is no node before it, or
2941
+ // a hard break, or a text node that ends with whitespace, strip the
2942
+ // leading space.
2943
+ if (/^[ \t\r\n\u000c]/.test(value) && this.open == this.nodes.length - 1) {
2944
+ let nodeBefore = top.content[top.content.length - 1];
2945
+ let domNodeBefore = dom.previousSibling;
2946
+ if (!nodeBefore ||
2947
+ (domNodeBefore && domNodeBefore.nodeName == 'BR') ||
2948
+ (nodeBefore.isText && /[ \t\r\n\u000c]$/.test(nodeBefore.text)))
2949
+ value = value.slice(1);
2950
+ }
2951
+ }
2952
+ else if (preserveWS === "full") {
2953
+ value = value.replace(/\r\n?/g, "\n");
2954
+ }
2955
+ else if (schema.linebreakReplacement && /[\r\n]/.test(value) && this.top.findWrapping(schema.linebreakReplacement.create())) {
2956
+ let lines = value.split(/\r?\n|\r/);
2957
+ for (let i = 0; i < lines.length; i++) {
2958
+ if (i)
2959
+ this.insertNode(schema.linebreakReplacement.create(), marks, true);
2960
+ if (lines[i])
2961
+ this.insertNode(schema.text(lines[i]), marks, !/\S/.test(lines[i]));
2962
+ }
2963
+ value = "";
2964
+ }
2965
+ else {
2966
+ value = value.replace(/\r?\n|\r/g, " ");
2967
+ }
2968
+ if (value)
2969
+ this.insertNode(schema.text(value), marks, !/\S/.test(value));
2970
+ this.findInText(dom);
2971
+ }
2972
+ else {
2973
+ this.findInside(dom);
2974
+ }
2975
+ }
2976
+ // Try to find a handler for the given tag and use that to parse. If
2977
+ // none is found, the element's content nodes are added directly.
2978
+ addElement(dom, marks, matchAfter) {
2979
+ let outerWS = this.localPreserveWS, top = this.top;
2980
+ if (dom.tagName == "PRE" || /pre/.test(dom.style && dom.style.whiteSpace))
2981
+ this.localPreserveWS = true;
2982
+ let name = dom.nodeName.toLowerCase(), ruleID;
2983
+ if (listTags.hasOwnProperty(name) && this.parser.normalizeLists)
2984
+ normalizeList(dom);
2985
+ let rule = (this.options.ruleFromNode && this.options.ruleFromNode(dom)) ||
2986
+ (ruleID = this.parser.matchTag(dom, this, matchAfter));
2987
+ out: if (rule ? rule.ignore : ignoreTags.hasOwnProperty(name)) {
2988
+ this.findInside(dom);
2989
+ this.ignoreFallback(dom, marks);
2990
+ }
2991
+ else if (!rule || rule.skip || rule.closeParent) {
2992
+ if (rule && rule.closeParent)
2993
+ this.open = Math.max(0, this.open - 1);
2994
+ else if (rule && rule.skip.nodeType)
2995
+ dom = rule.skip;
2996
+ let sync, oldNeedsBlock = this.needsBlock;
2997
+ if (blockTags.hasOwnProperty(name)) {
2998
+ if (top.content.length && top.content[0].isInline && this.open) {
2999
+ this.open--;
3000
+ top = this.top;
3001
+ }
3002
+ sync = true;
3003
+ if (!top.type)
3004
+ this.needsBlock = true;
3005
+ }
3006
+ else if (!dom.firstChild) {
3007
+ this.leafFallback(dom, marks);
3008
+ break out;
3009
+ }
3010
+ let innerMarks = rule && rule.skip ? marks : this.readStyles(dom, marks);
3011
+ if (innerMarks)
3012
+ this.addAll(dom, innerMarks);
3013
+ if (sync)
3014
+ this.sync(top);
3015
+ this.needsBlock = oldNeedsBlock;
3016
+ }
3017
+ else {
3018
+ let innerMarks = this.readStyles(dom, marks);
3019
+ if (innerMarks)
3020
+ this.addElementByRule(dom, rule, innerMarks, rule.consuming === false ? ruleID : undefined);
3021
+ }
3022
+ this.localPreserveWS = outerWS;
3023
+ }
3024
+ // Called for leaf DOM nodes that would otherwise be ignored
3025
+ leafFallback(dom, marks) {
3026
+ if (dom.nodeName == "BR" && this.top.type && this.top.type.inlineContent)
3027
+ this.addTextNode(dom.ownerDocument.createTextNode("\n"), marks);
3028
+ }
3029
+ // Called for ignored nodes
3030
+ ignoreFallback(dom, marks) {
3031
+ // Ignored BR nodes should at least create an inline context
3032
+ if (dom.nodeName == "BR" && (!this.top.type || !this.top.type.inlineContent))
3033
+ this.findPlace(this.parser.schema.text("-"), marks, true);
3034
+ }
3035
+ // Run any style parser associated with the node's styles. Either
3036
+ // return an updated array of marks, or null to indicate some of the
3037
+ // styles had a rule with `ignore` set.
3038
+ readStyles(dom, marks) {
3039
+ let styles = dom.style;
3040
+ // Because many properties will only show up in 'normalized' form
3041
+ // in `style.item` (i.e. text-decoration becomes
3042
+ // text-decoration-line, text-decoration-color, etc), we directly
3043
+ // query the styles mentioned in our rules instead of iterating
3044
+ // over the items.
3045
+ if (styles && styles.length)
3046
+ for (let i = 0; i < this.parser.matchedStyles.length; i++) {
3047
+ let name = this.parser.matchedStyles[i], value = styles.getPropertyValue(name);
3048
+ if (value)
3049
+ for (let after = undefined;;) {
3050
+ let rule = this.parser.matchStyle(name, value, this, after);
3051
+ if (!rule)
3052
+ break;
3053
+ if (rule.ignore)
3054
+ return null;
3055
+ if (rule.clearMark)
3056
+ marks = marks.filter(m => !rule.clearMark(m));
3057
+ else
3058
+ marks = marks.concat(this.parser.schema.marks[rule.mark].create(rule.attrs));
3059
+ if (rule.consuming === false)
3060
+ after = rule;
3061
+ else
3062
+ break;
3063
+ }
3064
+ }
3065
+ return marks;
3066
+ }
3067
+ // Look up a handler for the given node. If none are found, return
3068
+ // false. Otherwise, apply it, use its return value to drive the way
3069
+ // the node's content is wrapped, and return true.
3070
+ addElementByRule(dom, rule, marks, continueAfter) {
3071
+ let sync, nodeType;
3072
+ if (rule.node) {
3073
+ nodeType = this.parser.schema.nodes[rule.node];
3074
+ if (!nodeType.isLeaf) {
3075
+ let inner = this.enter(nodeType, rule.attrs || null, marks, rule.preserveWhitespace);
3076
+ if (inner) {
3077
+ sync = true;
3078
+ marks = inner;
3079
+ }
3080
+ }
3081
+ else if (!this.insertNode(nodeType.create(rule.attrs), marks, dom.nodeName == "BR")) {
3082
+ this.leafFallback(dom, marks);
3083
+ }
3084
+ }
3085
+ else {
3086
+ let markType = this.parser.schema.marks[rule.mark];
3087
+ marks = marks.concat(markType.create(rule.attrs));
3088
+ }
3089
+ let startIn = this.top;
3090
+ if (nodeType && nodeType.isLeaf) {
3091
+ this.findInside(dom);
3092
+ }
3093
+ else if (continueAfter) {
3094
+ this.addElement(dom, marks, continueAfter);
3095
+ }
3096
+ else if (rule.getContent) {
3097
+ this.findInside(dom);
3098
+ rule.getContent(dom, this.parser.schema).forEach(node => this.insertNode(node, marks, false));
3099
+ }
3100
+ else {
3101
+ let contentDOM = dom;
3102
+ if (typeof rule.contentElement == "string")
3103
+ contentDOM = dom.querySelector(rule.contentElement);
3104
+ else if (typeof rule.contentElement == "function")
3105
+ contentDOM = rule.contentElement(dom);
3106
+ else if (rule.contentElement)
3107
+ contentDOM = rule.contentElement;
3108
+ this.findAround(dom, contentDOM, true);
3109
+ this.addAll(contentDOM, marks);
3110
+ this.findAround(dom, contentDOM, false);
3111
+ }
3112
+ if (sync && this.sync(startIn))
3113
+ this.open--;
3114
+ }
3115
+ // Add all child nodes between `startIndex` and `endIndex` (or the
3116
+ // whole node, if not given). If `sync` is passed, use it to
3117
+ // synchronize after every block element.
3118
+ addAll(parent, marks, startIndex, endIndex) {
3119
+ let index = startIndex || 0;
3120
+ for (let dom = startIndex ? parent.childNodes[startIndex] : parent.firstChild, end = endIndex == null ? null : parent.childNodes[endIndex]; dom != end; dom = dom.nextSibling, ++index) {
3121
+ this.findAtPoint(parent, index);
3122
+ this.addDOM(dom, marks);
3123
+ }
3124
+ this.findAtPoint(parent, index);
3125
+ }
3126
+ // Try to find a way to fit the given node type into the current
3127
+ // context. May add intermediate wrappers and/or leave non-solid
3128
+ // nodes that we're in.
3129
+ findPlace(node, marks, cautious) {
3130
+ let route, sync;
3131
+ for (let depth = this.open, penalty = 0; depth >= 0; depth--) {
3132
+ let cx = this.nodes[depth];
3133
+ let found = cx.findWrapping(node);
3134
+ if (found && (!route || route.length > found.length + penalty)) {
3135
+ route = found;
3136
+ sync = cx;
3137
+ if (!found.length)
3138
+ break;
3139
+ }
3140
+ if (cx.solid) {
3141
+ if (cautious)
3142
+ break;
3143
+ penalty += 2;
3144
+ }
3145
+ }
3146
+ if (!route)
3147
+ return null;
3148
+ this.sync(sync);
3149
+ for (let i = 0; i < route.length; i++)
3150
+ marks = this.enterInner(route[i], null, marks, false);
3151
+ return marks;
3152
+ }
3153
+ // Try to insert the given node, adjusting the context when needed.
3154
+ insertNode(node, marks, cautious) {
3155
+ if (node.isInline && this.needsBlock && !this.top.type) {
3156
+ let block = this.textblockFromContext();
3157
+ if (block)
3158
+ marks = this.enterInner(block, null, marks);
3159
+ }
3160
+ let innerMarks = this.findPlace(node, marks, cautious);
3161
+ if (innerMarks) {
3162
+ this.closeExtra();
3163
+ let top = this.top;
3164
+ if (top.match)
3165
+ top.match = top.match.matchType(node.type);
3166
+ let nodeMarks = Mark.none;
3167
+ for (let m of innerMarks.concat(node.marks))
3168
+ if (top.type ? top.type.allowsMarkType(m.type) : markMayApply(m.type, node.type))
3169
+ nodeMarks = m.addToSet(nodeMarks);
3170
+ top.content.push(node.mark(nodeMarks));
3171
+ return true;
3172
+ }
3173
+ return false;
3174
+ }
3175
+ // Try to start a node of the given type, adjusting the context when
3176
+ // necessary.
3177
+ enter(type, attrs, marks, preserveWS) {
3178
+ let innerMarks = this.findPlace(type.create(attrs), marks, false);
3179
+ if (innerMarks)
3180
+ innerMarks = this.enterInner(type, attrs, marks, true, preserveWS);
3181
+ return innerMarks;
3182
+ }
3183
+ // Open a node of the given type
3184
+ enterInner(type, attrs, marks, solid = false, preserveWS) {
3185
+ this.closeExtra();
3186
+ let top = this.top;
3187
+ top.match = top.match && top.match.matchType(type);
3188
+ let options = wsOptionsFor(type, preserveWS, top.options);
3189
+ if ((top.options & OPT_OPEN_LEFT) && top.content.length == 0)
3190
+ options |= OPT_OPEN_LEFT;
3191
+ let applyMarks = Mark.none;
3192
+ marks = marks.filter(m => {
3193
+ if (top.type ? top.type.allowsMarkType(m.type) : markMayApply(m.type, type)) {
3194
+ applyMarks = m.addToSet(applyMarks);
3195
+ return false;
3196
+ }
3197
+ return true;
3198
+ });
3199
+ this.nodes.push(new NodeContext(type, attrs, applyMarks, solid, null, options));
3200
+ this.open++;
3201
+ return marks;
3202
+ }
3203
+ // Make sure all nodes above this.open are finished and added to
3204
+ // their parents
3205
+ closeExtra(openEnd = false) {
3206
+ let i = this.nodes.length - 1;
3207
+ if (i > this.open) {
3208
+ for (; i > this.open; i--)
3209
+ this.nodes[i - 1].content.push(this.nodes[i].finish(openEnd));
3210
+ this.nodes.length = this.open + 1;
3211
+ }
3212
+ }
3213
+ finish() {
3214
+ this.open = 0;
3215
+ this.closeExtra(this.isOpen);
3216
+ return this.nodes[0].finish(!!(this.isOpen || this.options.topOpen));
3217
+ }
3218
+ sync(to) {
3219
+ for (let i = this.open; i >= 0; i--) {
3220
+ if (this.nodes[i] == to) {
3221
+ this.open = i;
3222
+ return true;
3223
+ }
3224
+ else if (this.localPreserveWS) {
3225
+ this.nodes[i].options |= OPT_PRESERVE_WS;
3226
+ }
3227
+ }
3228
+ return false;
3229
+ }
3230
+ get currentPos() {
3231
+ this.closeExtra();
3232
+ let pos = 0;
3233
+ for (let i = this.open; i >= 0; i--) {
3234
+ let content = this.nodes[i].content;
3235
+ for (let j = content.length - 1; j >= 0; j--)
3236
+ pos += content[j].nodeSize;
3237
+ if (i)
3238
+ pos++;
3239
+ }
3240
+ return pos;
3241
+ }
3242
+ findAtPoint(parent, offset) {
3243
+ if (this.find)
3244
+ for (let i = 0; i < this.find.length; i++) {
3245
+ if (this.find[i].node == parent && this.find[i].offset == offset)
3246
+ this.find[i].pos = this.currentPos;
3247
+ }
3248
+ }
3249
+ findInside(parent) {
3250
+ if (this.find)
3251
+ for (let i = 0; i < this.find.length; i++) {
3252
+ if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node))
3253
+ this.find[i].pos = this.currentPos;
3254
+ }
3255
+ }
3256
+ findAround(parent, content, before) {
3257
+ if (parent != content && this.find)
3258
+ for (let i = 0; i < this.find.length; i++) {
3259
+ if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node)) {
3260
+ let pos = content.compareDocumentPosition(this.find[i].node);
3261
+ if (pos & (before ? 2 : 4))
3262
+ this.find[i].pos = this.currentPos;
3263
+ }
3264
+ }
3265
+ }
3266
+ findInText(textNode) {
3267
+ if (this.find)
3268
+ for (let i = 0; i < this.find.length; i++) {
3269
+ if (this.find[i].node == textNode)
3270
+ this.find[i].pos = this.currentPos - (textNode.nodeValue.length - this.find[i].offset);
3271
+ }
3272
+ }
3273
+ // Determines whether the given context string matches this context.
3274
+ matchesContext(context) {
3275
+ if (context.indexOf("|") > -1)
3276
+ return context.split(/\s*\|\s*/).some(this.matchesContext, this);
3277
+ let parts = context.split("/");
3278
+ let option = this.options.context;
3279
+ let useRoot = !this.isOpen && (!option || option.parent.type == this.nodes[0].type);
3280
+ let minDepth = -(option ? option.depth + 1 : 0) + (useRoot ? 0 : 1);
3281
+ let match = (i, depth) => {
3282
+ for (; i >= 0; i--) {
3283
+ let part = parts[i];
3284
+ if (part == "") {
3285
+ if (i == parts.length - 1 || i == 0)
3286
+ continue;
3287
+ for (; depth >= minDepth; depth--)
3288
+ if (match(i - 1, depth))
3289
+ return true;
3290
+ return false;
3291
+ }
3292
+ else {
3293
+ let next = depth > 0 || (depth == 0 && useRoot) ? this.nodes[depth].type
3294
+ : option && depth >= minDepth ? option.node(depth - minDepth).type
3295
+ : null;
3296
+ if (!next || (next.name != part && !next.isInGroup(part)))
3297
+ return false;
3298
+ depth--;
3299
+ }
3300
+ }
3301
+ return true;
3302
+ };
3303
+ return match(parts.length - 1, this.open);
3304
+ }
3305
+ textblockFromContext() {
3306
+ let $context = this.options.context;
3307
+ if ($context)
3308
+ for (let d = $context.depth; d >= 0; d--) {
3309
+ let deflt = $context.node(d).contentMatchAt($context.indexAfter(d)).defaultType;
3310
+ if (deflt && deflt.isTextblock && deflt.defaultAttrs)
3311
+ return deflt;
3312
+ }
3313
+ for (let name in this.parser.schema.nodes) {
3314
+ let type = this.parser.schema.nodes[name];
3315
+ if (type.isTextblock && type.defaultAttrs)
3316
+ return type;
3317
+ }
3318
+ }
3319
+ }
3320
+ // Kludge to work around directly nested list nodes produced by some
3321
+ // tools and allowed by browsers to mean that the nested list is
3322
+ // actually part of the list item above it.
3323
+ function normalizeList(dom) {
3324
+ for (let child = dom.firstChild, prevItem = null; child; child = child.nextSibling) {
3325
+ let name = child.nodeType == 1 ? child.nodeName.toLowerCase() : null;
3326
+ if (name && listTags.hasOwnProperty(name) && prevItem) {
3327
+ prevItem.appendChild(child);
3328
+ child = prevItem;
3329
+ }
3330
+ else if (name == "li") {
3331
+ prevItem = child;
3332
+ }
3333
+ else if (name) {
3334
+ prevItem = null;
3335
+ }
3336
+ }
3337
+ }
3338
+ // Apply a CSS selector.
3339
+ function matches(dom, selector) {
3340
+ return (dom.matches || dom.msMatchesSelector || dom.webkitMatchesSelector || dom.mozMatchesSelector).call(dom, selector);
3341
+ }
3342
+ function copy(obj) {
3343
+ let copy = {};
3344
+ for (let prop in obj)
3345
+ copy[prop] = obj[prop];
3346
+ return copy;
3347
+ }
3348
+ // Used when finding a mark at the top level of a fragment parse.
3349
+ // Checks whether it would be reasonable to apply a given mark type to
3350
+ // a given node, by looking at the way the mark occurs in the schema.
3351
+ function markMayApply(markType, nodeType) {
3352
+ let nodes = nodeType.schema.nodes;
3353
+ for (let name in nodes) {
3354
+ let parent = nodes[name];
3355
+ if (!parent.allowsMarkType(markType))
3356
+ continue;
3357
+ let seen = [], scan = (match) => {
3358
+ seen.push(match);
3359
+ for (let i = 0; i < match.edgeCount; i++) {
3360
+ let { type, next } = match.edge(i);
3361
+ if (type == nodeType)
3362
+ return true;
3363
+ if (seen.indexOf(next) < 0 && scan(next))
3364
+ return true;
3365
+ }
3366
+ };
3367
+ if (scan(parent.contentMatch))
3368
+ return true;
3369
+ }
3370
+ }
3371
+
3372
+ /**
3373
+ A DOM serializer knows how to convert ProseMirror nodes and
3374
+ marks of various types to DOM nodes.
3375
+ */
3376
+ class DOMSerializer {
3377
+ /**
3378
+ Create a serializer. `nodes` should map node names to functions
3379
+ that take a node and return a description of the corresponding
3380
+ DOM. `marks` does the same for mark names, but also gets an
3381
+ argument that tells it whether the mark's content is block or
3382
+ inline content (for typical use, it'll always be inline). A mark
3383
+ serializer may be `null` to indicate that marks of that type
3384
+ should not be serialized.
3385
+ */
3386
+ constructor(
3387
+ /**
3388
+ The node serialization functions.
3389
+ */
3390
+ nodes,
3391
+ /**
3392
+ The mark serialization functions.
3393
+ */
3394
+ marks) {
3395
+ this.nodes = nodes;
3396
+ this.marks = marks;
3397
+ }
3398
+ /**
3399
+ Serialize the content of this fragment to a DOM fragment. When
3400
+ not in the browser, the `document` option, containing a DOM
3401
+ document, should be passed so that the serializer can create
3402
+ nodes.
3403
+ */
3404
+ serializeFragment(fragment, options = {}, target) {
3405
+ if (!target)
3406
+ target = doc(options).createDocumentFragment();
3407
+ let top = target, active = [];
3408
+ fragment.forEach(node => {
3409
+ if (active.length || node.marks.length) {
3410
+ let keep = 0, rendered = 0;
3411
+ while (keep < active.length && rendered < node.marks.length) {
3412
+ let next = node.marks[rendered];
3413
+ if (!this.marks[next.type.name]) {
3414
+ rendered++;
3415
+ continue;
3416
+ }
3417
+ if (!next.eq(active[keep][0]) || next.type.spec.spanning === false)
3418
+ break;
3419
+ keep++;
3420
+ rendered++;
3421
+ }
3422
+ while (keep < active.length)
3423
+ top = active.pop()[1];
3424
+ while (rendered < node.marks.length) {
3425
+ let add = node.marks[rendered++];
3426
+ let markDOM = this.serializeMark(add, node.isInline, options);
3427
+ if (markDOM) {
3428
+ active.push([add, top]);
3429
+ top.appendChild(markDOM.dom);
3430
+ top = markDOM.contentDOM || markDOM.dom;
3431
+ }
3432
+ }
3433
+ }
3434
+ top.appendChild(this.serializeNodeInner(node, options));
3435
+ });
3436
+ return target;
3437
+ }
3438
+ /**
3439
+ @internal
3440
+ */
3441
+ serializeNodeInner(node, options) {
3442
+ let { dom, contentDOM } = renderSpec(doc(options), this.nodes[node.type.name](node), null, node.attrs);
3443
+ if (contentDOM) {
3444
+ if (node.isLeaf)
3445
+ throw new RangeError("Content hole not allowed in a leaf node spec");
3446
+ this.serializeFragment(node.content, options, contentDOM);
3447
+ }
3448
+ return dom;
3449
+ }
3450
+ /**
3451
+ Serialize this node to a DOM node. This can be useful when you
3452
+ need to serialize a part of a document, as opposed to the whole
3453
+ document. To serialize a whole document, use
3454
+ [`serializeFragment`](https://prosemirror.net/docs/ref/#model.DOMSerializer.serializeFragment) on
3455
+ its [content](https://prosemirror.net/docs/ref/#model.Node.content).
3456
+ */
3457
+ serializeNode(node, options = {}) {
3458
+ let dom = this.serializeNodeInner(node, options);
3459
+ for (let i = node.marks.length - 1; i >= 0; i--) {
3460
+ let wrap = this.serializeMark(node.marks[i], node.isInline, options);
3461
+ if (wrap) {
3462
+ (wrap.contentDOM || wrap.dom).appendChild(dom);
3463
+ dom = wrap.dom;
3464
+ }
3465
+ }
3466
+ return dom;
3467
+ }
3468
+ /**
3469
+ @internal
3470
+ */
3471
+ serializeMark(mark, inline, options = {}) {
3472
+ let toDOM = this.marks[mark.type.name];
3473
+ return toDOM && renderSpec(doc(options), toDOM(mark, inline), null, mark.attrs);
3474
+ }
3475
+ static renderSpec(doc, structure, xmlNS = null, blockArraysIn) {
3476
+ return renderSpec(doc, structure, xmlNS, blockArraysIn);
3477
+ }
3478
+ /**
3479
+ Build a serializer using the [`toDOM`](https://prosemirror.net/docs/ref/#model.NodeSpec.toDOM)
3480
+ properties in a schema's node and mark specs.
3481
+ */
3482
+ static fromSchema(schema) {
3483
+ return schema.cached.domSerializer ||
3484
+ (schema.cached.domSerializer = new DOMSerializer(this.nodesFromSchema(schema), this.marksFromSchema(schema)));
3485
+ }
3486
+ /**
3487
+ Gather the serializers in a schema's node specs into an object.
3488
+ This can be useful as a base to build a custom serializer from.
3489
+ */
3490
+ static nodesFromSchema(schema) {
3491
+ let result = gatherToDOM(schema.nodes);
3492
+ if (!result.text)
3493
+ result.text = node => node.text;
3494
+ return result;
3495
+ }
3496
+ /**
3497
+ Gather the serializers in a schema's mark specs into an object.
3498
+ */
3499
+ static marksFromSchema(schema) {
3500
+ return gatherToDOM(schema.marks);
3501
+ }
3502
+ }
3503
+ function gatherToDOM(obj) {
3504
+ let result = {};
3505
+ for (let name in obj) {
3506
+ let toDOM = obj[name].spec.toDOM;
3507
+ if (toDOM)
3508
+ result[name] = toDOM;
3509
+ }
3510
+ return result;
3511
+ }
3512
+ function doc(options) {
3513
+ return options.document || window.document;
3514
+ }
3515
+ const suspiciousAttributeCache = new WeakMap();
3516
+ function suspiciousAttributes(attrs) {
3517
+ let value = suspiciousAttributeCache.get(attrs);
3518
+ if (value === undefined)
3519
+ suspiciousAttributeCache.set(attrs, value = suspiciousAttributesInner(attrs));
3520
+ return value;
3521
+ }
3522
+ function suspiciousAttributesInner(attrs) {
3523
+ let result = null;
3524
+ function scan(value) {
3525
+ if (value && typeof value == "object") {
3526
+ if (Array.isArray(value)) {
3527
+ if (typeof value[0] == "string") {
3528
+ if (!result)
3529
+ result = [];
3530
+ result.push(value);
3531
+ }
3532
+ else {
3533
+ for (let i = 0; i < value.length; i++)
3534
+ scan(value[i]);
3535
+ }
3536
+ }
3537
+ else {
3538
+ for (let prop in value)
3539
+ scan(value[prop]);
3540
+ }
3541
+ }
3542
+ }
3543
+ scan(attrs);
3544
+ return result;
3545
+ }
3546
+ function renderSpec(doc, structure, xmlNS, blockArraysIn) {
3547
+ if (typeof structure == "string")
3548
+ return { dom: doc.createTextNode(structure) };
3549
+ if (structure.nodeType != null)
3550
+ return { dom: structure };
3551
+ if (structure.dom && structure.dom.nodeType != null)
3552
+ return structure;
3553
+ let tagName = structure[0], suspicious;
3554
+ if (typeof tagName != "string")
3555
+ throw new RangeError("Invalid array passed to renderSpec");
3556
+ if (blockArraysIn && (suspicious = suspiciousAttributes(blockArraysIn)) &&
3557
+ suspicious.indexOf(structure) > -1)
3558
+ throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");
3559
+ let space = tagName.indexOf(" ");
3560
+ if (space > 0) {
3561
+ xmlNS = tagName.slice(0, space);
3562
+ tagName = tagName.slice(space + 1);
3563
+ }
3564
+ let contentDOM;
3565
+ let dom = (xmlNS ? doc.createElementNS(xmlNS, tagName) : doc.createElement(tagName));
3566
+ let attrs = structure[1], start = 1;
3567
+ if (attrs && typeof attrs == "object" && attrs.nodeType == null && !Array.isArray(attrs)) {
3568
+ start = 2;
3569
+ for (let name in attrs)
3570
+ if (attrs[name] != null) {
3571
+ let space = name.indexOf(" ");
3572
+ if (space > 0)
3573
+ dom.setAttributeNS(name.slice(0, space), name.slice(space + 1), attrs[name]);
3574
+ else if (name == "style" && dom.style)
3575
+ dom.style.cssText = attrs[name];
3576
+ else
3577
+ dom.setAttribute(name, attrs[name]);
3578
+ }
3579
+ }
3580
+ for (let i = start; i < structure.length; i++) {
3581
+ let child = structure[i];
3582
+ if (child === 0) {
3583
+ if (i < structure.length - 1 || i > start)
3584
+ throw new RangeError("Content hole must be the only child of its parent node");
3585
+ return { dom, contentDOM: dom };
3586
+ }
3587
+ else {
3588
+ let { dom: inner, contentDOM: innerContent } = renderSpec(doc, child, xmlNS, blockArraysIn);
3589
+ dom.appendChild(inner);
3590
+ if (innerContent) {
3591
+ if (contentDOM)
3592
+ throw new RangeError("Multiple content holes");
3593
+ contentDOM = innerContent;
3594
+ }
3595
+ }
3596
+ }
3597
+ return { dom, contentDOM };
3598
+ }
3599
+
3600
+ const impl = Symbol("rte-internal-impl");
3601
+
3602
+ const sortedContributions = (contributions) => {
3603
+ return contributions.sort((a, b) => {
3604
+ const priorityDelta = a.priority - b.priority;
3605
+ if (priorityDelta !== 0) {
3606
+ return priorityDelta;
3607
+ }
3608
+ if (a.featureName === b.featureName) {
3609
+ return 0;
3610
+ }
3611
+ return a.featureName > b.featureName ? 1 : -1;
3612
+ }).map((c) => c.value);
3613
+ };
3614
+ const contributionPriority = {
3615
+ high: -10,
3616
+ default: 0};
3617
+ class RteFeature {
3618
+ }
3619
+ class RteFeatureImpl {
3620
+ /**
3621
+ * Creates a contribution of this feature.
3622
+ */
3623
+ contribution(value, order) {
3624
+ return {
3625
+ featureName: this.name,
3626
+ priority: order ?? contributionPriority.default,
3627
+ value
3628
+ };
3629
+ }
3630
+ getStyles() {
3631
+ return [];
3632
+ }
3633
+ getSchema(textblockAttrs, textblockMarks) {
3634
+ return [];
3635
+ }
3636
+ getTextblockAttrs() {
3637
+ return [];
3638
+ }
3639
+ getTextblockMarks() {
3640
+ return [];
3641
+ }
3642
+ getPlugins(rte) {
3643
+ return [];
3644
+ }
3645
+ getToolbarItems(rte) {
3646
+ return [];
3647
+ }
3648
+ // A feature may include additional features for better organization.
3649
+ getFeatures() {
3650
+ return [this];
3651
+ }
3652
+ }
3653
+ const featureFacade = (FeatureImpl) => {
3654
+ var _a;
3655
+ class Facade extends (_a = RteFeature, _a) {
3656
+ constructor(...args) {
3657
+ super();
3658
+ this[impl] = new FeatureImpl(...args);
3659
+ }
3660
+ }
3661
+ return Facade;
3662
+ };
3663
+
3664
+ exports.DOMParser = DOMParser;
3665
+ exports.DOMSerializer = DOMSerializer;
3666
+ exports.Fragment = Fragment;
3667
+ exports.Mark = Mark;
3668
+ exports.MarkType = MarkType;
3669
+ exports.Node = Node;
3670
+ exports.NodeRange = NodeRange;
3671
+ exports.ReplaceError = ReplaceError;
3672
+ exports.RteFeatureImpl = RteFeatureImpl;
3673
+ exports.Schema = Schema;
3674
+ exports.Slice = Slice;
3675
+ exports.contributionPriority = contributionPriority;
3676
+ exports.featureFacade = featureFacade;
3677
+ exports.impl = impl;
3678
+ exports.sortedContributions = sortedContributions;