@kerebron/extension-yjs 0.0.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.
@@ -0,0 +1,923 @@
1
+ /**
2
+ * @module bindings/prosemirror
3
+ */
4
+ import { createMutex } from 'lib0/mutex';
5
+ import * as PModel from 'prosemirror-model';
6
+ import { Plugin, TextSelection } from 'prosemirror-state'; // eslint-disable-line
7
+ import * as math from 'lib0/math';
8
+ import * as object from 'lib0/object';
9
+ import * as set from 'lib0/set';
10
+ import { simpleDiff } from 'lib0/diff';
11
+ import * as error from 'lib0/error';
12
+ import { ySyncPluginKey, yUndoPluginKey } from 'y-prosemirror';
13
+ import * as Y from 'yjs';
14
+ import { absolutePositionToRelativePosition, relativePositionToAbsolutePosition, } from 'y-prosemirror';
15
+ import * as random from 'lib0/random';
16
+ import * as environment from 'lib0/environment';
17
+ import * as dom from 'lib0/dom';
18
+ import * as eventloop from 'lib0/eventloop';
19
+ /**
20
+ * @param {Y.Item} item
21
+ * @param {Y.Snapshot} [snapshot]
22
+ */
23
+ export const isVisible = (item, snapshot) => snapshot === undefined
24
+ ? !item.deleted
25
+ : (snapshot.sv.has(item.id.client) && /** @type {number} */
26
+ (snapshot.sv.get(item.id.client)) > item.id.clock &&
27
+ !Y.isDeleted(snapshot.ds, item.id));
28
+ /**
29
+ * Either a node if type is YXmlElement or an Array of text nodes if YXmlText
30
+ * @typedef {Map<Y.AbstractType<any>, PModel.Node | Array<PModel.Node>>} ProsemirrorMapping
31
+ */
32
+ /**
33
+ * @typedef {Object} ColorDef
34
+ * @property {string} ColorDef.light
35
+ * @property {string} ColorDef.dark
36
+ */
37
+ /**
38
+ * @typedef {Object} YSyncOpts
39
+ * @property {Array<ColorDef>} [YSyncOpts.colors]
40
+ * @property {Map<string,ColorDef>} [YSyncOpts.colorMapping]
41
+ * @property {Y.PermanentUserData|null} [YSyncOpts.permanentUserData]
42
+ * @property {ProsemirrorMapping} [YSyncOpts.mapping]
43
+ * @property {function} [YSyncOpts.onFirstRender] Fired when the content from Yjs is initially rendered to ProseMirror
44
+ */
45
+ /**
46
+ * @type {Array<ColorDef>}
47
+ */
48
+ const defaultColors = [{ light: '#ecd44433', dark: '#ecd444' }];
49
+ /**
50
+ * @param {Map<string,ColorDef>} colorMapping
51
+ * @param {Array<ColorDef>} colors
52
+ * @param {string} user
53
+ * @return {ColorDef}
54
+ */
55
+ const getUserColor = (colorMapping, colors, user) => {
56
+ // @todo do not hit the same color twice if possible
57
+ if (!colorMapping.has(user)) {
58
+ if (colorMapping.size < colors.length) {
59
+ const usedColors = set.create();
60
+ colorMapping.forEach((color) => usedColors.add(color));
61
+ colors = colors.filter((color) => !usedColors.has(color));
62
+ }
63
+ colorMapping.set(user, random.oneOf(colors));
64
+ }
65
+ return /** @type {ColorDef} */ (colorMapping.get(user));
66
+ };
67
+ export const ySyncPlugin = (yXmlFragment, { colors = defaultColors, colorMapping = new Map(), permanentUserData = null, onFirstRender = () => { }, mapping, } = {}) => {
68
+ let initialContentChanged = false;
69
+ const binding = new ProsemirrorBinding(yXmlFragment, mapping);
70
+ const plugin = new Plugin({
71
+ props: {
72
+ editable: (state) => {
73
+ const syncState = ySyncPluginKey.getState(state);
74
+ return syncState.snapshot == null && syncState.prevSnapshot == null;
75
+ },
76
+ },
77
+ key: ySyncPluginKey,
78
+ state: {
79
+ /**
80
+ * @returns {any}
81
+ */
82
+ init: (_initargs, _state) => {
83
+ return {
84
+ type: yXmlFragment,
85
+ doc: yXmlFragment.doc,
86
+ binding,
87
+ snapshot: null,
88
+ prevSnapshot: null,
89
+ isChangeOrigin: false,
90
+ isUndoRedoOperation: false,
91
+ addToHistory: true,
92
+ colors,
93
+ colorMapping,
94
+ permanentUserData,
95
+ };
96
+ },
97
+ apply: (tr, pluginState) => {
98
+ const change = tr.getMeta(ySyncPluginKey);
99
+ if (change !== undefined) {
100
+ pluginState = Object.assign({}, pluginState);
101
+ for (const key in change) {
102
+ pluginState[key] = change[key];
103
+ }
104
+ }
105
+ pluginState.addToHistory = tr.getMeta('addToHistory') !== false;
106
+ // always set isChangeOrigin. If undefined, this is not change origin.
107
+ pluginState.isChangeOrigin = change !== undefined &&
108
+ !!change.isChangeOrigin;
109
+ pluginState.isUndoRedoOperation = change !== undefined &&
110
+ !!change.isChangeOrigin && !!change.isUndoRedoOperation;
111
+ if (binding.prosemirrorView !== null) {
112
+ if (change !== undefined &&
113
+ (change.snapshot != null || change.prevSnapshot != null)) {
114
+ // snapshot changed, rerender next
115
+ eventloop.timeout(0, () => {
116
+ if (binding.prosemirrorView == null) {
117
+ return;
118
+ }
119
+ if (change.restore == null) {
120
+ binding._renderSnapshot(change.snapshot, change.prevSnapshot, pluginState);
121
+ }
122
+ else {
123
+ binding._renderSnapshot(change.snapshot, change.snapshot, pluginState);
124
+ // reset to current prosemirror state
125
+ delete pluginState.restore;
126
+ delete pluginState.snapshot;
127
+ delete pluginState.prevSnapshot;
128
+ binding.mux(() => {
129
+ binding._prosemirrorChanged(binding.prosemirrorView.state.doc);
130
+ });
131
+ }
132
+ });
133
+ }
134
+ }
135
+ return pluginState;
136
+ },
137
+ },
138
+ view: (view) => {
139
+ binding.initView(view);
140
+ if (mapping == null) {
141
+ // force rerender to update the bindings mapping
142
+ binding._forceRerender();
143
+ }
144
+ onFirstRender();
145
+ return {
146
+ update: () => {
147
+ const pluginState = plugin.getState(view.state);
148
+ if (pluginState.snapshot == null && pluginState.prevSnapshot == null) {
149
+ if (
150
+ // If the content doesn't change initially, we don't render anything to Yjs
151
+ // If the content was cleared by a user action, we want to catch the change and
152
+ // represent it in Yjs
153
+ initialContentChanged ||
154
+ view.state.doc.content.findDiffStart(view.state.doc.type.createAndFill().content) !== null) {
155
+ initialContentChanged = true;
156
+ if (pluginState.addToHistory === false &&
157
+ !pluginState.isChangeOrigin) {
158
+ const yUndoPluginState = yUndoPluginKey.getState(view.state);
159
+ /**
160
+ * @type {Y.UndoManager}
161
+ */
162
+ const um = yUndoPluginState && yUndoPluginState.undoManager;
163
+ if (um) {
164
+ um.stopCapturing();
165
+ }
166
+ }
167
+ binding.mux(() => {
168
+ /** @type {Y.Doc} */ (pluginState.doc).transact((tr) => {
169
+ tr.meta.set('addToHistory', pluginState.addToHistory);
170
+ binding._prosemirrorChanged(view.state.doc);
171
+ }, ySyncPluginKey);
172
+ });
173
+ }
174
+ }
175
+ },
176
+ destroy: () => {
177
+ binding.destroy();
178
+ },
179
+ };
180
+ },
181
+ });
182
+ return plugin;
183
+ };
184
+ const restoreRelativeSelection = (tr, relSel, binding) => {
185
+ if (relSel !== null && relSel.anchor !== null && relSel.head !== null) {
186
+ const anchor = relativePositionToAbsolutePosition(binding.doc, binding.type, relSel.anchor, binding.mapping);
187
+ const head = relativePositionToAbsolutePosition(binding.doc, binding.type, relSel.head, binding.mapping);
188
+ if (anchor !== null && head !== null) {
189
+ tr = tr.setSelection(TextSelection.create(tr.doc, anchor, head));
190
+ }
191
+ }
192
+ };
193
+ export const getRelativeSelection = (pmbinding, state) => ({
194
+ anchor: absolutePositionToRelativePosition(state.selection.anchor, pmbinding.type, pmbinding.mapping),
195
+ head: absolutePositionToRelativePosition(state.selection.head, pmbinding.type, pmbinding.mapping),
196
+ });
197
+ /**
198
+ * Binding for prosemirror.
199
+ *
200
+ * @protected
201
+ */
202
+ export class ProsemirrorBinding {
203
+ constructor(yXmlFragment, mapping = new Map()) {
204
+ Object.defineProperty(this, "yXmlFragment", {
205
+ enumerable: true,
206
+ configurable: true,
207
+ writable: true,
208
+ value: yXmlFragment
209
+ });
210
+ Object.defineProperty(this, "mapping", {
211
+ enumerable: true,
212
+ configurable: true,
213
+ writable: true,
214
+ value: mapping
215
+ });
216
+ Object.defineProperty(this, "type", {
217
+ enumerable: true,
218
+ configurable: true,
219
+ writable: true,
220
+ value: void 0
221
+ });
222
+ Object.defineProperty(this, "mux", {
223
+ enumerable: true,
224
+ configurable: true,
225
+ writable: true,
226
+ value: void 0
227
+ });
228
+ Object.defineProperty(this, "_observeFunction", {
229
+ enumerable: true,
230
+ configurable: true,
231
+ writable: true,
232
+ value: void 0
233
+ });
234
+ Object.defineProperty(this, "prosemirrorView", {
235
+ enumerable: true,
236
+ configurable: true,
237
+ writable: true,
238
+ value: void 0
239
+ });
240
+ Object.defineProperty(this, "doc", {
241
+ enumerable: true,
242
+ configurable: true,
243
+ writable: true,
244
+ value: void 0
245
+ });
246
+ Object.defineProperty(this, "beforeTransactionSelection", {
247
+ enumerable: true,
248
+ configurable: true,
249
+ writable: true,
250
+ value: void 0
251
+ });
252
+ Object.defineProperty(this, "afterAllTransactions", {
253
+ enumerable: true,
254
+ configurable: true,
255
+ writable: true,
256
+ value: void 0
257
+ });
258
+ Object.defineProperty(this, "beforeAllTransactions", {
259
+ enumerable: true,
260
+ configurable: true,
261
+ writable: true,
262
+ value: void 0
263
+ });
264
+ this.type = yXmlFragment;
265
+ /**
266
+ * this will be set once the view is created
267
+ * @type {any}
268
+ */
269
+ this.prosemirrorView = null;
270
+ this.mux = createMutex();
271
+ this._observeFunction = this._typeChanged.bind(this);
272
+ this.doc = yXmlFragment.doc;
273
+ /**
274
+ * current selection as relative positions in the Yjs model
275
+ */
276
+ this.beforeTransactionSelection = null;
277
+ this.beforeAllTransactions = () => {
278
+ if (this.beforeTransactionSelection === null && this.prosemirrorView != null) {
279
+ this.beforeTransactionSelection = getRelativeSelection(this, this.prosemirrorView.state);
280
+ }
281
+ };
282
+ this.afterAllTransactions = () => {
283
+ this.beforeTransactionSelection = null;
284
+ };
285
+ this._domSelectionInView = null;
286
+ }
287
+ /**
288
+ * Create a transaction for changing the prosemirror state.
289
+ *
290
+ * @returns
291
+ */
292
+ get _tr() {
293
+ return this.prosemirrorView?.state.tr.setMeta('addToHistory', false);
294
+ }
295
+ _isLocalCursorInView() {
296
+ if (!this.prosemirrorView.hasFocus())
297
+ return false;
298
+ if (environment.isBrowser && this._domSelectionInView === null) {
299
+ // Calculate the domSelectionInView and clear by next tick after all events are finished
300
+ eventloop.timeout(0, () => {
301
+ this._domSelectionInView = null;
302
+ });
303
+ this._domSelectionInView = this._isDomSelectionInView();
304
+ }
305
+ return this._domSelectionInView;
306
+ }
307
+ _isDomSelectionInView() {
308
+ const selection = this.prosemirrorView._root.getSelection();
309
+ const range = this.prosemirrorView._root.createRange();
310
+ range.setStart(selection.anchorNode, selection.anchorOffset);
311
+ range.setEnd(selection.focusNode, selection.focusOffset);
312
+ // This is a workaround for an edgecase where getBoundingClientRect will
313
+ // return zero values if the selection is collapsed at the start of a newline
314
+ // see reference here: https://stackoverflow.com/a/59780954
315
+ const rects = range.getClientRects();
316
+ if (rects.length === 0) {
317
+ // probably buggy newline behavior, explicitly select the node contents
318
+ if (range.startContainer && range.collapsed) {
319
+ range.selectNodeContents(range.startContainer);
320
+ }
321
+ }
322
+ const bounding = range.getBoundingClientRect();
323
+ const documentElement = dom.doc.documentElement;
324
+ return bounding.bottom >= 0 && bounding.right >= 0 &&
325
+ bounding.left <=
326
+ (globalThis.innerWidth || documentElement.clientWidth || 0) &&
327
+ bounding.top <= (globalThis.innerHeight || documentElement.clientHeight || 0);
328
+ }
329
+ renderSnapshot(snapshot, prevSnapshot) {
330
+ if (!prevSnapshot) {
331
+ prevSnapshot = Y.createSnapshot(Y.createDeleteSet(), new Map());
332
+ }
333
+ this.prosemirrorView.dispatch(this._tr.setMeta(ySyncPluginKey, { snapshot, prevSnapshot }));
334
+ }
335
+ unrenderSnapshot() {
336
+ this.mapping.clear();
337
+ this.mux(() => {
338
+ const fragmentContent = this.type.toArray().map((t) => createNodeFromYElement(
339
+ /** @type {Y.XmlElement} */ (t), this.prosemirrorView.state.schema, this.mapping)).filter((n) => n !== null);
340
+ // @ts-ignore
341
+ const tr = this._tr.replace(0, this.prosemirrorView.state.doc.content.size, new PModel.Slice(PModel.Fragment.from(fragmentContent), 0, 0));
342
+ tr.setMeta(ySyncPluginKey, { snapshot: null, prevSnapshot: null });
343
+ this.prosemirrorView.dispatch(tr);
344
+ });
345
+ }
346
+ _forceRerender() {
347
+ this.mapping.clear();
348
+ this.mux(() => {
349
+ // If this is a forced rerender, this might neither happen as a pm change nor within a Yjs
350
+ // transaction. Then the "before selection" doesn't exist. In this case, we need to create a
351
+ // relative position before replacing content. Fixes #126
352
+ const sel = this.beforeTransactionSelection !== null
353
+ ? null
354
+ : this.prosemirrorView.state.selection;
355
+ const fragmentContent = this.type.toArray().map((t) => createNodeFromYElement(
356
+ /** @type {Y.XmlElement} */ (t), this.prosemirrorView.state.schema, this.mapping)).filter((n) => n !== null);
357
+ // @ts-ignore
358
+ const tr = this._tr.replace(0, this.prosemirrorView.state.doc.content.size, new PModel.Slice(PModel.Fragment.from(fragmentContent), 0, 0));
359
+ if (sel) {
360
+ tr.setSelection(TextSelection.create(tr.doc, sel.anchor, sel.head));
361
+ }
362
+ this.prosemirrorView.dispatch(tr.setMeta(ySyncPluginKey, { isChangeOrigin: true, binding: this }));
363
+ });
364
+ }
365
+ _renderSnapshot(snapshot, prevSnapshot, pluginState) {
366
+ /**
367
+ * The document that contains the full history of this document.
368
+ * @type {Y.Doc}
369
+ */
370
+ let historyDoc = this.doc;
371
+ if (!snapshot) {
372
+ snapshot = Y.snapshot(this.doc);
373
+ }
374
+ if (snapshot instanceof Uint8Array || prevSnapshot instanceof Uint8Array) {
375
+ if (!(snapshot instanceof Uint8Array) ||
376
+ !(prevSnapshot instanceof Uint8Array)) {
377
+ // expected both snapshots to be v2 updates
378
+ error.unexpectedCase();
379
+ }
380
+ historyDoc = new Y.Doc({ gc: false });
381
+ Y.applyUpdateV2(historyDoc, prevSnapshot);
382
+ prevSnapshot = Y.snapshot(historyDoc);
383
+ Y.applyUpdateV2(historyDoc, snapshot);
384
+ snapshot = Y.snapshot(historyDoc);
385
+ }
386
+ // clear mapping because we are going to rerender
387
+ this.mapping.clear();
388
+ this.mux(() => {
389
+ historyDoc.transact((transaction) => {
390
+ // before rendering, we are going to sanitize ops and split deleted ops
391
+ // if they were deleted by seperate users.
392
+ const pud = pluginState.permanentUserData;
393
+ if (pud) {
394
+ pud.dss.forEach((ds) => {
395
+ Y.iterateDeletedStructs(transaction, ds, (_item) => { });
396
+ });
397
+ }
398
+ const computeYChange = (type, id) => {
399
+ const user = type === 'added'
400
+ ? pud.getUserByClientId(id.client)
401
+ : pud.getUserByDeletedId(id);
402
+ return {
403
+ user,
404
+ type,
405
+ color: getUserColor(pluginState.colorMapping, pluginState.colors, user),
406
+ };
407
+ };
408
+ // Create document fragment and render
409
+ const fragmentContent = Y.typeListToArraySnapshot(this.type, new Y.Snapshot(prevSnapshot.ds, snapshot.sv)).map((t) => {
410
+ if (!t._item.deleted || isVisible(t._item, snapshot) ||
411
+ isVisible(t._item, prevSnapshot)) {
412
+ return createNodeFromYElement(t, this.prosemirrorView.state.schema, new Map(), snapshot, prevSnapshot, computeYChange);
413
+ }
414
+ else {
415
+ // No need to render elements that are not visible by either snapshot.
416
+ // If a client adds and deletes content in the same snapshot the element is not visible by either snapshot.
417
+ return null;
418
+ }
419
+ }).filter((n) => n !== null);
420
+ const tr = this._tr.replace(0, this.prosemirrorView.state.doc.content.size, new PModel.Slice(PModel.Fragment.from(fragmentContent), 0, 0));
421
+ this.prosemirrorView.dispatch(tr.setMeta(ySyncPluginKey, { isChangeOrigin: true }));
422
+ }, ySyncPluginKey);
423
+ });
424
+ }
425
+ _typeChanged(events, transaction) {
426
+ if (this.prosemirrorView == null)
427
+ return;
428
+ const syncState = ySyncPluginKey.getState(this.prosemirrorView.state);
429
+ if (events.length === 0 || syncState.snapshot != null ||
430
+ syncState.prevSnapshot != null) {
431
+ // drop out if snapshot is active
432
+ this.renderSnapshot(syncState.snapshot, syncState.prevSnapshot);
433
+ return;
434
+ }
435
+ this.mux(() => {
436
+ const delType = (_, type) => this.mapping.delete(type);
437
+ Y.iterateDeletedStructs(transaction, transaction.deleteSet, (struct) => {
438
+ if (struct.constructor === Y.Item) {
439
+ const type =
440
+ /** @type {Y.ContentType} */ ( /** @type {Y.Item} */(struct)
441
+ .content).type;
442
+ type && this.mapping.delete(type);
443
+ }
444
+ });
445
+ transaction.changed.forEach(delType);
446
+ transaction.changedParentTypes.forEach(delType);
447
+ const fragmentContent = this.type.toArray().map((t) => createNodeIfNotExists(
448
+ /** @type {Y.XmlElement | Y.XmlHook} */ (t), this.prosemirrorView.state.schema, this.mapping)).filter((n) => n !== null);
449
+ // @ts-ignore
450
+ let tr = this._tr.replace(0, this.prosemirrorView.state.doc.content.size, new PModel.Slice(PModel.Fragment.from(fragmentContent), 0, 0));
451
+ restoreRelativeSelection(tr, this.beforeTransactionSelection, this);
452
+ tr = tr.setMeta(ySyncPluginKey, {
453
+ isChangeOrigin: true,
454
+ isUndoRedoOperation: transaction.origin instanceof Y.UndoManager,
455
+ });
456
+ if (this.beforeTransactionSelection !== null && this._isLocalCursorInView()) {
457
+ tr.scrollIntoView();
458
+ }
459
+ this.prosemirrorView.dispatch(tr);
460
+ });
461
+ }
462
+ _prosemirrorChanged(doc) {
463
+ this.doc.transact(() => {
464
+ updateYFragment(this.doc, this.type, doc, this.mapping);
465
+ this.beforeTransactionSelection = getRelativeSelection(this, this.prosemirrorView.state);
466
+ }, ySyncPluginKey);
467
+ }
468
+ /**
469
+ * View is ready to listen to changes. Register observers.
470
+ * @param {any} prosemirrorView
471
+ */
472
+ initView(prosemirrorView) {
473
+ if (this.prosemirrorView != null)
474
+ this.destroy();
475
+ this.prosemirrorView = prosemirrorView;
476
+ this.doc.on('beforeAllTransactions', this.beforeAllTransactions);
477
+ this.doc.on('afterAllTransactions', this.afterAllTransactions);
478
+ this.type.observeDeep(this._observeFunction);
479
+ }
480
+ destroy() {
481
+ if (this.prosemirrorView == null)
482
+ return;
483
+ this.prosemirrorView = null;
484
+ this.type.unobserveDeep(this._observeFunction);
485
+ this.doc.off('beforeAllTransactions', this.beforeAllTransactions);
486
+ this.doc.off('afterAllTransactions', this.afterAllTransactions);
487
+ }
488
+ }
489
+ const createNodeIfNotExists = (el, schema, mapping, snapshot, prevSnapshot, computeYChange) => {
490
+ const node = /** @type {PModel.Node} */ (mapping.get(el));
491
+ if (node === undefined) {
492
+ if (el instanceof Y.XmlElement) {
493
+ return createNodeFromYElement(el, schema, mapping, snapshot, prevSnapshot, computeYChange);
494
+ }
495
+ else {
496
+ throw error.methodUnimplemented(); // we are currently not handling hooks
497
+ }
498
+ }
499
+ return node;
500
+ };
501
+ /**
502
+ * @private
503
+ * @param {Y.XmlElement} el
504
+ * @param {any} schema
505
+ * @param {ProsemirrorMapping} mapping
506
+ * @param {Y.Snapshot} [snapshot]
507
+ * @param {Y.Snapshot} [prevSnapshot]
508
+ * @param {function('removed' | 'added', Y.ID):any} [computeYChange]
509
+ * @return {PModel.Node | null} Returns node if node could be created. Otherwise it deletes the yjs type and returns null
510
+ */
511
+ export const createNodeFromYElement = (el, schema, mapping, snapshot, prevSnapshot, computeYChange) => {
512
+ const children = [];
513
+ const createChildren = (type) => {
514
+ if (type.constructor === Y.XmlElement) {
515
+ const n = createNodeIfNotExists(type, schema, mapping, snapshot, prevSnapshot, computeYChange);
516
+ if (n !== null) {
517
+ children.push(n);
518
+ }
519
+ }
520
+ else {
521
+ // If the next ytext exists and was created by us, move the content to the current ytext.
522
+ // This is a fix for #160 -- duplication of characters when two Y.Text exist next to each
523
+ // other.
524
+ const nextytext = type._item.right?.content.type;
525
+ if (nextytext != null && !nextytext._item.deleted &&
526
+ nextytext._item.id.client === nextytext.doc.clientID) {
527
+ type.applyDelta([
528
+ { retain: type.length },
529
+ ...nextytext.toDelta(),
530
+ ]);
531
+ nextytext.doc.transact((tr) => {
532
+ nextytext._item.delete(tr);
533
+ });
534
+ }
535
+ // now create the prosemirror text nodes
536
+ const ns = createTextNodesFromYText(type, schema, mapping, snapshot, prevSnapshot, computeYChange);
537
+ if (ns !== null) {
538
+ ns.forEach((textchild) => {
539
+ if (textchild !== null) {
540
+ children.push(textchild);
541
+ }
542
+ });
543
+ }
544
+ }
545
+ };
546
+ if (snapshot === undefined || prevSnapshot === undefined) {
547
+ el.toArray().forEach(createChildren);
548
+ }
549
+ else {
550
+ Y.typeListToArraySnapshot(el, new Y.Snapshot(prevSnapshot.ds, snapshot.sv))
551
+ .forEach(createChildren);
552
+ }
553
+ try {
554
+ const attrs = el.getAttributes(snapshot);
555
+ if (snapshot !== undefined) {
556
+ if (!isVisible(/** @type {Y.Item} */ (el._item), snapshot)) {
557
+ attrs.ychange = computeYChange
558
+ ? computeYChange('removed', /** @type {Y.Item} */ (el._item).id)
559
+ : { type: 'removed' };
560
+ }
561
+ else if (!isVisible(/** @type {Y.Item} */ (el._item), prevSnapshot)) {
562
+ attrs.ychange = computeYChange
563
+ ? computeYChange('added', /** @type {Y.Item} */ (el._item).id)
564
+ : { type: 'added' };
565
+ }
566
+ }
567
+ const node = schema.node(el.nodeName, attrs, children);
568
+ mapping.set(el, node);
569
+ return node;
570
+ }
571
+ catch (e) {
572
+ // an error occured while creating the node. This is probably a result of a concurrent action.
573
+ /** @type {Y.Doc} */ (el.doc).transact((transaction) => {
574
+ /** @type {Y.Item} */ (el._item).delete(transaction);
575
+ }, ySyncPluginKey);
576
+ mapping.delete(el);
577
+ return null;
578
+ }
579
+ };
580
+ const createTextNodesFromYText = (text, schema, _mapping, snapshot, prevSnapshot, computeYChange) => {
581
+ const nodes = [];
582
+ const deltas = text.toDelta(snapshot, prevSnapshot, computeYChange);
583
+ try {
584
+ for (let i = 0; i < deltas.length; i++) {
585
+ const delta = deltas[i];
586
+ const marks = [];
587
+ for (const markName in delta.attributes) {
588
+ marks.push(schema.mark(markName, delta.attributes[markName]));
589
+ }
590
+ nodes.push(schema.text(delta.insert, marks));
591
+ }
592
+ }
593
+ catch (e) {
594
+ // an error occured while creating the node. This is probably a result of a concurrent action.
595
+ /** @type {Y.Doc} */ (text.doc).transact((transaction) => {
596
+ /** @type {Y.Item} */ (text._item).delete(transaction);
597
+ }, ySyncPluginKey);
598
+ return null;
599
+ }
600
+ // @ts-ignore
601
+ return nodes;
602
+ };
603
+ const createTypeFromTextNodes = (nodes, mapping) => {
604
+ const type = new Y.XmlText();
605
+ const delta = nodes.map((node) => ({
606
+ // @ts-ignore
607
+ insert: node.text,
608
+ attributes: marksToAttributes(node.marks),
609
+ }));
610
+ type.applyDelta(delta);
611
+ mapping.set(type, nodes);
612
+ return type;
613
+ };
614
+ const createTypeFromElementNode = (node, mapping) => {
615
+ const type = new Y.XmlElement(node.type.name);
616
+ for (const key in node.attrs) {
617
+ const val = node.attrs[key];
618
+ if (val !== null && key !== 'ychange') {
619
+ type.setAttribute(key, val);
620
+ }
621
+ }
622
+ type.insert(0, normalizePNodeContent(node).map((n) => createTypeFromTextOrElementNode(n, mapping)));
623
+ mapping.set(type, node);
624
+ return type;
625
+ };
626
+ const createTypeFromTextOrElementNode = (node, mapping) => node instanceof Array
627
+ ? createTypeFromTextNodes(node, mapping)
628
+ : createTypeFromElementNode(node, mapping);
629
+ const isObject = (val) => typeof val === 'object' && val !== null;
630
+ const equalAttrs = (pattrs, yattrs) => {
631
+ const keys = Object.keys(pattrs).filter((key) => pattrs[key] !== null);
632
+ let eq = keys.length ===
633
+ Object.keys(yattrs).filter((key) => yattrs[key] !== null).length;
634
+ for (let i = 0; i < keys.length && eq; i++) {
635
+ const key = keys[i];
636
+ const l = pattrs[key];
637
+ const r = yattrs[key];
638
+ eq = key === 'ychange' || l === r ||
639
+ (isObject(l) && isObject(r) && equalAttrs(l, r));
640
+ }
641
+ return eq;
642
+ };
643
+ /**
644
+ * @typedef {Array<Array<PModel.Node>|PModel.Node>} NormalizedPNodeContent
645
+ */
646
+ /**
647
+ * @param {any} pnode
648
+ * @return {NormalizedPNodeContent}
649
+ */
650
+ const normalizePNodeContent = (pnode) => {
651
+ const c = pnode.content.content;
652
+ const res = [];
653
+ for (let i = 0; i < c.length; i++) {
654
+ const n = c[i];
655
+ if (n.isText) {
656
+ const textNodes = [];
657
+ for (let tnode = c[i]; i < c.length && tnode.isText; tnode = c[++i]) {
658
+ textNodes.push(tnode);
659
+ }
660
+ i--;
661
+ res.push(textNodes);
662
+ }
663
+ else {
664
+ res.push(n);
665
+ }
666
+ }
667
+ return res;
668
+ };
669
+ const equalYTextPText = (ytext, ptexts) => {
670
+ const delta = ytext.toDelta();
671
+ return delta.length === ptexts.length &&
672
+ delta.every((d, i) => d.insert === /** @type {any} */ (ptexts[i]).text &&
673
+ object.keys(d.attributes || {}).length === ptexts[i].marks.length &&
674
+ ptexts[i].marks.every((mark) => equalAttrs(d.attributes[mark.type.name] || {}, mark.attrs)));
675
+ };
676
+ const equalYTypePNode = (ytype, pnode) => {
677
+ if (ytype instanceof Y.XmlElement && !(pnode instanceof Array) &&
678
+ matchNodeName(ytype, pnode)) {
679
+ const normalizedContent = normalizePNodeContent(pnode);
680
+ return ytype._length === normalizedContent.length &&
681
+ equalAttrs(ytype.getAttributes(), pnode.attrs) &&
682
+ ytype.toArray().every((ychild, i) => equalYTypePNode(ychild, normalizedContent[i]));
683
+ }
684
+ return ytype instanceof Y.XmlText && pnode instanceof Array &&
685
+ equalYTextPText(ytype, pnode);
686
+ };
687
+ const mappedIdentity = (mapped, pcontent) => mapped === pcontent ||
688
+ (mapped instanceof Array && pcontent instanceof Array &&
689
+ mapped.length === pcontent.length &&
690
+ mapped.every((a, i) => pcontent[i] === a));
691
+ const computeChildEqualityFactor = (ytype, pnode, mapping) => {
692
+ const yChildren = ytype.toArray();
693
+ const pChildren = normalizePNodeContent(pnode);
694
+ const pChildCnt = pChildren.length;
695
+ const yChildCnt = yChildren.length;
696
+ const minCnt = math.min(yChildCnt, pChildCnt);
697
+ let left = 0;
698
+ let right = 0;
699
+ let foundMappedChild = false;
700
+ for (; left < minCnt; left++) {
701
+ const leftY = yChildren[left];
702
+ const leftP = pChildren[left];
703
+ if (mappedIdentity(mapping.get(leftY), leftP)) {
704
+ foundMappedChild = true; // definite (good) match!
705
+ }
706
+ else if (!equalYTypePNode(leftY, leftP)) {
707
+ break;
708
+ }
709
+ }
710
+ for (; left + right < minCnt; right++) {
711
+ const rightY = yChildren[yChildCnt - right - 1];
712
+ const rightP = pChildren[pChildCnt - right - 1];
713
+ if (mappedIdentity(mapping.get(rightY), rightP)) {
714
+ foundMappedChild = true;
715
+ }
716
+ else if (!equalYTypePNode(rightY, rightP)) {
717
+ break;
718
+ }
719
+ }
720
+ return {
721
+ equalityFactor: left + right,
722
+ foundMappedChild,
723
+ };
724
+ };
725
+ const ytextTrans = (ytext) => {
726
+ let str = '';
727
+ let n = ytext._start;
728
+ const nAttrs = {};
729
+ while (n !== null) {
730
+ if (!n.deleted) {
731
+ if (n.countable && n.content instanceof Y.ContentString) {
732
+ str += n.content.str;
733
+ }
734
+ else if (n.content instanceof Y.ContentFormat) {
735
+ nAttrs[n.content.key] = null;
736
+ }
737
+ }
738
+ n = n.right;
739
+ }
740
+ return {
741
+ str,
742
+ nAttrs,
743
+ };
744
+ };
745
+ const updateYText = (ytext, ptexts, mapping) => {
746
+ mapping.set(ytext, ptexts);
747
+ const { nAttrs, str } = ytextTrans(ytext);
748
+ const content = ptexts.map((p) => ({
749
+ insert: /** @type {any} */ (p).text,
750
+ attributes: Object.assign({}, nAttrs, marksToAttributes(p.marks)),
751
+ }));
752
+ const { insert, remove, index } = simpleDiff(str, content.map((c) => c.insert).join(''));
753
+ ytext.delete(index, remove);
754
+ ytext.insert(index, insert);
755
+ ytext.applyDelta(content.map((c) => ({ retain: c.insert.length, attributes: c.attributes })));
756
+ };
757
+ const marksToAttributes = (marks) => {
758
+ const pattrs = {};
759
+ marks.forEach((mark) => {
760
+ if (mark.type.name !== 'ychange') {
761
+ pattrs[mark.type.name] = mark.attrs;
762
+ }
763
+ });
764
+ return pattrs;
765
+ };
766
+ /**
767
+ * Update a yDom node by syncing the current content of the prosemirror node.
768
+ *
769
+ * This is a y-prosemirror internal feature that you can use at your own risk.
770
+ *
771
+ * @private
772
+ * @unstable
773
+ *
774
+ * @param {{transact: Function}} y
775
+ * @param {Y.XmlFragment} yDomFragment
776
+ * @param {any} pNode
777
+ * @param {ProsemirrorMapping} mapping
778
+ */
779
+ export const updateYFragment = (y, yDomFragment, pNode, mapping) => {
780
+ if (yDomFragment instanceof Y.XmlElement &&
781
+ yDomFragment.nodeName !== pNode.type.name) {
782
+ throw new Error('node name mismatch!');
783
+ }
784
+ mapping.set(yDomFragment, pNode);
785
+ // update attributes
786
+ if (yDomFragment instanceof Y.XmlElement) {
787
+ const yDomAttrs = yDomFragment.getAttributes();
788
+ const pAttrs = pNode.attrs;
789
+ for (const key in pAttrs) {
790
+ if (pAttrs[key] !== null) {
791
+ if (yDomAttrs[key] !== pAttrs[key] && key !== 'ychange') {
792
+ yDomFragment.setAttribute(key, pAttrs[key]);
793
+ }
794
+ }
795
+ else {
796
+ yDomFragment.removeAttribute(key);
797
+ }
798
+ }
799
+ // remove all keys that are no longer in pAttrs
800
+ for (const key in yDomAttrs) {
801
+ if (pAttrs[key] === undefined) {
802
+ yDomFragment.removeAttribute(key);
803
+ }
804
+ }
805
+ }
806
+ // update children
807
+ const pChildren = normalizePNodeContent(pNode);
808
+ const pChildCnt = pChildren.length;
809
+ const yChildren = yDomFragment.toArray();
810
+ const yChildCnt = yChildren.length;
811
+ const minCnt = math.min(pChildCnt, yChildCnt);
812
+ let left = 0;
813
+ let right = 0;
814
+ // find number of matching elements from left
815
+ for (; left < minCnt; left++) {
816
+ const leftY = yChildren[left];
817
+ const leftP = pChildren[left];
818
+ if (!mappedIdentity(mapping.get(leftY), leftP)) {
819
+ if (equalYTypePNode(leftY, leftP)) {
820
+ // update mapping
821
+ mapping.set(leftY, leftP);
822
+ }
823
+ else {
824
+ break;
825
+ }
826
+ }
827
+ }
828
+ // find number of matching elements from right
829
+ for (; right + left + 1 < minCnt; right++) {
830
+ const rightY = yChildren[yChildCnt - right - 1];
831
+ const rightP = pChildren[pChildCnt - right - 1];
832
+ if (!mappedIdentity(mapping.get(rightY), rightP)) {
833
+ if (equalYTypePNode(rightY, rightP)) {
834
+ // update mapping
835
+ mapping.set(rightY, rightP);
836
+ }
837
+ else {
838
+ break;
839
+ }
840
+ }
841
+ }
842
+ y.transact(() => {
843
+ // try to compare and update
844
+ while (yChildCnt - left - right > 0 && pChildCnt - left - right > 0) {
845
+ const leftY = yChildren[left];
846
+ const leftP = pChildren[left];
847
+ const rightY = yChildren[yChildCnt - right - 1];
848
+ const rightP = pChildren[pChildCnt - right - 1];
849
+ if (leftY instanceof Y.XmlText && leftP instanceof Array) {
850
+ if (!equalYTextPText(leftY, leftP)) {
851
+ updateYText(leftY, leftP, mapping);
852
+ }
853
+ left += 1;
854
+ }
855
+ else {
856
+ let updateLeft = leftY instanceof Y.XmlElement &&
857
+ matchNodeName(leftY, leftP);
858
+ let updateRight = rightY instanceof Y.XmlElement &&
859
+ matchNodeName(rightY, rightP);
860
+ if (updateLeft && updateRight) {
861
+ // decide which which element to update
862
+ const equalityLeft = computeChildEqualityFactor(
863
+ /** @type {Y.XmlElement} */ (leftY),
864
+ /** @type {PModel.Node} */ (leftP), mapping);
865
+ const equalityRight = computeChildEqualityFactor(
866
+ /** @type {Y.XmlElement} */ (rightY),
867
+ /** @type {PModel.Node} */ (rightP), mapping);
868
+ if (equalityLeft.foundMappedChild && !equalityRight.foundMappedChild) {
869
+ updateRight = false;
870
+ }
871
+ else if (!equalityLeft.foundMappedChild && equalityRight.foundMappedChild) {
872
+ updateLeft = false;
873
+ }
874
+ else if (equalityLeft.equalityFactor < equalityRight.equalityFactor) {
875
+ updateLeft = false;
876
+ }
877
+ else {
878
+ updateRight = false;
879
+ }
880
+ }
881
+ if (updateLeft) {
882
+ updateYFragment(y,
883
+ /** @type {Y.XmlFragment} */ (leftY),
884
+ /** @type {PModel.Node} */ (leftP), mapping);
885
+ left += 1;
886
+ }
887
+ else if (updateRight) {
888
+ updateYFragment(y,
889
+ /** @type {Y.XmlFragment} */ (rightY),
890
+ /** @type {PModel.Node} */ (rightP), mapping);
891
+ right += 1;
892
+ }
893
+ else {
894
+ mapping.delete(yDomFragment.get(left));
895
+ yDomFragment.delete(left, 1);
896
+ yDomFragment.insert(left, [
897
+ createTypeFromTextOrElementNode(leftP, mapping),
898
+ ]);
899
+ left += 1;
900
+ }
901
+ }
902
+ }
903
+ const yDelLen = yChildCnt - left - right;
904
+ if (yChildCnt === 1 && pChildCnt === 0 && yChildren[0] instanceof Y.XmlText) {
905
+ mapping.delete(yChildren[0]);
906
+ // Edge case handling https://github.com/yjs/y-prosemirror/issues/108
907
+ // Only delete the content of the Y.Text to retain remote changes on the same Y.Text object
908
+ yChildren[0].delete(0, yChildren[0].length);
909
+ }
910
+ else if (yDelLen > 0) {
911
+ yDomFragment.slice(left, left + yDelLen).forEach((type) => mapping.delete(type));
912
+ yDomFragment.delete(left, yDelLen);
913
+ }
914
+ if (left + right < pChildCnt) {
915
+ const ins = [];
916
+ for (let i = left; i < pChildCnt - right; i++) {
917
+ ins.push(createTypeFromTextOrElementNode(pChildren[i], mapping));
918
+ }
919
+ yDomFragment.insert(left, ins);
920
+ }
921
+ }, ySyncPluginKey);
922
+ };
923
+ const matchNodeName = (yElement, pNode) => !(pNode instanceof Array) && yElement.nodeName === pNode.type.name;