@nerd-bible/wordgard 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/doc.js ADDED
@@ -0,0 +1,3814 @@
1
+ class TextOutput {
2
+ blockSep;
3
+ leafText;
4
+ text = "";
5
+ started = false;
6
+ constructor(blockSep, leafText) {
7
+ this.blockSep = blockSep;
8
+ this.leafText = leafText;
9
+ }
10
+ serialize(node) {
11
+ let nodeText = node.isPlot ? null
12
+ : node.isText ? node.param
13
+ : node.type.spec.toText ? node.type.spec.toText(node)
14
+ : this.leafText ? this.leafText(node)
15
+ : "";
16
+ if (node.isLeaf ? node.type.isBlock && nodeText : node.isTextblock)
17
+ this.openBlock();
18
+ if (nodeText != null) {
19
+ this.text += nodeText;
20
+ this.started = true;
21
+ }
22
+ return nodeText != null;
23
+ }
24
+ openBlock() {
25
+ if (this.started)
26
+ this.text += this.blockSep;
27
+ else
28
+ this.started = true;
29
+ }
30
+ }
31
+
32
+ class SchemaError extends Error {
33
+ }
34
+ class ValidationError extends Error {
35
+ }
36
+
37
+ const Token = /*@__PURE__*/(function (Token) {
38
+ (function (Type) {
39
+ Type[Type["Open"] = 0] = "Open";
40
+ Type[Type["Close"] = 1] = "Close";
41
+ Type[Type["Node"] = 2] = "Node";
42
+ })(Token.Type || (Token.Type = {}));
43
+ Token.End = {
44
+ tokenType: Token.Type.Close,
45
+ toString() { return "[end]"; }
46
+ };
47
+ ;return Token})({});
48
+ class Slice {
49
+ content;
50
+ length;
51
+ constructor(content) {
52
+ this.content = content;
53
+ this.length = content.reduce((l, e) => l + (e.tokenType == Token.Type.Node ? e.length : 1), 0);
54
+ }
55
+ static of(content) { return new Slice(content); }
56
+ eq(other) {
57
+ if (other.content.length != this.content.length)
58
+ return false;
59
+ for (let i = 0; i < this.content.length; i++) {
60
+ let a = this.content[i], b = other.content[i];
61
+ if (a == Token.End) {
62
+ if (b != Token.End)
63
+ return false;
64
+ }
65
+ else if (a.tokenType == Token.Type.Node) {
66
+ if (!((b.tokenType == Token.Type.Node) && a.eq(b)))
67
+ return false;
68
+ }
69
+ else if (a.tokenType == Token.Type.Open) {
70
+ if (!((b.tokenType == Token.Type.Open) && a.eq(b)))
71
+ return false;
72
+ }
73
+ }
74
+ return true;
75
+ }
76
+ run(track, startPos = 0) {
77
+ let pos = startPos;
78
+ for (let elt of this.content) {
79
+ if (elt.tokenType == Token.Type.Open)
80
+ track.open(elt, pos++);
81
+ else if (elt.tokenType == Token.Type.Node) {
82
+ track.node(elt, pos);
83
+ pos += elt.length;
84
+ }
85
+ else
86
+ track.close(pos++);
87
+ }
88
+ }
89
+ slice(from, to = this.length) {
90
+ if (from == to)
91
+ return Slice.empty;
92
+ let result = [], off = 0;
93
+ for (let elt of this.content) {
94
+ let start = off;
95
+ off += elt.tokenType == Token.Type.Node ? elt.length : 1;
96
+ if (off <= from)
97
+ continue;
98
+ if (start < from || off > to) {
99
+ let inner = elt.sliceInner(Math.max(0, from - start), Math.min(elt.length, to - start));
100
+ for (let elt of inner.content)
101
+ result.push(elt);
102
+ }
103
+ else {
104
+ result.push(elt);
105
+ }
106
+ if (off >= to)
107
+ break;
108
+ }
109
+ return new Slice(result);
110
+ }
111
+ concat(other) {
112
+ let content = this.content.slice();
113
+ let i = 0;
114
+ if (content.length && other.content.length && other.content[0].tokenType == Token.Type.Node &&
115
+ content[content.length - 1].tokenType == Token.Type.Node) {
116
+ other.content[0].pushTo(content);
117
+ i = 1;
118
+ }
119
+ for (; i < other.content.length; i++)
120
+ content.push(other.content[i]);
121
+ return new Slice(content);
122
+ }
123
+ textContent(options = {}) {
124
+ let { blockSeparator = "\n", leafText } = options;
125
+ let out = new TextOutput(blockSeparator, leafText == null ? undefined : typeof leafText == "string" ? () => leafText : leafText);
126
+ for (let tok of this.content) {
127
+ if (tok.tokenType == Token.Type.Open) {
128
+ if (tok.isTextblock)
129
+ out.openBlock();
130
+ }
131
+ else if (tok.tokenType == Token.Type.Node) {
132
+ if (tok.isLeaf)
133
+ out.serialize(tok);
134
+ else
135
+ tok.iterate(node => !out.serialize(node));
136
+ }
137
+ }
138
+ return out.text;
139
+ }
140
+ static empty = /*@__PURE__*/(() => new Slice([]))();
141
+ toString() {
142
+ return `<${this.content.join()}>`;
143
+ }
144
+ toJSON() {
145
+ return this.content.map(e => e.tokenType == Token.Type.Close ? "." : e.toJSON());
146
+ }
147
+ static fromJSON(schema, json) {
148
+ if (!Array.isArray(json))
149
+ throw new ValidationError("Invalid slice JSON");
150
+ return new Slice(json.map(value => {
151
+ if (value === ".")
152
+ return Token.End;
153
+ if (!value || typeof value.type != "string")
154
+ throw new ValidationError("Invalid slice JSON");
155
+ let type = schema.getNode(value.type);
156
+ return type?.isLeaf || ("content" in value) ? schema.nodeFromJSON(value) : schema.tagFromJSON(value);
157
+ }));
158
+ }
159
+ }
160
+
161
+ const noChildren = [];
162
+ class Elt {
163
+ tagName;
164
+ attrs;
165
+ children;
166
+ constructor(
167
+ tagName,
168
+ attrs,
169
+ children) {
170
+ this.tagName = tagName;
171
+ this.attrs = attrs;
172
+ this.children = children;
173
+ }
174
+ static create(tagName, attrs, children) {
175
+ return new Elt(tagName, attrs, children);
176
+ }
177
+ static mk(name, arg1, arg2) {
178
+ let [attrs, children] = arg2 ? [Attributes.read(arg1), arg2] :
179
+ !arg1 ? [Attributes.none, noChildren] : Array.isArray(arg1) ? [Attributes.none, arg1]
180
+ : [Attributes.read(arg1), noChildren];
181
+ if (children.length == 1 && children[0] === 0)
182
+ children = Elt.hole;
183
+ return new Elt(name, attrs, children);
184
+ }
185
+ get hasContent() {
186
+ return this.children.some(ch => ch === 0 || ch instanceof Elt && ch.hasContent);
187
+ }
188
+ eqTag(elt) {
189
+ return elt.tagName == this.tagName && Attributes.eq(this.attrs, elt.attrs);
190
+ }
191
+ eqChildren(elt) {
192
+ if (elt.children == this.children)
193
+ return true;
194
+ if (this.children.length != elt.children.length)
195
+ return false;
196
+ for (let i = 0; i < this.children.length; i++) {
197
+ let a = this.children[i], b = elt.children[i];
198
+ if (a !== b && ((!a || !b || typeof a != "object" || typeof b != "object" ||
199
+ a.constructor != b.constructor || !a.eq ||
200
+ !a.eq(b))))
201
+ return false;
202
+ }
203
+ return true;
204
+ }
205
+ eq(other) {
206
+ return other instanceof Elt && this.eqTag(other) && this.eqChildren(other);
207
+ }
208
+ outerDOM(doc = document) {
209
+ let { tagName: name, attrs } = this;
210
+ let dom = /^svg:/.test(name) ? doc.createElementNS("http://www.w3.org/2000/svg", name.slice(4))
211
+ : /^math:/.test(name) ? doc.createElementNS("http://www.w3.org/1998/Math/MathML", name.slice(5))
212
+ : doc.createElement(name);
213
+ for (let i = 0; i < attrs.length;)
214
+ dom.setAttribute(attrs[i++], attrs[i++]);
215
+ return dom;
216
+ }
217
+ wrap(wrapper, target) {
218
+ if (target) {
219
+ let added = this.modifyBySelector(wrapper, target);
220
+ if (added)
221
+ return added;
222
+ }
223
+ return wrapper.fill([this]);
224
+ }
225
+ addAttrs(attrs, target) {
226
+ if (target) {
227
+ let added = this.modifyBySelector(attrs, target);
228
+ if (added)
229
+ return added;
230
+ }
231
+ return Elt.create(this.tagName, Attributes.merge(this.attrs, attrs), this.children);
232
+ }
233
+ fill(content) {
234
+ let children = [];
235
+ for (let ch of this.children) {
236
+ if (ch === 0) {
237
+ for (let c of content)
238
+ children.push(c);
239
+ }
240
+ else if (ch instanceof Elt && ch.hasContent) {
241
+ children.push(ch.fill(content));
242
+ }
243
+ else {
244
+ children.push(ch);
245
+ }
246
+ }
247
+ return new Elt(this.tagName, this.attrs, children);
248
+ }
249
+ modifyBySelector(mod, target) {
250
+ if (target.match(this))
251
+ return mod instanceof Elt ? mod.fill([this]) : this.addAttrs(mod);
252
+ for (let i = 0; i < this.children.length; i++) {
253
+ let ch = this.children[i], matched;
254
+ if (ch instanceof Elt && (matched = ch.modifyBySelector(mod, target))) {
255
+ let copy = this.children.slice();
256
+ copy[i] = matched;
257
+ return Elt.create(this.tagName, this.attrs, copy);
258
+ }
259
+ }
260
+ return null;
261
+ }
262
+ toHTML() { return toHTML(this); }
263
+ toDOM(doc) { return toDOM(this, doc); }
264
+ static empty = [];
265
+ static hole = [0];
266
+ }
267
+ const selfClosing = /*@__PURE__*/(() => new Set(["area", "base", "br", "col", "command", "embed", "frame",
268
+ "hr", "img", "input", "keygen", "link", "meta", "param",
269
+ "source", "track", "wbr", "menuitem"]))();
270
+ ;Elt = /*@__PURE__*/(function (Elt) {
271
+ class Fragment {
272
+ content;
273
+ constructor(content) {
274
+ this.content = content;
275
+ }
276
+ static create(content) { return new Fragment(content); }
277
+ toHTML() { return toHTML(this); }
278
+ toDOM(doc) {
279
+ let frag = getDoc(doc).createDocumentFragment();
280
+ for (let ch of this.content)
281
+ frag.appendChild(toDOM(ch, doc));
282
+ return frag;
283
+ }
284
+ }
285
+ Elt.Fragment = Fragment;
286
+ class Selector {
287
+ tag;
288
+ classes;
289
+ constructor(tag, classes) {
290
+ this.tag = tag;
291
+ this.classes = classes;
292
+ }
293
+ eq(other) {
294
+ return other.tag == this.tag && this.classes.length == other.classes.length &&
295
+ this.classes.every((c, i) => c == other.classes[i]);
296
+ }
297
+ match(elt) {
298
+ if (this.tag && elt.tagName != this.tag)
299
+ return false;
300
+ if (this.classes.length) {
301
+ let tagCls = Attributes.get(elt.attrs, "class");
302
+ if (!tagCls)
303
+ return false;
304
+ let pieces = tagCls.split(/ +/);
305
+ for (let cls of this.classes)
306
+ if (!pieces.includes(cls))
307
+ return false;
308
+ }
309
+ return true;
310
+ }
311
+ static parse(selector) {
312
+ let m, tag = null, classes = [], txt = selector;
313
+ if (m = /^[\w\d\-_\u0c00-\uffff]+/.exec(txt)) {
314
+ tag = m[0];
315
+ txt = txt.slice(m[0].length);
316
+ }
317
+ while (m = /^\.[\w\d\-_\u0c00-\uffff]+/.exec(txt)) {
318
+ classes.push(m[0].slice(1));
319
+ txt = txt.slice(m[0].length);
320
+ }
321
+ if (txt)
322
+ throw new Error("Invalid element selector " + selector);
323
+ return new Selector(tag, classes);
324
+ }
325
+ }
326
+ Elt.Selector = Selector;
327
+ ;return Elt})(Elt);
328
+ function toHTML(content) {
329
+ let html = "";
330
+ function scan(elt) {
331
+ if (typeof elt == "string") {
332
+ html += elt.replace(/[<&]/g, ch => ch == "<" ? "&lt;" : "&amp;");
333
+ return;
334
+ }
335
+ else if (elt === 0) {
336
+ return;
337
+ }
338
+ let { tagName: name, attrs } = elt, svg, math;
339
+ if (svg = /^svg:/.test(name))
340
+ name = name.slice(4);
341
+ if (math = /^math:/.test(name))
342
+ name = name.slice(5);
343
+ if (svg && name == "svg")
344
+ html += `<svg xmlns="http://www.w3.org/2000/svg"`;
345
+ if (math && name == "math")
346
+ html += `<math xmlns="http://www.w3.org/1998/Math/MathML"`;
347
+ else
348
+ html += `<${name}`;
349
+ for (let i = 0; i < attrs.length;) {
350
+ let name = attrs[i++], val = attrs[i++];
351
+ html += ` ${name}="${val.replace(/["&]/g, ch => ch == '"' ? "&quot;" : "&amp;")}"`;
352
+ }
353
+ if ((math || svg) && !elt.children.length) {
354
+ html += "/>";
355
+ }
356
+ else if (!math && !svg && selfClosing.has(name)) {
357
+ html += ">";
358
+ }
359
+ else {
360
+ html += ">";
361
+ for (let ch of elt.children)
362
+ scan(ch);
363
+ html += `</${name}>`;
364
+ }
365
+ }
366
+ if (content instanceof Elt.Fragment)
367
+ for (let elt of content.content)
368
+ scan(elt);
369
+ else
370
+ scan(content);
371
+ return html;
372
+ }
373
+ function getDoc(doc) {
374
+ if (doc)
375
+ return doc;
376
+ if (typeof document != "object" || !document.createElement)
377
+ throw new Error("No document available");
378
+ return document;
379
+ }
380
+ function toDOM(elt, doc) {
381
+ doc = getDoc(doc);
382
+ if (typeof elt == "string") {
383
+ return doc.createTextNode(elt);
384
+ }
385
+ else {
386
+ let dom = elt.outerDOM(doc);
387
+ for (let ch of elt.children)
388
+ if (ch !== 0)
389
+ dom.appendChild(toDOM(ch, doc));
390
+ return dom;
391
+ }
392
+ }
393
+ const Attributes = /*@__PURE__*/(function (Attributes) {
394
+ Attributes.none = [];
395
+ function eq(a, b) {
396
+ if (a == b)
397
+ return true;
398
+ if (a.length != b.length)
399
+ return false;
400
+ for (let i = 0; i < a.length; i++)
401
+ if (a[i] != b[i])
402
+ return false;
403
+ return true;
404
+ }
405
+ Attributes.eq = eq;
406
+ function compare(a, b) {
407
+ for (let iA = 0, iB = 0, score = 0;;) {
408
+ if (iA < a.length && iB < b.length && a[iA] == b[iB]) {
409
+ if (a[iA + 1] != b[iB + 1])
410
+ score--;
411
+ iA += 2;
412
+ iB += 2;
413
+ }
414
+ else if (iA < a.length && (iB == b.length || a[iA] < b[iB])) {
415
+ score--;
416
+ iA += 2;
417
+ }
418
+ else if (iB < b.length && iA == a.length) {
419
+ score--;
420
+ iB += 2;
421
+ }
422
+ else {
423
+ return score;
424
+ }
425
+ }
426
+ }
427
+ Attributes.compare = compare;
428
+ function merge(a, b) {
429
+ if (!a.length)
430
+ return b;
431
+ if (!b.length)
432
+ return a;
433
+ let result = [];
434
+ for (let iA = 0, iB = 0;;) {
435
+ let kA = iA < a.length ? a[iA] : null, kB = iB < b.length ? b[iB] : null;
436
+ if (kA == kB) {
437
+ if (kA == null)
438
+ return result;
439
+ let value = b[iB + 1];
440
+ if (kA == "class")
441
+ value = a[iA + 1] + " " + value;
442
+ else if (kA == "style")
443
+ value = a[iA + 1] + ";" + value;
444
+ result.push(kA, value);
445
+ iA += 2;
446
+ iB += 2;
447
+ }
448
+ else if (kA != null && (kB == null || kA < kB)) {
449
+ result.push(kA, a[iA + 1]);
450
+ iA += 2;
451
+ }
452
+ else {
453
+ result.push(kB, b[iB + 1]);
454
+ iB += 2;
455
+ }
456
+ }
457
+ }
458
+ Attributes.merge = merge;
459
+ function push(a, name, value) {
460
+ let i = 0;
461
+ while (i < a.length && a[i] < name)
462
+ i += 2;
463
+ if (i < a.length && a[i] == name) {
464
+ if (name == "class")
465
+ a[i + 1] += " " + value;
466
+ else if (name == "style")
467
+ a[i + 1] += ";" + value;
468
+ else
469
+ a[i + 1] = value;
470
+ }
471
+ else {
472
+ a.splice(i, 0, name, value);
473
+ }
474
+ }
475
+ Attributes.push = push;
476
+ function read(obj) {
477
+ let result = [];
478
+ for (let prop in obj)
479
+ if (prop != "_") {
480
+ let value = obj[prop];
481
+ if (value != null) {
482
+ if (/^style\//.test(prop)) {
483
+ value = prop.slice(6) + ": " + value;
484
+ prop = "style";
485
+ }
486
+ Attributes.push(result, prop, value);
487
+ }
488
+ }
489
+ return result.length ? result : Attributes.none;
490
+ }
491
+ Attributes.read = read;
492
+ function get(attrs, name) {
493
+ for (let i = 0; i < attrs.length; i += 2)
494
+ if (attrs[i] == name)
495
+ return attrs[i + 1];
496
+ return null;
497
+ }
498
+ Attributes.get = get;
499
+ ;return Attributes})({});
500
+ class NodeShape {
501
+ atom;
502
+ create;
503
+ constructor(atom,
504
+ create) {
505
+ this.atom = atom;
506
+ this.create = create;
507
+ }
508
+ static from(name, leaf, spec) {
509
+ let atom = spec.atom, create;
510
+ if ("element" in spec) {
511
+ if (atom == null)
512
+ atom = leaf;
513
+ let { element, attributes } = spec;
514
+ if (typeof attributes == "function") {
515
+ create = (param) => Elt.create(element, Attributes.read(attributes(param)), atom ? Elt.empty : Elt.hole);
516
+ }
517
+ else {
518
+ let elt = Elt.create(element, attributes ? Attributes.read(attributes) : Attributes.none, atom ? Elt.empty : Elt.hole);
519
+ create = () => elt;
520
+ }
521
+ }
522
+ else {
523
+ if (leaf)
524
+ atom = true;
525
+ let { structure } = spec;
526
+ if (typeof structure == "function") {
527
+ if (atom == null)
528
+ throw new Error(`Dynamic structure for tag ${name} must define an \`atom\` field`);
529
+ create = structure;
530
+ }
531
+ else {
532
+ if (atom == null)
533
+ atom = !structure.hasContent;
534
+ else if (atom != !structure.hasContent)
535
+ throw new Error(`Disagreement between \`atom\` field and structure for tag ${name}`);
536
+ create = () => structure;
537
+ }
538
+ }
539
+ if (atom == false && leaf)
540
+ throw new Error(`Leaf tag ${name}'s shape must be atomic`);
541
+ return new NodeShape(atom, create);
542
+ }
543
+ }
544
+
545
+ const none = [];
546
+ function compareDeep(a, b) {
547
+ if (a === b)
548
+ return true;
549
+ if (!a || !b || typeof a != "object" || typeof b != "object")
550
+ return false;
551
+ let array = Array.isArray(a);
552
+ if (Array.isArray(b) != array)
553
+ return false;
554
+ if (array) {
555
+ if (a.length != b.length)
556
+ return false;
557
+ for (let i = 0; i < a.length; i++)
558
+ if (!compareDeep(a[i], b[i]))
559
+ return false;
560
+ }
561
+ else {
562
+ for (let p in a)
563
+ if (!(p in b) || !compareDeep(a[p], b[p]))
564
+ return false;
565
+ for (let p in b)
566
+ if (!(p in a))
567
+ return false;
568
+ }
569
+ return true;
570
+ }
571
+ function eqArray(a, b) {
572
+ if (a == b)
573
+ return true;
574
+ if (a.length != b.length)
575
+ return false;
576
+ for (let i = 0; i < a.length; i++)
577
+ if (!a[i].eq(b[i]))
578
+ return false;
579
+ return true;
580
+ }
581
+ function validate(validator, value) {
582
+ if (typeof validator == "string") {
583
+ let types = validator.split("|");
584
+ let name = value === null ? "null" : typeof value;
585
+ if (types.indexOf(name) < 0)
586
+ throw new RangeError(`Expected value of type ${validator} got ${name}`);
587
+ }
588
+ else if (validator) {
589
+ validator(value);
590
+ }
591
+ return value;
592
+ }
593
+
594
+ function remove(arr, index) {
595
+ return arr.length == 1 ? none : arr.filter((_, i) => i != index);
596
+ }
597
+ function addSet(a, b, compare) {
598
+ let result = [];
599
+ for (let i = 0, j = 0;;) {
600
+ if (i == a.length) {
601
+ if (j == b.length)
602
+ return result;
603
+ result.push(b[j++]);
604
+ }
605
+ else if (j == b.length) {
606
+ result.push(a[i++]);
607
+ }
608
+ else {
609
+ let cmp = compare(a[i], b[j]);
610
+ if (cmp == 0)
611
+ i++;
612
+ else if (cmp < 0)
613
+ result.push(a[i++]);
614
+ else
615
+ result.push(b[j++]);
616
+ }
617
+ }
618
+ }
619
+ function subtractSet(a, b, compare) {
620
+ let result = [];
621
+ for (let i = 0, j = 0;;) {
622
+ if (i == a.length)
623
+ return result;
624
+ if (j == b.length) {
625
+ result.push(a[i++]);
626
+ }
627
+ else {
628
+ let cmp = compare(a[i], b[j]);
629
+ if (cmp == 0)
630
+ i++;
631
+ else if (cmp < 0)
632
+ result.push(a[i++]);
633
+ else
634
+ j++;
635
+ }
636
+ }
637
+ }
638
+ class Mark {
639
+ type;
640
+ value;
641
+ constructor(
642
+ type,
643
+ value) {
644
+ this.type = type;
645
+ this.value = value;
646
+ }
647
+ static create(type, value) { return new Mark(type, value); }
648
+ eq(other) {
649
+ return this.type == other.type && compareDeep(this.value, other.value);
650
+ }
651
+ get name() { return this.type.name; }
652
+ get rank() { return this.type.rank; }
653
+ get spanning() { return this.type.spanning; }
654
+ toString() { return this.value == null ? this.name : `${this.name}=${JSON.stringify(this.value)}`; }
655
+ static define(name, spec) {
656
+ return Mark.Type.define(name, spec, true).default;
657
+ }
658
+ addToSet(set) {
659
+ let placed = null, copy = [];
660
+ for (let i = 0; i < set.length; i++) {
661
+ let other = set[i];
662
+ if (this.eq(other))
663
+ return set;
664
+ if (other.type != this.type) {
665
+ if (!placed && this.type.compareRank(other.type) < 0)
666
+ copy.push(placed = this);
667
+ copy.push(other);
668
+ }
669
+ else if (this.type.set) {
670
+ copy.push(placed = new Mark(this.type, addSet(other.value, this.value, this.type.set)));
671
+ }
672
+ }
673
+ if (!placed)
674
+ copy.push(this);
675
+ return copy;
676
+ }
677
+ removeFromSet(set) {
678
+ let type = this.type;
679
+ for (var i = 0; i < set.length; i++)
680
+ if (set[i].type == type) {
681
+ let val = set[i], newSet;
682
+ if (type.set) {
683
+ let rest = subtractSet(val.value, this.value, type.set);
684
+ if (!rest.length) {
685
+ newSet = remove(set, i);
686
+ }
687
+ else {
688
+ newSet = set.slice();
689
+ newSet[i] = new Mark(type, rest);
690
+ }
691
+ }
692
+ else if (!val.eq(this)) {
693
+ continue;
694
+ }
695
+ else {
696
+ newSet = remove(set, i);
697
+ }
698
+ return newSet;
699
+ }
700
+ return set;
701
+ }
702
+ isInSet(set) {
703
+ for (let v of set)
704
+ if (v.eq(this))
705
+ return v;
706
+ return null;
707
+ }
708
+ static sameSet(a, b) {
709
+ return eqArray(a, b);
710
+ }
711
+ static none = none;
712
+ }
713
+ ;Mark = /*@__PURE__*/(function (Mark) {
714
+ class Type {
715
+ name;
716
+ rank;
717
+ set;
718
+ default;
719
+ inclusive;
720
+ element = null;
721
+ attribute = null;
722
+ spanning;
723
+ spec;
724
+ constructor(
725
+ name, spec, isFlag) {
726
+ this.name = name;
727
+ this.spec = spec;
728
+ this.rank = Math.max(0, Math.min(spec.rank ?? 100, 100));
729
+ this.set = spec.set ? spec.set.compare : null;
730
+ this.default = isFlag || "defaultParam" in spec ? Mark.create(this, isFlag ? null : spec.defaultParam) : null;
731
+ this.inclusive = spec.inclusive !== false;
732
+ if ("element" in spec.shape)
733
+ this.element = new ElementShape(spec.shape);
734
+ else
735
+ this.attribute = new AttributeShape(spec.shape, this);
736
+ this.spanning = this.element ? spec.spanning !== false : !!spec.spanning;
737
+ }
738
+ of(value) { return Mark.create(this, value); }
739
+ compareRank(other) {
740
+ return this.rank - other.rank || (other.name < this.name ? 1 : -1);
741
+ }
742
+ removeFromSet(set) {
743
+ for (var i = 0; i < set.length; i++)
744
+ if (set[i].type == this)
745
+ return remove(set, i);
746
+ return set;
747
+ }
748
+ isInSet(set) {
749
+ for (let v of set)
750
+ if (v.type == this)
751
+ return v;
752
+ return null;
753
+ }
754
+ get isElement() { return !!this.element; }
755
+ static define(name, spec,
756
+ isFlag = false) {
757
+ return new Mark.Type(name, spec, isFlag);
758
+ }
759
+ }
760
+ Mark.Type = Type;
761
+ ;return Mark})(Mark);
762
+ class ElementShape {
763
+ name;
764
+ attrs;
765
+ constructor(spec) {
766
+ this.name = spec.element;
767
+ const { attributes } = spec;
768
+ if (typeof attributes == "function") {
769
+ this.attrs = (value) => Attributes.read(attributes(value));
770
+ }
771
+ else {
772
+ let attrs = attributes ? Attributes.read(attributes) : Attributes.none;
773
+ this.attrs = () => attrs;
774
+ }
775
+ }
776
+ }
777
+ class AttributeShape {
778
+ get;
779
+ target;
780
+ constructor(spec, type) {
781
+ if ("attribute" in spec) {
782
+ const { value, attribute } = spec, style = /^style\//.test(attribute) ? attribute.slice(6) + ": " : null;
783
+ if (value === 0) {
784
+ if (type.default)
785
+ throw new SchemaError("Attribute shapes for parameter-less marks cannot use 0 as value");
786
+ if (style)
787
+ this.get = param => ["style", style + param];
788
+ else
789
+ this.get = param => [attribute, String(param)];
790
+ }
791
+ else if (typeof value == "function") {
792
+ if (style)
793
+ this.get = param => { let val = value(param); return val == null ? Attributes.none : ["style", style + val]; };
794
+ else
795
+ this.get = param => { let val = value(param); return val == null ? Attributes.none : [attribute, val]; };
796
+ }
797
+ else {
798
+ let attrs = style ? ["style", style + value] : [attribute, value];
799
+ this.get = () => attrs;
800
+ }
801
+ }
802
+ else {
803
+ const { attributes } = spec;
804
+ if (typeof attributes == "function") {
805
+ this.get = param => Attributes.read(attributes(param));
806
+ }
807
+ else {
808
+ let attrs = Attributes.read(attributes);
809
+ this.get = () => attrs;
810
+ }
811
+ }
812
+ this.target = spec.preferTarget ? Elt.Selector.parse(spec.preferTarget) : null;
813
+ }
814
+ }
815
+
816
+ class Pos {
817
+ parent;
818
+ pos;
819
+ index;
820
+ inText;
821
+ constructor(
822
+ parent,
823
+ pos,
824
+ index,
825
+ inText) {
826
+ this.parent = parent;
827
+ this.pos = pos;
828
+ this.index = index;
829
+ this.inText = inText;
830
+ }
831
+ static create(parent, pos, index, inText) {
832
+ return new Pos(parent, pos, index, inText);
833
+ }
834
+ matchingParent(pred) {
835
+ for (let { parent } = this;;) {
836
+ if (pred(parent.node))
837
+ return parent;
838
+ if (!parent.parent)
839
+ return null;
840
+ ({ parent } = parent);
841
+ }
842
+ }
843
+ advance(distance, walk) {
844
+ return distance ? advancePos(distance, this.parent, this.pos, this.index, this.inText, walk) : this;
845
+ }
846
+ walk(distance, walk) {
847
+ return distance ? advancePos(distance, this.parent, this.pos, this.index, this.inText, walk, true) : this;
848
+ }
849
+ get nodeAfter() {
850
+ if (this.index == this.parent.node.content.length)
851
+ return null;
852
+ let node = this.parent.node.content[this.index];
853
+ return this.inText ? node.sliceText(this.inText) : node;
854
+ }
855
+ get nodeBefore() {
856
+ if (this.inText)
857
+ return this.parent.node.content[this.index].sliceText(0, this.inText);
858
+ return this.index ? this.parent.node.content[this.index - 1] : null;
859
+ }
860
+ get textblockParent() {
861
+ for (let p = this.parent;; p = p.parent) {
862
+ if (!p || !p.node.inlineContent)
863
+ return null;
864
+ if (p.node.isTextblock)
865
+ return p;
866
+ }
867
+ }
868
+ get depth() { return this.parent.depth; }
869
+ parentAt(depth) {
870
+ let d = this.depth;
871
+ if (depth > d)
872
+ throw new RangeError("Asking for parent deeper than position depth");
873
+ for (let d = this.depth, p = this.parent;; p = p.parent)
874
+ if (d == depth)
875
+ return p;
876
+ }
877
+ isAtStart(parent) {
878
+ if (this.inText)
879
+ return false;
880
+ for (let p = this.parent, index = this.index;; index = p.index, p = p.parent) {
881
+ if (!p || index)
882
+ return false;
883
+ if (p.pos == parent.pos)
884
+ return true;
885
+ }
886
+ }
887
+ isAtEnd(parent) {
888
+ if (this.inText)
889
+ return false;
890
+ for (let p = this.parent, index = this.index;; index = p.index + 1, p = p.parent) {
891
+ if (!p || index < p.node.content.length)
892
+ return false;
893
+ if (p.pos == parent.pos)
894
+ return true;
895
+ }
896
+ }
897
+ get doc() { return this.parent.doc; }
898
+ marks(across) {
899
+ if (this.inText && (!across || across.pos == this.pos))
900
+ return this.parent.node.content[this.index].tag.marks;
901
+ let [from, to] = !across ? [this, this] : across.pos > this.pos ? [this, across] : [across, this];
902
+ if (!from.parent.node.inlineContent || !to.parent.node.inlineContent)
903
+ return Mark.none;
904
+ let before = from.nodeBefore, after = to.nodeAfter;
905
+ let [main, sec] = before ? [before.tag.marks, after ? after.tag.marks : none] : [after ? after.tag.marks : none, none];
906
+ return main.filter(p => p.spanning && (p.type.inclusive || p.isInSet(sec)));
907
+ }
908
+ static resolve(doc, pos) {
909
+ if (pos < 0 || pos > doc.length)
910
+ throw new RangeError(`Resolving invalid position ${pos}`);
911
+ let { top, cache } = cacheFor(doc), nearest, nearestDist = 0, result;
912
+ if (pos == 0)
913
+ return Pos.create(top, 0, 0, 0);
914
+ for (let elt of cache) {
915
+ if (elt.pos == pos)
916
+ return elt;
917
+ let dist = Math.abs(elt.pos - pos);
918
+ if (!nearest || dist < nearestDist) {
919
+ nearest = elt;
920
+ nearestDist = dist;
921
+ }
922
+ }
923
+ if (nearest) {
924
+ let { parent } = nearest;
925
+ while (parent.start > pos || parent.end < pos)
926
+ parent = parent.parent;
927
+ result = advancePos(pos - parent.start, parent, parent.start, 0, 0);
928
+ }
929
+ else {
930
+ result = advancePos(pos, top, 0, 0, 0);
931
+ }
932
+ return cache[cache.length < cacheSize ? cache.length : cachePos = (cachePos + 1) % cacheSize] = result;
933
+ }
934
+ static resolveNode(doc, pos) {
935
+ let base = this.resolve(doc, pos);
936
+ if (base.inText)
937
+ return null;
938
+ let after = base.nodeAfter;
939
+ return !after || after.isText ? null : after.isLeaf ? Pos.Node.create(base.parent, after, pos, base.index)
940
+ : Pos.Plot.create(base.parent, after, pos, base.index);
941
+ }
942
+ }
943
+ ;Pos = /*@__PURE__*/(function (Pos) {
944
+ class Node {
945
+ parent;
946
+ node;
947
+ pos;
948
+ index;
949
+ constructor(
950
+ parent,
951
+ node,
952
+ pos,
953
+ index) {
954
+ this.parent = parent;
955
+ this.node = node;
956
+ this.pos = pos;
957
+ this.index = index;
958
+ }
959
+ static create(parent, node, pos, index) {
960
+ return new Node(parent, node, pos, index);
961
+ }
962
+ get before() {
963
+ if (this.pos < 0)
964
+ throw new RangeError("Accessing `before` on the top level node");
965
+ return this.pos;
966
+ }
967
+ get after() {
968
+ if (this.pos < 0)
969
+ throw new RangeError("Accessing `after` on the top level node");
970
+ return this.pos + this.node.length;
971
+ }
972
+ get depth() {
973
+ let d = 0;
974
+ for (let n = this; n.parent; n = n.parent)
975
+ d++;
976
+ return d;
977
+ }
978
+ get doc() {
979
+ let n = this;
980
+ while (n.parent)
981
+ n = n.parent;
982
+ if (!(n.node.isDoc))
983
+ throw new Error("Outer parent not a document");
984
+ return n.node;
985
+ }
986
+ get isFirst() { return !this.parent || this.index == 0; }
987
+ get isLast() { return !this.parent || this.index == this.parent.node.content.length - 1; }
988
+ get nextSibling() { return this.isLast ? null : this.parent.node.content[this.index + 1]; }
989
+ get previousSibling() { return this.isFirst ? null : this.parent.node.content[this.index - 1]; }
990
+ }
991
+ Pos.Node = Node;
992
+ class Plot extends Pos.Node {
993
+ constructor(parent, node, pos, index) {
994
+ super(parent, node, pos, index);
995
+ }
996
+ static create(parent, node, pos, index) {
997
+ return new Plot(parent, node, pos, index);
998
+ }
999
+ get start() { return this.pos + 1; }
1000
+ get end() { return this.pos + 1 + this.node.contentLength; }
1001
+ }
1002
+ Pos.Plot = Plot;
1003
+ ;return Pos})(Pos);
1004
+ const posCache = /*@__PURE__*/(() => new Map())(), cacheSize = 8;
1005
+ let cachePos = 0;
1006
+ function cacheFor(doc) {
1007
+ let found = posCache.get(doc);
1008
+ if (!found)
1009
+ posCache.set(doc, found = { top: Pos.Plot.create(null, doc, -1, 0), cache: [] });
1010
+ return found;
1011
+ }
1012
+ function advancePos(distance, parent, pos, index, inText, walk, full = false) {
1013
+ let target = pos + distance, { node } = parent;
1014
+ if (inText) {
1015
+ let text = node.content[index];
1016
+ let textStart = pos - inText, textEnd = textStart + text.length;
1017
+ if (walk)
1018
+ walk.skip(text.sliceText(inText, Math.min(text.length, target - textStart)), pos, parent, index);
1019
+ if (target < textEnd)
1020
+ return Pos.create(parent, target, index, target - textStart);
1021
+ pos = textEnd;
1022
+ index++;
1023
+ }
1024
+ while (pos < target) {
1025
+ if (index == node.content.length) {
1026
+ if (!parent.parent)
1027
+ throw new Error("Moving past end of document");
1028
+ if (walk)
1029
+ walk.leavePlot(node.tag, pos, parent.parent, parent.index);
1030
+ ({ index, parent } = parent);
1031
+ node = parent.node;
1032
+ index++;
1033
+ pos++;
1034
+ }
1035
+ else {
1036
+ let next = node.content[index], end = pos + next.length;
1037
+ if (next.isLeaf) {
1038
+ if (next.isText && target < end) {
1039
+ if (walk)
1040
+ walk.skip(next.sliceText(0, target - pos), pos, parent, index);
1041
+ return Pos.create(parent, target, index, target - pos);
1042
+ }
1043
+ else {
1044
+ if (walk)
1045
+ walk.skip(next, pos, parent, index);
1046
+ pos = end;
1047
+ index++;
1048
+ }
1049
+ }
1050
+ else {
1051
+ let enter = full || target < end;
1052
+ if (walk) {
1053
+ if (!enter)
1054
+ walk.skip(next, pos, parent, index);
1055
+ else if (walk.enterPlot(next, pos, parent, index) === false && target >= end)
1056
+ enter = false;
1057
+ }
1058
+ if (enter) {
1059
+ parent = Pos.Plot.create(parent, next, pos, index);
1060
+ pos++;
1061
+ node = next;
1062
+ index = 0;
1063
+ }
1064
+ else {
1065
+ pos = end;
1066
+ index++;
1067
+ }
1068
+ }
1069
+ }
1070
+ }
1071
+ return Pos.create(parent, pos, index, 0);
1072
+ }
1073
+
1074
+ class BaseType {
1075
+ name;
1076
+ flags;
1077
+ shape;
1078
+ roles = new Set;
1079
+ constructor(
1080
+ name,
1081
+ flags, spec,
1082
+ shape) {
1083
+ this.name = name;
1084
+ this.flags = flags;
1085
+ this.shape = shape;
1086
+ if (spec.role instanceof Node.Role)
1087
+ this.roles.add(spec.role);
1088
+ else if (spec.role)
1089
+ for (let role of spec.role)
1090
+ this.roles.add(role);
1091
+ if (this.shape.atom)
1092
+ this.flags |= 4;
1093
+ }
1094
+ hasRole(role) { return this.roles.has(role); }
1095
+ get isInline() { return (this.flags & 1) > 0; }
1096
+ get isBlock() { return (this.flags & 1) == 0; }
1097
+ get isAtom() { return (this.flags & 4) > 0; }
1098
+ get isSelectable() { return (this.flags & 32) > 0; }
1099
+ }
1100
+ class BaseTag {
1101
+ param;
1102
+ marks;
1103
+ constructor(param, marks) {
1104
+ this.param = param;
1105
+ this.marks = marks;
1106
+ }
1107
+ mark(mark) {
1108
+ for (let v of this.marks)
1109
+ if (v.type == mark)
1110
+ return v.value;
1111
+ return undefined;
1112
+ }
1113
+ get name() { return this.type.name; }
1114
+ get isText() { return this.type == Leaf.Text; }
1115
+ is(type) { return this.type == type; }
1116
+ toJSON() {
1117
+ let result = { type: this.name };
1118
+ if (this != this.type.default)
1119
+ result.param = this.param;
1120
+ if (this.marks.length) {
1121
+ result.marks = Object.create(null);
1122
+ for (let { name, value } of this.marks)
1123
+ result.marks[name] = value;
1124
+ }
1125
+ return result;
1126
+ }
1127
+ }
1128
+ const Node = /*@__PURE__*/(function (Node) {
1129
+ (function (Type) {
1130
+ function get(ref) {
1131
+ return ref instanceof BaseType ? ref : ref.type;
1132
+ }
1133
+ Type.get = get;
1134
+ })(Node.Type || (Node.Type = {}));
1135
+ class Group {
1136
+ parent;
1137
+ constructor(
1138
+ parent) {
1139
+ this.parent = parent;
1140
+ }
1141
+ static define(parent) { return new Group(parent); }
1142
+ static All = Group.define();
1143
+ static Inline = Group.define();
1144
+ static Block = Group.define();
1145
+ static Leaf = Group.define();
1146
+ static Plot = Group.define();
1147
+ static Textblock = Group.define();
1148
+ static Content = Group.define();
1149
+ static TableCell = Group.define();
1150
+ static ListItem = Group.define();
1151
+ static builtin = [Group.All, Group.Inline, Group.Block, Group.Leaf, Group.Plot, Group.Textblock];
1152
+ }
1153
+ Node.Group = Group;
1154
+ class Role {
1155
+ constructor() { }
1156
+ static define() { return new Role; }
1157
+ static Code = Role.define();
1158
+ static List = Role.define();
1159
+ static LineBreak = Role.define();
1160
+ }
1161
+ Node.Role = Role;
1162
+ ;return Node})({});
1163
+ class Leaf extends BaseTag {
1164
+ type;
1165
+ constructor(
1166
+ type, param, marks) {
1167
+ super(param, marks);
1168
+ this.type = type;
1169
+ }
1170
+ static new(type, param, marks) {
1171
+ return new Leaf(type, param, marks);
1172
+ }
1173
+ get tag() { return this; }
1174
+ eq(other) {
1175
+ return this == other || other.isLeaf && this.type == other.type && compareDeep(this.param, other.param) &&
1176
+ Mark.sameSet(this.marks, other.marks);
1177
+ }
1178
+ static define(name, spec) {
1179
+ return Leaf.Type.new(name, flagsFor(spec) | 16, spec).default;
1180
+ }
1181
+ withMarks(marks) {
1182
+ return Mark.sameSet(this.marks, marks) ? this : this.type.of(this.param, marks);
1183
+ }
1184
+ get tokenType() { return Token.Type.Node; }
1185
+ get isLeaf() { return true; }
1186
+ get isPlot() { return false; }
1187
+ get length() { return this.is(Leaf.Text) ? this.param.length : 1; }
1188
+ pushTo(nodes) {
1189
+ if (this.is(Leaf.Text)) {
1190
+ let prevI = nodes.length - 1, prev = prevI >= 0 ? nodes[prevI] : null;
1191
+ if (prev && prev.is(Leaf.Text) && Mark.sameSet(prev.marks, this.marks)) {
1192
+ nodes[prevI] = Leaf.text(prev.param + this.param, this.marks);
1193
+ return;
1194
+ }
1195
+ }
1196
+ nodes.push(this);
1197
+ }
1198
+ sliceInner(from, to) {
1199
+ return from == to ? Slice.empty : Slice.of([this.is(Leaf.Text) ? this.sliceText(from, to) : this]);
1200
+ }
1201
+ sliceText(from, to) {
1202
+ if (!this.is(Leaf.Text))
1203
+ throw new Error("Calling sliceText on a non-text node");
1204
+ if (to == null)
1205
+ to = this.param.length;
1206
+ if (!from && to == this.param.length)
1207
+ return this;
1208
+ return Leaf.Text.of(this.param.slice(Math.max(from, 0), Math.max(0, to)), this.marks);
1209
+ }
1210
+ static text(text, marks = Mark.none) {
1211
+ return Leaf.Text.of(text, marks);
1212
+ }
1213
+ toString() {
1214
+ return (this.is(Leaf.Text) ? JSON.stringify(this.param) : this.name) + markString(this.marks);
1215
+ }
1216
+ }
1217
+ ;Leaf = /*@__PURE__*/(function (Leaf) {
1218
+ class Type extends BaseType {
1219
+ default;
1220
+ spec;
1221
+ constructor(name, flags, spec) {
1222
+ super(name, flags, spec, NodeShape.from(name, true, spec.shape));
1223
+ this.spec = spec;
1224
+ this.default = "defaultParam" in spec ? Leaf.new(this, spec.defaultParam, none) :
1225
+ (flags & 16) ? Leaf.new(this, null, none) : null;
1226
+ }
1227
+ static new(name, flags, spec) { return new Type(name, flags, spec); }
1228
+ static define(name, spec) {
1229
+ return new Leaf.Type(name, flagsFor(spec), spec);
1230
+ }
1231
+ of(param, marks = Mark.none) {
1232
+ if (!marks.length && this.default && compareDeep(this.default.param, param))
1233
+ return this.default;
1234
+ return Leaf.new(this, param, marks);
1235
+ }
1236
+ get isLeaf() { return true; }
1237
+ get isPlot() { return false; }
1238
+ }
1239
+ Leaf.Type = Type;
1240
+ Leaf.Text = Leaf.Type.new("Text", 1, {
1241
+ shape: { element: "" }
1242
+ });
1243
+ ;return Leaf})(Leaf);
1244
+ class Plot {
1245
+ tag;
1246
+ content;
1247
+ constructor(
1248
+ tag,
1249
+ content) {
1250
+ this.tag = tag;
1251
+ this.content = content;
1252
+ this.tag = tag;
1253
+ this.contentLength = content.reduce((s, c) => s + c.length, 0);
1254
+ }
1255
+ contentLength;
1256
+ static create(tag, content) { return new Plot(tag, content); }
1257
+ get name() { return this.tag.name; }
1258
+ get type() { return this.tag.type; }
1259
+ get marks() { return this.tag.marks; }
1260
+ get length() {
1261
+ return 2 + this.contentLength;
1262
+ }
1263
+ eq(other) {
1264
+ return this == other || other instanceof Plot && this.tag.eq(other.tag) && this.contentEq(other);
1265
+ }
1266
+ contentEq(other) {
1267
+ return eqArray(this.content, other.content);
1268
+ }
1269
+ sliceInner(from, to) {
1270
+ if (from == to)
1271
+ return Slice.empty;
1272
+ let content = [];
1273
+ this.slicePlot(content, from, to);
1274
+ return Slice.of(content);
1275
+ }
1276
+ slicePlot(out, from, to) {
1277
+ if (from <= 0) {
1278
+ if (to >= this.length) {
1279
+ out.push(this);
1280
+ return;
1281
+ }
1282
+ out.push(this.tag);
1283
+ }
1284
+ sliceContent(out, this.content, from - 1, to - 1);
1285
+ if (to >= this.length)
1286
+ out.push(Plot.End);
1287
+ }
1288
+ is(type) { return false; }
1289
+ get isText() { return false; }
1290
+ get inlineContent() { return this.type.inlineContent; }
1291
+ get isTextblock() { return this.type.isTextblock; }
1292
+ get isLeaf() { return false; }
1293
+ get isPlot() { return true; }
1294
+ get isDoc() { return this.type.isDoc; }
1295
+ get firstChild() {
1296
+ return this.content.length ? this.content[0] : null;
1297
+ }
1298
+ get lastChild() {
1299
+ let last = this.content.length - 1;
1300
+ return last < 0 ? null : this.content[last];
1301
+ }
1302
+ iterate(a, b, c) {
1303
+ let [from, to, f] = typeof a == "number" ? [a, b, c] : [0, this.length, a];
1304
+ if (this.isDoc || f(this, 0, null, 0) !== false)
1305
+ this.iterInner(0, from, to, f);
1306
+ }
1307
+ nodeAt(pos) {
1308
+ for (let node of this.content) {
1309
+ if (pos == 0)
1310
+ return node.isText ? null : node;
1311
+ if (pos < node.length)
1312
+ return node.isLeaf ? null : node.nodeAt(pos - 1);
1313
+ pos -= node.length;
1314
+ }
1315
+ return null;
1316
+ }
1317
+ plotAt(pos) {
1318
+ let node = this.nodeAt(pos);
1319
+ return node instanceof Plot ? node : null;
1320
+ }
1321
+ textContent(options = {}) {
1322
+ let { from = 0, to = this.length, blockSeparator = "\n", leafText } = options;
1323
+ let out = new TextOutput(blockSeparator, leafText == null ? undefined
1324
+ : typeof leafText == "string" ? () => leafText : leafText);
1325
+ this.iterate(from, to, (node, pos) => {
1326
+ return !out.serialize(node.is(Leaf.Text) ? node.sliceText(Math.max(0, from - pos), Math.min(node.length, to - pos)) : node);
1327
+ });
1328
+ return out.text;
1329
+ }
1330
+ iterInner(contentStart, from, to, f) {
1331
+ for (let pos = contentStart, i = 0; i < this.content.length; i++) {
1332
+ if (pos >= to)
1333
+ break;
1334
+ let node = this.content[i], start = pos;
1335
+ pos += node.length;
1336
+ if (pos <= from)
1337
+ continue;
1338
+ if (f(node, start, this, i) !== false && node.isPlot)
1339
+ node.iterInner(start + 1, from, to, f);
1340
+ }
1341
+ }
1342
+ toString() {
1343
+ return this.name + markString(this.tag.marks) + "(" + this.content.join() + ")";
1344
+ }
1345
+ toJSON() {
1346
+ let result = this.tag.toJSON();
1347
+ result.content = this.content.map(c => c.toJSON());
1348
+ return result;
1349
+ }
1350
+ mark(mark) { return this.tag.mark(mark); }
1351
+ pushTo(nodes) { nodes.push(this); }
1352
+ withMarks(marks) {
1353
+ return Mark.sameSet(this.tag.marks, marks) ? this : this.tag.withMarks(marks).create(this.content);
1354
+ }
1355
+ get tokenType() { return Token.Type.Node; }
1356
+ static define(name, spec) {
1357
+ return Plot.Type.new(name, flagsFor(spec) | 16, spec).default;
1358
+ }
1359
+ static defineDoc(spec) {
1360
+ if (!spec.inlineContent && !spec.blockContent)
1361
+ throw new SchemaError("Doc nodes must allow content");
1362
+ let flags = 16 | 8 | 16;
1363
+ if (spec.inlineContent)
1364
+ flags |= 2;
1365
+ if (spec.inlineContent || spec.canBeEmpty)
1366
+ flags |= 64;
1367
+ return Plot.Type.new("Doc", flags, {
1368
+ ...spec,
1369
+ shape: { element: "" }
1370
+ });
1371
+ }
1372
+ }
1373
+ ;Plot = /*@__PURE__*/(function (Plot) {
1374
+ Plot.End = Token.End;
1375
+ class Tag extends BaseTag {
1376
+ type;
1377
+ constructor(type, param, marks) {
1378
+ super(param, marks);
1379
+ this.type = type;
1380
+ }
1381
+ static new(type, param, marks) {
1382
+ return new Tag(type, param, marks);
1383
+ }
1384
+ eq(other) {
1385
+ return this == other || other instanceof Plot.Tag && this.type == other.type &&
1386
+ compareDeep(this.param, other.param) && Mark.sameSet(this.marks, other.marks);
1387
+ }
1388
+ create(content) {
1389
+ if (this.isDoc)
1390
+ throw new Error("Document nodes must be created with schema.doc()");
1391
+ return Plot.create(this, content ? joinText(content) : none);
1392
+ }
1393
+ withMarks(marks) {
1394
+ return Mark.sameSet(this.marks, marks) ? this : this.type.of(this.param, marks);
1395
+ }
1396
+ split(atEnd) {
1397
+ return this.marks.length ? this.withMarks(this.marks.filter(p => {
1398
+ let { keepOnSplit } = p.type.spec;
1399
+ return keepOnSplit && (keepOnSplit === true || keepOnSplit(this, atEnd));
1400
+ })) : this;
1401
+ }
1402
+ get tokenType() { return Token.Type.Open; }
1403
+ get inlineContent() { return this.type.inlineContent; }
1404
+ get isTextblock() { return this.type.isTextblock; }
1405
+ get isLeaf() { return false; }
1406
+ get isPlot() { return true; }
1407
+ get isDoc() { return this.type.isDoc; }
1408
+ toString() {
1409
+ return this.type.name + markString(this.marks);
1410
+ }
1411
+ }
1412
+ Plot.Tag = Tag;
1413
+ class Type extends BaseType {
1414
+ default;
1415
+ isolating;
1416
+ defining;
1417
+ neutral;
1418
+ preserveWhitespace;
1419
+ orientation;
1420
+ spec;
1421
+ constructor(name, flags, spec) {
1422
+ super(name, flags, spec, NodeShape.from(name, false, spec.shape));
1423
+ this.spec = spec;
1424
+ if (!spec.inlineContent && !spec.blockContent)
1425
+ throw new SchemaError("Plot definitions must specify either inlineContent or blockContent");
1426
+ this.isolating = !!spec.isolating;
1427
+ this.defining = !!spec.defining;
1428
+ this.neutral = spec.neutral ?? !this.defining;
1429
+ this.preserveWhitespace = spec.preserveWhitespace ?? !!this.hasRole(Node.Role.Code);
1430
+ this.orientation = flags & 2 ? "row" : spec.orientation || "column";
1431
+ this.default = "defaultParam" in spec ? Plot.Tag.new(this, spec.defaultParam, none) :
1432
+ (flags & 16) ? Plot.Tag.new(this, null, none) : null;
1433
+ if (!this.shape.atom && this.isInline && !this.inlineContent)
1434
+ throw new SchemaError("Inline tags with block content must be marked as atoms");
1435
+ }
1436
+ static new(name, flags, spec) {
1437
+ return new Type(name, flags, spec);
1438
+ }
1439
+ static define(name, spec) {
1440
+ return new Plot.Type(name, flagsFor(spec), spec);
1441
+ }
1442
+ of(param, marks = Mark.none) {
1443
+ if (!marks.length && this.default && compareDeep(this.default.param, param))
1444
+ return this.default;
1445
+ return Plot.Tag.new(this, param, marks);
1446
+ }
1447
+ get inlineContent() { return (this.flags & 2) > 0; }
1448
+ get isTextblock() { return this.isBlock && this.inlineContent; }
1449
+ get isDoc() { return (this.flags & 8) > 0; }
1450
+ get isLeaf() { return false; }
1451
+ get isPlot() { return true; }
1452
+ get canBeEmpty() { return (this.flags & 64) > 0; }
1453
+ }
1454
+ Plot.Type = Type;
1455
+ let validate = true;
1456
+ class Doc extends Plot {
1457
+ schema;
1458
+ constructor(
1459
+ schema, children) {
1460
+ super(schema.docTag, children);
1461
+ this.schema = schema;
1462
+ if (validate)
1463
+ schema.validate(this);
1464
+ }
1465
+ static new(schema, children) { return new Doc(schema, children); }
1466
+ get length() { return this.contentLength; }
1467
+ slicePlot(content, from, to) {
1468
+ sliceContent(content, this.content, from, to);
1469
+ }
1470
+ resolve(pos) {
1471
+ return Pos.resolve(this, pos);
1472
+ }
1473
+ resolveNode(pos) {
1474
+ return Pos.resolveNode(this, pos);
1475
+ }
1476
+ resolvePlot(pos) {
1477
+ let r = this.resolveNode(pos);
1478
+ return r instanceof Pos.Plot ? r : null;
1479
+ }
1480
+ contextAt(pos, maxDepth) {
1481
+ for (let { parent } = this.resolve(pos), context = [];;) {
1482
+ if (!parent.parent || maxDepth != null && context.length == maxDepth)
1483
+ return context;
1484
+ context.push(parent.node.tag);
1485
+ parent = parent.parent;
1486
+ }
1487
+ }
1488
+ slice(from, to = this.length) {
1489
+ return this.sliceInner(from, to);
1490
+ }
1491
+ static noValidate(f) {
1492
+ let prev = validate;
1493
+ validate = false;
1494
+ try {
1495
+ return f();
1496
+ }
1497
+ finally {
1498
+ validate = prev;
1499
+ }
1500
+ }
1501
+ }
1502
+ Plot.Doc = Doc;
1503
+ ;return Plot})(Plot);
1504
+ function flagsFor(spec) {
1505
+ let flags = spec.inline ? 1 : 0;
1506
+ if (spec.inlineContent && spec.blockContent)
1507
+ throw new SchemaError("A tag cannot have both block and inline content");
1508
+ if (spec.inlineContent)
1509
+ flags |= 2;
1510
+ if (spec.inlineContent || spec.canBeEmpty)
1511
+ flags |= 64;
1512
+ if (spec.selectable)
1513
+ flags |= 32;
1514
+ return flags;
1515
+ }
1516
+ function markString(marks) {
1517
+ let values = [];
1518
+ for (let mark of marks) {
1519
+ if (mark.type.default == mark)
1520
+ values.push(mark.type.name);
1521
+ else
1522
+ values.push(`${mark.type.name}=${mark.value}`);
1523
+ }
1524
+ return values.length ? `[${values.join()}]` : "";
1525
+ }
1526
+ function sliceContent(out, content, from, to) {
1527
+ let off = 0;
1528
+ for (let child of content) {
1529
+ if (off >= to)
1530
+ break;
1531
+ let start = off;
1532
+ off += child.length;
1533
+ if (off <= from)
1534
+ continue;
1535
+ if (child.isPlot) {
1536
+ child.slicePlot(out, from - start, to - start);
1537
+ }
1538
+ else if (child.isText) {
1539
+ out.push(child.sliceText(from - start, to - start));
1540
+ }
1541
+ else {
1542
+ out.push(child);
1543
+ }
1544
+ }
1545
+ }
1546
+ function joinText(nodes) {
1547
+ if (!nodes.length || nodes[0].type.isBlock)
1548
+ return nodes;
1549
+ let joined;
1550
+ for (let i = 0, last = null; i < nodes.length; i++) {
1551
+ let node = nodes[i];
1552
+ if (node.is(Leaf.Text)) {
1553
+ if (last && Mark.sameSet(last.marks, node.marks)) {
1554
+ if (!joined)
1555
+ joined = nodes.slice(0, i);
1556
+ last = joined[joined.length - 1] = Leaf.text(last.param + node.param, node.marks);
1557
+ continue;
1558
+ }
1559
+ else {
1560
+ last = node;
1561
+ }
1562
+ }
1563
+ else {
1564
+ last = null;
1565
+ }
1566
+ if (joined)
1567
+ joined.push(node);
1568
+ }
1569
+ return joined || nodes;
1570
+ }
1571
+
1572
+ class Schema {
1573
+ elements;
1574
+ nodes;
1575
+ marks;
1576
+ plotContent;
1577
+ markTarget;
1578
+ nodeGroup;
1579
+ docTag;
1580
+ lineBreak;
1581
+ nodesByName = Object.create(null);
1582
+ marksByName = Object.create(null);
1583
+ wrappingCache = Object.create(null);
1584
+ validated = new WeakSet;
1585
+ constructor(
1586
+ elements,
1587
+ nodes,
1588
+ marks, plotContent, markTarget, nodeGroup,
1589
+ docTag,
1590
+ lineBreak) {
1591
+ this.elements = elements;
1592
+ this.nodes = nodes;
1593
+ this.marks = marks;
1594
+ this.plotContent = plotContent;
1595
+ this.markTarget = markTarget;
1596
+ this.nodeGroup = nodeGroup;
1597
+ this.docTag = docTag;
1598
+ this.lineBreak = lineBreak;
1599
+ for (let tag of nodes)
1600
+ this.nodesByName[tag.name] = tag;
1601
+ for (let mark of marks)
1602
+ this.marksByName[mark.name] = mark;
1603
+ }
1604
+ doc(children) {
1605
+ return Plot.Doc.new(this, children);
1606
+ }
1607
+ validate(node) {
1608
+ if (this.validated.has(node))
1609
+ return;
1610
+ if (node.isLeaf) {
1611
+ this.validateTag(node);
1612
+ }
1613
+ else {
1614
+ this.validateTag(node.tag);
1615
+ if (!node.type.canBeEmpty && node.content.length == 0)
1616
+ throw new ValidationError(`Node ${node.name} with block content may not be empty`);
1617
+ for (let ch of node.content) {
1618
+ if (!this.canContain(node.type, ch.type) || node.inlineContent != ch.type.isInline)
1619
+ throw new ValidationError(`Node type ${node.name} cannot contain child ${ch.name}`);
1620
+ this.validate(ch);
1621
+ }
1622
+ }
1623
+ this.validated.add(node);
1624
+ }
1625
+ validateTag(tag) {
1626
+ if (this.nodesByName[tag.name] != tag.type)
1627
+ throw new ValidationError(`Tag type ${tag.name} not in schema`);
1628
+ for (let mark of tag.marks)
1629
+ this.validateMark(mark, tag.type);
1630
+ }
1631
+ validateMark(mark, node) {
1632
+ if (this.marksByName[mark.name] != mark.type)
1633
+ throw new ValidationError(`Mark type ${mark.name} not in schema`);
1634
+ if (!this.markAllowed(mark.type, node))
1635
+ throw new ValidationError(`Mark type ${mark.name} cannot target node ${node.name}`);
1636
+ }
1637
+ has(elt) {
1638
+ if (elt instanceof Mark || elt instanceof BaseTag)
1639
+ elt = elt.type;
1640
+ return (elt instanceof Mark.Type ? this.marksByName : this.nodesByName)[elt.name] == elt;
1641
+ }
1642
+ matchNode(node, q) {
1643
+ if (q instanceof Node.Group) {
1644
+ let groups = this.nodeGroup.get(node);
1645
+ return groups ? groups.has(q) : false;
1646
+ }
1647
+ if (q instanceof BaseType)
1648
+ return q == node;
1649
+ if (q instanceof BaseTag)
1650
+ return q.type == node;
1651
+ if ("and" in q)
1652
+ return q.and.every(q => this.matchNode(node, q));
1653
+ return q.some(q => this.matchNode(node, q));
1654
+ }
1655
+ markAllowed(mark, node) {
1656
+ let target = this.markTarget.get(mark);
1657
+ return target ? this.matchNode(node, target) : false;
1658
+ }
1659
+ sharesContent(a, b) {
1660
+ for (let tp of this.nodes)
1661
+ if (this.canContain(a, tp) && this.canContain(b, tp))
1662
+ return true;
1663
+ return false;
1664
+ }
1665
+ withMarksFrom(from, to) {
1666
+ if (!from.marks.length)
1667
+ return to;
1668
+ let marks = to.marks;
1669
+ for (let mark of from.marks)
1670
+ if (this.markAllowed(mark.type, to.type) && (mark.type.set || !mark.isInSet(marks))) {
1671
+ let { keepOnTypeChange } = mark.type.spec;
1672
+ if (keepOnTypeChange && (keepOnTypeChange === true || keepOnTypeChange(from, to)))
1673
+ marks = mark.addToSet(marks);
1674
+ }
1675
+ return to.withMarks(marks);
1676
+ }
1677
+ canContain(parent, child) {
1678
+ if (child.isPlot && child.isDoc)
1679
+ return false;
1680
+ let content = this.plotContent.get(parent);
1681
+ return content ? this.matchNode(child, content) : false;
1682
+ }
1683
+ defaultContentTag(parent) {
1684
+ for (let tag of this.nodes)
1685
+ if (tag.default && this.canContain(parent, tag))
1686
+ return tag.default;
1687
+ return null;
1688
+ }
1689
+ defaultContentPlot(parent) {
1690
+ for (let tag of this.nodes)
1691
+ if (tag.default && tag.isPlot && this.canContain(parent, tag))
1692
+ return tag.default;
1693
+ return null;
1694
+ }
1695
+ createDefault(parent) {
1696
+ let child = this.defaultContentTag(parent);
1697
+ if (!child)
1698
+ throw new Error(`No defaultable child node for ${parent.name}`);
1699
+ return this.createAndFill(child);
1700
+ }
1701
+ createAndFill(parent) {
1702
+ if (parent.isLeaf)
1703
+ return parent;
1704
+ return parent.create(parent.type.canBeEmpty ? [] : [this.createDefault(parent.type)]);
1705
+ }
1706
+ findWrapping(parent, child) {
1707
+ let key = `${parent.name}-${child.name}`, cached = this.wrappingCache[key];
1708
+ if (cached !== undefined)
1709
+ return cached;
1710
+ return this.wrappingCache[key] = this.findWrappingInner(parent, child);
1711
+ }
1712
+ findWrappingInner(parent, child) {
1713
+ let seen = new Set, work = [[]];
1714
+ for (let i = 0; i < work.length; i++) {
1715
+ let path = work[i], at = path.length ? path[path.length - 1].type : parent;
1716
+ for (let tag of this.nodes)
1717
+ if (this.canContain(at, tag)) {
1718
+ if (tag == child)
1719
+ return path;
1720
+ if (!seen.has(tag) && !tag.isLeaf && tag.default) {
1721
+ seen.add(tag);
1722
+ work.push(path.concat(tag.default));
1723
+ }
1724
+ }
1725
+ }
1726
+ return null;
1727
+ }
1728
+ getMark(name) { return this.marksByName[name]; }
1729
+ getNode(name) { return this.nodesByName[name]; }
1730
+ static define(spec) {
1731
+ let cached = findCachedSchema(spec);
1732
+ if (cached)
1733
+ return cached;
1734
+ let tags = [Leaf.Text], marks = [];
1735
+ let defaultI = 0;
1736
+ let tagNames = new Set, markNames = new Set;
1737
+ let plotContent = new Map();
1738
+ let markTarget = new Map();
1739
+ let nodeGroup = new Map();
1740
+ nodeGroup.set(Leaf.Text, new Set([Node.Group.Inline, Node.Group.Leaf, Node.Group.All]));
1741
+ let overrides = spec.filter(e => e instanceof Schema.Override).reverse();
1742
+ let elements = [];
1743
+ for (let e of spec) {
1744
+ let elt = normalizeElt(e);
1745
+ elements.push(elt);
1746
+ if (elt instanceof Plot.Type || elt instanceof Leaf.Type) {
1747
+ if (tags.includes(elt))
1748
+ continue;
1749
+ if (tagNames.has(elt.name))
1750
+ throw new SchemaError(`Duplicate use of tag name ${elt.name} in schema`);
1751
+ tagNames.add(elt.name);
1752
+ if (elt.isPlot) {
1753
+ let content = elt.spec.inlineContent === true ? Node.Group.Inline
1754
+ : elt.spec.inlineContent || elt.spec.blockContent;
1755
+ for (let o of overrides)
1756
+ if (o.type == elt && o.content)
1757
+ content = o.content(content);
1758
+ plotContent.set(elt, content);
1759
+ }
1760
+ if (elt.isPlot && elt.spec.defaultBlock)
1761
+ tags.splice(defaultI++, 0, elt);
1762
+ else
1763
+ tags.push(elt);
1764
+ let groups = new Set();
1765
+ groups.add(Node.Group.All);
1766
+ groups.add(elt.isInline ? Node.Group.Inline : Node.Group.Block);
1767
+ groups.add(elt.isLeaf ? Node.Group.Leaf : Node.Group.Plot);
1768
+ if (elt.isPlot && elt.isBlock && elt.inlineContent)
1769
+ groups.add(Node.Group.Textblock);
1770
+ let given = elt.spec.group instanceof Node.Group ? [elt.spec.group] : elt.spec.group;
1771
+ for (let o of overrides)
1772
+ if (o.type == elt && o.group)
1773
+ given = o.group;
1774
+ if (given)
1775
+ for (let g of given)
1776
+ for (let cur = g; cur; cur = cur.parent) {
1777
+ if (!Node.Group.builtin.includes(cur))
1778
+ groups.add(cur);
1779
+ }
1780
+ nodeGroup.set(elt, groups);
1781
+ }
1782
+ else if (elt instanceof Mark.Type) {
1783
+ if (marks.includes(elt))
1784
+ continue;
1785
+ if (markNames.has(elt.name))
1786
+ throw new SchemaError(`Duplicate use of mark name ${elt.name} in schema`);
1787
+ let target = elt.spec.target || { and: [Node.Group.Inline, Node.Group.Leaf] };
1788
+ for (let o of overrides)
1789
+ if (o.type == elt && o.target)
1790
+ target = o.target(target);
1791
+ markTarget.set(elt, target);
1792
+ markNames.add(elt.name);
1793
+ marks.push(elt);
1794
+ }
1795
+ else if (!(elt instanceof Schema.Override)) {
1796
+ throw new SchemaError("Unexpected schema element type. You may have multiple versions of @wordgard/doc loaded");
1797
+ }
1798
+ }
1799
+ let docType = null;
1800
+ let lineBreak = null;
1801
+ for (let tag of tags) {
1802
+ if (tag.isLeaf) {
1803
+ if (tag.hasRole(Node.Role.LineBreak)) {
1804
+ if (tag.isBlock || !tag.default)
1805
+ throw new SchemaError("Line break tags must be inline leaves with a default param");
1806
+ if (lineBreak)
1807
+ throw new SchemaError("Multiple line break tags provided");
1808
+ lineBreak = tag.default;
1809
+ }
1810
+ }
1811
+ else {
1812
+ if (tag.isDoc) {
1813
+ if (docType)
1814
+ throw new SchemaError("Multiple document types specified");
1815
+ docType = tag;
1816
+ }
1817
+ }
1818
+ }
1819
+ if (!docType)
1820
+ throw new SchemaError("A schema must define a document type");
1821
+ let schema = new Schema(elements, tags, marks, plotContent, markTarget, nodeGroup, docType.default, lineBreak);
1822
+ for (let tag of tags)
1823
+ if (tag.isPlot) {
1824
+ let sawDefaultable = false;
1825
+ for (let child of tags)
1826
+ if (schema.canContain(tag, child)) {
1827
+ if (child.default)
1828
+ sawDefaultable = true;
1829
+ if (child.isInline != tag.inlineContent)
1830
+ throw new SchemaError(`Node type ${tag.name} has ${tag.inlineContent ? "block" : "inline"} content, but allows ${child.name} as a child`);
1831
+ }
1832
+ if (!tag.canBeEmpty && !sawDefaultable)
1833
+ throw new SchemaError(`Node ${tag.name} has required content, but all possible children require non-default parameters`);
1834
+ }
1835
+ schemaCache.set(spec, new WeakRef(schema));
1836
+ return schema;
1837
+ }
1838
+ nodeFromJSON(json) {
1839
+ let tag = this.tagFromJSON(json), children = none;
1840
+ if (tag.isLeaf)
1841
+ return tag;
1842
+ if (json.content && Array.isArray(json.content))
1843
+ children = json.content.map(c => this.nodeFromJSON(c));
1844
+ if (tag.type.isDoc)
1845
+ return this.doc(children);
1846
+ return tag.create(children);
1847
+ }
1848
+ tagFromJSON(json) {
1849
+ if (!json || typeof json != "object" || !(json.type in this.nodesByName))
1850
+ throw new ValidationError("Invalid tag JSON");
1851
+ let type = this.nodesByName[json.type];
1852
+ let marks = json.marks ? this.marksFromJSON(json.marks) : none;
1853
+ let tag = "param" in json ? type.of(validate(type.spec.validate, json.param), marks)
1854
+ : !type.default ? null
1855
+ : marks.length ? type.of(type.default.param, marks) : type.default;
1856
+ if (!tag)
1857
+ throw new ValidationError(`Missing param for tag type ${type.name}`);
1858
+ return tag;
1859
+ }
1860
+ marksFromJSON(json) {
1861
+ if (!json || typeof json != "object")
1862
+ throw new ValidationError("Invalid mark JSON");
1863
+ let marks = none;
1864
+ for (let name in json) {
1865
+ let mark = this.marksByName[name];
1866
+ if (!mark)
1867
+ throw new ValidationError(`Unrecognized mark ${name} in JSON`);
1868
+ marks = mark.of(validate(mark.spec.validate, json[name])).addToSet(marks);
1869
+ }
1870
+ return marks;
1871
+ }
1872
+ docFromJSON(json) {
1873
+ if (!json || json.type != this.docTag.name)
1874
+ throw new ValidationError("Invalid document JSON");
1875
+ return this.nodeFromJSON(json);
1876
+ }
1877
+ }
1878
+ const schemaCache = /*@__PURE__*/(() => new Map())();
1879
+ function findCachedSchema(spec) {
1880
+ search: for (let [elts, ref] of schemaCache) {
1881
+ let active = ref.deref();
1882
+ if (!active) {
1883
+ schemaCache.delete(elts);
1884
+ }
1885
+ else if (elts.length == spec.length) {
1886
+ for (let i = 0; i < spec.length; i++) {
1887
+ let a = normalizeElt(spec[i]), b = normalizeElt(elts[i]);
1888
+ if (a != b && !(a instanceof Schema.Override && b instanceof Schema.Override && a.eq(b)))
1889
+ continue search;
1890
+ }
1891
+ return active;
1892
+ }
1893
+ }
1894
+ }
1895
+ function normalizeElt(elt) {
1896
+ return elt instanceof Plot.Tag || elt instanceof Leaf || elt instanceof Mark ? elt.type : elt;
1897
+ }
1898
+ ;Schema = /*@__PURE__*/(function (Schema) {
1899
+ class Override {
1900
+ type;
1901
+ target;
1902
+ content;
1903
+ group;
1904
+ constructor(
1905
+ type,
1906
+ target,
1907
+ content,
1908
+ group) {
1909
+ this.type = type;
1910
+ this.target = target;
1911
+ this.content = content;
1912
+ this.group = group;
1913
+ }
1914
+ eq(other) {
1915
+ return this == other || this.type == other.type && this.target == other.target && this.content == other.content &&
1916
+ this.group == other.group;
1917
+ }
1918
+ static markTarget(mark, target) {
1919
+ return new Schema.Override(mark instanceof Mark.Type ? mark : mark.type, typeof target == "function" ? target : () => target);
1920
+ }
1921
+ static plotContent(plot, content) {
1922
+ return new Schema.Override(plot instanceof Plot.Tag ? plot.type : plot, undefined, typeof content == "function" ? content : () => content);
1923
+ }
1924
+ static nodeGroup(node, group) {
1925
+ return new Schema.Override(node instanceof BaseTag ? node.type : node, undefined, undefined, group instanceof Node.Group ? [group] : group);
1926
+ }
1927
+ }
1928
+ Schema.Override = Override;
1929
+ ;return Schema})(Schema);
1930
+
1931
+ class BuildContext {
1932
+ tag;
1933
+ parent;
1934
+ children = [];
1935
+ constructor(tag, parent) {
1936
+ this.tag = tag;
1937
+ this.parent = parent;
1938
+ }
1939
+ }
1940
+ class Builder {
1941
+ stack;
1942
+ modifications = null;
1943
+ schema;
1944
+ constructor(doc) {
1945
+ this.schema = doc.schema;
1946
+ this.stack = new BuildContext(doc.tag, null);
1947
+ }
1948
+ add(node) {
1949
+ if (this.modifications) {
1950
+ if (node.isPlot)
1951
+ throw new ValidationError("Invalid modification on non-leaf node");
1952
+ node = node.withMarks(applyModifications(this.modifications, node.marks, node.type));
1953
+ }
1954
+ node.pushTo(this.stack.children);
1955
+ }
1956
+ enterPlot(plot) {
1957
+ this.open(plot.tag);
1958
+ }
1959
+ leavePlot() {
1960
+ if (this.modifications)
1961
+ throw new ValidationError("Invalid modification on close token");
1962
+ if (!this.stack.parent)
1963
+ throw new ValidationError("Surplus close token after " + this.stack.children);
1964
+ let top = this.stack;
1965
+ this.stack = this.stack.parent;
1966
+ this.add(top.tag.create(top.children));
1967
+ }
1968
+ skip(node) {
1969
+ this.add(node);
1970
+ }
1971
+ open(tag) {
1972
+ if (this.modifications)
1973
+ tag = tag.withMarks(applyModifications(this.modifications, tag.marks, tag.type));
1974
+ this.stack = new BuildContext(tag, this.stack);
1975
+ }
1976
+ close() { this.leavePlot(); }
1977
+ node(node) { this.skip(node); }
1978
+ finish() {
1979
+ if (this.stack.parent)
1980
+ throw new ValidationError("Invalid change");
1981
+ return this.schema.doc(this.stack.children);
1982
+ }
1983
+ }
1984
+ function isAdd(m) { return !!m.add; }
1985
+ function isRemove(m) { return !!m.remove; }
1986
+ function applyModifications(modifications, marks, type) {
1987
+ for (const m of modifications) {
1988
+ if (isAdd(m)) {
1989
+ marks = m.add.addToSet(marks);
1990
+ }
1991
+ else {
1992
+ marks = m.remove.removeFromSet(marks);
1993
+ }
1994
+ }
1995
+ return marks;
1996
+ }
1997
+ function modificationToJSON(m) {
1998
+ return isAdd(m) ? { add: m.add.name, value: m.add.value } : { remove: m.remove.name, value: m.remove.value };
1999
+ }
2000
+ function modificationFromJSON(schema, json) {
2001
+ let { add, remove } = json;
2002
+ if (typeof add == "string" || typeof remove == "string") {
2003
+ let mark = schema.getMark((add || remove));
2004
+ if (!mark)
2005
+ throw new ValidationError(`Unknown mark ${add || remove}`);
2006
+ let value = mark.of(validate(mark.spec.validate, json.value));
2007
+ if (mark)
2008
+ return add ? { add: value } : { remove: value };
2009
+ }
2010
+ throw new ValidationError("Invalid modification JSON");
2011
+ }
2012
+ function compareModifications(a, b) {
2013
+ if (a == b)
2014
+ return true;
2015
+ if (a.length != b.length)
2016
+ return false;
2017
+ for (let i = 0; i < a.length; i++)
2018
+ if (!compareModification(a[i], b[i]))
2019
+ return false;
2020
+ return true;
2021
+ }
2022
+ function compareModification(a, b) {
2023
+ return isAdd(a) ? isAdd(b) && a.add.eq(b.add) : isRemove(b) && a.remove.eq(b.remove);
2024
+ }
2025
+ function isNatNum(value) {
2026
+ return typeof value == "number" && Math.floor(value) == value && value >= 0;
2027
+ }
2028
+ const applyCache = /*@__PURE__*/(() => new WeakMap())();
2029
+ class ChangeSet {
2030
+ sections;
2031
+ data;
2032
+ _length = -1;
2033
+ _newLength = -1;
2034
+ constructor(
2035
+ sections,
2036
+ data) {
2037
+ this.sections = sections;
2038
+ this.data = data;
2039
+ }
2040
+ static new(sections, data) { return new ChangeSet(sections, data); }
2041
+ get length() {
2042
+ if (this._length < 0) {
2043
+ this._length = 0;
2044
+ for (let i = 0; i < this.sections.length; i += 2)
2045
+ this._length += this.sections[i];
2046
+ }
2047
+ return this._length;
2048
+ }
2049
+ get newLength() {
2050
+ if (this._newLength < 0) {
2051
+ this._newLength = 0;
2052
+ for (let i = 0; i < this.sections.length; i += 2) {
2053
+ let ins = this.sections[i + 1];
2054
+ this._newLength += ins < 0 ? this.sections[i] : ins;
2055
+ }
2056
+ }
2057
+ return this._newLength;
2058
+ }
2059
+ get empty() { return this.sections.length == 0 || this.sections.length == 2 && this.sections[1] < 0; }
2060
+ eq(other) {
2061
+ if (other.sections.length != this.sections.length)
2062
+ return false;
2063
+ for (let i = 0; i < this.sections.length; i++)
2064
+ if (this.sections[i] != other.sections[i])
2065
+ return false;
2066
+ for (let i = 0; i < this.data.length; i++) {
2067
+ let a = this.data[i], b = other.data[i];
2068
+ if (a && !(this.sections[(i << 1) + 1] < 0 ? compareModifications(a, b) : a.eq(b)))
2069
+ return false;
2070
+ }
2071
+ return true;
2072
+ }
2073
+ apply(doc) {
2074
+ if (this.length != doc.length)
2075
+ throw new ValidationError(`Trying to apply change of length ${this.length} to doc of length ${doc.length}`);
2076
+ if (this.empty)
2077
+ return doc;
2078
+ let cached = applyCache.get(this);
2079
+ if (cached && doc.eq(cached.a))
2080
+ return cached.b;
2081
+ let builder = new Builder(doc);
2082
+ let cursor = doc.resolve(0);
2083
+ for (let i = 0, iS = 0; i < this.data.length; i++) {
2084
+ let lenA = this.sections[iS++], lenB = this.sections[iS++];
2085
+ if (lenB < 0) {
2086
+ builder.modifications = this.data[i];
2087
+ cursor = cursor.advance(lenA, builder);
2088
+ builder.modifications = null;
2089
+ }
2090
+ else {
2091
+ cursor = cursor.advance(lenA);
2092
+ this.data[i].run(builder);
2093
+ }
2094
+ }
2095
+ if (cursor.pos != doc.length)
2096
+ throw new ValidationError("Change doesn't cover the entire document");
2097
+ let newDoc = builder.finish();
2098
+ applyCache.set(this, { a: doc, b: newDoc });
2099
+ return newDoc;
2100
+ }
2101
+ toJSON() {
2102
+ let result = [];
2103
+ for (let i = 0; i < this.data.length; i++) {
2104
+ let len = this.sections[i << 1], ins = this.sections[(i << 1) + 1];
2105
+ if (ins == -1)
2106
+ result.push(len);
2107
+ else if (ins == -2)
2108
+ result.push([len, this.data[i].map(modificationToJSON)]);
2109
+ else
2110
+ result.push([len, this.data[i].toJSON()]);
2111
+ }
2112
+ return result;
2113
+ }
2114
+ static fromJSON(schema, json) {
2115
+ if (!Array.isArray(json))
2116
+ throw new ValidationError("Invalid ChangeSet JSON");
2117
+ let sections = [], data = [];
2118
+ for (let elt of json) {
2119
+ if (isNatNum(elt)) {
2120
+ sections.push(elt, -1);
2121
+ data.push(null);
2122
+ }
2123
+ else {
2124
+ if (!Array.isArray(elt) || elt.length != 2 || !isNatNum(elt[0]) || !Array.isArray(elt[1]))
2125
+ throw new ValidationError("Invalid ChangeSet JSON");
2126
+ let [len, val] = elt;
2127
+ if (val.length && typeof val[0] == "object" && ("add" in val[0] || "remove" in val[0])) {
2128
+ sections.push(len, -2);
2129
+ data.push(val.map(m => modificationFromJSON(schema, m)));
2130
+ }
2131
+ else {
2132
+ let slice = Slice.fromJSON(schema, val);
2133
+ sections.push(len, slice.length);
2134
+ data.push(slice);
2135
+ }
2136
+ }
2137
+ }
2138
+ return new ChangeSet(sections, data);
2139
+ }
2140
+ transform(doc, other, before = false) {
2141
+ let { set, fix } = transform(this, other, doc, before, true);
2142
+ return fix ? set.compose(fix) : set;
2143
+ }
2144
+ compose(other) {
2145
+ let { sections, data } = compose(this.sections, other.sections, this.data, other.data);
2146
+ return new ChangeSet(sections, data);
2147
+ }
2148
+ invert(doc) {
2149
+ let sections = [], data = [];
2150
+ for (let i = 0, iS = 0, pos = 0; iS < this.sections.length; iS += 2, i++) {
2151
+ let len = this.sections[iS], ins = this.sections[iS + 1];
2152
+ if (ins >= 0) {
2153
+ addSection(sections, data, ins, len, doc.slice(pos, pos + len));
2154
+ }
2155
+ else {
2156
+ let mods = this.data[i];
2157
+ let at = pos, end = pos + len;
2158
+ if (mods)
2159
+ doc.iterate(pos, end, (node, nodePos) => {
2160
+ if (node.isLeaf || nodePos >= pos && nodePos < end) {
2161
+ let [from, to] = node.isText
2162
+ ? [Math.max(at, nodePos), Math.min(end, nodePos + node.length)]
2163
+ : [nodePos, nodePos + 1];
2164
+ if (at < from)
2165
+ addSection(sections, data, from - at, -1, null);
2166
+ addSection(sections, data, to - from, -2, invertMods(mods, node.tag));
2167
+ at = to;
2168
+ }
2169
+ });
2170
+ if (at < end)
2171
+ addSection(sections, data, end - at, -1, null);
2172
+ }
2173
+ pos += len;
2174
+ }
2175
+ return new ChangeSet(sections, data);
2176
+ }
2177
+ correct(doc, local = false) {
2178
+ let fitter = new ChangeFitter(doc, local);
2179
+ for (let i = 0, iS = 0, pos = 0; i < this.data.length; i++) {
2180
+ let len = this.sections[iS++], ins = this.sections[iS++];
2181
+ if (ins < 0)
2182
+ fitter.preserved(pos, pos += len);
2183
+ else
2184
+ fitter.replaced(this.data[i], pos, pos += len);
2185
+ }
2186
+ let fit = fitter.finish();
2187
+ return fit ? this.compose(fit) : this;
2188
+ }
2189
+ mapPos(pos, assoc = -1, track) {
2190
+ let posA = 0, posB = 0;
2191
+ for (let i = 0; i < this.sections.length;) {
2192
+ let len = this.sections[i++], type = this.sections[i++], endA = posA + len;
2193
+ if (type < 0) {
2194
+ if (endA > pos)
2195
+ return posB + (pos - posA);
2196
+ posB += len;
2197
+ }
2198
+ else {
2199
+ if (track && endA >= pos &&
2200
+ (track == "around" && posA < pos && endA > pos ||
2201
+ track == "before" && posA < pos ||
2202
+ track == "after" && endA > pos))
2203
+ return null;
2204
+ if (endA > pos || endA == pos && assoc < 0 && !len)
2205
+ return pos == posA || assoc < 0 ? posB : posB + type;
2206
+ posB += type;
2207
+ }
2208
+ posA = endA;
2209
+ }
2210
+ if (pos > posA)
2211
+ throw new RangeError(`Position ${pos} is out of range for changeset of length ${posA}`);
2212
+ return posB;
2213
+ }
2214
+ findInserted(pred) {
2215
+ let found = null;
2216
+ this.iterChanges((_f, _t, pos, _to, inserted) => {
2217
+ if (found != null)
2218
+ return;
2219
+ for (let tok of inserted.content) {
2220
+ if (tok.tokenType == Token.Type.Node) {
2221
+ if (pred(tok.tag))
2222
+ return found = pos;
2223
+ pos += tok.length;
2224
+ }
2225
+ else {
2226
+ if (tok.tokenType == Token.Type.Open && pred(tok))
2227
+ return found = pos;
2228
+ pos++;
2229
+ }
2230
+ }
2231
+ });
2232
+ return found;
2233
+ }
2234
+ touchesRange(from, to) {
2235
+ for (let i = 0, pos = 0; i < this.sections.length && pos <= to;) {
2236
+ let len = this.sections[i++], ins = this.sections[i++], end = pos + len;
2237
+ if (ins >= 0 && pos <= to && end >= from)
2238
+ return pos < from && end > to ? "cover" : true;
2239
+ pos = end;
2240
+ }
2241
+ return false;
2242
+ }
2243
+ iterChanges(replaced, preserved) {
2244
+ for (let posA = 0, posB = 0, i = 0, iS = 0; i < this.data.length;) {
2245
+ let len = this.sections[iS++], ins = this.sections[iS++], data = this.data[i++];
2246
+ if (ins < 0) {
2247
+ if (preserved)
2248
+ preserved(posA, posA + len, posB, posB + len, data);
2249
+ posA += len;
2250
+ posB += len;
2251
+ }
2252
+ else {
2253
+ replaced(posA, posA += len, posB, posB += ins, data);
2254
+ }
2255
+ }
2256
+ }
2257
+ iterGaps(gap, change) {
2258
+ for (let i = 0, posA = 0, posB = 0; i < this.sections.length;) {
2259
+ let len = this.sections[i++], ins = this.sections[i++];
2260
+ if (ins < 0) {
2261
+ while (i < this.sections.length && this.sections[i + 1] < 0) {
2262
+ len += this.sections[i];
2263
+ i += 2;
2264
+ }
2265
+ gap(posA, posA + len, posB, posB + len);
2266
+ posB += len;
2267
+ }
2268
+ else {
2269
+ while (i < this.sections.length && this.sections[i + 1] >= 0) {
2270
+ len += this.sections[i++];
2271
+ ins += this.sections[i++];
2272
+ }
2273
+ if (change)
2274
+ change(posA, posA + len, posB, posB + ins);
2275
+ posB += ins;
2276
+ }
2277
+ posA += len;
2278
+ }
2279
+ }
2280
+ iterChangedRanges(range) {
2281
+ for (let i = 0, posA = 0, posB = 0; i < this.sections.length;) {
2282
+ let len = this.sections[i++], ins = this.sections[i++];
2283
+ if (ins == -1) {
2284
+ posB += len;
2285
+ }
2286
+ else {
2287
+ if (ins == -2)
2288
+ ins = len;
2289
+ while (i < this.sections.length && this.sections[i + 1] != -1) {
2290
+ let addLen = this.sections[i++], addIns = this.sections[i++];
2291
+ len += addLen;
2292
+ ins += addIns == -2 ? addLen : addIns;
2293
+ }
2294
+ range(posA, posA + len, posB, posB + ins);
2295
+ posB += ins;
2296
+ }
2297
+ posA += len;
2298
+ }
2299
+ }
2300
+ pad(before, after) {
2301
+ if (this.empty)
2302
+ return ChangeSet.empty(this.length + before + after);
2303
+ let sections = this.sections.slice(), data = this.data.slice();
2304
+ if (before) {
2305
+ if (sections[1] == -1) {
2306
+ sections[0] += before;
2307
+ }
2308
+ else {
2309
+ sections.splice(0, 0, before, -1);
2310
+ data.splice(0, 0, null);
2311
+ }
2312
+ }
2313
+ if (after) {
2314
+ if (sections[sections.length - 1] == -1) {
2315
+ sections[sections.length - 2] += after;
2316
+ }
2317
+ else {
2318
+ sections.push(after, -1);
2319
+ data.push(null);
2320
+ }
2321
+ }
2322
+ return new ChangeSet(sections, data);
2323
+ }
2324
+ clip(from, to) {
2325
+ let sections = [], data = [];
2326
+ for (let i = 0, pos = 0; i < this.sections.length && pos <= to;) {
2327
+ let value = this.data[i >> 1], len = this.sections[i++], ins = this.sections[i++];
2328
+ let end = pos + len;
2329
+ if (ins > 0) {
2330
+ if (pos >= from && end <= to)
2331
+ addSection(sections, data, end - pos, ins, value);
2332
+ else if (end > from && pos < from)
2333
+ return null;
2334
+ }
2335
+ else if (pos < to && end > from) {
2336
+ addSection(sections, data, Math.min(end, to) - Math.max(pos, from), ins, value);
2337
+ }
2338
+ pos = end;
2339
+ }
2340
+ return new ChangeSet(sections, data);
2341
+ }
2342
+ static create(doc, spec) {
2343
+ return createChangeSet(doc, spec);
2344
+ }
2345
+ static empty(length) {
2346
+ return length ? new ChangeSet([length, -1], [null]) : new ChangeSet([], []);
2347
+ }
2348
+ toString() {
2349
+ let result = "";
2350
+ for (let i = 0, iS = 0, pos = 0; i < this.data.length; i++) {
2351
+ let len = this.sections[iS++], ins = this.sections[iS++], data = this.data[i];
2352
+ let text = "";
2353
+ if (ins >= 0) {
2354
+ text += data;
2355
+ }
2356
+ else if (data) {
2357
+ text += `[${data.map(mod => {
2358
+ return `${isAdd(mod) ? "+" + mod.add : "-" + mod.remove}`;
2359
+ })}]`;
2360
+ }
2361
+ if (text)
2362
+ result += `${result ? "," : ""}${pos}${len ? `-${pos + len}` : ""}${text}`;
2363
+ pos += len;
2364
+ }
2365
+ return result;
2366
+ }
2367
+ static composeSections(a, b) {
2368
+ return compose(a, b).sections;
2369
+ }
2370
+ static transform(doc, a, b) {
2371
+ let { set: mA, fix } = transform(a, b, doc, true, true);
2372
+ let mB = transform(b, a, doc, false, false).set;
2373
+ return fix ? { a: mA.compose(fix), b: mB.compose(fix) } : { a: mA, b: mB };
2374
+ }
2375
+ }
2376
+ class ChangeSetBuilder {
2377
+ docLen;
2378
+ constructor(docLen) {
2379
+ this.docLen = docLen;
2380
+ }
2381
+ sections = [];
2382
+ data = [];
2383
+ pos = 0;
2384
+ }
2385
+ function createChangeSet(doc, spec, mayCorrect = true) {
2386
+ let cur = null;
2387
+ let accum = null;
2388
+ let doCorrect = false;
2389
+ let flush = () => {
2390
+ if (cur) {
2391
+ if (cur.pos < cur.docLen)
2392
+ addSection(cur.sections, cur.data, cur.docLen - cur.pos, -1, null);
2393
+ push(ChangeSet.new(cur.sections, cur.data));
2394
+ cur = null;
2395
+ }
2396
+ };
2397
+ let push = (set) => {
2398
+ accum = accum ? accum.compose(transform(set, accum, doc, false, false).set) : set;
2399
+ };
2400
+ let section = (from, to, ins, value) => {
2401
+ if (!cur || from < cur.pos) {
2402
+ flush();
2403
+ cur = new ChangeSetBuilder(doc.length);
2404
+ }
2405
+ if (from > cur.pos)
2406
+ addSection(cur.sections, cur.data, from - cur.pos, -1, null);
2407
+ addSection(cur.sections, cur.data, to - from, ins, value);
2408
+ cur.pos = to;
2409
+ };
2410
+ let build = (spec) => {
2411
+ if (Array.isArray(spec)) {
2412
+ for (let elt of spec)
2413
+ build(elt);
2414
+ }
2415
+ else if (spec instanceof ChangeSet) {
2416
+ flush();
2417
+ push(spec);
2418
+ }
2419
+ else if ("correct" in spec) {
2420
+ flush();
2421
+ let { correct, local } = spec;
2422
+ let inner = createChangeSet(doc, correct, false);
2423
+ push(mayCorrect || local ? inner.correct(doc, local) : inner);
2424
+ }
2425
+ else {
2426
+ let { from, to, add, remove, insert, fit } = spec;
2427
+ let modifies = add || remove;
2428
+ if (modifies) {
2429
+ if (insert)
2430
+ throw new ValidationError(`A Change object cannot both ${add ? "add" : "remove"} a mark and replace a range`);
2431
+ if (to == null)
2432
+ to = from + 1;
2433
+ if (add) {
2434
+ let mods = [{ add }];
2435
+ markableSections(doc, from, to, add.type.spanning, (node, from, to) => {
2436
+ if (!doc.schema.markAllowed(add.type, node.type))
2437
+ return false;
2438
+ let has = add.type.isInSet(node.tag.marks);
2439
+ if (add.type.set) {
2440
+ let modsHere = mods;
2441
+ if (has) {
2442
+ let left = subtractSet(add.value, has.value, add.type.set);
2443
+ if (!left.length)
2444
+ return false;
2445
+ modsHere = [{ add: add.type.of(left) }];
2446
+ }
2447
+ section(from, to, -2, modsHere);
2448
+ }
2449
+ else if (!has || !has.eq(add)) {
2450
+ section(from, to, -2, mods);
2451
+ }
2452
+ return true;
2453
+ });
2454
+ }
2455
+ if (remove) {
2456
+ let mods = [{ remove }];
2457
+ markableSections(doc, from, to, remove.type.spanning, (node, from, to) => {
2458
+ const has = remove.isInSet(node.tag.marks);
2459
+ if (!has || !doc.schema.markAllowed(remove.type, node.type))
2460
+ return false;
2461
+ let modsHere = mods;
2462
+ if (remove.type.set) {
2463
+ let left = subtractSet(remove.value, has.value, remove.type.set);
2464
+ if (!left.length)
2465
+ return false;
2466
+ modsHere = [{ remove: remove.type.of(left) }];
2467
+ }
2468
+ section(from, to, -2, modsHere);
2469
+ return true;
2470
+ });
2471
+ }
2472
+ }
2473
+ else {
2474
+ if (to == null)
2475
+ to = from;
2476
+ insert = (!insert ? Slice.empty : Array.isArray(insert) ? Slice.of(insert) : insert);
2477
+ if (to <= from)
2478
+ to = from;
2479
+ if (fit) {
2480
+ doCorrect = true;
2481
+ ({ from, to, slice: insert } =
2482
+ fitReplacement(doc, doc.resolve(from), doc.resolve(to), insert, fit === true ? [] : fit));
2483
+ }
2484
+ if (insert.length || to != from)
2485
+ section(from, to, insert.length, insert);
2486
+ }
2487
+ }
2488
+ };
2489
+ build(spec);
2490
+ flush();
2491
+ return !accum ? ChangeSet.empty(doc.length) : doCorrect && mayCorrect ? accum.correct(doc) : accum;
2492
+ }
2493
+ function transform(setA, setB, doc, before, fit) {
2494
+ if (setA.length != doc.length || setB.length != doc.length)
2495
+ throw new ValidationError("Transforming a change that doesn't match the start document");
2496
+ let sections = [], data = [];
2497
+ let fitter = fit ? new ChangeFitter(doc, false) : null;
2498
+ let a = new SectionIter(setA.sections, setA.data), b = new SectionIter(setB.sections, setB.data), pos = 0;
2499
+ for (let inserted = -1;;) {
2500
+ if (a.keep && b.keep) {
2501
+ let len = Math.min(a.len, b.len);
2502
+ let mods = before ? a.mods : filterMods(a.mods, b.mods);
2503
+ addSection(sections, data, len, mods ? -2 : -1, mods);
2504
+ a.forward(len);
2505
+ b.forward(len);
2506
+ if (fitter)
2507
+ fitter.preserved(pos, pos + len);
2508
+ pos += len;
2509
+ }
2510
+ else if (b.ins >= 0 && (a.ins < 0 || inserted == a.i || a.off == 0 && (b.len < a.len || b.len == a.len && !before))) {
2511
+ let end = pos + b.len;
2512
+ addSection(sections, data, b.ins, -1, null);
2513
+ if (fitter)
2514
+ fitter.replaced(b.slice, pos, end, true);
2515
+ while (pos < end) {
2516
+ if (a.done)
2517
+ throw new ValidationError("Mismatched change sets");
2518
+ let piece = Math.min(a.len, end - pos);
2519
+ if (a.ins >= 0 && inserted < a.i && a.len <= piece) {
2520
+ addSection(sections, data, 0, a.ins, a.slice);
2521
+ if (fitter)
2522
+ fitter.replaced(a.slice, pos - a.off, pos + a.len);
2523
+ inserted = a.i;
2524
+ }
2525
+ a.forward(piece);
2526
+ pos += piece;
2527
+ }
2528
+ b.next();
2529
+ }
2530
+ else if (a.ins >= 0) {
2531
+ let start = pos, end = pos + a.len, len = 0;
2532
+ while (pos < end) {
2533
+ if (b.keep) {
2534
+ let piece = Math.min(end - pos, b.len);
2535
+ pos += piece;
2536
+ len += piece;
2537
+ b.forward(piece);
2538
+ }
2539
+ else if (b.ins == 0 && pos + b.len < end) {
2540
+ if (fitter)
2541
+ fitter.replaced(b.slice, pos, pos + b.len, true);
2542
+ pos += b.len;
2543
+ b.next();
2544
+ }
2545
+ else {
2546
+ break;
2547
+ }
2548
+ }
2549
+ if (inserted < a.i) {
2550
+ addSection(sections, data, len, a.ins, a.slice);
2551
+ if (fitter)
2552
+ fitter.replaced(a.slice, start - a.off, start + a.len);
2553
+ inserted = a.i;
2554
+ }
2555
+ else {
2556
+ addSection(sections, data, len, 0, Slice.empty);
2557
+ }
2558
+ a.forward(pos - start);
2559
+ }
2560
+ else {
2561
+ return {
2562
+ set: ChangeSet.new(sections, data),
2563
+ fix: fitter && fitter.finish()
2564
+ };
2565
+ }
2566
+ }
2567
+ }
2568
+ function compose(sectionsA, sectionsB, dataA, dataB) {
2569
+ let sections = [], data = dataA ? [] : null;
2570
+ let a = new SectionIter(sectionsA, dataA), b = new SectionIter(sectionsB, dataB);
2571
+ for (let open = false;;) {
2572
+ if (a.done && b.done) {
2573
+ return { sections, data };
2574
+ }
2575
+ else if (a.ins == 0) { addSection(sections, data, a.len, 0, a.slice, open);
2576
+ a.next();
2577
+ }
2578
+ else if (b.len == 0 && !b.done) { addSection(sections, data, 0, b.ins, b.slice, open);
2579
+ b.next();
2580
+ }
2581
+ else if (a.done || b.done) {
2582
+ throw new ValidationError("Mismatched change set lengths");
2583
+ }
2584
+ else {
2585
+ let len = Math.min(a.len2, b.len), sectionLen = sections.length;
2586
+ if (a.keep && b.keep) {
2587
+ let mods = combineMods(a.mods, b.mods);
2588
+ addSection(sections, data, len, (data ? mods : a.ins == -2 || b.ins == -2) ? -2 : -1, mods, open);
2589
+ }
2590
+ else if (a.keep) {
2591
+ addSection(sections, data, len, b.off ? 0 : b.ins, b.off ? Slice.empty : b.slice, open);
2592
+ }
2593
+ else if (b.keep) {
2594
+ addSection(sections, data, a.off ? 0 : a.len, len, data ? applyModsToSlice(a.slicePart(len), b.mods) : null, open);
2595
+ }
2596
+ else {
2597
+ addSection(sections, data, a.off ? 0 : a.len, b.off ? 0 : b.ins, b.off ? Slice.empty : b.slice, open);
2598
+ }
2599
+ open = (a.ins > len || b.ins >= 0 && b.len > len) && (open || sections.length > sectionLen);
2600
+ a.forward2(len);
2601
+ b.forward(len);
2602
+ }
2603
+ }
2604
+ }
2605
+ function combineMods(a, b) {
2606
+ return !a ? b : !b ? a : a.concat(b);
2607
+ }
2608
+ function filterMods(mods, against) {
2609
+ if (!mods || !against)
2610
+ return mods;
2611
+ return mods.filter(m => !against.some(a => modCancels(a, m)));
2612
+ }
2613
+ function modCancels(mod, other) {
2614
+ if (isAdd(other)) {
2615
+ return isAdd(mod) ? mod.add.type == other.add.type && !mod.add.type.set : mod.remove.eq(other.add);
2616
+ }
2617
+ else {
2618
+ return isAdd(mod) && mod.add.eq(isAdd(other) ? other.add : other.remove);
2619
+ }
2620
+ }
2621
+ function invertMods(mods, target) {
2622
+ return mods.map(mod => {
2623
+ if (isRemove(mod))
2624
+ return { add: mod.remove };
2625
+ if (!mod.add.type.set) {
2626
+ let existed = mod.add.type.isInSet(target.marks);
2627
+ if (existed)
2628
+ return { add: existed };
2629
+ }
2630
+ return { remove: mod.add };
2631
+ });
2632
+ }
2633
+ function applyModsToSlice(slice, mods) {
2634
+ if (!mods)
2635
+ return slice;
2636
+ let content = [];
2637
+ for (let tok of slice.content) {
2638
+ if (tok.tokenType == Token.Type.Open) {
2639
+ content.push(tok.withMarks(applyModifications(mods, tok.marks, tok.type)));
2640
+ }
2641
+ else if (tok.tokenType == Token.Type.Node) {
2642
+ let node = tok.withMarks(applyModifications(mods, tok.marks, tok.type));
2643
+ if (content.length && content[content.length - 1].tokenType == Token.Type.Node)
2644
+ node.pushTo(content);
2645
+ else
2646
+ content.push(node);
2647
+ }
2648
+ else {
2649
+ content.push(tok);
2650
+ }
2651
+ }
2652
+ return Slice.of(content);
2653
+ }
2654
+ class FitLevel {
2655
+ tag;
2656
+ next;
2657
+ flags = 0;
2658
+ constructor(tag, next) {
2659
+ this.tag = tag;
2660
+ this.next = next;
2661
+ if (!this.tag.type.canBeEmpty)
2662
+ this.flags |= 1;
2663
+ }
2664
+ }
2665
+ const counter = {
2666
+ count: 0,
2667
+ skip() { },
2668
+ enterPlot() { this.count++; },
2669
+ leavePlot() { this.count--; },
2670
+ countDelta(pos, distance) {
2671
+ this.count = 0;
2672
+ return pos.advance(distance, this);
2673
+ }
2674
+ };
2675
+ class ChangeFitter {
2676
+ local;
2677
+ stack;
2678
+ inputPos;
2679
+ delInputPos;
2680
+ pos = 0;
2681
+ patches = [];
2682
+ stackDelta = 0;
2683
+ inputDelta = 0;
2684
+ inserting = false;
2685
+ activeContext = null;
2686
+ activeContextPos = -1;
2687
+ nextSync = -1;
2688
+ schema;
2689
+ constructor(doc, local) {
2690
+ this.local = local;
2691
+ this.schema = doc.schema;
2692
+ this.stack = new FitLevel(doc.tag, null);
2693
+ this.inputPos = this.delInputPos = doc.resolve(0);
2694
+ }
2695
+ getPos(at) {
2696
+ let { inputPos, delInputPos } = this;
2697
+ if (inputPos.pos == at)
2698
+ return inputPos;
2699
+ if (delInputPos.pos == at)
2700
+ return delInputPos;
2701
+ return inputPos.advance(at - inputPos.pos);
2702
+ }
2703
+ preserved(from, to) {
2704
+ let { nextSync } = this;
2705
+ if (nextSync >= from && nextSync <= to) {
2706
+ this.stackDelta = 0;
2707
+ this.nextSync = -1;
2708
+ if (nextSync > from)
2709
+ this.preserved(from, nextSync);
2710
+ this.syncToContext(this.inputPos);
2711
+ if (to > nextSync)
2712
+ this.preserved(nextSync, to);
2713
+ return;
2714
+ }
2715
+ let inputPos = this.getPos(from);
2716
+ if (!this.inputDelta && this.stackDelta) {
2717
+ this.syncToContext(inputPos);
2718
+ this.stackDelta = 0;
2719
+ }
2720
+ this.activeContext = inputPos;
2721
+ this.activeContextPos = this.pos;
2722
+ this.inputPos = inputPos.advance(to - from, this);
2723
+ }
2724
+ lastCoverFrom = -1;
2725
+ lastCoverTo = -1;
2726
+ doubleDeleteDelta = 0;
2727
+ replaced(slice, from, to, covering = false) {
2728
+ this.doubleDeleteDelta = 0;
2729
+ if (covering) {
2730
+ this.lastCoverFrom = from;
2731
+ this.lastCoverTo = to;
2732
+ }
2733
+ else if (slice.length) {
2734
+ let overlapFrom = Math.max(from, this.lastCoverFrom);
2735
+ let overlapTo = Math.min(to, this.lastCoverTo);
2736
+ if (overlapFrom < overlapTo) {
2737
+ counter.countDelta(this.getPos(overlapFrom), overlapTo - overlapFrom);
2738
+ this.doubleDeleteDelta = counter.count;
2739
+ }
2740
+ }
2741
+ if (from != to) {
2742
+ this.delInputPos = counter.countDelta(this.getPos(from), to - from);
2743
+ this.inputDelta -= counter.count;
2744
+ }
2745
+ this.inserting = true;
2746
+ slice.run(this, this.pos);
2747
+ this.inserting = false;
2748
+ if (this.local)
2749
+ this.nextSync = Math.max(this.nextSync, localSyncPosAfter(this.inputPos = this.getPos(to)));
2750
+ }
2751
+ fit(tag) {
2752
+ if (this.schema.canContain(this.stack.tag.type, tag.type))
2753
+ return true;
2754
+ let fix = null;
2755
+ let dDelta = this.stackDelta - this.inputDelta;
2756
+ for (let level = this.stack, leave = 0, leaveCost = 0; level; level = level.next, leave++) {
2757
+ if (fix && leaveCost > fix.cost)
2758
+ break;
2759
+ let enter = this.schema.findWrapping(level.tag.type, tag.type);
2760
+ if (enter) {
2761
+ let cost = leaveCost + enter.length * 2 - Math.max(0, Math.min(-dDelta, enter.length));
2762
+ if (!fix || fix.cost > cost && !fix.context)
2763
+ fix = { leave, enter, cost, context: false };
2764
+ }
2765
+ if (this.activeContextPos == this.pos) {
2766
+ let top = this.activeContext?.parent || null;
2767
+ for (let cx = top, i = 1; cx; cx = cx.parent, i++) {
2768
+ if (this.schema.canContain(level.tag.type, cx.node.type)) {
2769
+ let cost = leaveCost + i * 2 - Math.max(0, Math.min(-dDelta, i));
2770
+ if (!fix || fix.cost > cost || !fix.context) {
2771
+ let enter = [];
2772
+ for (let scan = top;; scan = scan.parent) {
2773
+ enter.unshift(scan.node.tag);
2774
+ if (scan == cx)
2775
+ break;
2776
+ }
2777
+ fix = { leave, enter, cost, context: true };
2778
+ }
2779
+ break;
2780
+ }
2781
+ }
2782
+ }
2783
+ leaveCost += level.flags & 2 ? 0 : dDelta > leave ? 1 : 2;
2784
+ }
2785
+ if (!fix)
2786
+ return false;
2787
+ for (let i = 0; i < fix.leave; i++) {
2788
+ this.insertClose();
2789
+ this.stackDelta--;
2790
+ }
2791
+ for (let wrapper of fix.enter) {
2792
+ this.patch(0, wrapper);
2793
+ this.stack.flags &= -2;
2794
+ this.stack = new FitLevel(wrapper, this.stack);
2795
+ this.stack.flags |= 2;
2796
+ this.stackDelta++;
2797
+ }
2798
+ return true;
2799
+ }
2800
+ syncToContext(context) {
2801
+ let cur = [], sync = [];
2802
+ for (let l = this.stack; l; l = l.next)
2803
+ cur.push(l);
2804
+ cur.reverse();
2805
+ for (let level = context.parent; level; level = level.parent)
2806
+ sync.push(level.node.tag);
2807
+ sync.reverse();
2808
+ while (cur.length > sync.length) {
2809
+ this.insertClose();
2810
+ cur.pop();
2811
+ }
2812
+ for (let d = 1; d < Math.min(sync.length, cur.length); d++) {
2813
+ if (!this.schema.sharesContent(sync[d].type, cur[d].tag.type)) {
2814
+ while (cur.length > d) {
2815
+ this.insertClose();
2816
+ cur.pop();
2817
+ }
2818
+ break;
2819
+ }
2820
+ }
2821
+ for (let i = cur.length; i < sync.length; i++) {
2822
+ let tag = sync[i];
2823
+ this.stack = new FitLevel(tag, this.stack);
2824
+ this.patch(0, tag);
2825
+ }
2826
+ }
2827
+ insertClose() {
2828
+ if (this.stack.flags & 1)
2829
+ this.patch(0, this.schema.createDefault(this.stack.tag.type), Plot.End);
2830
+ else
2831
+ this.patch(0, Plot.End);
2832
+ this.stack = this.stack.next;
2833
+ }
2834
+ patch(length, ...insert) {
2835
+ let prev = this.patches.length ? this.patches[this.patches.length - 1] : null;
2836
+ if (prev && prev.to == this.pos) {
2837
+ prev.to += length;
2838
+ for (let tok of insert)
2839
+ prev.insert.push(tok);
2840
+ }
2841
+ else {
2842
+ this.patches.push({ from: this.pos, to: this.pos + length, insert });
2843
+ }
2844
+ }
2845
+ open(tag) { this.enter(tag); }
2846
+ close() { this.leavePlot(); }
2847
+ node(node) { this.skip(node); }
2848
+ skip(node) {
2849
+ if (this.fit(node.tag))
2850
+ this.stack.flags &= -2;
2851
+ else
2852
+ this.patch(node.length);
2853
+ this.pos += node.length;
2854
+ }
2855
+ enterPlot(node) { this.enter(node.tag); }
2856
+ enter(tag) {
2857
+ if (this.inserting)
2858
+ this.inputDelta++;
2859
+ if (this.doubleDeleteDelta > 0) {
2860
+ this.doubleDeleteDelta--;
2861
+ this.patch(1);
2862
+ }
2863
+ else if (this.fit(tag)) {
2864
+ this.stack.flags &= -2;
2865
+ this.stack = new FitLevel(tag, this.stack);
2866
+ if (this.inserting)
2867
+ this.stackDelta++;
2868
+ }
2869
+ else {
2870
+ this.patch(1);
2871
+ }
2872
+ this.pos++;
2873
+ }
2874
+ leavePlot() {
2875
+ if (this.inserting)
2876
+ this.inputDelta--;
2877
+ if (this.doubleDeleteDelta < 0) {
2878
+ this.doubleDeleteDelta++;
2879
+ this.patch(1);
2880
+ }
2881
+ else if (this.stack.next) {
2882
+ if (this.stack.flags & 1)
2883
+ this.patch(0, this.schema.createDefault(this.stack.tag.type));
2884
+ this.stack = this.stack.next;
2885
+ if (this.inserting)
2886
+ this.stackDelta++;
2887
+ }
2888
+ else {
2889
+ this.patch(1);
2890
+ }
2891
+ this.pos++;
2892
+ }
2893
+ finish() {
2894
+ while (this.stack.next || (this.stack.flags && 1)) {
2895
+ if (this.stack.flags & 1) {
2896
+ this.patch(0, this.schema.createDefault(this.stack.tag.type));
2897
+ this.stack.flags &= -2;
2898
+ }
2899
+ else {
2900
+ this.patch(0, Plot.End);
2901
+ this.stack = this.stack.next;
2902
+ }
2903
+ }
2904
+ if (!this.patches.length)
2905
+ return null;
2906
+ let sections = [], data = [], pos = 0;
2907
+ for (let { from, to, insert } of this.patches) {
2908
+ addSection(sections, data, from - pos, -1, null);
2909
+ let slice = Slice.of(insert);
2910
+ addSection(sections, data, to - from, slice.length, slice);
2911
+ pos = to;
2912
+ }
2913
+ addSection(sections, data, this.pos - pos, -1, null);
2914
+ return ChangeSet.new(sections, data);
2915
+ }
2916
+ }
2917
+ function localSyncPosAfter(pos) {
2918
+ let found = pos.pos;
2919
+ for (let cx = pos.parent, index = pos.index;; index = cx.index, cx = cx.parent) {
2920
+ if (!cx.parent || !cx.node.inlineContent && index != cx.node.content.length - 1)
2921
+ break;
2922
+ found = cx.after;
2923
+ }
2924
+ return found;
2925
+ }
2926
+ function markableSections(doc, from, to, spanning, f) {
2927
+ doc.iterate(from, to, (node, pos) => {
2928
+ if ((pos >= from && pos + (spanning ? node.length : 1) <= to) || node.isText) {
2929
+ if (node.isText ? f(node, Math.max(pos, from), Math.min(pos + node.length, to)) : f(node, pos, pos + 1))
2930
+ return false;
2931
+ }
2932
+ });
2933
+ }
2934
+ class SectionIter {
2935
+ sections;
2936
+ data;
2937
+ i = 0;
2938
+ len;
2939
+ off;
2940
+ ins;
2941
+ constructor(sections, data) {
2942
+ this.sections = sections;
2943
+ this.data = data;
2944
+ this.next();
2945
+ }
2946
+ next() {
2947
+ let { sections } = this;
2948
+ if (this.i < sections.length) {
2949
+ this.len = sections[this.i++];
2950
+ this.ins = sections[this.i++];
2951
+ }
2952
+ else {
2953
+ this.len = 0;
2954
+ this.ins = -3;
2955
+ }
2956
+ this.off = 0;
2957
+ }
2958
+ get keep() { return this.ins == -1 || this.ins == -2; }
2959
+ get done() { return this.ins == -3; }
2960
+ get len2() { return this.ins < 0 ? this.len : this.ins; }
2961
+ get mods() {
2962
+ return this.data ? this.data[(this.i - 2) >> 1] : null;
2963
+ }
2964
+ get slice() {
2965
+ return this.data ? this.data[(this.i - 2) >> 1] : Slice.empty;
2966
+ }
2967
+ slicePart(len) {
2968
+ return this.slice.slice(this.off, len == null ? undefined : this.off + len);
2969
+ }
2970
+ forward(len) {
2971
+ if (len == this.len)
2972
+ this.next();
2973
+ else {
2974
+ this.len -= len;
2975
+ this.off += len;
2976
+ }
2977
+ }
2978
+ forward2(len) {
2979
+ if (this.keep)
2980
+ this.forward(len);
2981
+ else if (len == this.ins)
2982
+ this.next();
2983
+ else {
2984
+ this.ins -= len;
2985
+ this.off += len;
2986
+ }
2987
+ }
2988
+ }
2989
+ function addSection(sections, data, len, ins, value, forceJoin = false) {
2990
+ if (len == 0 && ins <= 0)
2991
+ return;
2992
+ let last = sections.length - 2;
2993
+ if (last >= 0 && ins <= 0 && ins == sections[last + 1]) {
2994
+ let lastValue = data ? data[data.length - 1] : null;
2995
+ let match = ins == 0 ? true
2996
+ : value ? lastValue && compareModifications(lastValue, value)
2997
+ : !lastValue;
2998
+ if (match) {
2999
+ sections[last] += len;
3000
+ return;
3001
+ }
3002
+ }
3003
+ if (forceJoin || last >= 0 && len == 0 && sections[last] == 0) {
3004
+ sections[last] += len;
3005
+ sections[last + 1] += ins;
3006
+ if (data)
3007
+ data[data.length - 1] = data[data.length - 1].concat(value);
3008
+ }
3009
+ else {
3010
+ sections.push(len, ins);
3011
+ if (data)
3012
+ data.push(value);
3013
+ }
3014
+ }
3015
+ function finishCx(cx, schema) {
3016
+ return cx.tag.create(cx.children.length || cx.tag.type.canBeEmpty ? cx.children
3017
+ : [schema.createDefault(cx.tag.type)]);
3018
+ }
3019
+ function closeSlice(schema, slice, context, depth, closeEnd = false) {
3020
+ let top = [], stack = null;
3021
+ for (let i = depth - 1; i >= 0; i--)
3022
+ stack = new BuildContext(context[i], stack);
3023
+ for (let token of slice.content) {
3024
+ if (token.tokenType == Token.Type.Close) {
3025
+ if (stack) {
3026
+ let node = finishCx(stack, schema);
3027
+ stack = stack.parent;
3028
+ (stack ? stack.children : top).push(node);
3029
+ }
3030
+ else {
3031
+ top.push(token);
3032
+ }
3033
+ }
3034
+ else if (token.tokenType == Token.Type.Open) {
3035
+ stack = new BuildContext(token, stack);
3036
+ }
3037
+ else {
3038
+ (stack ? stack.children : top).push(token);
3039
+ }
3040
+ }
3041
+ if (closeEnd)
3042
+ while (stack) {
3043
+ let node = finishCx(stack, schema);
3044
+ stack = stack.parent;
3045
+ (stack ? stack.children : top).push(node);
3046
+ }
3047
+ if (stack)
3048
+ splatContext(top, stack);
3049
+ return Slice.of(top);
3050
+ }
3051
+ function splatContext(top, cx) {
3052
+ if (cx.parent)
3053
+ splatContext(top, cx.parent);
3054
+ top.push(cx.tag);
3055
+ for (let ch of cx.children)
3056
+ top.push(ch);
3057
+ }
3058
+ function fitReplacement(doc, from, to, slice, context) {
3059
+ if (!slice.length)
3060
+ return fitDeletion(doc, from, to);
3061
+ let preferredContext = -1;
3062
+ for (let i = 0; i < context.length; i++) {
3063
+ let next = context[i];
3064
+ if (next.type.defining)
3065
+ preferredContext = i;
3066
+ else if (!next.isTextblock)
3067
+ break;
3068
+ }
3069
+ let firstType = null, closeCount = 0;
3070
+ for (let i = 0, opened = 0; i < slice.content.length; i++) {
3071
+ let tok = slice.content[i];
3072
+ if (tok.tokenType == Token.Type.Close) {
3073
+ if (opened)
3074
+ opened--;
3075
+ else
3076
+ closeCount++;
3077
+ }
3078
+ else {
3079
+ if (!i)
3080
+ firstType = tok.type;
3081
+ if (tok.tokenType == Token.Type.Open)
3082
+ opened++;
3083
+ }
3084
+ }
3085
+ let found, foundCost = 1e8;
3086
+ let neutral = true, toEnd = true;
3087
+ scan: for (let cxFrom = from.parent, cxTo = to.parent, fromDepth = from.depth, toDepth = to.depth, start = from.pos, end = to.pos; cxFrom.parent; cxFrom = cxFrom.parent, start--, fromDepth--) {
3088
+ if (cxFrom.start != start || cxFrom.node.type.isolating)
3089
+ break;
3090
+ while (toDepth > fromDepth) {
3091
+ if (cxTo.node.type.isolating)
3092
+ break scan;
3093
+ cxTo = cxTo.parent;
3094
+ toDepth--;
3095
+ end++;
3096
+ }
3097
+ if (cxTo.end != end) {
3098
+ if (!closeCount)
3099
+ break;
3100
+ toEnd = false;
3101
+ }
3102
+ if (!cxFrom.node.type.neutral)
3103
+ neutral = false;
3104
+ if (fromDepth == toDepth)
3105
+ for (let i = -1, type; i < context.length; i++) {
3106
+ if (i >= 0)
3107
+ type = context[i].type;
3108
+ else if (!firstType)
3109
+ continue;
3110
+ else
3111
+ type = firstType;
3112
+ if (doc.schema.canContain(cxFrom.parent.node.type, type)) {
3113
+ let cost = (neutral ? 0 : 2) + (i < preferredContext ? context.length - i : i - preferredContext) + (toEnd ? 0 : 1e7);
3114
+ if (foundCost > cost) {
3115
+ found = { from: cxFrom.before, to: toEnd ? cxTo.after : to.pos,
3116
+ slice: i >= 0 ? closeSlice(doc.schema, slice, context, i + 1, toEnd) : slice };
3117
+ foundCost = cost;
3118
+ }
3119
+ }
3120
+ }
3121
+ }
3122
+ if (found)
3123
+ return found;
3124
+ if (from.pos == to.pos && !from.inText) {
3125
+ let cx = from.parent, before = from.pos, after = from.pos;
3126
+ for (; cx.parent && !cx.node.type.isolating && (before == cx.start || after == cx.end); cx = cx.parent, before--, after++) {
3127
+ for (let i = -1; i < context.length; i++) {
3128
+ let type = i >= 0 ? context[i].type : firstType;
3129
+ if (!type)
3130
+ continue;
3131
+ if (doc.schema.canContain(cx.parent.node.type, type)) {
3132
+ let pos = before == cx.start ? cx.before : cx.after;
3133
+ return { from: pos, to: pos, slice: i >= 0 ? closeSlice(doc.schema, slice, context, i + 1, true) : slice };
3134
+ }
3135
+ }
3136
+ }
3137
+ }
3138
+ for (let i = 0; i < context.length; i++) {
3139
+ if (doc.schema.canContain(from.parent.node.type, context[i].type)) {
3140
+ slice = closeSlice(doc.schema, slice, context, i + 1, true);
3141
+ break;
3142
+ }
3143
+ }
3144
+ return { from: from.pos, to: to.pos, slice };
3145
+ }
3146
+ function fitDeletion(doc, from, to) {
3147
+ let toDepth = to.depth;
3148
+ let covered;
3149
+ for (let cx = from.parent, cxTo = to.parent, depth = from.depth, start = from.pos, end = to.pos; cx.parent; start--, cx = cx.parent, depth--) {
3150
+ if (cx.start != start || cx.node.type.isolating)
3151
+ break;
3152
+ while (toDepth > depth) {
3153
+ cxTo = cxTo.parent;
3154
+ toDepth--;
3155
+ end++;
3156
+ }
3157
+ let toAtEnd = toDepth == depth && cxTo.end == end; if (cx.end < to.pos && cx.parent.end > to.pos && !toAtEnd)
3158
+ return { from: cx.before, to: to.pos, slice: Slice.empty };
3159
+ if (!cx.node.inlineContent && toAtEnd && cx.parent.start == cxTo.parent.start &&
3160
+ !(from.parent.start == to.parent.start && from.parent.node.inlineContent))
3161
+ covered = { from: cx.before, to: cxTo.after, slice: Slice.empty };
3162
+ }
3163
+ return covered || { from: from.pos, to: to.pos, slice: Slice.empty };
3164
+ }
3165
+
3166
+ function parse(schema, doc, options = {}) {
3167
+ let top = new NodeContext(schema.docTag, 4, null);
3168
+ let cx = new ParseContext(schema, options, top);
3169
+ cx.parseChildren(doc, [], false);
3170
+ cx.sync(top);
3171
+ return cx.finishNode(cx.top);
3172
+ }
3173
+ ;parse = /*@__PURE__*/(function (parse) {
3174
+ function slice(schema, doc, options = {}) {
3175
+ let top = new NodeContext(guessParent(doc, schema), 4 | 1 | 2, null);
3176
+ let cx = new ParseContext(schema, options, top);
3177
+ cx.parseChildren(doc, [], true);
3178
+ cx.sync(top);
3179
+ let tokens = [], context = [];
3180
+ let emitTokens = (children, openStart, openEnd) => {
3181
+ for (let i = 0; i < children.length; i++) {
3182
+ let child = children[i];
3183
+ if (openStart && i == 0 && child.isPlot && ((cx.open.get(child) || 0) & 1)) {
3184
+ if (children.length == 1 && openEnd && ((cx.open.get(child) || 0) & 2)) {
3185
+ emitTokens(child.content, true, true);
3186
+ }
3187
+ else {
3188
+ emitTokens(child.content, true, false);
3189
+ tokens.push(Plot.End);
3190
+ }
3191
+ context.push(child.tag);
3192
+ }
3193
+ else if (openEnd && i == children.length - 1 && child.isPlot && ((cx.open.get(child) || 0) & 2)) {
3194
+ tokens.push(child.tag);
3195
+ emitTokens(child.content, false, true);
3196
+ }
3197
+ else {
3198
+ tokens.push(child);
3199
+ }
3200
+ }
3201
+ };
3202
+ emitTokens(top.children, true, true);
3203
+ return { slice: Slice.of(tokens), context };
3204
+ }
3205
+ parse.slice = slice;
3206
+ (function (Rule) {
3207
+ const schemaCache = new WeakMap();
3208
+ function addByPrec(array, value) {
3209
+ let prec = value.precedence ?? 0, i = array.length;
3210
+ while (i > 0 && prec > (array[i - 1].precedence ?? 0))
3211
+ i--;
3212
+ array.splice(i, 0, value);
3213
+ }
3214
+ class Set {
3215
+ rules;
3216
+ elementRules = [];
3217
+ attributeRules = [];
3218
+ constructor(
3219
+ rules) {
3220
+ this.rules = rules;
3221
+ for (let rule of rules)
3222
+ addByPrec("selector" in rule ? this.elementRules : this.attributeRules, rule);
3223
+ }
3224
+ static of(rules) { return new Set(rules); }
3225
+ static fromSchema(schema) {
3226
+ let cached = schemaCache.get(schema);
3227
+ if (cached)
3228
+ return cached;
3229
+ let rules = [];
3230
+ for (let tag of schema.nodes) {
3231
+ let { spec: { shape, parseRules } } = tag;
3232
+ if ("element" in shape && shape.element && (shape.readElement || tag.default))
3233
+ rules.push({
3234
+ selector: shape.selector || shape.element,
3235
+ readElement: shape.readElement,
3236
+ tag
3237
+ });
3238
+ if (parseRules)
3239
+ for (let rule of parseRules)
3240
+ rules.push({
3241
+ ...rule,
3242
+ tag: rule.tag || tag
3243
+ });
3244
+ }
3245
+ for (let mark of schema.marks) {
3246
+ let { shape, parseRules } = mark.spec;
3247
+ if (parseRules)
3248
+ for (let rule of parseRules)
3249
+ rules.push({ ...rule, mark: rule.mark || mark });
3250
+ if ("element" in shape && (shape.readElement || mark.default)) {
3251
+ rules.push({
3252
+ selector: shape.selector || shape.element,
3253
+ readElement: shape.readElement,
3254
+ mark
3255
+ });
3256
+ }
3257
+ else if ("attribute" in shape) {
3258
+ if (shape.readAttribute) {
3259
+ rules.push({
3260
+ attribute: shape.attribute,
3261
+ readAttribute: shape.readAttribute,
3262
+ mark
3263
+ });
3264
+ }
3265
+ else if (typeof shape.value == "string") {
3266
+ rules.push({
3267
+ attribute: shape.attribute,
3268
+ value: shape.value,
3269
+ mark
3270
+ });
3271
+ }
3272
+ else if (shape.value === 0) {
3273
+ rules.push({
3274
+ attribute: shape.attribute,
3275
+ readAttribute: param => param,
3276
+ mark
3277
+ });
3278
+ }
3279
+ }
3280
+ }
3281
+ let result = new Rule.Set(rules);
3282
+ schemaCache.set(schema, result);
3283
+ return result;
3284
+ }
3285
+ matchElement(elt) {
3286
+ for (let rule of this.elementRules) {
3287
+ if (elt.matches(rule.selector)) {
3288
+ if (!rule.readElement)
3289
+ return Object.prototype.hasOwnProperty.call(rule, "param") ? { rule, value: rule.param } : { rule };
3290
+ let result = rule.readElement(elt);
3291
+ if (result === parse.Reject)
3292
+ continue;
3293
+ return { rule, value: result };
3294
+ }
3295
+ }
3296
+ return null;
3297
+ }
3298
+ }
3299
+ Rule.Set = Set;
3300
+ })(parse.Rule || (parse.Rule = {}));
3301
+ parse.Reject = Symbol("reject");
3302
+ ;return parse})(parse);
3303
+ class ParseContext {
3304
+ schema;
3305
+ options;
3306
+ top;
3307
+ rules;
3308
+ open = new Map;
3309
+ constructor(schema, options, top) {
3310
+ this.schema = schema;
3311
+ this.options = options;
3312
+ this.top = top;
3313
+ this.rules = options.ruleSet || parse.Rule.Set.fromSchema(schema);
3314
+ }
3315
+ parseChildren(parent, marks, endOfSlice, ignore) {
3316
+ for (let ch = parent.firstChild; ch; ch = ch.nextSibling) {
3317
+ if (ch.nodeType == 1)
3318
+ this.parseElement(ch, marks, endOfSlice && !ch.nextSibling);
3319
+ else if (ch.nodeType == 3 &&
3320
+ !(ignore && (typeof ignore == "string" ? ch.matches(ignore) : ignore(ch))))
3321
+ this.parseTextNode(ch, marks);
3322
+ }
3323
+ }
3324
+ ignoreElement(elt, marks) {
3325
+ if (elt.nodeName == "BR" && !this.top.tag.inlineContent)
3326
+ this.findPlace(Leaf.Text.of("-"), marks, false);
3327
+ }
3328
+ parseElement(elt, marks, endOfSlice) {
3329
+ let name = elt.nodeName.toLowerCase();
3330
+ if (name in normalizers)
3331
+ normalizers[name](elt);
3332
+ let match = this.rules.matchElement(elt);
3333
+ if (match ? match.rule.ignore === true : ignoreTags.has(name)) {
3334
+ this.ignoreElement(elt, marks);
3335
+ }
3336
+ else if (!match || match.rule.ignore === "skip") {
3337
+ let sync, top = this.top;
3338
+ if (blockTags.has(name)) {
3339
+ if (top.children.length && top.children[0].type.isInline && top.parent)
3340
+ this.close();
3341
+ sync = true;
3342
+ }
3343
+ let innerMarks = match && match.rule.ignore ? marks : this.parseAttributes(elt, marks);
3344
+ if (innerMarks)
3345
+ this.parseChildren(elt, innerMarks, endOfSlice);
3346
+ if (sync)
3347
+ this.sync(top);
3348
+ }
3349
+ else {
3350
+ let innerMarks = this.parseAttributes(elt, marks);
3351
+ if (innerMarks && match.rule.marksFrom) {
3352
+ let inner = elt.querySelector(match.rule.marksFrom);
3353
+ if (inner)
3354
+ innerMarks = this.parseAttributes(inner, innerMarks);
3355
+ }
3356
+ if (innerMarks)
3357
+ this.parseElementByRule(elt, match, innerMarks, endOfSlice);
3358
+ }
3359
+ }
3360
+ parseElementByRule(elt, match, marks, endOfSlice) {
3361
+ let sync, isLeaf = false, { rule } = match, hasValue = Object.prototype.hasOwnProperty.call(match, "value");
3362
+ if (rule.tag) {
3363
+ let tag = rule.tag instanceof BaseTag ? rule.tag :
3364
+ hasValue ? rule.tag.of(match.value) : rule.tag.default;
3365
+ if (!tag)
3366
+ throw new SchemaError(`Parse rule for ${rule.selector} is missing a parameter`);
3367
+ if (tag.isPlot) {
3368
+ let innerMarks = this.enter(tag, marks, endOfSlice, elt);
3369
+ if (innerMarks) {
3370
+ sync = true;
3371
+ marks = innerMarks;
3372
+ }
3373
+ }
3374
+ else {
3375
+ this.insertNode(tag, marks);
3376
+ isLeaf = true;
3377
+ }
3378
+ }
3379
+ else {
3380
+ let mark = rule.mark instanceof Mark ? rule.mark :
3381
+ rule.mark instanceof Mark.Type ? (hasValue ? rule.mark.of(match.value) : rule.mark.default) : null;
3382
+ if (!mark)
3383
+ throw new Error(`Parse rule for ${rule.selector} does not produce a mark`);
3384
+ marks = marks.concat(mark);
3385
+ }
3386
+ let startIn = this.top;
3387
+ if (!isLeaf) {
3388
+ let content = elt;
3389
+ if (typeof rule.contentElement == "string")
3390
+ content = elt.querySelector(rule.contentElement) || elt;
3391
+ else if (typeof rule.contentElement == "function")
3392
+ content = rule.contentElement(elt);
3393
+ this.parseChildren(content, marks, endOfSlice, rule.ignoreContent);
3394
+ }
3395
+ if (sync && this.sync(startIn))
3396
+ this.close();
3397
+ }
3398
+ parseTextNode(dom, marks) {
3399
+ let text = dom.nodeValue;
3400
+ if (!this.top.tag.type.preserveWhitespace && this.options.collapseWhiteSpace !== false) {
3401
+ if (!this.top.tag.inlineContent && !/[^ \t\r\n\u000c]/.test(text))
3402
+ return;
3403
+ text = text.replace(/[ \t\r\n\u000c]+/g, " ");
3404
+ if (/^ /.test(text)) {
3405
+ let nodeBefore = this.top.children[this.top.children.length - 1];
3406
+ if (nodeBefore
3407
+ ? nodeBefore == this.schema.lineBreak || nodeBefore.is(Leaf.Text) && / $/.test(nodeBefore.param)
3408
+ : !(this.top.flags & 1))
3409
+ text = text.slice(1);
3410
+ }
3411
+ if (text)
3412
+ this.insertNode(Leaf.text(text), marks);
3413
+ }
3414
+ else if (this.top.tag.type.preserveWhitespace && this.schema.lineBreak) {
3415
+ let lines = text.split(/\r?\n|\r/g);
3416
+ for (let i = 0; i < lines.length; i++) {
3417
+ if (i)
3418
+ this.insertNode(this.schema.lineBreak, marks);
3419
+ if (lines[i])
3420
+ this.insertNode(Leaf.text(lines[i]), marks);
3421
+ }
3422
+ }
3423
+ else {
3424
+ text = text.replace(/\r?\n|\r/g, " ");
3425
+ if (text)
3426
+ this.insertNode(Leaf.text(text), marks);
3427
+ }
3428
+ }
3429
+ parseAttributes(elt, marks) {
3430
+ let matched = new Set(), style = elt.style, hasStyles = style && style.length > 0;
3431
+ for (let rule of this.rules.attributeRules)
3432
+ if (!matched.has(rule.attribute)) {
3433
+ let isStyle = /^style\//.test(rule.attribute);
3434
+ let value = !isStyle ? elt.getAttribute(rule.attribute) :
3435
+ hasStyles ? style.getPropertyValue(rule.attribute.slice(6)) : "";
3436
+ if (!value)
3437
+ continue;
3438
+ let hasParam = Object.prototype.hasOwnProperty.call(rule, "param"), param = rule.param;
3439
+ if (rule.readAttribute) {
3440
+ param = rule.readAttribute(value);
3441
+ hasParam = true;
3442
+ if (param == parse.Reject)
3443
+ continue;
3444
+ }
3445
+ else if (rule.value != null && rule.value != value) {
3446
+ continue;
3447
+ }
3448
+ if (rule.ignore)
3449
+ return null;
3450
+ if (rule.consuming !== false)
3451
+ matched.add(rule.attribute);
3452
+ if (rule.clearMark) {
3453
+ marks = marks.filter(p => !rule.clearMark(p));
3454
+ }
3455
+ else {
3456
+ let mark = rule.mark instanceof Mark ? rule.mark :
3457
+ rule.mark instanceof Mark.Type ? (hasParam ? rule.mark.of(param) : rule.mark.default) : null;
3458
+ if (!mark)
3459
+ throw new Error(`Parse rule for ${rule.attribute} does not produce a mark (or have ignore/clearMark properties)`);
3460
+ marks = marks.concat(mark);
3461
+ }
3462
+ }
3463
+ return marks;
3464
+ }
3465
+ insertNode(node, marks) {
3466
+ let innerMarks = this.findPlace(node.tag, marks, false);
3467
+ if (innerMarks) {
3468
+ let top = this.top;
3469
+ for (let p of innerMarks)
3470
+ if (this.schema.markAllowed(p.type, node.type))
3471
+ node = node.withMarks(p.addToSet(node.marks));
3472
+ for (let p of node.tag.marks)
3473
+ node = node.withMarks(p.addToSet(node.marks));
3474
+ node.pushTo(top.children);
3475
+ return true;
3476
+ }
3477
+ return false;
3478
+ }
3479
+ findPlace(tag, marks, endOfSlice) {
3480
+ let route, under;
3481
+ for (let cx = this.top;; cx = cx.parent) {
3482
+ let found = this.schema.findWrapping(cx.tag.type, tag.type);
3483
+ if (found && (!route || route.length > found.length)) {
3484
+ route = found;
3485
+ under = cx;
3486
+ if (!found.length)
3487
+ break;
3488
+ }
3489
+ if (cx.flags & 4)
3490
+ break;
3491
+ }
3492
+ if (!route)
3493
+ return null;
3494
+ this.sync(under);
3495
+ for (let i = 0; i < route.length; i++)
3496
+ marks = this.enterInner(route[i], marks, endOfSlice, null);
3497
+ return marks;
3498
+ }
3499
+ enter(tag, marks, endOfSlice, elt) {
3500
+ let innerMarks = this.findPlace(tag, marks, endOfSlice);
3501
+ if (innerMarks)
3502
+ innerMarks = this.enterInner(tag, marks, endOfSlice, elt);
3503
+ return innerMarks;
3504
+ }
3505
+ enterInner(tag, marks, endOfSlice, element) {
3506
+ marks = marks.filter(p => {
3507
+ if (!this.schema.markAllowed(p.type, tag.type))
3508
+ return true;
3509
+ tag = tag.withMarks(p.addToSet(tag.marks));
3510
+ return false;
3511
+ });
3512
+ let test, open = (this.top.children.length ? 0 : this.top.flags & 1) |
3513
+ (endOfSlice ? this.top.flags & 2 : 0);
3514
+ if ((open && element && this.options.isOpen) && (test = this.options.isOpen(element))) {
3515
+ open &= -4;
3516
+ if (test == "start")
3517
+ open |= 1;
3518
+ else if (test == "end")
3519
+ open |= 2;
3520
+ else if (test == "start end")
3521
+ open |= 1 | 2;
3522
+ }
3523
+ this.top = new NodeContext(tag, (element ? 4 : 0) | open, this.top);
3524
+ return marks;
3525
+ }
3526
+ sync(to) {
3527
+ if (!this.top.isIn(to))
3528
+ return false;
3529
+ while (this.top != to)
3530
+ this.close();
3531
+ return true;
3532
+ }
3533
+ close() {
3534
+ let parent = this.top.parent;
3535
+ parent.children.push(this.finishNode(this.top));
3536
+ this.top = parent;
3537
+ }
3538
+ finishNode(cx) {
3539
+ if (!(cx.flags & 2) && cx.children.length && !cx.tag.type.preserveWhitespace &&
3540
+ this.options.collapseWhiteSpace !== false) {
3541
+ let last = cx.children[cx.children.length - 1].tag, m;
3542
+ if (last.is(Leaf.Text) && (m = /[ \t\r\n\u000c]+$/.exec(last.param))) {
3543
+ let len = last.length - m[0].length;
3544
+ if (!len)
3545
+ cx.children.pop();
3546
+ else
3547
+ cx.children[cx.children.length - 1] = last.sliceText(0, len);
3548
+ }
3549
+ }
3550
+ let open = cx.flags & (2 | 1);
3551
+ if (!open && !cx.tag.type.canBeEmpty && cx.tag.isPlot && !cx.children.length)
3552
+ cx.children.push(this.schema.createDefault(cx.tag.type));
3553
+ let node = cx.tag.isDoc ? this.schema.doc(cx.children) : cx.tag.create(cx.children);
3554
+ if (open)
3555
+ this.open.set(node, open);
3556
+ return node;
3557
+ }
3558
+ }
3559
+ class NodeContext {
3560
+ tag;
3561
+ flags;
3562
+ parent;
3563
+ children = [];
3564
+ constructor(tag, flags, parent) {
3565
+ this.tag = tag;
3566
+ this.flags = flags;
3567
+ this.parent = parent;
3568
+ }
3569
+ isIn(parent) {
3570
+ for (let cx = this; cx; cx = cx.parent)
3571
+ if (cx == parent)
3572
+ return true;
3573
+ return false;
3574
+ }
3575
+ }
3576
+ function normalizeList(dom) {
3577
+ for (let child = dom.firstChild, prevItem = null; child; child = child.nextSibling) {
3578
+ if (child.nodeType != 1)
3579
+ continue;
3580
+ let name = child.nodeName.toLowerCase();
3581
+ if (prevItem && (name == "ol" || name == "ul")) {
3582
+ prevItem.appendChild(child);
3583
+ child = prevItem;
3584
+ }
3585
+ else {
3586
+ prevItem = name == "li" ? child : null;
3587
+ }
3588
+ }
3589
+ }
3590
+ const normalizers = { ol: normalizeList, ul: normalizeList };
3591
+ const ignoreTags = /*@__PURE__*/(() => new Set(["head", "noscript", "object", "script", "style", "title"]))();
3592
+ const blockTags = /*@__PURE__*/(() => new Set(["address", "article", "aside", "blockquote", "canvas", "dd", "div", "dl",
3593
+ "fieldset", "figcaption", "figure", "footer", "form", "h1", "h2", "h3", "h4", "h5",
3594
+ "h6", "header", "hgroup", "hr", "li", "noscript", "ol", "output", "p", "pre",
3595
+ "section", "table", "tfoot", "ul"]))();
3596
+ function guessParent(content, schema) {
3597
+ let rules = parse.Rule.Set.fromSchema(schema);
3598
+ let tags = [], blocks = 0;
3599
+ let explore = (node) => {
3600
+ if (node.nodeType == 3) {
3601
+ tags.push(Leaf.Text);
3602
+ }
3603
+ else if (node.nodeType == 1) {
3604
+ if (blockTags.has(node.nodeName.toLowerCase()))
3605
+ blocks++;
3606
+ let match = rules.matchElement(node);
3607
+ if (match && match.rule.tag) {
3608
+ tags.push(Node.Type.get(match.rule.tag));
3609
+ }
3610
+ else if (!(match && match.rule.ignore)) {
3611
+ for (let ch = node.firstChild; ch; ch = ch.nextSibling)
3612
+ explore(ch);
3613
+ }
3614
+ }
3615
+ };
3616
+ explore(content);
3617
+ let best, bestCost = 0;
3618
+ for (let parent of schema.nodes)
3619
+ if (parent.isPlot && parent.default) {
3620
+ let cost = parent.isDoc ? -1 : 0;
3621
+ if (blocks > 1 && parent.inlineContent)
3622
+ cost += 5;
3623
+ for (let child of tags) {
3624
+ let fit = schema.findWrapping(parent, child);
3625
+ cost += fit ? fit.length * 2 : 1000;
3626
+ }
3627
+ if (!best || bestCost > cost) {
3628
+ best = parent.default;
3629
+ bestCost = cost;
3630
+ }
3631
+ }
3632
+ return best;
3633
+ }
3634
+
3635
+ class SerializeContext {
3636
+ openAttr;
3637
+ emitNewlines;
3638
+ override;
3639
+ constructor(options, openAttr) {
3640
+ this.openAttr = openAttr;
3641
+ this.emitNewlines = options.emitNewlines !== false;
3642
+ this.override = options.override;
3643
+ }
3644
+ }
3645
+ function serialize(doc, options = {}) {
3646
+ return Elt.Fragment.create(serializeChildren(doc.content, new SerializeContext(options)));
3647
+ }
3648
+ ;serialize = /*@__PURE__*/(function (serialize) {
3649
+ function node(node, options) {
3650
+ return serializeChildren([node], new SerializeContext(options))[0];
3651
+ }
3652
+ serialize.node = node;
3653
+ function slice(slice, options) {
3654
+ return Elt.Fragment.create(serializeChildren(flattenSlice(slice.content, options.context || [], options.includeContext || 0, !!options.openAttr), new SerializeContext(options, options.openAttr)));
3655
+ }
3656
+ serialize.slice = slice;
3657
+ ;return serialize})(serialize);
3658
+ const genericTag = /*@__PURE__*/(() => Plot.define("generic", {
3659
+ blockContent: Node.Group.All,
3660
+ shape: { element: "div" }
3661
+ }))();
3662
+ const openMark = /*@__PURE__*/(() => Mark.Type.define("Open", {
3663
+ shape: { attribute: "wg-open", value: 0 },
3664
+ target: Node.Group.All
3665
+ }))();
3666
+ function flattenSlice(content, context, includeContext, markOpen) {
3667
+ let depth = 0, i = 0, scan = (inner) => {
3668
+ let result = [];
3669
+ for (; i < content.length;) {
3670
+ let tok = content[i++];
3671
+ if (tok.tokenType == Token.Type.Close) {
3672
+ if (inner)
3673
+ break;
3674
+ let tag = depth < context.length ? context[depth++] : genericTag;
3675
+ if (markOpen)
3676
+ tag = tag.withMarks(openMark.of("start").addToSet(tag.marks));
3677
+ result = [tag.create(result)];
3678
+ }
3679
+ else if (tok.tokenType == Token.Type.Open) {
3680
+ let content = scan(true), tag = tok;
3681
+ if (markOpen)
3682
+ tag = tag.withMarks(openMark.of("end").addToSet(tag.marks));
3683
+ result.push(tag.create(content));
3684
+ }
3685
+ else {
3686
+ result.push(tok);
3687
+ }
3688
+ }
3689
+ return result;
3690
+ };
3691
+ let result = scan(false);
3692
+ while (depth < includeContext && depth < context.length) {
3693
+ let tag = context[depth++];
3694
+ if (markOpen)
3695
+ tag = tag.withMarks(openMark.of("start end").addToSet(tag.marks));
3696
+ result = [tag.create(result)];
3697
+ }
3698
+ return result;
3699
+ }
3700
+ function serializeNodeInner(node, cx) {
3701
+ let markAttrs = Attributes.none, targeted;
3702
+ for (let mark of node.tag.marks)
3703
+ if (mark.type.attribute) {
3704
+ if (mark.type == openMark) {
3705
+ markAttrs = Attributes.merge(markAttrs, [cx.openAttr, mark.value]);
3706
+ }
3707
+ else {
3708
+ let { target, get } = mark.type.attribute, attrs = get(mark.value);
3709
+ if (target && !node.isText) {
3710
+ (targeted || (targeted = [])).push({ attrs, target });
3711
+ }
3712
+ else if (!node.isText || mark.spanning) {
3713
+ markAttrs = Attributes.merge(markAttrs, attrs);
3714
+ }
3715
+ }
3716
+ }
3717
+ if (node.is(Leaf.Text))
3718
+ return markAttrs.length ? Elt.create("span", markAttrs, [node.param]) : node.param;
3719
+ let children;
3720
+ if (node.isLeaf) {
3721
+ children = [];
3722
+ }
3723
+ else {
3724
+ let { content } = node;
3725
+ if (cx.emitNewlines && node.type.preserveWhitespace)
3726
+ content = lineBreaksToNewlines(content);
3727
+ children = serializeChildren(content, cx);
3728
+ }
3729
+ let elt = (cx.override && cx.override(node.tag)) || node.type.shape.create(node.tag.param);
3730
+ if (markAttrs.length)
3731
+ elt = elt.addAttrs(markAttrs);
3732
+ if (targeted)
3733
+ for (let { attrs, target } of targeted)
3734
+ elt = elt.addAttrs(attrs, target);
3735
+ return elt.hasContent ? withContent(elt, children) : elt;
3736
+ }
3737
+ function withContent(elt, content) {
3738
+ let children = [];
3739
+ for (let ch of elt.children) {
3740
+ if (ch === 0)
3741
+ for (let inner of content)
3742
+ children.push(inner);
3743
+ else if (typeof ch == "string")
3744
+ children.push(ch);
3745
+ else
3746
+ children.push(withContent(ch, content));
3747
+ }
3748
+ return Elt.create(elt.tagName, elt.attrs, children);
3749
+ }
3750
+ function lineBreaksToNewlines(nodes) {
3751
+ if (!nodes.some(n => n.type.hasRole(Node.Role.LineBreak)))
3752
+ return nodes;
3753
+ let result = [], lastText = false;
3754
+ for (let node of nodes) {
3755
+ let next = node.type.hasRole(Node.Role.LineBreak) ? Leaf.text("\n", node.marks) : node;
3756
+ if (lastText && next instanceof Plot)
3757
+ next.pushTo(result);
3758
+ else
3759
+ result.push(next);
3760
+ lastText = next.isText;
3761
+ }
3762
+ return result;
3763
+ }
3764
+ class EltCx {
3765
+ tagName;
3766
+ attrs;
3767
+ parent;
3768
+ children = [];
3769
+ constructor(tagName, attrs, parent) {
3770
+ this.tagName = tagName;
3771
+ this.attrs = attrs;
3772
+ this.parent = parent;
3773
+ }
3774
+ pop() {
3775
+ let repr = Elt.create(this.tagName, this.attrs, this.children);
3776
+ let parent = this.parent;
3777
+ parent.children.push(repr);
3778
+ return parent;
3779
+ }
3780
+ }
3781
+ function serializeChildren(children, cx) {
3782
+ let active = [], top = new EltCx("", Attributes.none, null);
3783
+ for (let child of children) {
3784
+ if (active.length || child.marks.some(p => p.type.element)) {
3785
+ let keep = 0, rendered = 0, eltMarks = [];
3786
+ for (let mark of child.marks)
3787
+ if (mark.type.element)
3788
+ eltMarks.push(mark);
3789
+ while (keep < active.length && rendered < eltMarks.length) {
3790
+ let next = eltMarks[rendered];
3791
+ if (!next.eq(active[keep]) || !next.type.spanning)
3792
+ break;
3793
+ keep++;
3794
+ rendered++;
3795
+ }
3796
+ while (keep < active.length) {
3797
+ top = top.pop();
3798
+ active.pop();
3799
+ }
3800
+ while (rendered < eltMarks.length) {
3801
+ let add = eltMarks[rendered++];
3802
+ let repr = add.type.element;
3803
+ top = new EltCx(repr.name, repr.attrs(add.value), top);
3804
+ active.push(add);
3805
+ }
3806
+ }
3807
+ top.children.push(serializeNodeInner(child, cx));
3808
+ }
3809
+ for (let i = 0; i < active.length; i++)
3810
+ top = top.pop();
3811
+ return top.children;
3812
+ }
3813
+
3814
+ export { Attributes, ChangeSet, Elt, Leaf, Mark, Node, Plot, Pos, Schema, SchemaError, Slice, Token, ValidationError, parse, serialize };