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