@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/state.js ADDED
@@ -0,0 +1,2024 @@
1
+ import { Leaf, ValidationError, Pos, ChangeSet, Plot, SchemaError, parse, Schema } from 'wordgard/doc';
2
+ import { findClusterBreak } from '@marijn/find-cluster-break';
3
+
4
+ function dec(str) {
5
+ let result = [];
6
+ for (let i = 0; i < str.length; i++)
7
+ result.push(1 << +str[i]);
8
+ return result;
9
+ }
10
+ const LowTypes = /*@__PURE__*/dec("88888888888888888888888888888888888666888888787833333333337888888000000000000000000000000008888880000000000000000000000000088888888888888888888888888888888888887866668888088888663380888308888800000000000000000000000800000000000000000000000000000008");
11
+ const ArabicTypes = /*@__PURE__*/dec("4444448826627288999999999992222222222222222222222222222222222222222222222229999999999999999999994444444444644222822222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222999999949999999229989999223333333333");
12
+ const Brackets = /*@__PURE__*/(() => {
13
+ let result = Object.create(null);
14
+ for (let p of ["()", "[]", "{}"]) {
15
+ let l = p.charCodeAt(0), r = p.charCodeAt(1);
16
+ result[l] = r;
17
+ result[r] = -l;
18
+ }
19
+ return result;
20
+ })();
21
+ const BracketStack = [];
22
+ function charType(ch) {
23
+ return ch <= 0xf7 ? LowTypes[ch] :
24
+ 0x590 <= ch && ch <= 0x5f4 ? 2 :
25
+ 0x600 <= ch && ch <= 0x6f9 ? ArabicTypes[ch - 0x600] :
26
+ 0x6ee <= ch && ch <= 0x8ac ? 4 :
27
+ 0x2000 <= ch && ch <= 0x200c ? 256 :
28
+ 0xfb50 <= ch && ch <= 0xfdff ? 4 :
29
+ ch == 0xfffc ? 256 : 1;
30
+ }
31
+ const BidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac\ufb50-\ufdff]/;
32
+ class BidiSpan {
33
+ from;
34
+ to;
35
+ level;
36
+ get ltr() { return (this.level % 2) == 0; }
37
+ constructor(
38
+ from,
39
+ to,
40
+ level) {
41
+ this.from = from;
42
+ this.to = to;
43
+ this.level = level;
44
+ }
45
+ side(end, ltr) { return (this.ltr == ltr) == end ? this.to : this.from; }
46
+ forward(forward, ltr) { return forward == (this.ltr == ltr); }
47
+ static find(order, index, assoc) {
48
+ let maybe = -1;
49
+ for (let i = 0; i < order.length; i++) {
50
+ let span = order[i];
51
+ if (span.from <= index && span.to >= index &&
52
+ (maybe < 0 || (assoc != 0 ? (assoc < 0 ? span.from < index : span.to > index) : order[maybe].level > span.level)))
53
+ maybe = i;
54
+ }
55
+ if (maybe < 0)
56
+ throw new RangeError("Index out of range");
57
+ return maybe;
58
+ }
59
+ static strongDir(ch) {
60
+ let type = charType(ch);
61
+ if (type == 1)
62
+ return true;
63
+ if (type == 2 || type == 4)
64
+ return false;
65
+ return null;
66
+ }
67
+ }
68
+ const types = [];
69
+ function computeCharTypes(line, rFrom, rTo, isolates, outerType) {
70
+ for (let iI = 0; iI <= isolates.length; iI++) {
71
+ let from = iI ? isolates[iI - 1].to : rFrom, to = iI < isolates.length ? isolates[iI].from : rTo;
72
+ let prevType = iI ? 256 : outerType;
73
+ for (let i = from, prev = prevType, prevStrong = prevType; i < to; i++) {
74
+ let type = charType(line.charCodeAt(i));
75
+ if (type == 512)
76
+ type = prev;
77
+ else if (type == 8 && prevStrong == 4)
78
+ type = 16;
79
+ types[i] = type == 4 ? 2 : type;
80
+ if (type & 7)
81
+ prevStrong = type;
82
+ prev = type;
83
+ }
84
+ for (let i = from, prev = prevType, prevStrong = prevType; i < to; i++) {
85
+ let type = types[i];
86
+ if (type == 128) {
87
+ if (i < to - 1 && prev == types[i + 1] && (prev & 24))
88
+ type = types[i] = prev;
89
+ else
90
+ types[i] = 256;
91
+ }
92
+ else if (type == 64) {
93
+ let end = i + 1;
94
+ while (end < to && types[end] == 64)
95
+ end++;
96
+ let replace = (i && prev == 8) || (end < rTo && types[end] == 8) ? (prevStrong == 1 ? 1 : 8) : 256;
97
+ for (let j = i; j < end; j++)
98
+ types[j] = replace;
99
+ i = end - 1;
100
+ }
101
+ else if (type == 8 && prevStrong == 1) {
102
+ types[i] = 1;
103
+ }
104
+ prev = type;
105
+ if (type & 7)
106
+ prevStrong = type;
107
+ }
108
+ }
109
+ }
110
+ function processBracketPairs(line, rFrom, rTo, isolates, outerType) {
111
+ let oppositeType = outerType == 1 ? 2 : 1;
112
+ for (let iI = 0, sI = 0, context = 0; iI <= isolates.length; iI++) {
113
+ let from = iI ? isolates[iI - 1].to : rFrom, to = iI < isolates.length ? isolates[iI].from : rTo;
114
+ for (let i = from, ch, br, type; i < to; i++) {
115
+ if (br = Brackets[ch = line.charCodeAt(i)]) {
116
+ if (br < 0) { for (let sJ = sI - 3; sJ >= 0; sJ -= 3) {
117
+ if (BracketStack[sJ + 1] == -br) {
118
+ let flags = BracketStack[sJ + 2];
119
+ let type = (flags & 2) ? outerType :
120
+ !(flags & 4) ? 0 :
121
+ (flags & 1) ? oppositeType : outerType;
122
+ if (type)
123
+ types[i] = types[BracketStack[sJ]] = type;
124
+ sI = sJ;
125
+ break;
126
+ }
127
+ }
128
+ }
129
+ else if (BracketStack.length == 189) {
130
+ break;
131
+ }
132
+ else {
133
+ BracketStack[sI++] = i;
134
+ BracketStack[sI++] = ch;
135
+ BracketStack[sI++] = context;
136
+ }
137
+ }
138
+ else if ((type = types[i]) == 2 || type == 1) {
139
+ let embed = type == outerType;
140
+ context = embed ? 0 : 1;
141
+ for (let sJ = sI - 3; sJ >= 0; sJ -= 3) {
142
+ let cur = BracketStack[sJ + 2];
143
+ if (cur & 2)
144
+ break;
145
+ if (embed) {
146
+ BracketStack[sJ + 2] |= 2;
147
+ }
148
+ else {
149
+ if (cur & 4)
150
+ break;
151
+ BracketStack[sJ + 2] |= 4;
152
+ }
153
+ }
154
+ }
155
+ }
156
+ }
157
+ }
158
+ function processNeutrals(rFrom, rTo, isolates, outerType) {
159
+ for (let iI = 0, prev = outerType; iI <= isolates.length; iI++) {
160
+ let from = iI ? isolates[iI - 1].to : rFrom, to = iI < isolates.length ? isolates[iI].from : rTo;
161
+ for (let i = from; i < to;) {
162
+ let type = types[i];
163
+ if (type == 256) {
164
+ let end = i + 1;
165
+ for (;;) {
166
+ if (end == to) {
167
+ if (iI == isolates.length)
168
+ break;
169
+ end = isolates[iI++].to;
170
+ to = iI < isolates.length ? isolates[iI].from : rTo;
171
+ }
172
+ else if (types[end] == 256) {
173
+ end++;
174
+ }
175
+ else {
176
+ break;
177
+ }
178
+ }
179
+ let beforeL = prev == 1;
180
+ let afterL = (end < rTo ? types[end] : outerType) == 1;
181
+ let replace = beforeL == afterL ? (beforeL ? 1 : 2) : outerType;
182
+ for (let j = end, jI = iI, fromJ = jI ? isolates[jI - 1].to : rFrom; j > i;) {
183
+ if (j == fromJ) {
184
+ j = isolates[--jI].from;
185
+ fromJ = jI ? isolates[jI - 1].to : rFrom;
186
+ }
187
+ types[--j] = replace;
188
+ }
189
+ i = end;
190
+ }
191
+ else {
192
+ prev = type;
193
+ i++;
194
+ }
195
+ }
196
+ }
197
+ }
198
+ function emitSpans(line, from, to, level, baseLevel, isolates, order) {
199
+ let ourType = level % 2 ? 2 : 1;
200
+ if ((level % 2) == (baseLevel % 2)) { for (let iCh = from, iI = 0; iCh < to;) {
201
+ let sameDir = true, isNum = false;
202
+ if (iI == isolates.length || iCh < isolates[iI].from) {
203
+ let next = types[iCh];
204
+ if (next != ourType) {
205
+ sameDir = false;
206
+ isNum = next == 16;
207
+ }
208
+ }
209
+ let recurse = !sameDir && ourType == 1 ? [] : null;
210
+ let localLevel = sameDir ? level : level + 1;
211
+ let iScan = iCh;
212
+ run: for (;;) {
213
+ if (iI < isolates.length && iScan == isolates[iI].from) {
214
+ if (isNum)
215
+ break run;
216
+ let iso = isolates[iI];
217
+ if (!sameDir)
218
+ for (let upto = iso.to, jI = iI + 1;;) {
219
+ if (upto == to)
220
+ break run;
221
+ if (jI < isolates.length && isolates[jI].from == upto)
222
+ upto = isolates[jI++].to;
223
+ else if (types[upto] == ourType)
224
+ break run;
225
+ else
226
+ break;
227
+ }
228
+ iI++;
229
+ if (recurse) {
230
+ recurse.push(iso);
231
+ }
232
+ else {
233
+ if (iso.from > iCh)
234
+ order.push(new BidiSpan(iCh, iso.from, localLevel));
235
+ let dirSwap = iso.ltr != !(localLevel % 2);
236
+ computeSectionOrder(line, dirSwap ? level + 1 : level, baseLevel, iso.inner, iso.from, iso.to, order);
237
+ iCh = iso.to;
238
+ }
239
+ iScan = iso.to;
240
+ }
241
+ else if (iScan == to || (sameDir ? types[iScan] != ourType : types[iScan] == ourType)) {
242
+ break;
243
+ }
244
+ else {
245
+ iScan++;
246
+ }
247
+ }
248
+ if (recurse)
249
+ emitSpans(line, iCh, iScan, level + 1, baseLevel, recurse, order);
250
+ else if (iCh < iScan)
251
+ order.push(new BidiSpan(iCh, iScan, localLevel));
252
+ iCh = iScan;
253
+ }
254
+ }
255
+ else {
256
+ for (let iCh = to, iI = isolates.length; iCh > from;) {
257
+ let sameDir = true, isNum = false;
258
+ if (!iI || iCh > isolates[iI - 1].to) {
259
+ let next = types[iCh - 1];
260
+ if (next != ourType) {
261
+ sameDir = false;
262
+ isNum = next == 16;
263
+ }
264
+ }
265
+ let recurse = !sameDir && ourType == 1 ? [] : null;
266
+ let localLevel = sameDir ? level : level + 1;
267
+ let iScan = iCh;
268
+ run: for (;;) {
269
+ if (iI && iScan == isolates[iI - 1].to) {
270
+ if (isNum)
271
+ break run;
272
+ let iso = isolates[--iI];
273
+ if (!sameDir)
274
+ for (let upto = iso.from, jI = iI;;) {
275
+ if (upto == from)
276
+ break run;
277
+ if (jI && isolates[jI - 1].to == upto)
278
+ upto = isolates[--jI].from;
279
+ else if (types[upto - 1] == ourType)
280
+ break run;
281
+ else
282
+ break;
283
+ }
284
+ if (recurse) {
285
+ recurse.push(iso);
286
+ }
287
+ else {
288
+ if (iso.to < iCh)
289
+ order.push(new BidiSpan(iso.to, iCh, localLevel));
290
+ let dirSwap = iso.ltr != !(localLevel % 2);
291
+ computeSectionOrder(line, dirSwap ? level + 1 : level, baseLevel, iso.inner, iso.from, iso.to, order);
292
+ iCh = iso.from;
293
+ }
294
+ iScan = iso.from;
295
+ }
296
+ else if (iScan == from || (sameDir ? types[iScan - 1] != ourType : types[iScan - 1] == ourType)) {
297
+ break;
298
+ }
299
+ else {
300
+ iScan--;
301
+ }
302
+ }
303
+ if (recurse)
304
+ emitSpans(line, iScan, iCh, level + 1, baseLevel, recurse, order);
305
+ else if (iScan < iCh)
306
+ order.push(new BidiSpan(iScan, iCh, localLevel));
307
+ iCh = iScan;
308
+ }
309
+ }
310
+ }
311
+ function computeSectionOrder(line, level, baseLevel, isolates, from, to, order) {
312
+ let outerType = (level % 2 ? 2 : 1);
313
+ computeCharTypes(line, from, to, isolates, outerType);
314
+ processBracketPairs(line, from, to, isolates, outerType);
315
+ processNeutrals(from, to, isolates, outerType);
316
+ emitSpans(line, from, to, level, baseLevel, isolates, order);
317
+ }
318
+ function computeOrder(line, ltr, isolates) {
319
+ if (!line)
320
+ return [new BidiSpan(0, 0, ltr ? 0 : 1)];
321
+ if (ltr && !isolates.length && !BidiRE.test(line))
322
+ return trivialOrder(line.length);
323
+ if (isolates.length)
324
+ while (line.length > types.length)
325
+ types[types.length] = 256; let order = [], level = ltr ? 0 : 1;
326
+ computeSectionOrder(line, level, level, isolates, 0, line.length, order);
327
+ return order;
328
+ }
329
+ function trivialOrder(length) {
330
+ return [new BidiSpan(0, length, 0)];
331
+ }
332
+
333
+ const cache = /*@__PURE__*/(() => new WeakMap)();
334
+ class TextblockMap {
335
+ start;
336
+ node;
337
+ ltr;
338
+ text;
339
+ _order;
340
+ config;
341
+ sections;
342
+ constructor(
343
+ start,
344
+ node,
345
+ ltr,
346
+ text, _order, config,
347
+ sections) {
348
+ this.start = start;
349
+ this.node = node;
350
+ this.ltr = ltr;
351
+ this.text = text;
352
+ this._order = _order;
353
+ this.config = config;
354
+ this.sections = sections;
355
+ }
356
+ get order() {
357
+ return this._order || (this._order = computeOrder(this.text, this.ltr, []));
358
+ }
359
+ static get(cx, start, node) {
360
+ let cached = cache.get(node);
361
+ if (cached && cached.config == cx.config)
362
+ return cached.start == start ? cached
363
+ : new TextblockMap(start, node, cached.ltr, cached.text, cached._order, cx.config, cached.sections);
364
+ let result = TextblockMap.create(start, node, cx.config);
365
+ cache.set(node, result);
366
+ return result;
367
+ }
368
+ static create(start, node, config) {
369
+ let text = "", sections = [], sectionPos = 0;
370
+ let flush = (upto) => {
371
+ if (upto > sectionPos)
372
+ sections.push((upto - sectionPos) << 2);
373
+ };
374
+ let scan = (node, pos) => {
375
+ for (let ch of node.content) {
376
+ if (ch.is(Leaf.Text)) {
377
+ text += ch.param;
378
+ }
379
+ else if (ch.isLeaf || config.isAtom(ch.type)) {
380
+ text += "\ufffc";
381
+ if (ch.length > 1) {
382
+ flush(pos);
383
+ sections.push((ch.length << 2) | 1);
384
+ sectionPos = pos + ch.length;
385
+ }
386
+ }
387
+ else if (ch.type.spec.cursorInsideBounds) {
388
+ text += " ";
389
+ scan(ch, pos + 1);
390
+ text += " ";
391
+ }
392
+ else {
393
+ flush(pos);
394
+ sections.push((1 << 2) | 3);
395
+ scan(ch, sectionPos = pos + 1);
396
+ flush(pos + ch.length - 1);
397
+ sections.push((1 << 2) | 2);
398
+ sectionPos = pos + ch.length;
399
+ }
400
+ pos += ch.length;
401
+ }
402
+ };
403
+ scan(node, 0);
404
+ flush(node.contentLength);
405
+ return new TextblockMap(start, node, config.textblockLTR(node), text, null, config, sections);
406
+ }
407
+ toIndex(pos) {
408
+ if (pos < this.start)
409
+ return 0;
410
+ let off = pos - this.start, idx = 0;
411
+ for (let n of this.sections) {
412
+ let len = n >> 2, flag = n & 3;
413
+ if (flag == 0) {
414
+ if (off <= len)
415
+ return idx + off;
416
+ off -= len;
417
+ idx += len;
418
+ }
419
+ else if (flag == 1) {
420
+ off = Math.max(0, off - len);
421
+ if (off < 0)
422
+ return idx;
423
+ idx++;
424
+ }
425
+ else {
426
+ if (off > 0)
427
+ off--;
428
+ }
429
+ }
430
+ return idx;
431
+ }
432
+ fromIndex(index) {
433
+ let off = this.start;
434
+ for (let n of this.sections) {
435
+ let len = n >> 2, flag = n & 3;
436
+ if (flag == 0) {
437
+ if (len > index)
438
+ return off + index;
439
+ index -= len;
440
+ }
441
+ else if (flag == 1) {
442
+ if (!index)
443
+ return off;
444
+ index--;
445
+ }
446
+ else {
447
+ if (!index)
448
+ return off + (flag == 2 ? 1 : 0);
449
+ }
450
+ off += len;
451
+ }
452
+ return off;
453
+ }
454
+ moveVisually(start, side, forward, skipped) {
455
+ let startIndex = this.toIndex(start), { order, ltr } = this;
456
+ let spanI = BidiSpan.find(order, startIndex, side);
457
+ let span = order[spanI], spanEnd = span.side(forward, ltr);
458
+ if (startIndex == spanEnd) {
459
+ let nextI = spanI += forward ? 1 : -1;
460
+ if (nextI < 0 || nextI >= order.length)
461
+ return null;
462
+ span = order[spanI = nextI];
463
+ startIndex = span.side(!forward, ltr);
464
+ spanEnd = span.side(forward, ltr);
465
+ }
466
+ let nextIndex = findClusterBreak(this.text, startIndex, span.forward(forward, ltr));
467
+ if (nextIndex == startIndex)
468
+ return null;
469
+ if (nextIndex < span.from || nextIndex > span.to)
470
+ nextIndex = spanEnd;
471
+ if (skipped)
472
+ skipped[0] = this.text.slice(Math.min(startIndex, nextIndex), Math.max(startIndex, nextIndex));
473
+ let nextSpan = spanI == (forward ? order.length - 1 : 0) ? null : order[spanI + (forward ? 1 : -1)];
474
+ if (nextSpan && nextIndex == spanEnd && nextSpan.level + (forward ? 0 : 1) < span.level)
475
+ return { pos: this.fromIndex(nextSpan.side(!forward, ltr)), side: nextSpan.forward(forward, ltr) ? 1 : -1 };
476
+ return { pos: this.fromIndex(nextIndex), side: nextIndex != spanEnd ? 1 : span.forward(forward, ltr) ? -1 : 1 };
477
+ }
478
+ skipWord(start, side, forward, visually) {
479
+ let word = "", skipped = [""], cur = null;
480
+ let history = new Map();
481
+ for (;;) {
482
+ let next, char, from = cur ? cur.pos : start;
483
+ if (visually) {
484
+ next = this.moveVisually(from, cur ? cur.side : side, forward, skipped);
485
+ char = skipped[0];
486
+ }
487
+ else {
488
+ next = this.moveLogically(from, forward);
489
+ char = next ? this.text.slice(Math.min(next.pos, from), Math.max(next.pos, from)) : "";
490
+ }
491
+ if (!next)
492
+ break;
493
+ if (/\p{L}|\p{N}/u.test(char)) {
494
+ if (forward)
495
+ word += char;
496
+ else
497
+ word = skipped[0] + word;
498
+ history.set(word.length, next);
499
+ }
500
+ else if (word) {
501
+ break;
502
+ }
503
+ cur = next;
504
+ }
505
+ if (!word)
506
+ return null;
507
+ if (!Intl.Segmenter)
508
+ return cur; let segments = [...new Intl.Segmenter(undefined, { granularity: "word" }).segment(word)];
509
+ return history.get(segments[forward ? 0 : segments.length - 1].segment.length) || cur;
510
+ }
511
+ visualSide(start) {
512
+ let pos, side;
513
+ if (start) {
514
+ let span = this.order[0];
515
+ [pos, side] = span.ltr == this.ltr ? [span.from, 1] : [span.to, -1];
516
+ }
517
+ else {
518
+ let span = this.order[this.order.length - 1];
519
+ [pos, side] = span.ltr == this.ltr ? [span.to, -1] : [span.from, 1];
520
+ }
521
+ return { pos: this.fromIndex(pos), side };
522
+ }
523
+ moveLogically(start, forward) {
524
+ let index = this.toIndex(start);
525
+ let next = findClusterBreak(this.text, index, forward);
526
+ return next == index ? null : { pos: this.fromIndex(next), side: 1 };
527
+ }
528
+ }
529
+
530
+ class SelectionType {
531
+ tag;
532
+ cls;
533
+ toJSON;
534
+ fromJSON;
535
+ constructor(tag, cls, toJSON, fromJSON) {
536
+ this.tag = tag;
537
+ this.cls = cls;
538
+ this.toJSON = toJSON;
539
+ this.fromJSON = fromJSON;
540
+ }
541
+ }
542
+ class GardSelection {
543
+ anchor;
544
+ head;
545
+ goalColumn;
546
+ constructor(
547
+ anchor,
548
+ head,
549
+ goalColumn) {
550
+ this.anchor = anchor;
551
+ this.head = head;
552
+ this.goalColumn = goalColumn;
553
+ }
554
+ get from() { return Math.min(this.anchor, this.head); }
555
+ get to() { return Math.max(this.anchor, this.head); }
556
+ get empty() { return this.anchor == this.head; }
557
+ get isCursor() { return this.empty && this instanceof GardSelection.Text; }
558
+ get ranges() { return [this]; }
559
+ get replacementRange() { return this; }
560
+ get domSelection() { return this; }
561
+ get headSide() { return this.head > this.anchor ? -1 : 1; }
562
+ get anchorSide() { return this.anchor > this.head ? -1 : 1; }
563
+ eqPos(other) {
564
+ return this.anchor == other.anchor && this.head == other.head;
565
+ }
566
+ check(config, doc) {
567
+ if (!config.staticFacet(GardSelection.selectionType).some(t => this instanceof t.cls))
568
+ throw new RangeError("Unsupported selection type");
569
+ for (let { from, to } of this.ranges)
570
+ if (from < 0 || to > doc.length)
571
+ throw new RangeError(`Selection out of document range`);
572
+ }
573
+ resolve(doc) { return GardSelection.Resolved.create(doc, this); }
574
+ toJSON(state) {
575
+ let type = state.facet(GardSelection.selectionType).find(tp => this instanceof tp.cls);
576
+ if (!type)
577
+ throw new Error("Selection type not enabled in state given to GardSelection.toJSON");
578
+ let result = type.toJSON(this);
579
+ result.type = type.tag;
580
+ return result;
581
+ }
582
+ static fromJSON(cx, json) {
583
+ let { doc, config } = cx, tag = json.type;
584
+ let types = config.staticFacet(GardSelection.selectionType);
585
+ let type = types.find(tp => tp.tag == tag);
586
+ if (!type)
587
+ throw new Error(`Unknown selection type '${tag}' in GardSelection.fromJSON`);
588
+ return type.fromJSON(doc, json);
589
+ }
590
+ static cursor(pos, side, goalColumn) {
591
+ return GardSelection.Text.createInner(pos, pos, side, goalColumn);
592
+ }
593
+ static range(anchor, head, headSide, goalColumn) {
594
+ return GardSelection.Text.createInner(anchor, head ?? anchor, headSide, goalColumn);
595
+ }
596
+ static node(pos, node, goalColumn) {
597
+ return GardSelection.Node.create(pos, node, goalColumn);
598
+ }
599
+ nextNormalCursor(cx, forward = true) {
600
+ let found = scanNormalFrom(cx, this.head, this.headSide, forward, true);
601
+ return found && GardSelection.cursor(found.pos, found.side);
602
+ }
603
+ normalCursorAtBound(cx, forward = true) {
604
+ let found = scanNormalFrom(cx, forward ? this.to : this.from, forward ? -1 : 1, forward, false);
605
+ return found && GardSelection.cursor(found.pos, found.side);
606
+ }
607
+ skipWord(cx, forward = true) {
608
+ let found = skipWord(cx, this.head, this.headSide, forward);
609
+ return found && GardSelection.cursor(found.pos, found.side);
610
+ }
611
+ static near(cx, pos, bias = 1) {
612
+ let norm = scanNormalFrom(cx, pos, bias, bias > 0, false) ??
613
+ scanNormalFrom(cx, pos, -bias, bias < 0, false) ??
614
+ { pos: pos, side: -1 };
615
+ return GardSelection.cursor(norm.pos, norm.side);
616
+ }
617
+ static atStart(cx, block) {
618
+ return cursorAtStart(cx, block);
619
+ }
620
+ static atEnd(cx, block) {
621
+ let found = block
622
+ ? TextblockMap.get(cx, block.start, block.node).visualSide(false)
623
+ : cx.doc.inlineContent ? TextblockMap.get(cx, 0, cx.doc).visualSide(false)
624
+ : scanNormalFrom(cx, cx.doc.length, -1, false, false) ?? { pos: cx.doc.length, side: -1 };
625
+ return GardSelection.cursor(found.pos, found.side);
626
+ }
627
+ }
628
+ ;GardSelection = /*@__PURE__*/(function (GardSelection) {
629
+ function define(tag, cls, toJSON, fromJSON) {
630
+ return GardSelection.selectionType.of(new SelectionType(tag, cls, toJSON, fromJSON));
631
+ }
632
+ GardSelection.define = define;
633
+ class Text extends GardSelection {
634
+ _headSide;
635
+ marks;
636
+ constructor(anchor, head, _headSide, goalColumn,
637
+ marks) {
638
+ super(anchor, head, goalColumn);
639
+ this._headSide = _headSide;
640
+ this.marks = marks;
641
+ }
642
+ static createInner(anchor, head, side, goalColumn, marks) {
643
+ return new Text(anchor, head, side ?? (head > anchor ? -1 : 1), goalColumn, marks);
644
+ }
645
+ get headSide() {
646
+ return this._headSide;
647
+ }
648
+ get anchorSide() {
649
+ return this.anchor == this.head ? this._headSide : super.anchorSide;
650
+ }
651
+ static create(spec) {
652
+ let { anchor, head = anchor } = spec;
653
+ return Text.createInner(anchor, head, spec.headSide, spec.goalColumn, spec.marks);
654
+ }
655
+ map(change, cx, assoc = -1) {
656
+ let from, to;
657
+ if (this.empty) {
658
+ from = to = change.mapPos(this.from, assoc);
659
+ }
660
+ else {
661
+ from = change.mapPos(this.from, 1);
662
+ to = Math.max(from, change.mapPos(this.to, -1));
663
+ }
664
+ return Text.createInner(from, to, this.headSide, this.goalColumn, this.marks);
665
+ }
666
+ eq(other) {
667
+ return other instanceof Text && this.eqPos(other) && this.headSide == other.headSide &&
668
+ (this.marks == other.marks || !!(this.marks && other.marks && this.marks.length == other.marks.length &&
669
+ this.marks.every((p, i) => p.eq(other.marks[i]))));
670
+ }
671
+ }
672
+ GardSelection.Text = Text;
673
+ (function (Text) {
674
+ Text.type = new SelectionType("text", Text, ((sel) => {
675
+ let result = { anchor: sel.anchor };
676
+ if (sel.headSide != (sel.head > sel.anchor ? -1 : 1))
677
+ result.side = sel.headSide;
678
+ if (!sel.empty)
679
+ result.head = sel.head;
680
+ if (sel.marks) {
681
+ result.marks = {};
682
+ for (let mark of sel.marks)
683
+ result.marks[mark.name] = mark.value;
684
+ }
685
+ return result;
686
+ }), ((doc, json) => {
687
+ if (!json || typeof json.anchor != "number")
688
+ throw new ValidationError("Invalid JSON representation for GardSelection.Text");
689
+ let anchor = json.anchor, head = typeof json.head == "number" ? json.head : anchor;
690
+ let marks = json.marks ? doc.schema.marksFromJSON(json.marks) : undefined;
691
+ return Text.createInner(anchor, head, json.side == 1 || json.side == -1 ? json.side : undefined, undefined, marks);
692
+ }));
693
+ })(Text = GardSelection.Text || (GardSelection.Text = {}));
694
+ class Node extends GardSelection {
695
+ node;
696
+ constructor(from, to,
697
+ node, goalColumn) {
698
+ super(from, to, goalColumn);
699
+ this.node = node;
700
+ }
701
+ static create(pos, node, goalColumn) {
702
+ return new Node(pos, pos + node.length, node, goalColumn);
703
+ }
704
+ map(change, cx, assoc = -1) {
705
+ let newPos = change.mapPos(this.anchor, 1, "after");
706
+ if (newPos == null)
707
+ return GardSelection.near(cx, change.mapPos(this.anchor, assoc), assoc);
708
+ return Node.create(newPos, cx.doc.nodeAt(newPos));
709
+ }
710
+ eq(other) {
711
+ return other instanceof Node && other.anchor == this.anchor;
712
+ }
713
+ }
714
+ GardSelection.Node = Node;
715
+ (function (Node) {
716
+ Node.type = new SelectionType("node", Node, (sel) => ({ pos: sel.anchor }), (doc, json) => {
717
+ let node = json && typeof json.pos == "number" && doc.nodeAt(json.pos);
718
+ if (!node || node.isText || !node.type.isSelectable)
719
+ throw new ValidationError("Invalid GardSelection.Node JSON representation");
720
+ return Node.create(json.pos, node);
721
+ });
722
+ })(Node = GardSelection.Node || (GardSelection.Node = {}));
723
+ class Resolved {
724
+ doc;
725
+ selection;
726
+ anchor;
727
+ head;
728
+ _ranges = null;
729
+ constructor(
730
+ doc,
731
+ selection) {
732
+ this.doc = doc;
733
+ this.selection = selection;
734
+ this.anchor = doc.resolve(selection.anchor);
735
+ this.head = selection.empty ? this.anchor : doc.resolve(selection.head);
736
+ }
737
+ static create(doc, selection) { return new Resolved(doc, selection); }
738
+ get from() { return this.anchor.pos < this.head.pos ? this.anchor : this.head; }
739
+ get to() { return this.anchor.pos > this.head.pos ? this.anchor : this.head; }
740
+ get ranges() {
741
+ return this._ranges || (this._ranges = this.resolveRanges());
742
+ }
743
+ resolveRanges() {
744
+ return this.selection.ranges.map(({ from, to }) => ({ from: this.doc.resolve(from), to: this.doc.resolve(to) }));
745
+ }
746
+ get replacementRange() {
747
+ let repl = this.selection.replacementRange;
748
+ if (repl.from == this.selection.from && repl.to == this.selection.to)
749
+ return this;
750
+ return { from: this.doc.resolve(repl.from), to: this.doc.resolve(repl.to) };
751
+ }
752
+ get activeMarks() {
753
+ let repl = this.replacementRange;
754
+ return (this.selection instanceof GardSelection.Text && this.selection.marks) || repl.from.marks(repl.to);
755
+ }
756
+ }
757
+ GardSelection.Resolved = Resolved;
758
+ ;return GardSelection})(GardSelection);
759
+ function cursorAtStart(cx, block) {
760
+ let found = block
761
+ ? TextblockMap.get(cx, block.start, block.node).visualSide(true)
762
+ : cx.doc.inlineContent ? TextblockMap.get(cx, 0, cx.doc).visualSide(true)
763
+ : scanNormalFrom(cx, 0, 1, true, false) ?? { pos: 0, side: 1 };
764
+ return GardSelection.cursor(found.pos, found.side);
765
+ }
766
+ function isBarrier(cx, node) {
767
+ if (node.isLeaf)
768
+ return node.type.isBlock;
769
+ let override = node.type.spec.cursorBarrier;
770
+ if (override != null)
771
+ return override;
772
+ return node.type.isolating || node.type.preserveWhitespace || node.type.isBlock && cx.config.isAtom(node.type);
773
+ }
774
+ function scanNormalFrom(cx, from, side, forward, mustMove) {
775
+ let pos = cx.doc.resolve(from), pastBarrier = false;
776
+ if (pos.parent.node.inlineContent) {
777
+ if (!mustMove)
778
+ return { pos: pos.pos, side };
779
+ let block = pos.textblockParent;
780
+ let map = TextblockMap.get(cx, block.start, block.node);
781
+ let next = cx.config.visualCursorMotion ? map.moveVisually(pos.pos, side, forward) : map.moveLogically(pos.pos, forward);
782
+ if (next != null)
783
+ return next;
784
+ if (!block.parent)
785
+ return null;
786
+ pos = Pos.create(block.parent, forward ? block.after : block.before, block.index + (forward ? 1 : 0), 0);
787
+ pastBarrier = isBarrier(cx, block.node);
788
+ }
789
+ else {
790
+ pastBarrier = !pos.parent.parent && pos.index == (forward ? 0 : pos.parent.node.content.length);
791
+ for (let { parent: { node }, index } = pos; !pastBarrier && (forward ? index : index < node.content.length);) {
792
+ let next = node.content[forward ? index - 1 : index];
793
+ if (isBarrier(cx, next))
794
+ pastBarrier = true;
795
+ if (next.isLeaf) {
796
+ index += forward ? 1 : -1;
797
+ }
798
+ else {
799
+ if (next.inlineContent)
800
+ break;
801
+ node = next;
802
+ index = forward ? next.content.length : 0;
803
+ }
804
+ }
805
+ }
806
+ let bottom = pos.pos, step = forward ? 1 : -1;
807
+ for (let { parent, index } = pos, p = pos.pos;;) {
808
+ let { node, parent: next } = parent;
809
+ if (node.inlineContent) {
810
+ if (cx.config.visualCursorMotion)
811
+ return TextblockMap.get(cx, parent.start, parent.node).visualSide(forward);
812
+ return { pos: p, side: forward ? 1 : -1 };
813
+ }
814
+ if (index == (forward ? node.content.length : 0)) {
815
+ let barrier = !next || isBarrier(cx, node);
816
+ if ((bottom != from || !mustMove) && pastBarrier && barrier)
817
+ return { pos: bottom, side: forward ? -1 : 1 };
818
+ if (!next)
819
+ return null;
820
+ index = parent.index + (forward ? 1 : 0);
821
+ parent = next;
822
+ p += step;
823
+ bottom = p;
824
+ if (barrier)
825
+ pastBarrier = true;
826
+ }
827
+ else {
828
+ let nextNode = node.content[index - (forward ? 0 : 1)];
829
+ let barrier = isBarrier(cx, nextNode);
830
+ if (pastBarrier && (bottom != from || !mustMove) && barrier)
831
+ return { pos: bottom, side: forward ? -1 : 1 };
832
+ if (nextNode.isLeaf || cx.config.isAtom(nextNode.type)) {
833
+ index += step;
834
+ p += nextNode.length * step;
835
+ }
836
+ else {
837
+ if (!forward)
838
+ index--;
839
+ parent = Pos.Plot.create(parent, nextNode, forward ? p : p - nextNode.length, index);
840
+ p += step;
841
+ index = forward ? 0 : nextNode.content.length;
842
+ }
843
+ if (barrier) {
844
+ pastBarrier = true;
845
+ bottom = p;
846
+ }
847
+ }
848
+ }
849
+ }
850
+ function skipWord(cx, start, side, forward) {
851
+ let last = null;
852
+ for (let pos = start, visually = cx.config.visualCursorMotion;;) {
853
+ let block = cx.doc.resolve(pos).textblockParent;
854
+ if (!block) {
855
+ let next = scanNormalFrom(cx, pos, side, forward, true);
856
+ if (!next)
857
+ return last;
858
+ ({ pos, side } = next);
859
+ }
860
+ else {
861
+ let map = TextblockMap.get(cx, block.start, block.node);
862
+ let next = map.skipWord(pos, side, forward, visually);
863
+ if (next)
864
+ return next;
865
+ if (!block.parent)
866
+ return last;
867
+ let end = visually ? map.visualSide(!forward)
868
+ : forward ? { pos: block.end, side: -1 } : { pos: block.start, side: 1 };
869
+ if (end.pos != start)
870
+ last = end;
871
+ pos = forward ? block.after : block.before;
872
+ }
873
+ }
874
+ }
875
+ function wordAt(state, pos, bias) {
876
+ let res = state.doc.resolve(pos);
877
+ if (!res.parent.node.inlineContent)
878
+ return GardSelection.cursor(pos, bias);
879
+ let start = pos, end = pos, text = "";
880
+ scanBack: for (let i = res.index - (res.inText ? 0 : 1), cur = res.nodeBefore; cur;) {
881
+ if (!cur.is(Leaf.Text))
882
+ break;
883
+ for (let j = cur.length; j > 0;) {
884
+ let next = findClusterBreak(cur.param, j, false);
885
+ let ch = cur.param.slice(next, j);
886
+ if (!/\p{L}|\p{N}/u.test(ch))
887
+ break scanBack;
888
+ text = ch + text;
889
+ start -= (j - next);
890
+ j = next;
891
+ }
892
+ if (!i)
893
+ break;
894
+ cur = res.parent.node.content[--i];
895
+ }
896
+ scanForward: for (let i = res.index + 1, cur = res.nodeAfter; cur;) {
897
+ if (!cur.is(Leaf.Text))
898
+ break;
899
+ for (let j = 0; j < cur.length;) {
900
+ let next = findClusterBreak(cur.param, j, true);
901
+ let ch = cur.param.slice(j, next);
902
+ if (!/\p{L}|\p{N}/u.test(ch))
903
+ break scanForward;
904
+ text += ch;
905
+ end += (next - j);
906
+ j = next;
907
+ }
908
+ if (i == res.parent.node.content.length)
909
+ break;
910
+ cur = res.parent.node.content[i++];
911
+ }
912
+ if (!Intl.Segmenter)
913
+ return GardSelection.range(start, end);
914
+ let best = null, local = pos - start;
915
+ for (let segment of new Intl.Segmenter(undefined, { granularity: "word" }).segment(text)) {
916
+ if (segment.isWordLike && segment.index <= local && segment.index + segment.segment.length >= local && (!best || bias > 0))
917
+ best = segment;
918
+ }
919
+ return best ? GardSelection.range(start + best.index, start + best.index + best.segment.length) : GardSelection.cursor(pos, bias);
920
+ }
921
+
922
+ class Transaction {
923
+ startState;
924
+ changes;
925
+ selection;
926
+ effects;
927
+ annotations;
928
+ scrollIntoView;
929
+ _state = null;
930
+ constructor(
931
+ startState,
932
+ changes,
933
+ selection,
934
+ effects,
935
+ annotations,
936
+ scrollIntoView) {
937
+ this.startState = startState;
938
+ this.changes = changes;
939
+ this.selection = selection;
940
+ this.effects = effects;
941
+ this.annotations = annotations;
942
+ this.scrollIntoView = scrollIntoView;
943
+ if (!annotations.some((a) => a.type == Transaction.time))
944
+ this.annotations = annotations.concat(Transaction.time.of(Date.now()));
945
+ this.newDoc = this.changes.apply(this.startState.doc);
946
+ this.newSelection = selection || startState.selection.map(changes, { doc: this.newDoc, config: this.startState.config });
947
+ this.newSelection.check(startState.config, this.newDoc);
948
+ }
949
+ newSelection;
950
+ newDoc;
951
+ static create(startState, spec) {
952
+ return new Transaction(startState, spec.changes, spec.selection, spec.effects, spec.annotations, spec.scrollIntoView);
953
+ }
954
+ get state() {
955
+ if (!this._state)
956
+ this.startState.applyTransaction(this);
957
+ return this._state;
958
+ }
959
+ annotation(type) {
960
+ for (let ann of this.annotations)
961
+ if (ann.type == type)
962
+ return ann.value;
963
+ return undefined;
964
+ }
965
+ get docChanged() { return !this.changes.empty; }
966
+ get reconfigured() { return this.startState.config != this.state.config; }
967
+ isUserEvent(event) {
968
+ let e = this.annotation(Transaction.userEvent);
969
+ return !!(e && (e == event || e.length > event.length && e.startsWith(event) && e[event.length] == "."));
970
+ }
971
+ }
972
+ ;Transaction = /*@__PURE__*/(function (Transaction) {
973
+ function merge(state, a, b) {
974
+ let rA = resolveTransactionInner(state, null, a);
975
+ return mergeTransaction(state, rA, resolveTransactionInner(state, rA.changes, b));
976
+ }
977
+ Transaction.merge = merge;
978
+ function append(tr) {
979
+ let result = [tr], top = tr.state;
980
+ let appenders = tr.startState.facet(Transaction.appender);
981
+ if (!appenders.length)
982
+ return result;
983
+ for (let seen = appenders.map(() => 0);;) {
984
+ let done = true;
985
+ for (let i = 0; i < appenders.length; i++) {
986
+ let from = seen[i];
987
+ if (from < result.length) {
988
+ let add = appenders[i](from ? result.slice(from) : result, top);
989
+ if (add) {
990
+ let tr = top.update(Transaction.merge(top, add, { annotations: Transaction.appended.of(true) }));
991
+ result.push(tr);
992
+ top = tr.state;
993
+ done = false;
994
+ }
995
+ seen[i] = result.length;
996
+ }
997
+ }
998
+ if (done)
999
+ return result;
1000
+ }
1001
+ }
1002
+ Transaction.append = append;
1003
+ class Annotation {
1004
+ type;
1005
+ value;
1006
+ constructor(
1007
+ type,
1008
+ value) {
1009
+ this.type = type;
1010
+ this.value = value;
1011
+ }
1012
+ static define() { return new Transaction.Annotation.Type(); }
1013
+ }
1014
+ Transaction.Annotation = Annotation;
1015
+ (function (Annotation) {
1016
+ class Type {
1017
+ of(value) { return new Transaction.Annotation(this, value); }
1018
+ }
1019
+ Annotation.Type = Type;
1020
+ })(Annotation = Transaction.Annotation || (Transaction.Annotation = {}));
1021
+ Transaction.time = Transaction.Annotation.define();
1022
+ Transaction.userEvent = Annotation.define();
1023
+ Transaction.addToHistory = Annotation.define();
1024
+ Transaction.remote = Annotation.define();
1025
+ Transaction.appended = Annotation.define();
1026
+ class Effect {
1027
+ type;
1028
+ value;
1029
+ constructor(
1030
+ type,
1031
+ value) {
1032
+ this.type = type;
1033
+ this.value = value;
1034
+ }
1035
+ map(mapping) {
1036
+ let mapped = this.type.map(this.value, mapping);
1037
+ return mapped === undefined ? undefined : mapped == this.value ? this : new Transaction.Effect(this.type, mapped);
1038
+ }
1039
+ is(type) { return this.type == type; }
1040
+ static define(spec = {}) {
1041
+ return new Transaction.Effect.Type(spec.map || (v => v));
1042
+ }
1043
+ }
1044
+ Transaction.Effect = Effect;
1045
+ (function (Effect) {
1046
+ function mapEffects(effects, mapping) {
1047
+ if (!effects.length)
1048
+ return effects;
1049
+ let result = [];
1050
+ for (let effect of effects) {
1051
+ let mapped = effect.map(mapping);
1052
+ if (mapped)
1053
+ result.push(mapped);
1054
+ }
1055
+ return result;
1056
+ }
1057
+ Effect.mapEffects = mapEffects;
1058
+ class Type {
1059
+ map;
1060
+ constructor(
1061
+ map) {
1062
+ this.map = map;
1063
+ }
1064
+ of(value) { return new Transaction.Effect(this, value); }
1065
+ }
1066
+ Effect.Type = Type;
1067
+ })(Effect = Transaction.Effect || (Transaction.Effect = {}));
1068
+ ;return Transaction})(Transaction);
1069
+ function selCx(config, doc, changes) {
1070
+ let newDoc;
1071
+ return { get doc() { return newDoc || (newDoc = changes.apply(doc)); }, config };
1072
+ }
1073
+ function mergeTransaction(state, a, b) {
1074
+ let changes = a.changes.compose(b.changes);
1075
+ return {
1076
+ changes,
1077
+ selection: b.selection || (a.selection && a.selection.map(b.changes, selCx(state.config, state.doc, changes))),
1078
+ effects: Transaction.Effect.mapEffects(a.effects, b.changes).concat(b.effects),
1079
+ annotations: a.annotations.length ? a.annotations.concat(b.annotations) : b.annotations,
1080
+ scrollIntoView: a.scrollIntoView || b.scrollIntoView
1081
+ };
1082
+ }
1083
+ function resolveTransactionInner(state, after, spec) {
1084
+ let { changes, sequential } = spec;
1085
+ if (after && after.empty)
1086
+ after = null;
1087
+ let doc = after && sequential ? after.apply(state.doc) : state.doc;
1088
+ if (!(changes instanceof ChangeSet))
1089
+ changes = ChangeSet.create(doc, changes || []);
1090
+ let effects = asArray(spec.effects), annotations = asArray(spec.annotations);
1091
+ if (spec.userEvent)
1092
+ annotations = annotations.concat(Transaction.userEvent.of(spec.userEvent));
1093
+ let selection = !spec.selection ? undefined
1094
+ : spec.selection instanceof GardSelection ? spec.selection
1095
+ : typeof spec.selection == "function" ? spec.selection({ doc: changes.apply(doc), config: state.config }, changes) ?? undefined
1096
+ : GardSelection.Text.create(spec.selection);
1097
+ if (after && !sequential) {
1098
+ if (selection) {
1099
+ let { a, b } = ChangeSet.transform(state.doc, after, changes);
1100
+ selection = selection.map(a, selCx(state.config, doc, changes));
1101
+ changes = b;
1102
+ }
1103
+ else {
1104
+ changes = changes.transform(state.doc, after);
1105
+ }
1106
+ effects = Transaction.Effect.mapEffects(effects, after);
1107
+ }
1108
+ return { changes, selection, effects, annotations, scrollIntoView: !!spec.scrollIntoView };
1109
+ }
1110
+ function resolveTransaction(state, spec) {
1111
+ let s = resolveTransactionInner(state, null, spec);
1112
+ let extenders = state.facet(Transaction.extender), tr = Transaction.create(state, s);
1113
+ for (let i = extenders.length - 1; i >= 0; i--) {
1114
+ let extension = extenders[i](tr);
1115
+ if (extension) {
1116
+ s = mergeTransaction(state, s, resolveTransactionInner(state, tr.changes, extension));
1117
+ tr = Transaction.create(state, s);
1118
+ }
1119
+ }
1120
+ return tr;
1121
+ }
1122
+ const none$1 = [];
1123
+ function asArray(value) {
1124
+ return value == null ? none$1 : Array.isArray(value) ? value : [value];
1125
+ }
1126
+
1127
+ let nextID = 0;
1128
+ const none = [];
1129
+ function readHTML(html) {
1130
+ if (typeof document != "object" || !document.implementation)
1131
+ throw new Error("Trying to parse an HTML string in a non-browser context.");
1132
+ let detachedDoc = document.implementation.createHTMLDocument("title");
1133
+ let trustedTypes = window.trustedTypes;
1134
+ if (trustedTypes) {
1135
+ html = trustedTypes.createPolicy("detachedDocument", { createHTML: (s) => s }).createHTML(html);
1136
+ }
1137
+ let elt = detachedDoc.createElement("div");
1138
+ elt.innerHTML = html;
1139
+ return elt;
1140
+ }
1141
+ function readDoc(schema, doc) {
1142
+ if (!doc)
1143
+ return schema.doc(schema.docTag.type.canBeEmpty ? [] : [
1144
+ schema.createAndFill(schema.defaultContentTag(schema.docTag.type))
1145
+ ]);
1146
+ if (doc instanceof Plot.Doc)
1147
+ return doc.schema == schema ? doc : schema.doc(doc.content);
1148
+ if (typeof doc == "function")
1149
+ return doc(schema);
1150
+ if (typeof doc == "string")
1151
+ doc = readHTML(doc);
1152
+ let { nodeType } = doc;
1153
+ if (nodeType === 1 || nodeType === 11)
1154
+ return parse(schema, doc);
1155
+ return schema.docFromJSON(doc);
1156
+ }
1157
+ class GardState {
1158
+ config;
1159
+ _doc;
1160
+ _selection;
1161
+ values;
1162
+ status;
1163
+ computeSlot;
1164
+ resolvedSel = null;
1165
+ trackAccess = null;
1166
+ static create(spec) {
1167
+ let config = spec.config instanceof GardState.Configuration ? spec.config
1168
+ : GardState.Configuration.resolve(spec.config || [], new Map);
1169
+ let schema = config.schema;
1170
+ if (!schema) {
1171
+ if (spec.doc instanceof Plot.Doc)
1172
+ schema = spec.doc.schema;
1173
+ else
1174
+ throw new SchemaError(`No document plot provided, unable to create schema`);
1175
+ }
1176
+ let doc = readDoc(schema, spec.doc);
1177
+ let selection = !spec.selection ? cursorAtStart({ doc, config })
1178
+ : typeof spec.selection == "function" ? spec.selection({ doc, config })
1179
+ : spec.selection instanceof GardSelection ? spec.selection
1180
+ : GardSelection.Text.create(spec.selection);
1181
+ return GardState.fromConfig(config, doc, selection);
1182
+ }
1183
+ constructor(
1184
+ config, _doc, _selection,
1185
+ values, computeSlot, tr) {
1186
+ this.config = config;
1187
+ this._doc = _doc;
1188
+ this._selection = _selection;
1189
+ this.values = values;
1190
+ this.status = config.statusTemplate.slice();
1191
+ this.computeSlot = computeSlot;
1192
+ if (tr)
1193
+ tr._state = this;
1194
+ for (let i = 0; i < this.config.dynamicSlots.length; i++)
1195
+ ensureAddr(this, i << 1);
1196
+ this.computeSlot = null;
1197
+ }
1198
+ get doc() {
1199
+ if (this.trackAccess)
1200
+ addValue(this.trackAccess, "doc");
1201
+ return this._doc;
1202
+ }
1203
+ get schema() {
1204
+ if (this.trackAccess)
1205
+ addValue(this.trackAccess, "schema");
1206
+ return this._doc.schema;
1207
+ }
1208
+ get selection() {
1209
+ if (this.trackAccess)
1210
+ addValue(this.trackAccess, "selection");
1211
+ return this._selection;
1212
+ }
1213
+ get sel() {
1214
+ return this.resolvedSel || (this.resolvedSel = this.selection.resolve(this.doc));
1215
+ }
1216
+ field(field, require = true) {
1217
+ let addr = this.config.address[field.id];
1218
+ if (addr == null) {
1219
+ if (require)
1220
+ throw new RangeError("Field is not present in this state");
1221
+ return undefined;
1222
+ }
1223
+ let track = this.trackAccess;
1224
+ if (track) {
1225
+ addValue(track, field);
1226
+ track = null;
1227
+ }
1228
+ ensureAddr(this, addr);
1229
+ if (track)
1230
+ this.trackAccess = track;
1231
+ return getAddr(this, addr);
1232
+ }
1233
+ facet(facet) {
1234
+ if (this.trackAccess)
1235
+ addValue(this.trackAccess, facet);
1236
+ let addr = this.config.address[facet.id];
1237
+ if (addr == null)
1238
+ return facet.default;
1239
+ ensureAddr(this, addr);
1240
+ return getAddr(this, addr);
1241
+ }
1242
+ update(spec) {
1243
+ return resolveTransaction(this, spec);
1244
+ }
1245
+ applyTransaction(tr) {
1246
+ let conf = this.config, { base, compartments } = conf;
1247
+ for (let effect of tr.effects) {
1248
+ if (effect.is(GardState.Compartment.reconfigureCompartment)) {
1249
+ if (conf) {
1250
+ compartments = new Map;
1251
+ conf.compartments.forEach((val, key) => compartments.set(key, val));
1252
+ conf = null;
1253
+ }
1254
+ compartments.set(effect.value.compartment, effect.value.extension);
1255
+ }
1256
+ else if (effect.is(GardState.reconfigure)) {
1257
+ conf = null;
1258
+ base = effect.value;
1259
+ }
1260
+ else if (effect.is(GardState.appendConfig)) {
1261
+ conf = null;
1262
+ base = asArray(base).concat(effect.value);
1263
+ }
1264
+ }
1265
+ let startValues, doc = tr.newDoc;
1266
+ if (!conf) {
1267
+ conf = GardState.Configuration.resolve(base, compartments, this);
1268
+ let intermediateState = new GardState(conf, this.doc, this.selection, conf.dynamicSlots.map(() => null), (state, slot) => slot.reconfigure(state, this), null);
1269
+ startValues = intermediateState.values;
1270
+ if (conf.staticFacet(GardState.schemaElement) != this.facet(GardState.schemaElement)) {
1271
+ let schema = conf.schema;
1272
+ if (schema)
1273
+ doc = schema.doc(doc.content);
1274
+ }
1275
+ }
1276
+ else {
1277
+ startValues = tr.startState.values.slice();
1278
+ }
1279
+ new GardState(conf, doc, tr.newSelection, startValues, (state, slot) => slot.update(state, tr), tr);
1280
+ }
1281
+ recordAccess(slots, f) {
1282
+ let prev = this.trackAccess;
1283
+ this.trackAccess = slots;
1284
+ let result = f(this);
1285
+ this.trackAccess = prev;
1286
+ return result;
1287
+ }
1288
+ textblockMap(node) {
1289
+ return TextblockMap.get(this, node.start, node.node);
1290
+ }
1291
+ toJSON(fields) {
1292
+ let result = {
1293
+ doc: this.doc.toJSON(),
1294
+ selection: this.selection.toJSON(this)
1295
+ };
1296
+ if (fields)
1297
+ for (let prop in fields) {
1298
+ let value = fields[prop];
1299
+ if (value instanceof GardState.Field && this.config.address[value.id] != null)
1300
+ result[prop] = value.spec.toJSON(this.field(fields[prop]), this);
1301
+ }
1302
+ return result;
1303
+ }
1304
+ static fromJSON(json, extensions, fields) {
1305
+ if (!json)
1306
+ throw new ValidationError("Invalid JSON representation for GardState");
1307
+ let fieldInit = [];
1308
+ if (fields)
1309
+ for (let prop in fields) {
1310
+ if (Object.prototype.hasOwnProperty.call(json, prop)) {
1311
+ let field = fields[prop], value = json[prop];
1312
+ fieldInit.push(field.init(state => field.spec.fromJSON(value, state)));
1313
+ }
1314
+ }
1315
+ let config = GardState.Configuration.create([extensions, fieldInit]);
1316
+ let schema = config.schema;
1317
+ if (!schema)
1318
+ throw new SchemaError("No document plot provided to GardState.fromJSON");
1319
+ let doc = schema.docFromJSON(json.doc);
1320
+ return GardState.fromConfig(config, doc, GardSelection.fromJSON({ config, doc }, json.selection));
1321
+ }
1322
+ static fromConfig(config, doc, selection) {
1323
+ selection.check(config, doc);
1324
+ return new GardState(config, doc, selection, config.dynamicSlots.map(() => null), (state, slot) => slot.create(state), null);
1325
+ }
1326
+ get readOnly() { return this.facet(GardState.readOnly); }
1327
+ get textLTR() { return this.config.textLTR; }
1328
+ textblockLTR(plot) { return this.config.textblockLTR(plot); }
1329
+ isAtom(type) { return this.config.isAtom(type); }
1330
+ wordAt(pos, bias = 1) {
1331
+ return wordAt(this, pos, bias);
1332
+ }
1333
+ static reconfigure = /*@__PURE__*/Transaction.Effect.define();
1334
+ static appendConfig = /*@__PURE__*/Transaction.Effect.define();
1335
+ }
1336
+ ;GardState = /*@__PURE__*/(function (GardState) {
1337
+ class Field {
1338
+ id;
1339
+ createF;
1340
+ updateF;
1341
+ compareF;
1342
+ spec;
1343
+ provides = undefined;
1344
+ constructor(
1345
+ id, createF, updateF, compareF,
1346
+ spec) {
1347
+ this.id = id;
1348
+ this.createF = createF;
1349
+ this.updateF = updateF;
1350
+ this.compareF = compareF;
1351
+ this.spec = spec;
1352
+ }
1353
+ static define(config) {
1354
+ let field = new GardState.Field(nextID++, config.create, config.update, config.compare || ((a, b) => a === b), config);
1355
+ if (config.provide)
1356
+ field.provides = config.provide(field);
1357
+ return field;
1358
+ }
1359
+ create(state) {
1360
+ let init = state.facet(initField).find(i => i.field == this);
1361
+ return (init?.create || this.createF)(state);
1362
+ }
1363
+ slot(addresses) {
1364
+ let idx = addresses[this.id] >> 1;
1365
+ return {
1366
+ create: (state) => {
1367
+ state.values[idx] = this.create(state);
1368
+ return 1;
1369
+ },
1370
+ update: (state, tr) => {
1371
+ let oldVal = state.values[idx];
1372
+ let value = this.updateF(oldVal, tr);
1373
+ if (this.compareF(oldVal, value))
1374
+ return 0;
1375
+ state.values[idx] = value;
1376
+ return 1;
1377
+ },
1378
+ reconfigure: (state, oldState) => {
1379
+ if (oldState.config.address[this.id] != null) {
1380
+ state.values[idx] = oldState.field(this);
1381
+ return 0;
1382
+ }
1383
+ state.values[idx] = this.create(state);
1384
+ return 1;
1385
+ }
1386
+ };
1387
+ }
1388
+ get extension() { return this; }
1389
+ init(create) {
1390
+ return [this, initField.of({ field: this, create })];
1391
+ }
1392
+ }
1393
+ GardState.Field = Field;
1394
+ class Facet {
1395
+ combine;
1396
+ compareInput;
1397
+ compare;
1398
+ isStatic;
1399
+ id = nextID++;
1400
+ default;
1401
+ extensions;
1402
+ constructor(
1403
+ combine,
1404
+ compareInput,
1405
+ compare,
1406
+ isStatic, enables) {
1407
+ this.combine = combine;
1408
+ this.compareInput = compareInput;
1409
+ this.compare = compare;
1410
+ this.isStatic = isStatic;
1411
+ this.default = combine(none);
1412
+ this.extensions = typeof enables == "function" ? enables(this) : enables;
1413
+ }
1414
+ get reader() { return this; }
1415
+ static define(config = {}) {
1416
+ return new GardState.Facet(config.combine || ((a) => a), config.compareInput || ((a, b) => a === b), config.compare || (!config.combine ? sameArray : (a, b) => a === b), !!config.static, config.enables);
1417
+ }
1418
+ of(value) {
1419
+ return new FacetProvider(none, this, 1, value);
1420
+ }
1421
+ compute(get) {
1422
+ if (this.isStatic)
1423
+ throw new Error("Can't compute a static facet");
1424
+ return new FacetProvider([], this, 4, get);
1425
+ }
1426
+ computeN(get) {
1427
+ if (this.isStatic)
1428
+ throw new Error("Can't compute a static facet");
1429
+ return new FacetProvider([], this, 2 | 4, get);
1430
+ }
1431
+ from(field, get) {
1432
+ if (this.isStatic)
1433
+ throw new Error("Can't compute a static facet");
1434
+ if (!get)
1435
+ get = x => x;
1436
+ return new FacetProvider([field], this, 0, state => get(state.field(field)));
1437
+ }
1438
+ tag;
1439
+ }
1440
+ GardState.Facet = Facet;
1441
+ (function (Facet) {
1442
+ function combineConfig(configs, defaults, combine = {}) {
1443
+ let result = {};
1444
+ for (let config of configs)
1445
+ for (let key of Object.keys(config)) {
1446
+ let value = config[key], current = result[key];
1447
+ if (current === undefined)
1448
+ result[key] = value;
1449
+ else if (current === value || value === undefined) ; else if (Object.hasOwnProperty.call(combine, key))
1450
+ result[key] = combine[key](current, value);
1451
+ else
1452
+ throw new Error("Config merge conflict for field " + key);
1453
+ }
1454
+ for (let key in defaults)
1455
+ if (result[key] === undefined)
1456
+ result[key] = defaults[key];
1457
+ return result;
1458
+ }
1459
+ Facet.combineConfig = combineConfig;
1460
+ })(Facet = GardState.Facet || (GardState.Facet = {}));
1461
+ class Configuration {
1462
+ base;
1463
+ compartments;
1464
+ dynamicSlots;
1465
+ address;
1466
+ staticValues;
1467
+ facets;
1468
+ statusTemplate = [];
1469
+ constructor(
1470
+ base,
1471
+ compartments,
1472
+ dynamicSlots,
1473
+ address,
1474
+ staticValues,
1475
+ facets) {
1476
+ this.base = base;
1477
+ this.compartments = compartments;
1478
+ this.dynamicSlots = dynamicSlots;
1479
+ this.address = address;
1480
+ this.staticValues = staticValues;
1481
+ this.facets = facets;
1482
+ while (this.statusTemplate.length < dynamicSlots.length)
1483
+ this.statusTemplate.push(0);
1484
+ }
1485
+ staticFacet(facet) {
1486
+ if (!facet.isStatic)
1487
+ throw new Error("Only static facets can be accessed from a configuration");
1488
+ let addr = this.address[facet.id];
1489
+ return addr == null ? facet.default : this.staticValues[addr >> 1];
1490
+ }
1491
+ static resolve(base, compartments, oldState) {
1492
+ let fields = [];
1493
+ let facets = Object.create(null);
1494
+ let newCompartments = new Map();
1495
+ for (let ext of flatten(base, compartments, newCompartments)) {
1496
+ if (ext instanceof FacetProvider)
1497
+ (facets[ext.facet.id] || (facets[ext.facet.id] = [])).push(ext);
1498
+ else
1499
+ fields.push(ext);
1500
+ }
1501
+ let address = Object.create(null);
1502
+ let staticValues = [];
1503
+ let dynamicSlots = [];
1504
+ for (let field of fields) {
1505
+ address[field.id] = dynamicSlots.length << 1;
1506
+ dynamicSlots.push(a => field.slot(a));
1507
+ }
1508
+ let oldFacets = oldState?.config.facets;
1509
+ for (let id in facets) {
1510
+ let providers = facets[id], facet = providers[0].facet;
1511
+ let oldProviders = oldFacets && oldFacets[id] || none;
1512
+ if (providers.every(p => p.flags & 1)) {
1513
+ address[facet.id] = (staticValues.length << 1) | 1;
1514
+ if (sameArray(oldProviders, providers)) {
1515
+ staticValues.push(oldState.facet(facet));
1516
+ }
1517
+ else {
1518
+ let value = facet.combine(providers.map(p => p.value));
1519
+ staticValues.push(oldState && facet.compare(value, oldState.facet(facet)) ? oldState.facet(facet) : value);
1520
+ }
1521
+ }
1522
+ else {
1523
+ for (let p of providers) {
1524
+ if (p.flags & 1) {
1525
+ address[p.id] = (staticValues.length << 1) | 1;
1526
+ staticValues.push(p.value);
1527
+ }
1528
+ else {
1529
+ address[p.id] = dynamicSlots.length << 1;
1530
+ dynamicSlots.push(a => p.dynamicSlot(a));
1531
+ }
1532
+ }
1533
+ address[facet.id] = dynamicSlots.length << 1;
1534
+ dynamicSlots.push(a => dynamicFacetSlot(a, facet, providers));
1535
+ }
1536
+ }
1537
+ let dynamic = dynamicSlots.map(f => f(address));
1538
+ return new GardState.Configuration(base, newCompartments, dynamic, address, staticValues, facets);
1539
+ }
1540
+ static create(extensions) {
1541
+ return GardState.Configuration.resolve(extensions, new Map);
1542
+ }
1543
+ get schema() {
1544
+ let elts = this.staticFacet(GardState.schemaElement);
1545
+ if (!elts.some(elt => elt instanceof Plot.Type && elt.isDoc))
1546
+ return null;
1547
+ return Schema.define(elts);
1548
+ }
1549
+ get textLTR() { return this.staticFacet(GardState.textLTR); }
1550
+ textblockLTR(plot) {
1551
+ for (let f of this.staticFacet(GardState.textblockLTR)) {
1552
+ let result = f(plot);
1553
+ if (result != null)
1554
+ return result;
1555
+ }
1556
+ return this.textLTR;
1557
+ }
1558
+ get visualCursorMotion() { return this.staticFacet(GardState.visualCursorMotion); }
1559
+ isAtom(type) {
1560
+ return type.isLeaf || (this.staticFacet(GardState.isAtom).get(type) ?? type.isAtom);
1561
+ }
1562
+ }
1563
+ GardState.Configuration = Configuration;
1564
+ function flatten(extension, compartments, newCompartments) {
1565
+ let result = [[], [], [], [], []];
1566
+ let seen = new Map();
1567
+ function inner(ext, prec) {
1568
+ let known = seen.get(ext);
1569
+ if (known != null) {
1570
+ if (known <= prec)
1571
+ return;
1572
+ let found = result[known].indexOf(ext);
1573
+ if (found > -1)
1574
+ result[known].splice(found, 1);
1575
+ if (ext instanceof CompartmentInstance)
1576
+ newCompartments.delete(ext.compartment);
1577
+ }
1578
+ seen.set(ext, prec);
1579
+ if (Array.isArray(ext)) {
1580
+ for (let e of ext)
1581
+ inner(e, prec);
1582
+ }
1583
+ else if (ext instanceof CompartmentInstance) {
1584
+ if (newCompartments.has(ext.compartment))
1585
+ throw new RangeError(`Duplicate use of compartment in extensions`);
1586
+ let content = compartments.get(ext.compartment) || ext.inner;
1587
+ newCompartments.set(ext.compartment, content);
1588
+ inner(content, prec);
1589
+ }
1590
+ else if (ext instanceof PrecExtension) {
1591
+ inner(ext.inner, ext.prec);
1592
+ }
1593
+ else if (ext instanceof GardState.Field) {
1594
+ result[prec].push(ext);
1595
+ if (ext.provides)
1596
+ inner(ext.provides, prec);
1597
+ }
1598
+ else if (ext instanceof FacetProvider) {
1599
+ result[prec].push(ext);
1600
+ if (ext.facet.extensions)
1601
+ inner(ext.facet.extensions, 2);
1602
+ }
1603
+ else {
1604
+ let content = ext.extension;
1605
+ if (!content)
1606
+ throw new Error(`Unrecognized extension value in extension set (${ext}). This sometimes happens because multiple instances of wordgard/state are loaded, breaking instanceof checks.`);
1607
+ inner(content, prec);
1608
+ }
1609
+ }
1610
+ inner(extension, 2);
1611
+ return result.reduce((a, b) => a.concat(b));
1612
+ }
1613
+ GardState.prec = {
1614
+ highest: mkPrec(0),
1615
+ high: mkPrec(1),
1616
+ default: mkPrec(2),
1617
+ low: mkPrec(3),
1618
+ lowest: mkPrec(4)
1619
+ };
1620
+ class Compartment {
1621
+ constructor() { }
1622
+ static define() { return new Compartment; }
1623
+ of(ext) { return new CompartmentInstance(this, ext); }
1624
+ reconfigure(content) {
1625
+ return GardState.Compartment.reconfigureCompartment.of({ compartment: this, extension: content });
1626
+ }
1627
+ get(state) {
1628
+ return state.config.compartments.get(this);
1629
+ }
1630
+ static reconfigureCompartment = Transaction.Effect.define();
1631
+ }
1632
+ GardState.Compartment = Compartment;
1633
+ GardState.schemaElement = GardState.Facet.define({
1634
+ combine: values => values.reduce((set, elt) => set.concat(elt), none),
1635
+ static: true
1636
+ });
1637
+ GardState.readOnly = GardState.Facet.define({
1638
+ combine: values => values.length ? values[0] : false
1639
+ });
1640
+ GardState.textLTR = GardState.Facet.define({
1641
+ combine: values => values.length ? values[0] : true,
1642
+ static: true
1643
+ });
1644
+ GardState.textblockLTR = GardState.Facet.define({
1645
+ static: true
1646
+ });
1647
+ GardState.visualCursorMotion = GardState.Facet.define({
1648
+ combine(values) { return !values.length ? true : values[0]; },
1649
+ static: true
1650
+ });
1651
+ GardState.isAtom = GardState.Facet.define({
1652
+ static: true,
1653
+ combine(inputs) {
1654
+ let map = new Map();
1655
+ for (let i = inputs.length - 1; i >= 0; i--)
1656
+ map.set(inputs[i][0], inputs[i][1]);
1657
+ return map;
1658
+ }
1659
+ });
1660
+ ;return GardState})(GardState);
1661
+ const initField = /*@__PURE__*/GardState.Facet.define({ static: true });
1662
+ function addValue(set, value) {
1663
+ if (set.indexOf(value) < 0)
1664
+ set.push(value);
1665
+ }
1666
+ function mkPrec(value) {
1667
+ return (ext) => new PrecExtension(ext, value);
1668
+ }
1669
+ class PrecExtension {
1670
+ inner;
1671
+ prec;
1672
+ constructor(inner, prec) {
1673
+ this.inner = inner;
1674
+ this.prec = prec;
1675
+ }
1676
+ extension;
1677
+ }
1678
+ function sameArray(a, b) {
1679
+ return a == b || a.length == b.length && a.every((e, i) => e === b[i]);
1680
+ }
1681
+ class DependencySet {
1682
+ doc = false;
1683
+ sel = false;
1684
+ schema = false;
1685
+ addrs = [];
1686
+ count = 0;
1687
+ update(deps, addresses) {
1688
+ while (this.count < deps.length) {
1689
+ let dep = deps[this.count++];
1690
+ if (dep === "doc")
1691
+ this.doc = true;
1692
+ else if (dep === "selection")
1693
+ this.sel = true;
1694
+ else if (dep === "schema")
1695
+ this.schema = true;
1696
+ else if (((addresses[dep.id] ?? 1) & 1) == 0)
1697
+ this.addrs.push(addresses[dep.id]);
1698
+ }
1699
+ }
1700
+ }
1701
+ class FacetProvider {
1702
+ facet;
1703
+ flags;
1704
+ value;
1705
+ id = nextID++;
1706
+ extension; dependencies;
1707
+ constructor(dependencies, facet, flags, value) {
1708
+ this.facet = facet;
1709
+ this.flags = flags;
1710
+ this.value = value;
1711
+ this.dependencies = dependencies; }
1712
+ dynamicSlot(addresses) {
1713
+ let getter = this.value;
1714
+ let compare = this.facet.compareInput;
1715
+ let id = this.id, idx = addresses[id] >> 1;
1716
+ let multi = this.flags & 2;
1717
+ let dependencies = this.dependencies;
1718
+ let auto = this.flags & 4 ? dependencies : null;
1719
+ let depSet = new DependencySet;
1720
+ return {
1721
+ create(state) {
1722
+ state.values[idx] = state.recordAccess(auto, getter);
1723
+ return 1;
1724
+ },
1725
+ update(state, tr) {
1726
+ depSet.update(dependencies, addresses);
1727
+ if ((depSet.doc && tr.docChanged) || (depSet.sel && (tr.docChanged || tr.selection)) ||
1728
+ (depSet.schema && tr.startState.schema != state.schema) || ensureAll(state, depSet.addrs)) {
1729
+ let newVal = state.recordAccess(auto, getter);
1730
+ if (multi ? !compareArray(newVal, state.values[idx], compare) : !compare(newVal, state.values[idx])) {
1731
+ state.values[idx] = newVal;
1732
+ return 1;
1733
+ }
1734
+ }
1735
+ return 0;
1736
+ },
1737
+ reconfigure(state, oldState) {
1738
+ let newVal, oldAddr = oldState.config.address[id];
1739
+ if (oldAddr != null) {
1740
+ let oldVal = getAddr(oldState, oldAddr);
1741
+ if (dependencies.every(dep => {
1742
+ return dep instanceof GardState.Facet ? oldState.facet(dep) === state.facet(dep)
1743
+ : dep instanceof GardState.Field ? oldState.field(dep, false) == state.field(dep, false)
1744
+ : true;
1745
+ }) || (multi ? compareArray(newVal = getter(state), oldVal, compare) : compare(newVal = getter(state), oldVal))) {
1746
+ state.values[idx] = oldVal;
1747
+ return 0;
1748
+ }
1749
+ }
1750
+ else {
1751
+ newVal = state.recordAccess(auto, getter);
1752
+ }
1753
+ state.values[idx] = newVal;
1754
+ return 1;
1755
+ }
1756
+ };
1757
+ }
1758
+ }
1759
+ function compareArray(a, b, compare) {
1760
+ if (a.length != b.length)
1761
+ return false;
1762
+ for (let i = 0; i < a.length; i++)
1763
+ if (!compare(a[i], b[i]))
1764
+ return false;
1765
+ return true;
1766
+ }
1767
+ function ensureAll(state, addrs) {
1768
+ let changed = false;
1769
+ for (let addr of addrs)
1770
+ if (ensureAddr(state, addr) & 1)
1771
+ changed = true;
1772
+ return changed;
1773
+ }
1774
+ function dynamicFacetSlot(addresses, facet, providers) {
1775
+ let providerAddrs = providers.map(p => addresses[p.id]);
1776
+ let dynamic = providerAddrs.filter(p => !(p & 1));
1777
+ let idx = addresses[facet.id] >> 1;
1778
+ function get(state) {
1779
+ let values = [];
1780
+ for (let i = 0; i < providerAddrs.length; i++) {
1781
+ let value = getAddr(state, providerAddrs[i]);
1782
+ if (providers[i].flags & 2)
1783
+ for (let val of value)
1784
+ values.push(val);
1785
+ else
1786
+ values.push(value);
1787
+ }
1788
+ return facet.combine(values);
1789
+ }
1790
+ return {
1791
+ create(state) {
1792
+ for (let addr of providerAddrs)
1793
+ ensureAddr(state, addr);
1794
+ state.values[idx] = get(state);
1795
+ return 1;
1796
+ },
1797
+ update(state, tr) {
1798
+ if (!ensureAll(state, dynamic))
1799
+ return 0;
1800
+ let value = get(state);
1801
+ if (facet.compare(value, state.values[idx]))
1802
+ return 0;
1803
+ state.values[idx] = value;
1804
+ return 1;
1805
+ },
1806
+ reconfigure(state, oldState) {
1807
+ let depChanged = ensureAll(state, providerAddrs);
1808
+ let oldProviders = oldState.config.facets[facet.id], oldValue = oldState.facet(facet);
1809
+ if (oldProviders && !depChanged && sameArray(providers, oldProviders)) {
1810
+ state.values[idx] = oldValue;
1811
+ return 0;
1812
+ }
1813
+ let value = get(state);
1814
+ if (facet.compare(value, oldValue)) {
1815
+ state.values[idx] = oldValue;
1816
+ return 0;
1817
+ }
1818
+ state.values[idx] = value;
1819
+ return 1;
1820
+ }
1821
+ };
1822
+ }
1823
+ function ensureAddr(state, addr) {
1824
+ if (addr & 1)
1825
+ return 2;
1826
+ let idx = addr >> 1;
1827
+ let status = state.status[idx];
1828
+ if (status == 4)
1829
+ throw new Error("Cyclic dependency between fields and/or facets");
1830
+ if (status & 2)
1831
+ return status;
1832
+ state.status[idx] = 4;
1833
+ let changed = state.computeSlot(state, state.config.dynamicSlots[idx]);
1834
+ return state.status[idx] = 2 | changed;
1835
+ }
1836
+ function getAddr(state, addr) {
1837
+ return addr & 1 ? state.config.staticValues[addr >> 1] : state.values[addr >> 1];
1838
+ }
1839
+ class CompartmentInstance {
1840
+ compartment;
1841
+ inner;
1842
+ constructor(compartment, inner) {
1843
+ this.compartment = compartment;
1844
+ this.inner = inner;
1845
+ }
1846
+ extension;
1847
+ }
1848
+ GardSelection = /*@__PURE__*/(GardSelection => {GardSelection.selectionType = GardState.Facet.define({
1849
+ combine(values) {
1850
+ let types = [GardSelection.Text.type, GardSelection.Node.type, ...values];
1851
+ for (let i = 0; i < types.length; i++)
1852
+ for (let j = i + 1; j < types.length; j++) {
1853
+ if (types[i].tag == types[j].tag)
1854
+ throw new Error("Duplicate selection JSON tag: " + types[i].tag);
1855
+ }
1856
+ return types;
1857
+ },
1858
+ static: true
1859
+ }); return GardSelection})(GardSelection);
1860
+ Transaction = /*@__PURE__*/(Transaction => {Transaction.extender = GardState.Facet.define(); return Transaction})(Transaction);
1861
+ Transaction = /*@__PURE__*/(Transaction => {Transaction.appender = GardState.Facet.define(); return Transaction})(Transaction);
1862
+
1863
+ function scanChanges(changes, doc, corrections) {
1864
+ let buckets = [[], [], []], [childList, content, marks] = buckets;
1865
+ for (let c of corrections)
1866
+ buckets[c.event].push(c);
1867
+ let plan = [];
1868
+ let queried = new Set, newNode = childList.concat(content);
1869
+ let updateWalker, { schema } = doc;
1870
+ let checkMarks = (node, pos, parent, index) => {
1871
+ for (let correction of marks)
1872
+ if (schema.matchNode(node.type, correction.query))
1873
+ plan.push({ node: Pos.Node.create(parent, node, pos, index), correction });
1874
+ };
1875
+ if (marks.length)
1876
+ updateWalker = {
1877
+ enterPlot: checkMarks,
1878
+ skip(node, pos, parent, index) {
1879
+ if (node.isText && !parent.node.content.includes(node)) {
1880
+ for (let off = parent.start, i = 0;; i++) {
1881
+ let next = parent.node.content[i], end = off + next.length;
1882
+ if (end > pos) {
1883
+ node = next;
1884
+ pos = off;
1885
+ break;
1886
+ }
1887
+ }
1888
+ if (queried.has(pos))
1889
+ return;
1890
+ queried.add(pos);
1891
+ }
1892
+ checkMarks(node, pos, parent, index);
1893
+ },
1894
+ leavePlot() { }
1895
+ };
1896
+ let changeWalker = {
1897
+ enterPlot(node, pos, parent, index) {
1898
+ queried.add(pos);
1899
+ this.skip(node, pos, parent, index);
1900
+ },
1901
+ skip(node, pos, parent, index) {
1902
+ if (node.isPlot)
1903
+ for (let correction of newNode)
1904
+ if (schema.matchNode(node.type, correction.query))
1905
+ plan.push({ node: Pos.Plot.create(parent, node, pos, index), correction });
1906
+ },
1907
+ leavePlot() { }
1908
+ };
1909
+ let pos = doc.resolve(0);
1910
+ for (let i = 0, { sections } = changes; i < sections.length;) {
1911
+ let len = sections[i++], ins = sections[i++];
1912
+ if (ins == -1 || ins == -2 && !updateWalker) {
1913
+ if (i == sections.length)
1914
+ break;
1915
+ pos = pos.advance(len);
1916
+ }
1917
+ else if (ins == -2) {
1918
+ while (i < sections.length && sections[i + 1] == -2) {
1919
+ len += sections[i++];
1920
+ i++;
1921
+ }
1922
+ pos = pos.walk(len, updateWalker);
1923
+ }
1924
+ else {
1925
+ while (i < sections.length && sections[i + 1] >= 0) {
1926
+ len += sections[i++];
1927
+ ins += sections[i++];
1928
+ }
1929
+ let start = pos.pos, end = start + ins;
1930
+ for (let checkChildList = childList.length > 0, parent = pos.parent;;) {
1931
+ if (queried.has(parent.start - 1))
1932
+ break;
1933
+ queried.add(parent.start - 1);
1934
+ if (checkChildList) {
1935
+ for (let correction of childList)
1936
+ if (schema.matchNode(parent.node.type, correction.query))
1937
+ plan.push({ node: parent, correction });
1938
+ if (start >= parent.start && end <= parent.end)
1939
+ checkChildList = false;
1940
+ }
1941
+ for (let correction of content)
1942
+ if (schema.matchNode(parent.node.type, correction.query))
1943
+ plan.push({ node: parent, correction });
1944
+ if (!parent.parent || !content.length && !checkChildList)
1945
+ break;
1946
+ parent = parent.parent;
1947
+ }
1948
+ pos = pos.walk(ins, changeWalker);
1949
+ }
1950
+ }
1951
+ return plan;
1952
+ }
1953
+ const corrections = /*@__PURE__*/GardState.Facet.define();
1954
+ const planCache = /*@__PURE__*/(() => new WeakMap())();
1955
+ class Correction {
1956
+ event;
1957
+ query;
1958
+ correct;
1959
+ extension;
1960
+ constructor(
1961
+ event,
1962
+ query,
1963
+ correct) {
1964
+ this.event = event;
1965
+ this.query = query;
1966
+ this.correct = correct;
1967
+ this.extension = [
1968
+ corrections.of(this),
1969
+ Transaction.extender.of(tr => this.extend(tr))
1970
+ ];
1971
+ }
1972
+ extend(tr) {
1973
+ if (!tr.docChanged || tr.annotation(Transaction.remote))
1974
+ return null;
1975
+ let plan = planCache.get(tr);
1976
+ if (!plan)
1977
+ planCache.set(tr, plan = scanChanges(tr.changes, tr.newDoc, tr.startState.facet(corrections)));
1978
+ let changes = [];
1979
+ for (let elt of plan)
1980
+ if (elt.correction == this) {
1981
+ let change = this.correct(elt.node);
1982
+ if (change)
1983
+ changes.push(change);
1984
+ }
1985
+ return changes.length ? { changes, sequential: true } : null;
1986
+ }
1987
+ scan(state) {
1988
+ let changes = [];
1989
+ state.doc.iterate((node, pos) => {
1990
+ if (state.schema.matchNode(node.type, this.query) && (this.event == 2 || node.isPlot)) {
1991
+ let change = this.correct(state.doc.resolveNode(pos));
1992
+ if (change)
1993
+ changes.push(change);
1994
+ }
1995
+ });
1996
+ if (changes.length)
1997
+ return state.update({ changes });
1998
+ return null;
1999
+ }
2000
+ static onChildList(query, correct) {
2001
+ return new Correction(0, query, correct);
2002
+ }
2003
+ static onContent(query, correct) {
2004
+ return new Correction(1, query, correct);
2005
+ }
2006
+ static onMarks(query, correct) {
2007
+ return new Correction(2, query, correct);
2008
+ }
2009
+ static check(changes, doc, corrections) {
2010
+ if (!corrections.length || changes.empty)
2011
+ return null;
2012
+ let plan = scanChanges(changes, doc, corrections), changed = [];
2013
+ for (let c of corrections)
2014
+ for (let elt of plan)
2015
+ if (elt.correction == c) {
2016
+ let change = c.correct(elt.node);
2017
+ if (change)
2018
+ changed.push(change);
2019
+ }
2020
+ return changed.length ? ChangeSet.create(doc, changed) : null;
2021
+ }
2022
+ }
2023
+
2024
+ export { BidiSpan, Correction, GardSelection, GardState, TextblockMap, Transaction };