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

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