@articollab/prosemirror 0.0.0-stage → 0.12.0-beta.1

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/sync.js ADDED
@@ -0,0 +1,752 @@
1
+ import { Node } from "prosemirror-model";
2
+ import { Plugin, PluginKey, Selection, TextSelection } from "prosemirror-state";
3
+ import { basicMapping, EMBED_CHARACTER, lineLength, sameJson, TextShape, textLines, } from "./mapping.js";
4
+ const syncKey = new PluginKey("articollab-text-sync");
5
+ /**
6
+ * What each element of some lines compares as, with "\n" between lines: a code point, or for an
7
+ * embed U+FFFC and its key. So an embed of one kind becomes one of another by a deletion and an
8
+ * insertion, but a new value does not.
9
+ */
10
+ function codePoints(lines) {
11
+ const points = [];
12
+ for (const [index, line] of lines.entries()) {
13
+ if (index > 0)
14
+ points.push("\n");
15
+ for (const run of line.runs) {
16
+ if ("embed" in run)
17
+ points.push(EMBED_CHARACTER + run.embed.key);
18
+ else
19
+ for (const point of run.text)
20
+ points.push(point);
21
+ }
22
+ }
23
+ return points;
24
+ }
25
+ /** Each element's marks, with `undefined` for the "\n" between lines. */
26
+ function pointMarks(lines) {
27
+ const marks = [];
28
+ for (const [index, line] of lines.entries()) {
29
+ if (index > 0)
30
+ marks.push(undefined);
31
+ for (const run of line.runs) {
32
+ if ("embed" in run)
33
+ marks.push(run.marks);
34
+ else
35
+ for (const _ of run.text)
36
+ marks.push(run.marks);
37
+ }
38
+ }
39
+ return marks;
40
+ }
41
+ /** The embeds of some lines by element index, as `codePoints` counts. */
42
+ function embedsOf(lines) {
43
+ const embeds = new Map();
44
+ let element = 0;
45
+ for (const [index, line] of lines.entries()) {
46
+ if (index > 0)
47
+ element++;
48
+ for (const run of line.runs) {
49
+ if ("embed" in run)
50
+ embeds.set(element++, run.embed);
51
+ else
52
+ for (const _ of run.text)
53
+ element++;
54
+ }
55
+ }
56
+ return embeds;
57
+ }
58
+ /** Whether a token stands for an embed, not for a code point, which is at most two UTF-16 units and never U+FFFC and more. */
59
+ function isEmbed(token) {
60
+ return token.length > 1 && token.startsWith(EMBED_CHARACTER);
61
+ }
62
+ /**
63
+ * The one replacement that turns `before` into `after`: `count` code points from `index` become
64
+ * `insert`. An insertion or deletion within a run of equal elements could be at any place in the
65
+ * run; with `caret`, the element gap of the caret after the edit, it is where the caret is, so that
66
+ * deleting one of two equal embeds deletes the one the user deleted.
67
+ */
68
+ function splice(before, after, caret) {
69
+ let prefix = 0;
70
+ while (prefix < before.length && prefix < after.length && before[prefix] === after[prefix])
71
+ prefix++;
72
+ let suffix = 0;
73
+ while (suffix < before.length - prefix && suffix < after.length - prefix &&
74
+ before[before.length - 1 - suffix] === after[after.length - 1 - suffix])
75
+ suffix++;
76
+ let index = prefix;
77
+ const count = before.length - prefix - suffix, length = after.length - prefix - suffix;
78
+ if (caret !== undefined && (count === 0) !== (length === 0)) {
79
+ // The longest common prefix puts the edit last in the run: move it back toward the caret.
80
+ const changed = count === 0 ? after : before, size = count + length, target = count === 0 ? caret - length : caret;
81
+ while (index > target && index > 0 && changed[index - 1] === changed[index - 1 + size])
82
+ index--;
83
+ }
84
+ return { index, count, insert: after.slice(index, index + length) };
85
+ }
86
+ /** A fragment's nodes, so that nodes cross between copies of prosemirror-model as an array. */
87
+ function children(fragment) {
88
+ const nodes = [];
89
+ fragment.forEach((node) => { nodes.push(node); });
90
+ return nodes;
91
+ }
92
+ /** Whether a fragment holds exactly `nodes`. */
93
+ function holds(fragment, nodes) {
94
+ return fragment.childCount === nodes.length && nodes.every((node, index) => node.eq(fragment.child(index)));
95
+ }
96
+ /** The length in elements of some lines joined by line breaks. */
97
+ function textLength(lines) {
98
+ return lines.reduce((sum, line) => sum + lineLength(line), 0) + Math.max(0, lines.length - 1);
99
+ }
100
+ /**
101
+ * The top-level children that differ between two documents, with one unchanged neighbor on each
102
+ * side: `[from, toA)` in `a` and `[from, toB)` in `b`. Rebuilding such a window can never call for
103
+ * a merge with a node outside it, since its neighbors' edge lines did not change.
104
+ */
105
+ function changedWindow(a, b) {
106
+ const start = a.content.findDiffStart(b.content);
107
+ if (start === null)
108
+ return undefined;
109
+ const end = a.content.findDiffEnd(b.content) ?? { a: a.content.size, b: b.content.size };
110
+ let endA = end.a, endB = end.b;
111
+ // When the change repeats nearby content, the two ends can overlap the start.
112
+ const overlap = start - Math.min(endA, endB);
113
+ if (overlap > 0) {
114
+ endA += overlap;
115
+ endB += overlap;
116
+ }
117
+ const after = (doc, position) => {
118
+ const resolved = doc.resolve(position);
119
+ return resolved.depth === 0 ? resolved.index(0) : resolved.index(0) + 1;
120
+ };
121
+ const first = Math.min(a.resolve(start).index(0), after(a, endA), after(b, endB));
122
+ return {
123
+ from: Math.max(0, first - 1),
124
+ toA: Math.min(a.childCount, after(a, endA) + 1),
125
+ toB: Math.min(b.childCount, after(b, endB) + 1),
126
+ };
127
+ }
128
+ /** Keeps one editor and one Text in step; created when the plugin's view starts. */
129
+ export class TextBinding {
130
+ shape;
131
+ text;
132
+ doc;
133
+ options;
134
+ view;
135
+ stop;
136
+ /** True while this binding writes, so its own changes are not applied back. */
137
+ writing = false;
138
+ failure;
139
+ /** The selection as cursors, kept current so a change from elsewhere can put it back on the same text. */
140
+ selection;
141
+ composition;
142
+ ending;
143
+ constructor(doc, text, schema, options) {
144
+ this.doc = doc;
145
+ this.text = text;
146
+ this.options = options;
147
+ this.shape = new TextShape(schema, options.mapping ?? basicMapping);
148
+ }
149
+ get failed() { return this.failure !== undefined; }
150
+ get composing() { return this.composition !== undefined; }
151
+ /** Whether a composition that ended waits to be written. */
152
+ get finishing() { return this.ending !== undefined; }
153
+ /** Whether a local edit may be written now. */
154
+ canWrite() {
155
+ return !this.failed && (this.options.canEdit?.() ?? true) && this.doc.replayConflict === null;
156
+ }
157
+ fail(error) {
158
+ if (this.failure === undefined) {
159
+ this.failure = { error };
160
+ this.composition = undefined;
161
+ try {
162
+ this.options.onError?.(error);
163
+ }
164
+ catch { /* Reporting a failure must not replace it. */ }
165
+ }
166
+ throw this.failure.error;
167
+ }
168
+ attach(view) {
169
+ this.view = view;
170
+ this.stop = this.text.observe((event) => { this.received(event); });
171
+ // Show the Text if the editor started from something else.
172
+ const standard = this.shape.doc(textLines(this.text));
173
+ if (!standard.eq(view.state.doc))
174
+ this.show(view, standard);
175
+ else
176
+ this.selection = this.cursorsOf(view.state);
177
+ }
178
+ detach() {
179
+ this.stop?.();
180
+ this.stop = undefined;
181
+ this.view = undefined;
182
+ this.composition = undefined;
183
+ clearTimeout(this.ending);
184
+ }
185
+ /** The selection of `state` as cursors; its document must show the Text. */
186
+ cursorsOf(state) {
187
+ const start = this.shape.elementAt(state.doc, state.selection.from), end = this.shape.elementAt(state.doc, state.selection.to);
188
+ if (start === end) {
189
+ const caret = this.text.cursorAt(start);
190
+ return { from: caret, to: caret };
191
+ }
192
+ return { from: this.text.cursorAt(start, "right"), to: this.text.cursorAt(end) };
193
+ }
194
+ /** A selection's current positions in `doc`, or undefined while an anchor is unknown here. */
195
+ resolve(cursors, doc) {
196
+ const from = this.text.cursorIndex(cursors.from), to = this.text.cursorIndex(cursors.to);
197
+ if (from === undefined || to === undefined)
198
+ return undefined;
199
+ // A deleted selection collapses instead of inverting.
200
+ return { from: this.shape.positionAt(doc, Math.min(from, to)), to: this.shape.positionAt(doc, Math.max(from, to)) };
201
+ }
202
+ /** Replaces the editor's document with `target`, keeping the selection on the same text. */
203
+ show(view, target) {
204
+ const tr = view.state.tr;
205
+ if (!target.eq(tr.doc))
206
+ tr.replaceWith(0, tr.doc.content.size, children(target.content));
207
+ this.restoreSelection(tr);
208
+ view.dispatch(tr.setMeta(syncKey, "text").setMeta("addToHistory", false));
209
+ }
210
+ restoreSelection(tr) {
211
+ const range = this.selection === undefined ? undefined : this.resolve(this.selection, tr.doc);
212
+ if (range !== undefined)
213
+ tr.setSelection(TextSelection.between(tr.doc.resolve(range.from), tr.doc.resolve(range.to)));
214
+ this.selection = this.cursorsOf(tr);
215
+ }
216
+ // Local edits.
217
+ /** Formats `want` from `offset` where the Text's marks there now, `have`, differ: one format per run. */
218
+ formatRuns(want, have, offset) {
219
+ for (const key of Object.keys(this.shape.mapping.marks)) {
220
+ for (let index = 0; index < want.length;) {
221
+ const wanted = want[index]?.[key], had = have[index]?.[key];
222
+ if (want[index] === undefined || sameJson(wanted ?? null, had ?? null)) {
223
+ index++;
224
+ continue;
225
+ }
226
+ let end = index + 1;
227
+ while (end < want.length && want[end] !== undefined && sameJson(want[end]?.[key] ?? null, wanted ?? null) &&
228
+ !sameJson(have[end]?.[key] ?? null, wanted ?? null))
229
+ end++;
230
+ this.text.format(offset + index, end - index, key, wanted ?? null);
231
+ index = end;
232
+ }
233
+ }
234
+ }
235
+ /**
236
+ * Writes `after` over the Text's `before` lines at element `offset`, in the current transaction.
237
+ * Returns whether the Text's lines there hold an embed.
238
+ */
239
+ writeLines(offset, before, after, caret) {
240
+ const change = splice(codePoints(before), codePoints(after), caret === undefined ? undefined : caret - offset);
241
+ const wanted = embedsOf(after);
242
+ if (change.count > 0)
243
+ this.text.delete(offset + change.index, change.count);
244
+ if (wanted.size === 0) {
245
+ if (change.insert.length > 0)
246
+ this.text.insert(offset + change.index, change.insert.join(""));
247
+ }
248
+ else {
249
+ // Runs of text in one insertion, and each embed in one of its own.
250
+ let at = offset + change.index, run = "", length = 0;
251
+ const flush = () => { if (length > 0)
252
+ this.text.insert(at, run); at += length; run = ""; length = 0; };
253
+ for (const [position, token] of change.insert.entries()) {
254
+ const embed = wanted.get(change.index + position);
255
+ if (embed === undefined) {
256
+ run += token;
257
+ length++;
258
+ continue;
259
+ }
260
+ flush();
261
+ this.text.insertEmbed(at++, embed.key, embed.value);
262
+ }
263
+ flush();
264
+ }
265
+ const now = textLines(this.text, offset, textLength(after)), current = embedsOf(now);
266
+ // An embed whose node changed in place keeps its element and takes the new value.
267
+ for (const [index, embed] of current) {
268
+ const want = wanted.get(index);
269
+ if (want !== undefined && want.key === embed.key && !sameJson(want.value, embed.value))
270
+ this.text.setEmbed(offset + index, want.value);
271
+ }
272
+ this.formatRuns(pointMarks(after), pointMarks(now), offset);
273
+ // Paragraph attributes: each line against the Text's line at the same place. Keys the mapping
274
+ // does not use stay as they are.
275
+ let start = offset;
276
+ const keys = this.shape.keys().blocks;
277
+ for (const [index, line] of after.entries()) {
278
+ const have = now[index]?.attributes ?? {};
279
+ for (const key of keys) {
280
+ const value = line.attributes[key];
281
+ if (!this.shape.sameAttribute(key, value, have[key]))
282
+ this.text.formatBlocks(start, 0, key, value ?? null);
283
+ }
284
+ start += lineLength(line) + 1;
285
+ }
286
+ return current.size > 0;
287
+ }
288
+ /** The lines of children `[from, to)` of `doc`. */
289
+ windowLines(doc, from, to) {
290
+ const lines = [];
291
+ for (let index = from; index < to; index++)
292
+ lines.push(...this.shape.nodeLines(doc.child(index)));
293
+ return lines;
294
+ }
295
+ /** The Text element where children `[from, …)` of `doc` start: their first line's. */
296
+ windowStart(doc, from, to) {
297
+ const layout = this.shape.layout(doc);
298
+ for (let index = from; index < to; index++)
299
+ if (layout.lined.includes(index))
300
+ return layout.elements[index];
301
+ return undefined;
302
+ }
303
+ /**
304
+ * Writes the change from `before` to `after`, which shows `before` plus local edits, as one batch.
305
+ * `head`, the caret's position in `after`, places an edit within a run of equal elements. Returns
306
+ * the nodes that show the written part of the Text, with their range in `after`, where they differ
307
+ * from `after`: an embed that showed as U+FFFC on a code line shows as its node once the line is
308
+ * not code.
309
+ */
310
+ write(before, after, head) {
311
+ const window = changedWindow(before, after);
312
+ if (window === undefined)
313
+ return undefined;
314
+ let oldLines = this.windowLines(before, window.from, window.toA);
315
+ let newLines = this.windowLines(after, window.from, window.toB);
316
+ let offset = this.windowStart(before, window.from, window.toA);
317
+ let from = window.from, to = window.toB;
318
+ if (offset === undefined || oldLines.length === 0 || newLines.length === 0) {
319
+ // A window that has no lines on one side: write the whole document.
320
+ oldLines = this.shape.lines(before);
321
+ newLines = this.shape.lines(after);
322
+ offset = 0;
323
+ from = 0;
324
+ to = after.childCount;
325
+ }
326
+ const caret = head === undefined ? undefined : this.shape.elementAt(after, head);
327
+ let embeds = false;
328
+ this.writing = true;
329
+ try {
330
+ this.doc.transact(() => { embeds = this.writeLines(offset, oldLines, newLines, caret); });
331
+ }
332
+ finally {
333
+ this.writing = false;
334
+ }
335
+ // Only a Text with embeds can show otherwise than the editor's own lines.
336
+ if (!embeds)
337
+ return undefined;
338
+ const nodes = this.shape.nodes(textLines(this.text, offset, textLength(newLines))), layout = this.shape.layout(after);
339
+ const fromPos = layout.positions[from] ?? 0, toPos = to < after.childCount ? layout.positions[to] : after.content.size;
340
+ return holds(after.slice(fromPos, toPos).content, nodes) ? undefined : { from: fromPos, to: toPos, nodes };
341
+ }
342
+ /** The standard shape of what changed from `before` to `after`, or undefined when already standard. */
343
+ standardize(before, after, tr) {
344
+ const window = changedWindow(before, after);
345
+ if (window === undefined)
346
+ return undefined;
347
+ const lines = this.windowLines(after, window.from, window.toB);
348
+ const whole = window.from === 0 && window.toB === after.childCount;
349
+ const nodes = lines.length === 0 ? (whole ? children(this.shape.doc([]).content) : undefined) : this.shape.nodes(lines);
350
+ // A window without lines inside a larger document: the neighbors' lines decide; rebuild it all.
351
+ const standard = nodes ?? children(this.shape.doc(this.shape.lines(after)).content);
352
+ const fromPos = nodes === undefined ? 0 : this.shape.layout(after).positions[window.from] ?? 0;
353
+ const toPos = nodes === undefined ? after.content.size
354
+ : window.toB < after.childCount ? this.shape.layout(after).positions[window.toB] : after.content.size;
355
+ if (holds(after.slice(fromPos, toPos).content, standard))
356
+ return undefined;
357
+ // The lines stay the same, so the selection keeps its elements.
358
+ const head = this.shape.elementAt(after, tr.selection.head), anchor = this.shape.elementAt(after, tr.selection.anchor);
359
+ tr.replaceWith(fromPos, toPos, standard);
360
+ tr.setSelection(TextSelection.between(tr.doc.resolve(this.shape.positionAt(tr.doc, anchor)), tr.doc.resolve(this.shape.positionAt(tr.doc, head))));
361
+ return tr.setMeta(syncKey, "standard").setMeta("addToHistory", false);
362
+ }
363
+ /** After a local transaction: writes it to the Text. */
364
+ updated(view, previous) {
365
+ if (this.composing || this.failed)
366
+ return;
367
+ const state = view.state;
368
+ if (syncKey.getState(state)?.fromText === true)
369
+ return;
370
+ if (previous.doc !== state.doc) {
371
+ let shown;
372
+ try {
373
+ shown = this.write(previous.doc, state.doc, state.selection.head);
374
+ }
375
+ catch (error) {
376
+ this.fail(error);
377
+ }
378
+ if (shown !== undefined) {
379
+ // The lines stay the same, so the selection keeps its elements.
380
+ this.selection = this.cursorsOf(state);
381
+ const tr = state.tr.replaceWith(shown.from, shown.to, shown.nodes);
382
+ this.restoreSelection(tr);
383
+ view.dispatch(tr.setMeta(syncKey, "text").setMeta("addToHistory", false));
384
+ return;
385
+ }
386
+ }
387
+ if (previous.doc !== state.doc || !previous.selection.eq(state.selection))
388
+ this.selection = this.cursorsOf(state);
389
+ }
390
+ // Changes from elsewhere.
391
+ received(event) {
392
+ const view = this.view;
393
+ if (this.writing || view === undefined || this.failed)
394
+ return;
395
+ if (this.composition !== undefined) {
396
+ this.composition.incoming = true;
397
+ return;
398
+ }
399
+ try {
400
+ this.apply(view, event);
401
+ }
402
+ catch (error) {
403
+ this.fail(error);
404
+ }
405
+ }
406
+ /** Rebuilds just the top-level nodes an event touched, with one neighbor on each side. */
407
+ apply(view, event) {
408
+ const doc = view.state.doc;
409
+ const delta = event.afterLength - event.beforeLength;
410
+ let start = Infinity, endPre = -Infinity, endPost = -Infinity;
411
+ for (const { index, deleteCount } of event.changes) {
412
+ start = Math.min(start, index);
413
+ endPre = Math.max(endPre, index + deleteCount);
414
+ }
415
+ if (endPre > -Infinity)
416
+ endPost = endPre + delta;
417
+ for (const { index, count } of event.formats ?? []) {
418
+ start = Math.min(start, index);
419
+ endPost = Math.max(endPost, index + count);
420
+ }
421
+ for (const { index } of event.blocks ?? []) {
422
+ start = Math.min(start, index);
423
+ endPost = Math.max(endPost, index);
424
+ }
425
+ for (const { index } of event.embeds ?? []) {
426
+ start = Math.min(start, index);
427
+ endPost = Math.max(endPost, index + 1);
428
+ }
429
+ if (start === Infinity)
430
+ return;
431
+ endPre = Math.max(endPre, endPost - delta);
432
+ const first = this.shape.childAtElement(doc, start), last = this.shape.childAtElement(doc, Math.max(start, endPre));
433
+ const from = Math.max(0, first - 1), to = Math.min(doc.childCount, last + 2);
434
+ const offset = this.windowStart(doc, from, to);
435
+ const before = this.windowLines(doc, from, to);
436
+ if (offset === undefined || before.length === 0) {
437
+ this.show(view, this.shape.doc(textLines(this.text)));
438
+ return;
439
+ }
440
+ const lines = textLines(this.text, offset, textLength(before) + delta);
441
+ const layout = this.shape.layout(doc);
442
+ const fromPos = layout.positions[from], toPos = to < doc.childCount ? layout.positions[to] : doc.content.size;
443
+ const tr = view.state.tr.replaceWith(fromPos, toPos, this.shape.nodes(lines.length === 0 ? [{ runs: [], attributes: {} }] : lines));
444
+ this.restoreSelection(tr);
445
+ view.dispatch(tr.setMeta(syncKey, "text").setMeta("addToHistory", false));
446
+ }
447
+ // Input method compositions.
448
+ /** Starts keeping edits in the editor: candidates are not written until the composition ends. */
449
+ startComposition(state) {
450
+ if (this.composition !== undefined || this.failed)
451
+ return;
452
+ const doc = state.doc;
453
+ const layout = this.shape.layout(doc);
454
+ const head = this.shape.elementAt(doc, state.selection.from), tail = this.shape.elementAt(doc, state.selection.to);
455
+ // The composition's paragraphs: from the start of the selection's first line to the end of its last.
456
+ const lineBounds = (element) => {
457
+ const child = this.shape.childAtElement(doc, element);
458
+ const info = this.shape.nodeInfo(doc.child(child));
459
+ let start = layout.elements[child];
460
+ for (const length of info.lengths) {
461
+ if (element <= start + length)
462
+ return [start, start + length];
463
+ start += length + 1;
464
+ }
465
+ return [start, start];
466
+ };
467
+ const from = lineBounds(head)[0], to = lineBounds(tail)[1];
468
+ const gaps = [];
469
+ for (let element = from; element <= to; element++)
470
+ gaps.push({ left: this.text.cursorAt(element), right: this.text.cursorAt(element, "right") });
471
+ this.composition = { base: doc, from, gaps, selection: this.selection, incoming: false, cancelled: false };
472
+ }
473
+ /** Marks the composition cancelled, as an Escape that ends it does. */
474
+ cancelComposition() { if (this.composition !== undefined)
475
+ this.composition.cancelled = true; }
476
+ /** Undoes a cancellation, as a key that keeps composing does. */
477
+ resumeComposition() { if (this.composition !== undefined)
478
+ this.composition.cancelled = false; }
479
+ /** Ends the composition once ProseMirror has read its final text. */
480
+ scheduleFinish(view) {
481
+ this.ending ??= setTimeout(() => { this.ending = undefined; if (!view.composing)
482
+ this.finishComposition(view); }, 0);
483
+ }
484
+ /**
485
+ * Writes the composition's text as one batch, unless it was cancelled, and shows the changes from
486
+ * elsewhere that waited. A composition that cannot be written goes to `onUnsentComposition`.
487
+ */
488
+ finishComposition(view) {
489
+ clearTimeout(this.ending);
490
+ this.ending = undefined;
491
+ const started = this.composition;
492
+ if (started === undefined || this.failed)
493
+ return;
494
+ this.composition = undefined;
495
+ try {
496
+ const draft = view.state.doc;
497
+ const window = changedWindow(started.base, draft);
498
+ const before = window === undefined ? [] : this.windowLines(started.base, window.from, window.toA);
499
+ const after = window === undefined ? [] : this.windowLines(draft, window.from, window.toB);
500
+ const offset = window === undefined ? 0 : this.windowStart(started.base, window.from, window.toA) ?? 0;
501
+ let unsent = window !== undefined && !started.cancelled;
502
+ let rebased;
503
+ // The caret ends the composed text, which places it within a run of equal elements.
504
+ const head = view.state.selection.head;
505
+ const change = splice(codePoints(before), codePoints(after), this.shape.elementAt(draft, head) - offset);
506
+ if (unsent && this.canWrite()) {
507
+ this.options.history?.stopCapturing();
508
+ this.writing = true;
509
+ try {
510
+ if (!started.incoming) {
511
+ // Nothing changed elsewhere: the usual comparison is exact.
512
+ this.write(started.base, draft, head);
513
+ unsent = false;
514
+ }
515
+ else {
516
+ this.doc.transact(() => { rebased = this.rebase(started, offset, before, after, change); });
517
+ unsent = rebased === undefined;
518
+ }
519
+ }
520
+ finally {
521
+ this.writing = false;
522
+ }
523
+ this.options.history?.stopCapturing();
524
+ }
525
+ if (started.cancelled || unsent)
526
+ this.selection = started.selection;
527
+ else if (!started.incoming)
528
+ this.selection = this.cursorsOf(view.state);
529
+ else {
530
+ // The caret in the draft: in the inserted text, or in the base lines around it.
531
+ const element = this.shape.elementAt(draft, head), index = offset + change.index;
532
+ const shift = change.insert.length - change.count;
533
+ if (rebased !== undefined && element >= index && element <= index + change.insert.length) {
534
+ const caret = this.text.cursorAt(rebased + element - index);
535
+ this.selection = { from: caret, to: caret };
536
+ }
537
+ else {
538
+ const gap = started.gaps[(element < index ? element : element - shift) - started.from];
539
+ this.selection = gap === undefined ? started.selection : { from: gap.left, to: gap.left };
540
+ }
541
+ }
542
+ // Shown even when unchanged, so the selection and other writers' carets are placed again.
543
+ this.show(view, this.shape.doc(textLines(this.text)));
544
+ if (unsent) {
545
+ this.options.onUnsentComposition?.(change.insert.map((token) => (isEmbed(token) ? EMBED_CHARACTER : token)).join("") || "(a deletion)");
546
+ }
547
+ }
548
+ catch (error) {
549
+ this.fail(error);
550
+ }
551
+ }
552
+ /**
553
+ * Writes a composition's replacement into a Text that changed since it started: elements deleted
554
+ * elsewhere stay deleted, and text inserted elsewhere stays. Returns where the inserted text
555
+ * starts, or undefined when the change is not inside the composition's paragraphs.
556
+ */
557
+ rebase(started, offset, before, after, change) {
558
+ const index = offset + change.index, { count, insert } = change, { from, gaps } = started;
559
+ // A composition types text: a replacement with a line break or an embed is something else.
560
+ if (index < from || index + count > from + gaps.length - 1 || insert.includes("\n") || insert.some(isEmbed))
561
+ return undefined;
562
+ // Formatting outside the replacement is not a composition's: leave such a change unsent.
563
+ const marksBefore = pointMarks(before), marksAfter = pointMarks(after), shift = insert.length - count;
564
+ for (const [at, marks] of marksAfter.entries()) {
565
+ if (at >= change.index && at < change.index + insert.length)
566
+ continue;
567
+ if (!sameJson(marks ?? null, marksBefore[at < change.index ? at : at - shift] ?? null))
568
+ return undefined;
569
+ }
570
+ if (!sameJson(after.map((line) => line.attributes), before.map((line) => line.attributes)))
571
+ return undefined;
572
+ const gap = (element) => {
573
+ const found = gaps[element - from];
574
+ if (found === undefined)
575
+ throw new Error("Composition gap out of range");
576
+ return found;
577
+ };
578
+ const removed = [];
579
+ for (let element = index; element < index + count; element++) {
580
+ // Both cursors bind to the element: the gaps before and after it are one apart while it exists.
581
+ const start = this.text.cursorIndex(gap(element).right), end = this.text.cursorIndex(gap(element + 1).left);
582
+ if (start !== undefined && end === start + 1)
583
+ removed.push(start);
584
+ }
585
+ for (const element of removed.toSorted((a, b) => b - a))
586
+ this.text.delete(element, 1);
587
+ const at = this.text.cursorIndex(gap(index).left);
588
+ if (at === undefined)
589
+ throw new Error("Composition position is not known");
590
+ if (insert.length === 0)
591
+ return at;
592
+ this.text.insert(at, insert.join(""));
593
+ const wanted = marksAfter.slice(change.index, change.index + insert.length);
594
+ const have = pointMarks(textLines(this.text, at, insert.length));
595
+ this.formatRuns(wanted, have, at);
596
+ return at;
597
+ }
598
+ }
599
+ /**
600
+ * A ProseMirror plugin that keeps the editor and the Text at `path` in step. Local transactions are
601
+ * compared with the Text only where they changed the document, and written as one batch; changes
602
+ * from elsewhere rebuild only the top-level nodes they touched. The editor always shows the Text's
603
+ * standard shape. An input method composition is written once confirmed, and not at all when
604
+ * Escape cancels it.
605
+ */
606
+ export function textSync(doc, path, options = {}) {
607
+ const synced = doc;
608
+ if (!Object.hasOwn(synced.state, path))
609
+ throw new TypeError(`Unknown collection path: ${path}`);
610
+ const collection = synced.state[path];
611
+ if (typeof collection !== "object" || collection === null || !("toDelta" in collection))
612
+ throw new TypeError(`Not a Text collection: ${path}`);
613
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- A Text, checked above; its mark and block keys come from the mapping.
614
+ const text = collection;
615
+ let binding;
616
+ const bindingFor = (schema) => (binding ??= new TextBinding(synced, text, schema, options));
617
+ return new Plugin({
618
+ key: syncKey,
619
+ state: {
620
+ init: (_config, state) => {
621
+ // Nodes and selections are checked by class: the editor must load the same ProseMirror as this package.
622
+ if (!(state.doc instanceof Node) || !(state.selection instanceof Selection)) {
623
+ throw new TypeError("The editor loads another copy of prosemirror-model or prosemirror-state than @articollab/prosemirror: " +
624
+ "install one version of each, such as the one your editor depends on");
625
+ }
626
+ return { binding: bindingFor(state.schema), fromText: false };
627
+ },
628
+ apply: (tr, value) => {
629
+ const fromText = tr.getMeta(syncKey) === "text";
630
+ return value.fromText === fromText ? value : { binding: value.binding, fromText };
631
+ },
632
+ },
633
+ filterTransaction(tr, state) {
634
+ const own = bindingFor(state.schema);
635
+ // A composition that started before its compositionstart event reached this editor.
636
+ if (!own.composing && tr.getMeta("composition") !== undefined)
637
+ own.startComposition(state);
638
+ if (!tr.docChanged || tr.getMeta(syncKey) !== undefined || own.composing)
639
+ return true;
640
+ // Refused edits leave the editor as it was.
641
+ return own.canWrite();
642
+ },
643
+ appendTransaction(transactions, oldState, newState) {
644
+ const own = bindingFor(newState.schema);
645
+ if (own.composing || own.failed || oldState.doc === newState.doc)
646
+ return null;
647
+ if (transactions.some((tr) => tr.getMeta(syncKey) === "text"))
648
+ return null;
649
+ return own.standardize(oldState.doc, newState.doc, newState.tr) ?? null;
650
+ },
651
+ view(view) {
652
+ const own = bindingFor(view.state.schema);
653
+ own.attach(view);
654
+ return {
655
+ update(updated, previous) {
656
+ if (own.composing && !updated.composing)
657
+ own.scheduleFinish(updated);
658
+ own.updated(updated, previous);
659
+ },
660
+ destroy() { own.detach(); },
661
+ };
662
+ },
663
+ props: {
664
+ handleDOMEvents: {
665
+ compositionstart(view) {
666
+ const own = bindingFor(view.state.schema);
667
+ // The last composition is still waiting to be written: write it first.
668
+ if (own.finishing)
669
+ own.finishComposition(view);
670
+ own.startComposition(view.state);
671
+ return false;
672
+ },
673
+ compositionend(view) { bindingFor(view.state.schema).scheduleFinish(view); return false; },
674
+ keydown(view, event) {
675
+ const own = bindingFor(view.state.schema);
676
+ if (!own.composing)
677
+ return false;
678
+ // A key after the composition, which ProseMirror may end without compositionend: write it first.
679
+ if (!view.composing)
680
+ own.finishComposition(view);
681
+ // macOS Zhuyin can end an Escape cancellation with the phonetic text still in the editor.
682
+ else if (event.key === "Escape")
683
+ own.cancelComposition();
684
+ else if (event.isComposing)
685
+ own.resumeComposition();
686
+ return false;
687
+ },
688
+ },
689
+ },
690
+ });
691
+ }
692
+ /** The ProseMirror document showing a Text, in the mapping's standard shape. */
693
+ export function textToDoc(text, schema, mapping = basicMapping) {
694
+ return new TextShape(schema, mapping).doc(textLines(text));
695
+ }
696
+ /** The editor's selection as cursors, for sharing as presence; undefined without the `textSync` plugin. */
697
+ export function selectionCursors(state) {
698
+ const sync = syncKey.getState(state);
699
+ if (sync === undefined || sync.binding.composing)
700
+ return undefined;
701
+ return sync.binding.selection ?? sync.binding.cursorsOf(state);
702
+ }
703
+ /** Another writer's selection in this editor's positions, or undefined while its text is unknown here. */
704
+ export function resolveSelection(state, cursors) {
705
+ const sync = syncKey.getState(state);
706
+ if (sync === undefined || sync.binding.composing)
707
+ return undefined;
708
+ return sync.binding.resolve(cursors, state.doc);
709
+ }
710
+ /** The binding of an editor with the `textSync` plugin. Internal, for the remote selections plugin. */
711
+ export function bindingOf(state) {
712
+ return syncKey.getState(state)?.binding;
713
+ }
714
+ /** Whether an input method composition is open in the editor; commands and keys should wait for it. */
715
+ export function isComposing(view) {
716
+ return view.composing || bindingOf(view.state)?.composing === true;
717
+ }
718
+ /** Whether `tr` shows a change from the Text, which positions from cursors already match. */
719
+ export function isFromText(tr) {
720
+ return tr.getMeta(syncKey) === "text";
721
+ }
722
+ /** A command that undoes this writer's latest change; false when there is nothing to undo or undo is not possible now. */
723
+ export function undo(history) {
724
+ return (state, dispatch, view) => {
725
+ if (!history.canUndo || bindingOf(state)?.composing === true || view?.composing === true)
726
+ return false;
727
+ if (dispatch === undefined)
728
+ return true;
729
+ try {
730
+ return history.undo();
731
+ }
732
+ catch {
733
+ return false;
734
+ }
735
+ };
736
+ }
737
+ /** A command that redoes the latest undone change. */
738
+ export function redo(history) {
739
+ return (state, dispatch, view) => {
740
+ if (!history.canRedo || bindingOf(state)?.composing === true || view?.composing === true)
741
+ return false;
742
+ if (dispatch === undefined)
743
+ return true;
744
+ try {
745
+ return history.redo();
746
+ }
747
+ catch {
748
+ return false;
749
+ }
750
+ };
751
+ }
752
+ //# sourceMappingURL=sync.js.map