@articollab/codemirror 0.0.0-stage → 0.13.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.
package/dist/sync.js ADDED
@@ -0,0 +1,759 @@
1
+ import { Annotation, ChangeSet, EditorState, Facet, MapMode, StateEffect, StateField, Transaction, } from "@codemirror/state";
2
+ import { Decoration, EditorView, ViewPlugin } from "@codemirror/view";
3
+ import { createMirror, editorEdits, editorOffset, elementIndexAt, textEdits } from "./mirror.js";
4
+ /** A change the editor shows because the Text changed: already in the Text, so never written back. */
5
+ const fromText = Annotation.define();
6
+ /** A transaction on a composition's shadow state, which is no local edit either. */
7
+ const internal = Annotation.define();
8
+ const setMarks = StateEffect.define();
9
+ const setLines = StateEffect.define();
10
+ const setEmbeds = StateEffect.define();
11
+ const restoreFormatting = StateEffect.define();
12
+ /** Replaces the remote selections the editor draws. */
13
+ const setRemoteRanges = StateEffect.define();
14
+ /** Replaces the marks of each run; a run with no attributes clears it. */
15
+ function applyMarks(ranges, runs) {
16
+ let result = [...ranges];
17
+ for (const run of runs) {
18
+ const next = [];
19
+ for (const range of result) {
20
+ if (range.to <= run.from || range.from >= run.to) {
21
+ next.push(range);
22
+ continue;
23
+ }
24
+ if (range.from < run.from)
25
+ next.push({ ...range, to: run.from });
26
+ if (range.to > run.to)
27
+ next.push({ ...range, from: run.to });
28
+ }
29
+ if (Object.keys(run.attributes).length !== 0 && run.from < run.to)
30
+ next.push(run);
31
+ result = next.toSorted((left, right) => left.from - right.from);
32
+ }
33
+ // Join touching runs with the same marks; the Text sorts attribute keys, so JSON compares them.
34
+ return result.reduce((joined, range) => {
35
+ const last = joined.at(-1);
36
+ if (last !== undefined && last.to === range.from && JSON.stringify(last.attributes) === JSON.stringify(range.attributes)) {
37
+ joined[joined.length - 1] = { ...last, to: range.to };
38
+ }
39
+ else
40
+ joined.push(range);
41
+ return joined;
42
+ }, []);
43
+ }
44
+ const NO_FORMATTING = { marks: [], lines: [], embeds: [] };
45
+ /**
46
+ * The Text's formatting, kept in the editor's offsets. Text inserted at a run's edge is outside it
47
+ * until the Text's change event says otherwise, which the binding applies right after the edit.
48
+ */
49
+ const formatting = StateField.define({
50
+ create: (state) => state.facet(bindings)[0]?.initialFormatting() ?? NO_FORMATTING,
51
+ update(value, tr) {
52
+ for (const effect of tr.effects)
53
+ if (effect.is(restoreFormatting))
54
+ return effect.value;
55
+ let { marks, lines, embeds } = value;
56
+ if (tr.docChanged) {
57
+ marks = marks.flatMap((range) => {
58
+ const from = tr.changes.mapPos(range.from, 1), to = tr.changes.mapPos(range.to, -1);
59
+ return from < to ? [{ ...range, from, to }] : [];
60
+ });
61
+ const kept = new Map();
62
+ for (const line of lines) {
63
+ // A line whose "\n" was deleted, even if replaced, loses its entry: the Text says what a new one has.
64
+ const from = line.from === 0 ? 0 : tr.changes.mapPos(line.from, -1, MapMode.TrackBefore);
65
+ if (from !== null && tr.state.doc.lineAt(from).from === from)
66
+ kept.set(from, line.attributes);
67
+ }
68
+ lines = [...kept].map(([from, attributes]) => ({ from, attributes }));
69
+ // An embed whose U+FFFC was deleted, even if replaced, is gone.
70
+ embeds = embeds.flatMap((entry) => {
71
+ const from = tr.changes.mapPos(entry.from, 1, MapMode.TrackAfter);
72
+ return from === null ? [] : [{ ...entry, from }];
73
+ });
74
+ }
75
+ for (const effect of tr.effects) {
76
+ if (effect.is(setMarks))
77
+ marks = applyMarks(marks, effect.value);
78
+ else if (effect.is(setLines)) {
79
+ const next = new Map(lines.map((line) => [line.from, line.attributes]));
80
+ for (const { from, attributes } of effect.value) {
81
+ if (Object.keys(attributes).length === 0)
82
+ next.delete(from);
83
+ else
84
+ next.set(from, attributes);
85
+ }
86
+ lines = [...next].map(([from, attributes]) => ({ from, attributes }));
87
+ }
88
+ else if (effect.is(setEmbeds)) {
89
+ const next = new Map(embeds.map((entry) => [entry.from, entry.embed]));
90
+ for (const { from, embed } of effect.value)
91
+ next.set(from, embed);
92
+ embeds = [...next].map(([from, embed]) => ({ from, embed }));
93
+ }
94
+ }
95
+ if (marks === value.marks && lines === value.lines && embeds === value.embeds)
96
+ return value;
97
+ return {
98
+ marks, lines: lines.toSorted((left, right) => left.from - right.from),
99
+ embeds: embeds.toSorted((left, right) => left.from - right.from),
100
+ };
101
+ },
102
+ });
103
+ /**
104
+ * Other writers' selections, resolved from their cursors when they are set and after the document
105
+ * changes. In between, a range start stays after text inserted at it, and an end or a caret before.
106
+ */
107
+ export const remoteRanges = StateField.define({
108
+ create: () => [],
109
+ update(ranges, tr) {
110
+ for (const effect of tr.effects)
111
+ if (effect.is(setRemoteRanges))
112
+ return effect.value;
113
+ if (!tr.docChanged || ranges.length === 0)
114
+ return ranges;
115
+ return ranges.map((range) => {
116
+ const to = tr.changes.mapPos(range.to, -1);
117
+ const from = range.from === range.to ? to : Math.min(tr.changes.mapPos(range.from, 1), to);
118
+ return { label: range.label, from, to };
119
+ });
120
+ },
121
+ });
122
+ /** Keeps one editor and one Text in step. */
123
+ export class TextBinding {
124
+ mirror;
125
+ view;
126
+ unsubscribe;
127
+ local = false;
128
+ localMarks = [];
129
+ localLines = [];
130
+ localEmbeds = [];
131
+ flushScheduled = false;
132
+ remoteScheduled = false;
133
+ composition;
134
+ failure;
135
+ /** The editor did not start from the Text's content and waits to be replaced with it. */
136
+ resetting = false;
137
+ /** Selections from `setRemoteSelections`, resolved again after each change. */
138
+ remote = [];
139
+ doc;
140
+ text;
141
+ options;
142
+ constructor(doc, text, options) {
143
+ this.doc = doc;
144
+ this.text = text;
145
+ this.options = options;
146
+ this.mirror = createMirror(text);
147
+ }
148
+ get composing() { return this.composition !== undefined; }
149
+ get failed() { return this.failure !== undefined; }
150
+ /** Whether a local edit may be written now. */
151
+ canWrite() {
152
+ return this.view !== undefined && this.failure === undefined && !this.resetting && this.doc.replayConflict === null &&
153
+ (this.options.canEdit?.() ?? true);
154
+ }
155
+ /** The Text's formatting in UTF-16 offsets, for a new editor state. */
156
+ initialFormatting() {
157
+ const mirror = createMirror(this.text);
158
+ const marks = [];
159
+ const embeds = [];
160
+ let index = 0;
161
+ for (const { insert, attributes } of this.text.toDelta()) {
162
+ // oxlint-disable-next-line typescript/no-misused-spread -- The Text counts code points, as the spread does.
163
+ const count = typeof insert === "string" ? [...insert].length : 1;
164
+ const from = editorOffset(mirror, index), to = editorOffset(mirror, index + count);
165
+ if (attributes !== undefined && Object.keys(attributes).length !== 0)
166
+ marks.push({ from, to, attributes });
167
+ if (typeof insert !== "string")
168
+ embeds.push({ from, embed: insert });
169
+ index += count;
170
+ }
171
+ const lines = this.text.blocks().filter(({ attributes }) => Object.keys(attributes).length !== 0)
172
+ .map(({ index: start, attributes }) => ({ from: editorOffset(mirror, start), attributes }));
173
+ return { marks: applyMarks([], marks), lines, embeds };
174
+ }
175
+ /** Starts following `view`; after `detach`, such as for `view.setState()`, it can attach again. */
176
+ attach(view) {
177
+ if (this.view !== undefined)
178
+ throw new Error("This textSync extension is already in an editor: create one per editor");
179
+ this.view = view;
180
+ this.mirror = createMirror(this.text);
181
+ this.unsubscribe = this.text.observe((event) => { this.received(event); });
182
+ if (view.state.doc.toString() !== this.text.toString()) {
183
+ // Shown as a change from the Text once the editor has finished starting.
184
+ this.resetting = true;
185
+ queueMicrotask(() => { this.reset(); });
186
+ }
187
+ }
188
+ detach(view) {
189
+ if (this.view !== view)
190
+ return;
191
+ this.view = undefined;
192
+ this.composition = undefined;
193
+ this.resetting = false;
194
+ this.localMarks = [];
195
+ this.localLines = [];
196
+ this.localEmbeds = [];
197
+ this.unsubscribe?.();
198
+ this.unsubscribe = undefined;
199
+ }
200
+ stop(error) {
201
+ if (this.failure !== undefined)
202
+ throw this.failure.error;
203
+ this.failure = { error };
204
+ this.composition = undefined;
205
+ try {
206
+ this.options.onError?.(error);
207
+ }
208
+ catch { /* Reporting a failure must not replace it. */ }
209
+ throw error;
210
+ }
211
+ /** Runs `work`, stopping the binding if it throws; an error that already stopped it is not reported again. */
212
+ guard(work) {
213
+ try {
214
+ work();
215
+ }
216
+ catch (error) {
217
+ if (this.failure === undefined) {
218
+ try {
219
+ this.stop(error);
220
+ }
221
+ catch { /* Reported through onError. */ }
222
+ }
223
+ }
224
+ }
225
+ reset() {
226
+ const view = this.view;
227
+ if (view === undefined || !this.resetting)
228
+ return;
229
+ this.guard(() => {
230
+ this.mirror = createMirror(this.text);
231
+ const insert = this.text.toString();
232
+ this.resetting = false;
233
+ view.dispatch({
234
+ changes: { from: 0, to: view.state.doc.length, insert },
235
+ effects: restoreFormatting.of(this.initialFormatting()),
236
+ annotations: [fromText.of(true), Transaction.addToHistory.of(false), Transaction.remote.of(true)],
237
+ });
238
+ });
239
+ }
240
+ writeEdits(edits) {
241
+ if (edits.length === 0)
242
+ return;
243
+ this.local = true;
244
+ try {
245
+ this.doc.transact(() => {
246
+ for (const edit of edits) {
247
+ if (edit.deleteCount !== 0)
248
+ this.text.delete(edit.index, edit.deleteCount);
249
+ if (edit.insert !== "")
250
+ this.text.insert(edit.index, edit.insert);
251
+ }
252
+ });
253
+ }
254
+ finally {
255
+ this.local = false;
256
+ }
257
+ }
258
+ /** The formatting the Text gave this writer's own edits, as effects; the pending lists empty. */
259
+ takeLocalFormatting() {
260
+ const effects = [setMarks.of(this.localMarks), setLines.of(this.localLines), setEmbeds.of(this.localEmbeds)];
261
+ this.localMarks = [];
262
+ this.localLines = [];
263
+ this.localEmbeds = [];
264
+ return effects;
265
+ }
266
+ get hasLocalFormatting() {
267
+ return this.localMarks.length !== 0 || this.localLines.length !== 0 || this.localEmbeds.length !== 0;
268
+ }
269
+ /** A change to the Text: from this editor, from another writer, or from undo. */
270
+ received(event) {
271
+ this.guard(() => {
272
+ if (this.failure !== undefined)
273
+ throw this.failure.error;
274
+ const next = textEdits(this.mirror, event);
275
+ this.mirror = next.mirror;
276
+ const { marks, lines, embeds } = this.formattingOf(event);
277
+ // This editor's own edit: the editor already shows it, and its formatting follows once the update ends.
278
+ if (this.local) {
279
+ this.localMarks.push(...marks);
280
+ this.localLines.push(...lines);
281
+ this.localEmbeds.push(...embeds);
282
+ return;
283
+ }
284
+ const view = this.view;
285
+ if (view === undefined || this.resetting)
286
+ return;
287
+ const shared = this.composition?.shared ?? view.state;
288
+ const changes = next.changes.filter(({ from, to, insert }) => shared.doc.sliceString(from, to, "\n") !== insert);
289
+ if (changes.length === 0 && marks.length === 0 && lines.length === 0 && embeds.length === 0)
290
+ return;
291
+ let effects = [setMarks.of(marks), setLines.of(lines), setEmbeds.of(embeds)];
292
+ if (this.composition === undefined && this.hasLocalFormatting) {
293
+ // This writer's own formatting is older: map it through the change and apply it first.
294
+ this.mapLocalFormatting(view.state.changes(changes));
295
+ effects = [...this.takeLocalFormatting(), ...effects];
296
+ }
297
+ if (this.composition !== undefined) {
298
+ // Kept out of the composing editor until the composition ends.
299
+ const tr = shared.update({ changes, effects, annotations: internal.of(true) });
300
+ this.composition.shared = tr.state;
301
+ this.composition.incoming = this.composition.incoming.compose(tr.changes);
302
+ return;
303
+ }
304
+ view.dispatch({
305
+ changes, effects,
306
+ annotations: [fromText.of(true), Transaction.addToHistory.of(false), Transaction.remote.of(true)],
307
+ });
308
+ this.scheduleRemote();
309
+ });
310
+ }
311
+ /**
312
+ * The formatting an event changed, as effects in the editor's offsets after it. Inserted text can
313
+ * be text that is not new, such as text a rebase removed and put back with its marks, an embed or
314
+ * a "\n" that starts a paragraph with attributes. So the marks of inserted runs, each inserted
315
+ * U+FFFC and each paragraph after an inserted "\n" are read from the Text, along with what the
316
+ * event lists as changed.
317
+ */
318
+ formattingOf(event) {
319
+ const marks = [];
320
+ const embeds = new Map();
321
+ const starts = new Set();
322
+ // In ascending order, each change's elements land after the shifts of the changes before it.
323
+ let shift = 0;
324
+ for (const { index, deleteCount, insert } of event.changes.toReversed()) {
325
+ let position = index + shift;
326
+ for (const { insert: run, attributes } of insert.length === 0 ? [] : this.text.toDelta(position, insert.length)) {
327
+ // oxlint-disable-next-line typescript/no-misused-spread -- The Text counts code points, as the spread does.
328
+ const count = typeof run === "string" ? [...run].length : 1;
329
+ marks.push({ from: editorOffset(this.mirror, position), to: editorOffset(this.mirror, position + count), attributes: attributes ?? {} });
330
+ position += count;
331
+ }
332
+ insert.forEach((element, offset) => {
333
+ const at = index + shift + offset;
334
+ if (element === "\n")
335
+ starts.add(at + 1);
336
+ else if (element === "\ufffc") {
337
+ const embed = this.text.embedAt(at);
338
+ if (embed !== undefined)
339
+ embeds.set(at, embed);
340
+ }
341
+ });
342
+ shift += insert.length - deleteCount;
343
+ }
344
+ for (const { index, count, attributes } of event.formats ?? []) {
345
+ marks.push({ from: editorOffset(this.mirror, index), to: editorOffset(this.mirror, index + count), attributes });
346
+ }
347
+ for (const { index, embed } of event.embeds ?? [])
348
+ embeds.set(index, embed);
349
+ const lines = new Map();
350
+ for (const start of starts)
351
+ lines.set(start, this.text.blocks(start, 0).find((block) => block.index === start)?.attributes ?? {});
352
+ for (const { index, attributes } of event.blocks ?? [])
353
+ lines.set(index, attributes);
354
+ return {
355
+ marks,
356
+ embeds: [...embeds].map(([index, embed]) => ({ from: editorOffset(this.mirror, index), embed })),
357
+ lines: [...lines].map(([index, attributes]) => ({ from: editorOffset(this.mirror, index), attributes })),
358
+ };
359
+ }
360
+ /** Writes the local edits of a view update to the Text; called from the plugin's update. */
361
+ updated(update) {
362
+ if (this.view !== update.view || this.failure !== undefined)
363
+ return;
364
+ this.guard(() => {
365
+ for (const tr of update.transactions) {
366
+ // Formatting from an earlier transaction of this update is in that transaction's offsets.
367
+ if (tr.docChanged && this.hasLocalFormatting)
368
+ this.mapLocalFormatting(tr.changes);
369
+ if (tr.annotation(fromText) === true)
370
+ continue;
371
+ // A composition whose compositionstart this editor did not see. A compose transaction after the
372
+ // composition ended is the browser's final text, written as any other edit.
373
+ if (this.composition === undefined && tr.docChanged && update.view.compositionStarted)
374
+ this.startComposition(tr.startState);
375
+ if (this.composition !== undefined) {
376
+ if (tr.docChanged)
377
+ this.composition.draft = this.composition.draft.compose(tr.changes);
378
+ continue;
379
+ }
380
+ if (!tr.docChanged)
381
+ continue;
382
+ this.writeEdits(editorEdits(this.mirror, tr));
383
+ }
384
+ });
385
+ if (this.hasLocalFormatting)
386
+ this.scheduleFlush();
387
+ if (update.docChanged)
388
+ this.scheduleRemote();
389
+ }
390
+ mapLocalFormatting(changes) {
391
+ this.localMarks = this.localMarks.map((range) => ({ ...range, from: changes.mapPos(range.from, 1), to: changes.mapPos(range.to, -1) }));
392
+ // As in the editor's state, a line or an embed whose character was deleted is gone.
393
+ this.localLines = this.localLines.flatMap((line) => {
394
+ const from = line.from === 0 ? 0 : changes.mapPos(line.from, -1, MapMode.TrackBefore);
395
+ return from === null ? [] : [{ ...line, from }];
396
+ });
397
+ this.localEmbeds = this.localEmbeds.flatMap((entry) => {
398
+ const from = changes.mapPos(entry.from, 1, MapMode.TrackAfter);
399
+ return from === null ? [] : [{ ...entry, from }];
400
+ });
401
+ }
402
+ /** Applies the formatting of this writer's own edits once the editor's update has ended. */
403
+ scheduleFlush() {
404
+ if (this.flushScheduled)
405
+ return;
406
+ this.flushScheduled = true;
407
+ queueMicrotask(() => {
408
+ this.flushScheduled = false;
409
+ const view = this.view;
410
+ if (view === undefined || !this.hasLocalFormatting)
411
+ return;
412
+ // Unformatted text where the editor shows no marks needs nothing, so plain typing costs no second update.
413
+ const shown = view.state.field(formatting).marks;
414
+ this.localMarks = this.localMarks.filter(({ from, to, attributes }) => Object.keys(attributes).length !== 0 || shown.some((range) => range.from < to && range.to > from));
415
+ if (!this.hasLocalFormatting)
416
+ return;
417
+ this.guard(() => { view.dispatch({ effects: this.takeLocalFormatting(), annotations: fromText.of(true) }); });
418
+ });
419
+ }
420
+ /** Places the remote selections again from their cursors, once the editor's update has ended. */
421
+ scheduleRemote() {
422
+ if (this.remote.length === 0 || this.remoteScheduled)
423
+ return;
424
+ this.remoteScheduled = true;
425
+ queueMicrotask(() => {
426
+ this.remoteScheduled = false;
427
+ const view = this.view;
428
+ if (view !== undefined && this.failure === undefined && this.composition === undefined) {
429
+ this.guard(() => { this.resolveRemote(view); });
430
+ }
431
+ });
432
+ }
433
+ /** Resolves the remote selections and, unless a composition is open, shows them. */
434
+ resolveRemote(view) {
435
+ const statuses = [];
436
+ const ranges = [];
437
+ for (const { label, selection } of this.remote) {
438
+ const from = this.text.cursorIndex(selection.from);
439
+ const to = this.text.cursorIndex(selection.to);
440
+ if (from === undefined || to === undefined) {
441
+ statuses.push({ label, resolved: false });
442
+ continue;
443
+ }
444
+ statuses.push({ label, resolved: true });
445
+ // A deleted selection collapses instead of inverting.
446
+ const end = Math.max(from, to);
447
+ ranges.push({ label, from: editorOffset(this.mirror, from), to: editorOffset(this.mirror, end) });
448
+ }
449
+ if (this.composition === undefined && !this.resetting && view.state.field(remoteRanges, false) !== undefined) {
450
+ view.dispatch({ effects: setRemoteRanges.of(ranges) });
451
+ }
452
+ return statuses;
453
+ }
454
+ startComposition(state) {
455
+ if (this.composition !== undefined || !this.canWrite())
456
+ return;
457
+ // Formatting of this writer's last edits is part of what the composition starts from.
458
+ const base = this.hasLocalFormatting ? state.update({ effects: this.takeLocalFormatting(), annotations: internal.of(true) }).state : state;
459
+ const empty = ChangeSet.empty(state.doc.length);
460
+ this.composition = { base, shared: base, draft: empty, incoming: empty };
461
+ }
462
+ /** Writes a finished composition once, or none if `cancelled`, and shows what arrived meanwhile. */
463
+ finishComposition(cancelled) {
464
+ const completed = this.composition;
465
+ const view = this.view;
466
+ if (completed === undefined || view === undefined || this.failure !== undefined)
467
+ return;
468
+ this.guard(() => {
469
+ const { base, shared, draft, incoming } = completed;
470
+ const changed = [];
471
+ draft.iterChanges((from, to, _fromB, _toB, insert) => {
472
+ if (!base.doc.slice(from, to).eq(insert))
473
+ changed.push({ from, to, insert });
474
+ });
475
+ const net = base.changes(changed);
476
+ const allowed = this.doc.replayConflict === null && (this.options.canEdit?.() ?? true);
477
+ const discard = cancelled || !allowed;
478
+ const translated = discard ? undefined : shared.update({ changes: net.map(incoming), annotations: internal.of(true) });
479
+ const edits = translated === undefined ? [] : editorEdits(this.mirror, translated);
480
+ let final = shared;
481
+ if (translated !== undefined && edits.length !== 0) {
482
+ this.options.history?.stopCapturing();
483
+ this.writeEdits(edits);
484
+ this.options.history?.stopCapturing();
485
+ final = translated.state.update({ effects: this.takeLocalFormatting(), annotations: internal.of(true) }).state;
486
+ }
487
+ // The editor shows the draft over `base`: undo it, or keep it and add what arrived, ordered before it.
488
+ const changes = discard ? draft.invert(base.doc).compose(incoming) : incoming.map(net, true);
489
+ this.composition = undefined;
490
+ view.dispatch({
491
+ changes, selection: view.state.selection.map(changes),
492
+ effects: restoreFormatting.of(final.field(formatting)),
493
+ annotations: [fromText.of(true), Transaction.addToHistory.of(false)],
494
+ });
495
+ if (!cancelled && !allowed && !net.empty) {
496
+ const unsent = [];
497
+ net.iterChanges((from, to, _fromB, _toB, insert) => {
498
+ unsent.push(insert.length === 0 ? "Delete: " + base.doc.sliceString(from, to) : insert.toString());
499
+ });
500
+ this.options.onUnsentComposition?.(unsent.join("\n"));
501
+ }
502
+ this.scheduleRemote();
503
+ });
504
+ }
505
+ /** The main selection in Text element indices; undefined while a composition is open. */
506
+ indicesOf(state) {
507
+ if (this.composition !== undefined || this.resetting || this.failure !== undefined)
508
+ return undefined;
509
+ const { from, to } = state.selection.main;
510
+ return { start: elementIndexAt(this.mirror, from), end: elementIndexAt(this.mirror, to) };
511
+ }
512
+ cursorsOf(state) {
513
+ const indices = this.indicesOf(state);
514
+ if (indices === undefined)
515
+ return undefined;
516
+ const { start, end } = indices;
517
+ if (start === end) {
518
+ const caret = this.text.cursorAt(start);
519
+ return { from: caret, to: caret };
520
+ }
521
+ return { from: this.text.cursorAt(start, "right"), to: this.text.cursorAt(end) };
522
+ }
523
+ resolve(cursors) {
524
+ if (this.composition !== undefined || this.resetting || this.failure !== undefined)
525
+ return undefined;
526
+ const from = this.text.cursorIndex(cursors.from), to = this.text.cursorIndex(cursors.to);
527
+ if (from === undefined || to === undefined)
528
+ return undefined;
529
+ return { from: editorOffset(this.mirror, from), to: editorOffset(this.mirror, Math.max(from, to)) };
530
+ }
531
+ }
532
+ /** The binding of the editor's `textSync` extension. */
533
+ const bindings = Facet.define();
534
+ /** The binding of an editor with the `textSync` extension. Internal, for the remote selections extension. */
535
+ export function bindingOf(state) {
536
+ return state.facet(bindings)[0];
537
+ }
538
+ /** Composition events, which CodeMirror may send to an EditContext instead of the content element. */
539
+ class CompositionWatcher {
540
+ target;
541
+ /** The composition this watcher is following, by number; a later one ignores an earlier one's timer. */
542
+ generation = 0;
543
+ following = false;
544
+ cancelled = false;
545
+ timer;
546
+ view;
547
+ binding;
548
+ constructor(view, binding) {
549
+ this.view = view;
550
+ this.binding = binding;
551
+ view.contentDOM.addEventListener("keydown", this.key, true);
552
+ this.watch();
553
+ }
554
+ /** Listens where composition events arrive now: CodeMirror attaches an EditContext when the editor becomes editable. */
555
+ watch() {
556
+ const content = this.view.contentDOM;
557
+ const context = "editContext" in content ? content.editContext : undefined;
558
+ const next = context instanceof EventTarget ? context : content;
559
+ if (next === this.target)
560
+ return;
561
+ this.target?.removeEventListener("compositionstart", this.start, true);
562
+ this.target?.removeEventListener("compositionend", this.end);
563
+ this.target = next;
564
+ next.addEventListener("compositionstart", this.start, true);
565
+ next.addEventListener("compositionend", this.end);
566
+ // The content element sends them too while an EditContext is not in use.
567
+ if (next !== content) {
568
+ content.addEventListener("compositionstart", this.start, true);
569
+ content.addEventListener("compositionend", this.end);
570
+ }
571
+ }
572
+ start = () => {
573
+ // The last composition is still waiting to be written: write it first.
574
+ if (this.timer !== undefined)
575
+ this.finish();
576
+ if (!this.binding.composing)
577
+ this.binding.startComposition(this.view.state);
578
+ this.follow();
579
+ };
580
+ /** Follows the binding's open composition, which it may have started from a transaction. */
581
+ follow() {
582
+ if (this.following || !this.binding.composing)
583
+ return;
584
+ this.following = true;
585
+ this.generation++;
586
+ this.cancelled = false;
587
+ }
588
+ key = (event) => {
589
+ if (!this.binding.composing)
590
+ return;
591
+ // A key after the composition, before it was written: write it first.
592
+ if (this.timer !== undefined && !this.view.compositionStarted) {
593
+ this.finish();
594
+ return;
595
+ }
596
+ // macOS Zhuyin can end an Escape cancellation with the phonetic text still in the editor.
597
+ if (event.key === "Escape")
598
+ this.cancelled = true;
599
+ else if (event.isComposing || this.view.compositionStarted)
600
+ this.cancelled = false;
601
+ };
602
+ end = () => {
603
+ this.follow();
604
+ if (!this.binding.composing || this.timer !== undefined)
605
+ return;
606
+ const current = this.generation;
607
+ // The browser's final text can reach CodeMirror after compositionend: wait for it.
608
+ this.timer = setTimeout(() => {
609
+ this.timer = undefined;
610
+ if (this.generation !== current)
611
+ return;
612
+ if (this.view.compositionStarted)
613
+ return; // Another composition went on; its end writes both.
614
+ this.finish();
615
+ }, 0);
616
+ };
617
+ /** Called after each update: a composition the view ended without compositionend ends here. */
618
+ updated() {
619
+ this.watch();
620
+ this.follow();
621
+ if (this.binding.composing && !this.view.compositionStarted)
622
+ this.end();
623
+ }
624
+ finish() {
625
+ clearTimeout(this.timer);
626
+ this.timer = undefined;
627
+ this.following = false;
628
+ this.binding.finishComposition(this.cancelled);
629
+ }
630
+ destroy() {
631
+ clearTimeout(this.timer);
632
+ const content = this.view.contentDOM;
633
+ content.removeEventListener("keydown", this.key, true);
634
+ for (const target of new Set([this.target, content])) {
635
+ target?.removeEventListener("compositionstart", this.start, true);
636
+ target?.removeEventListener("compositionend", this.end);
637
+ }
638
+ }
639
+ }
640
+ /**
641
+ * An extension that keeps the editor and the Text at `path` in step. Local edits are written to the
642
+ * Text, all of a transaction's changes in one batch, and changes from elsewhere are shown in the
643
+ * editor. Offsets are converted between the Text's code points and CodeMirror's UTF-16 units. An
644
+ * input method composition is written once confirmed, and not at all when Escape cancels it. Create
645
+ * the editor with the Text's string as its document; one extension serves one editor.
646
+ */
647
+ export function textSync(doc, path, options = {}) {
648
+ const synced = doc;
649
+ if (!Object.hasOwn(synced.state, path))
650
+ throw new TypeError(`Unknown collection path: ${path}`);
651
+ const collection = synced.state[path];
652
+ if (typeof collection !== "object" || collection === null || !("toDelta" in collection) || !("observe" in collection)) {
653
+ throw new TypeError(`Not a Text collection: ${path}`);
654
+ }
655
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- A Text, checked above.
656
+ const binding = new TextBinding(synced, collection, options);
657
+ const plugin = ViewPlugin.define((view) => {
658
+ binding.attach(view);
659
+ const watcher = new CompositionWatcher(view, binding);
660
+ return {
661
+ update(update) {
662
+ binding.updated(update);
663
+ watcher.updated();
664
+ },
665
+ destroy() {
666
+ watcher.destroy();
667
+ binding.detach(view);
668
+ },
669
+ };
670
+ });
671
+ const extensions = [
672
+ bindings.of(binding),
673
+ formatting,
674
+ // Refused edits leave the editor as it was. A composition's edits wait for it to end.
675
+ EditorState.transactionFilter.of((tr) => {
676
+ if (!tr.docChanged || tr.annotation(fromText) === true || tr.annotation(internal) === true || binding.composing)
677
+ return tr;
678
+ return binding.canWrite() ? tr : [];
679
+ }),
680
+ plugin,
681
+ ];
682
+ const { decorate } = options;
683
+ if (decorate !== undefined) {
684
+ extensions.push(EditorView.decorations.compute([formatting], (state) => {
685
+ const { marks, lines, embeds } = state.field(formatting);
686
+ const ranges = [];
687
+ if (decorate.mark !== undefined) {
688
+ for (const { from, to, attributes } of marks) {
689
+ const decoration = decorate.mark(attributes);
690
+ if (decoration !== null)
691
+ ranges.push(decoration.range(from, to));
692
+ }
693
+ }
694
+ if (decorate.line !== undefined) {
695
+ for (const { from, attributes } of lines) {
696
+ const decoration = decorate.line(attributes);
697
+ if (decoration !== null)
698
+ ranges.push(decoration.range(from));
699
+ }
700
+ }
701
+ if (decorate.embed !== undefined) {
702
+ for (const { from, embed } of embeds) {
703
+ const decoration = decorate.embed(embed);
704
+ if (decoration !== null)
705
+ ranges.push(decoration.range(from, from + 1));
706
+ }
707
+ }
708
+ return Decoration.set(ranges, true);
709
+ }));
710
+ }
711
+ return extensions;
712
+ }
713
+ /** The Text's marks, paragraph attributes and embeds in the editor's offsets; empty without `textSync`. */
714
+ export function textFormatting(state) {
715
+ return state.field(formatting, false) ?? NO_FORMATTING;
716
+ }
717
+ /** The main selection in Text element indices, for formatting the Text; undefined while composing or without `textSync`. */
718
+ export function selectionIndices(state) {
719
+ return bindingOf(state)?.indicesOf(state);
720
+ }
721
+ /** The editor's selection as cursors, for sharing as presence; undefined while composing or without `textSync`. */
722
+ export function selectionCursors(state) {
723
+ return bindingOf(state)?.cursorsOf(state);
724
+ }
725
+ /** Another writer's selection in this editor's offsets, or undefined while its text is unknown here. */
726
+ export function resolveSelection(state, cursors) {
727
+ return bindingOf(state)?.resolve(cursors);
728
+ }
729
+ /** Whether an input method composition is open in the editor; commands and keys should wait for it. */
730
+ export function isComposing(view) {
731
+ return view.compositionStarted || bindingOf(view.state)?.composing === true;
732
+ }
733
+ /** A command that undoes this writer's latest change; false when there is nothing to undo or undo is not possible now. */
734
+ export function undo(history) {
735
+ return (view) => {
736
+ if (!history.canUndo || isComposing(view))
737
+ return false;
738
+ try {
739
+ return history.undo();
740
+ }
741
+ catch {
742
+ return false;
743
+ }
744
+ };
745
+ }
746
+ /** A command that redoes the latest undone change. */
747
+ export function redo(history) {
748
+ return (view) => {
749
+ if (!history.canRedo || isComposing(view))
750
+ return false;
751
+ try {
752
+ return history.redo();
753
+ }
754
+ catch {
755
+ return false;
756
+ }
757
+ };
758
+ }
759
+ //# sourceMappingURL=sync.js.map