@kerebron/yjs 0.0.0-stage → 0.9.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.
Files changed (114) hide show
  1. package/LICENSE +23 -0
  2. package/README.md +4 -2
  3. package/esm/ExtensionYjs.d.ts +20 -0
  4. package/esm/ExtensionYjs.d.ts.map +1 -0
  5. package/esm/ExtensionYjs.js +144 -0
  6. package/esm/ExtensionYjs.js.map +1 -0
  7. package/esm/MarkYChange.d.ts +7 -0
  8. package/esm/MarkYChange.d.ts.map +1 -0
  9. package/esm/MarkYChange.js +21 -0
  10. package/esm/MarkYChange.js.map +1 -0
  11. package/esm/WebsocketProvider.d.ts +70 -0
  12. package/esm/WebsocketProvider.d.ts.map +1 -0
  13. package/esm/WebsocketProvider.js +377 -0
  14. package/esm/WebsocketProvider.js.map +1 -0
  15. package/esm/YjsEditorKit.d.ts +11 -0
  16. package/esm/YjsEditorKit.d.ts.map +1 -0
  17. package/esm/YjsEditorKit.js +44 -0
  18. package/esm/YjsEditorKit.js.map +1 -0
  19. package/esm/YjsProvider.d.ts +48 -0
  20. package/esm/YjsProvider.d.ts.map +1 -0
  21. package/esm/YjsProvider.js +12 -0
  22. package/esm/YjsProvider.js.map +1 -0
  23. package/esm/_dnt.shims.d.ts +2 -0
  24. package/esm/_dnt.shims.d.ts.map +1 -0
  25. package/esm/_dnt.shims.js +58 -0
  26. package/esm/_dnt.shims.js.map +1 -0
  27. package/esm/binding/BindingMetadata.d.ts +6 -0
  28. package/esm/binding/BindingMetadata.d.ts.map +1 -0
  29. package/esm/binding/BindingMetadata.js +2 -0
  30. package/esm/binding/BindingMetadata.js.map +1 -0
  31. package/esm/binding/DiffViewer.d.ts +17 -0
  32. package/esm/binding/DiffViewer.d.ts.map +1 -0
  33. package/esm/binding/DiffViewer.js +95 -0
  34. package/esm/binding/DiffViewer.js.map +1 -0
  35. package/esm/binding/PmYjsBinding.d.ts +47 -0
  36. package/esm/binding/PmYjsBinding.d.ts.map +1 -0
  37. package/esm/binding/PmYjsBinding.js +246 -0
  38. package/esm/binding/PmYjsBinding.js.map +1 -0
  39. package/esm/binding/convertUtils.d.ts +48 -0
  40. package/esm/binding/convertUtils.d.ts.map +1 -0
  41. package/esm/binding/convertUtils.js +80 -0
  42. package/esm/binding/convertUtils.js.map +1 -0
  43. package/esm/binding/createNodeFromYElement.d.ts +10 -0
  44. package/esm/binding/createNodeFromYElement.d.ts.map +1 -0
  45. package/esm/binding/createNodeFromYElement.js +123 -0
  46. package/esm/binding/createNodeFromYElement.js.map +1 -0
  47. package/esm/binding/updateYFragment.d.ts +17 -0
  48. package/esm/binding/updateYFragment.d.ts.map +1 -0
  49. package/esm/binding/updateYFragment.js +337 -0
  50. package/esm/binding/updateYFragment.js.map +1 -0
  51. package/esm/debug.d.ts +13 -0
  52. package/esm/debug.d.ts.map +1 -0
  53. package/esm/debug.js +158 -0
  54. package/esm/debug.js.map +1 -0
  55. package/esm/keys.d.ts +8 -0
  56. package/esm/keys.d.ts.map +1 -0
  57. package/esm/keys.js +5 -0
  58. package/esm/keys.js.map +1 -0
  59. package/esm/lib.d.ts +8 -0
  60. package/esm/lib.d.ts.map +1 -0
  61. package/esm/lib.js +2 -0
  62. package/esm/lib.js.map +1 -0
  63. package/esm/package.json +3 -0
  64. package/esm/position.d.ts +8 -0
  65. package/esm/position.d.ts.map +1 -0
  66. package/esm/position.js +165 -0
  67. package/esm/position.js.map +1 -0
  68. package/esm/ui/RoomController.d.ts +17 -0
  69. package/esm/ui/RoomController.d.ts.map +1 -0
  70. package/esm/ui/RoomController.js +115 -0
  71. package/esm/ui/RoomController.js.map +1 -0
  72. package/esm/ui/selection.d.ts +29 -0
  73. package/esm/ui/selection.d.ts.map +1 -0
  74. package/esm/ui/selection.js +129 -0
  75. package/esm/ui/selection.js.map +1 -0
  76. package/esm/utils.d.ts +4 -0
  77. package/esm/utils.d.ts.map +1 -0
  78. package/esm/utils.js +15 -0
  79. package/esm/utils.js.map +1 -0
  80. package/esm/yPositionPlugin.d.ts +27 -0
  81. package/esm/yPositionPlugin.d.ts.map +1 -0
  82. package/esm/yPositionPlugin.js +216 -0
  83. package/esm/yPositionPlugin.js.map +1 -0
  84. package/esm/ySyncPlugin.d.ts +23 -0
  85. package/esm/ySyncPlugin.d.ts.map +1 -0
  86. package/esm/ySyncPlugin.js +140 -0
  87. package/esm/ySyncPlugin.js.map +1 -0
  88. package/esm/yUndoPlugin.d.ts +23 -0
  89. package/esm/yUndoPlugin.d.ts.map +1 -0
  90. package/esm/yUndoPlugin.js +128 -0
  91. package/esm/yUndoPlugin.js.map +1 -0
  92. package/package.json +46 -3
  93. package/src/ExtensionYjs.ts +204 -0
  94. package/src/MarkYChange.ts +23 -0
  95. package/src/WebsocketProvider.ts +528 -0
  96. package/src/YjsEditorKit.ts +58 -0
  97. package/src/YjsProvider.ts +75 -0
  98. package/src/_dnt.shims.ts +60 -0
  99. package/src/binding/BindingMetadata.ts +6 -0
  100. package/src/binding/DiffViewer.ts +138 -0
  101. package/src/binding/PmYjsBinding.ts +383 -0
  102. package/src/binding/convertUtils.ts +124 -0
  103. package/src/binding/createNodeFromYElement.ts +175 -0
  104. package/src/binding/updateYFragment.ts +447 -0
  105. package/src/debug.ts +239 -0
  106. package/src/keys.ts +14 -0
  107. package/src/lib.ts +12 -0
  108. package/src/position.ts +191 -0
  109. package/src/ui/RoomController.ts +131 -0
  110. package/src/ui/selection.ts +218 -0
  111. package/src/utils.ts +19 -0
  112. package/src/yPositionPlugin.ts +351 -0
  113. package/src/ySyncPlugin.ts +211 -0
  114. package/src/yUndoPlugin.ts +175 -0
@@ -0,0 +1,60 @@
1
+ const dntGlobals = {
2
+ };
3
+ export const dntGlobalThis = createMergeProxy(globalThis, dntGlobals);
4
+
5
+ function createMergeProxy<T extends object, U extends object>(
6
+ baseObj: T,
7
+ extObj: U,
8
+ ): Omit<T, keyof U> & U {
9
+ return new Proxy(baseObj, {
10
+ get(_target, prop, _receiver) {
11
+ if (prop in extObj) {
12
+ return (extObj as any)[prop];
13
+ } else {
14
+ return (baseObj as any)[prop];
15
+ }
16
+ },
17
+ set(_target, prop, value) {
18
+ if (prop in extObj) {
19
+ delete (extObj as any)[prop];
20
+ }
21
+ (baseObj as any)[prop] = value;
22
+ return true;
23
+ },
24
+ deleteProperty(_target, prop) {
25
+ let success = false;
26
+ if (prop in extObj) {
27
+ delete (extObj as any)[prop];
28
+ success = true;
29
+ }
30
+ if (prop in baseObj) {
31
+ delete (baseObj as any)[prop];
32
+ success = true;
33
+ }
34
+ return success;
35
+ },
36
+ ownKeys(_target) {
37
+ const baseKeys = Reflect.ownKeys(baseObj);
38
+ const extKeys = Reflect.ownKeys(extObj);
39
+ const extKeysSet = new Set(extKeys);
40
+ return [...baseKeys.filter((k) => !extKeysSet.has(k)), ...extKeys];
41
+ },
42
+ defineProperty(_target, prop, desc) {
43
+ if (prop in extObj) {
44
+ delete (extObj as any)[prop];
45
+ }
46
+ Reflect.defineProperty(baseObj, prop, desc);
47
+ return true;
48
+ },
49
+ getOwnPropertyDescriptor(_target, prop) {
50
+ if (prop in extObj) {
51
+ return Reflect.getOwnPropertyDescriptor(extObj, prop);
52
+ } else {
53
+ return Reflect.getOwnPropertyDescriptor(baseObj, prop);
54
+ }
55
+ },
56
+ has(_target, prop) {
57
+ return prop in extObj || prop in baseObj;
58
+ },
59
+ }) as any;
60
+ }
@@ -0,0 +1,6 @@
1
+ import { ProsemirrorMapping } from '../lib.js';
2
+
3
+ export interface BindingMetadata {
4
+ mapping: ProsemirrorMapping;
5
+ isOverlappingMark: Map<string, boolean>;
6
+ }
@@ -0,0 +1,138 @@
1
+ import * as Y from 'yjs';
2
+
3
+ import { Node } from 'prosemirror-model';
4
+ import { EditorState } from 'prosemirror-state';
5
+
6
+ import { isVisible } from '../utils.js';
7
+ import { YjsData } from './PmYjsBinding.js';
8
+ import { createNodeFromYElement } from './createNodeFromYElement.js';
9
+
10
+ export class DiffViewer {
11
+ prevSnapshot?: Y.Snapshot;
12
+ snapshot?: Y.Snapshot;
13
+
14
+ private historyYXmlFragment: Y.XmlFragment | undefined;
15
+ private historyDoc: Y.Doc | undefined;
16
+
17
+ constructor() {
18
+ }
19
+
20
+ isActive() {
21
+ return !!this.snapshot || !!this.prevSnapshot;
22
+ }
23
+
24
+ setSnapshot(yjs: YjsData, uSnapshot: Uint8Array, uPrevSnapshot?: Uint8Array) {
25
+ this.prevSnapshot = undefined;
26
+ if (uPrevSnapshot) {
27
+ this.prevSnapshot = Y.decodeSnapshotV2(uPrevSnapshot);
28
+ }
29
+
30
+ this.snapshot = Y.decodeSnapshotV2(uSnapshot);
31
+
32
+ this.historyDoc = Y.createDocFromSnapshot(
33
+ yjs.ydoc,
34
+ this.snapshot,
35
+ new Y.Doc({ gc: false }),
36
+ );
37
+
38
+ if (yjs.xmlFragment._item === null) {
39
+ /**
40
+ * If is a root type, we need to find the root key in the initial document
41
+ * and use it to get the history type.
42
+ */
43
+ const share: Map<string, Y.AbstractType<Y.YEvent<any>>> = yjs.ydoc.share;
44
+ const rootKey = Array.from(share.keys()).find(
45
+ (key) => share.get(key) === yjs.xmlFragment as Y.AbstractType<any>,
46
+ );
47
+ this.historyYXmlFragment = this.historyDoc.getXmlFragment(rootKey);
48
+ } else {
49
+ /**
50
+ * If it is a sub type, we use the item id to find the history type.
51
+ */
52
+ const historyStructs =
53
+ this.historyDoc.store.clients.get(yjs.xmlFragment._item.id.client) ??
54
+ [];
55
+ const itemIndex = Y.findIndexSS(
56
+ historyStructs,
57
+ yjs.xmlFragment._item.id.clock,
58
+ );
59
+ if (historyStructs[itemIndex] instanceof Y.GC) {
60
+ throw new Error('Incorrect type Y.GC');
61
+ }
62
+ const item: Y.Item = historyStructs[itemIndex];
63
+ const content: Y.ContentType = item.content;
64
+ this.historyYXmlFragment = content.type as Y.XmlFragment;
65
+ }
66
+ }
67
+
68
+ reset() {
69
+ this.snapshot = undefined;
70
+ this.prevSnapshot = undefined;
71
+ this.historyDoc = undefined;
72
+ this.historyYXmlFragment = undefined;
73
+ }
74
+
75
+ getFragmentContent(
76
+ state: EditorState,
77
+ ytr: Y.Transaction,
78
+ permanentUserData?: Y.PermanentUserData,
79
+ ): Node[] | undefined {
80
+ if (!this.historyYXmlFragment || !this.snapshot) {
81
+ return;
82
+ }
83
+
84
+ // before rendering, we are going to sanitize ops and split deleted ops
85
+ // if they were deleted by seperate users.
86
+ // pluginState.permanentUserData;
87
+ if (permanentUserData) {
88
+ permanentUserData.dss.forEach((ds) => {
89
+ Y.iterateDeletedStructs(ytr, ds, (_item) => {});
90
+ });
91
+ }
92
+ const computeYChange = (type: 'removed' | 'added', id: Y.ID) => {
93
+ const user = permanentUserData
94
+ ? (type === 'added'
95
+ ? permanentUserData.getUserByClientId(id.client)
96
+ : permanentUserData.getUserByDeletedId(id))
97
+ : undefined;
98
+ return {
99
+ user,
100
+ type,
101
+ };
102
+ };
103
+
104
+ const deleteSet = this.prevSnapshot
105
+ ? this.prevSnapshot.ds
106
+ : Y.emptySnapshot.ds;
107
+
108
+ // Create document fragment and render
109
+ const fragmentContent = Y.typeListToArraySnapshot(
110
+ this.historyYXmlFragment,
111
+ new Y.Snapshot(deleteSet, this.snapshot.sv),
112
+ ).map((t) => {
113
+ if (
114
+ !t._item.deleted || isVisible(t._item, this.snapshot) ||
115
+ isVisible(t._item, this.prevSnapshot)
116
+ ) {
117
+ return createNodeFromYElement(
118
+ t,
119
+ state.schema,
120
+ { mapping: new Map(), isOverlappingMark: new Map() },
121
+ this.snapshot,
122
+ this.prevSnapshot,
123
+ computeYChange,
124
+ );
125
+ } else {
126
+ // No need to render elements that are not visible by either snapshot.
127
+ // If a client adds and deletes content in the same snapshot the element is not visible by either snapshot.
128
+ return null;
129
+ }
130
+ }).filter((n) => n !== null);
131
+
132
+ return fragmentContent;
133
+ }
134
+
135
+ getHistoryDoc(): Y.Doc | undefined {
136
+ return this.historyDoc;
137
+ }
138
+ }
@@ -0,0 +1,383 @@
1
+ import * as Y from 'yjs';
2
+
3
+ import { Fragment, Slice } from 'prosemirror-model';
4
+ import { Transaction } from 'prosemirror-state';
5
+
6
+ import { CoreEditor } from '@kerebron/editor';
7
+ import { User } from '@kerebron/editor/user';
8
+
9
+ import { CreateYjsProvider, YjsProvider } from '../YjsProvider.js';
10
+ import { ProsemirrorMapping } from '../lib.js';
11
+ import { SelectionStash } from '../ui/selection.js';
12
+ import { ySyncPluginKey } from '../keys.js';
13
+
14
+ import { yXmlFragmentToProseMirrorRootNode } from './convertUtils.js';
15
+ import { updateYFragment } from './updateYFragment.js';
16
+ import { BindingMetadata } from './BindingMetadata.js';
17
+ import { createNodeIfNotExists } from './createNodeFromYElement.js';
18
+ import { DiffViewer } from './DiffViewer.js';
19
+
20
+ type Mutex = (f: () => void, g?: () => void) => void;
21
+
22
+ export const createMutex = (): Mutex => {
23
+ let token = true;
24
+ return (f: () => void, g?: () => void) => {
25
+ if (token) {
26
+ token = false;
27
+ try {
28
+ f();
29
+ } finally {
30
+ token = true;
31
+ }
32
+ } else if (g !== undefined) {
33
+ g();
34
+ }
35
+ };
36
+ };
37
+
38
+ type ConnectionState = 'idle' | 'joining' | 'synced' | 'leaving' | 'error';
39
+
40
+ export type YjsData = { ydoc: Y.Doc; xmlFragment: Y.XmlFragment };
41
+
42
+ export class PmYjsBinding extends EventTarget {
43
+ private provider: YjsProvider | undefined;
44
+ private connectionState: ConnectionState = 'idle';
45
+
46
+ private yjs: YjsData | undefined;
47
+ private selectionStash: SelectionStash | undefined;
48
+ public readonly diffViewer: DiffViewer;
49
+
50
+ public addToYjsHistory = true;
51
+ private hasImported = false;
52
+ private mux: Mutex;
53
+ private bindingMetadata: BindingMetadata;
54
+
55
+ private syncedHandler: (
56
+ event: CustomEvent<{
57
+ state: boolean;
58
+ }>,
59
+ ) => void;
60
+ private _observeFunction: (
61
+ events: Array<Y.YEvent<any>>,
62
+ transaction: Y.Transaction,
63
+ ) => void;
64
+ private permanentUserData: Y.PermanentUserData | undefined;
65
+ private user: User | undefined;
66
+
67
+ constructor(private readonly editor: CoreEditor) {
68
+ super();
69
+
70
+ this.diffViewer = new DiffViewer();
71
+ this.bindingMetadata = { mapping: new Map(), isOverlappingMark: new Map() };
72
+
73
+ this.mux = createMutex();
74
+
75
+ this.syncedHandler = (
76
+ event: CustomEvent<{
77
+ state: boolean;
78
+ }>,
79
+ ) => {
80
+ const synced = event.detail.state;
81
+ if (synced && !this.hasImported) {
82
+ this.importRemoteYdoc();
83
+ } else {
84
+ // this.ydocChanged();
85
+ }
86
+ };
87
+
88
+ this._observeFunction = (events, transaction) => {
89
+ this.yXmlChanged(events, transaction);
90
+ };
91
+ }
92
+
93
+ destroy() {
94
+ this.connectionState = 'idle';
95
+ const tr = this.editor.state.tr;
96
+ this.leaveRoom(tr);
97
+ this.editor.dispatchTransaction(tr);
98
+ this.diffViewer.reset();
99
+ this.selectionStash?.destroy();
100
+ }
101
+
102
+ changeUser(user: User) {
103
+ this.user = user;
104
+ if (!this.provider) {
105
+ return;
106
+ }
107
+
108
+ if (this.yjs && user.id) {
109
+ const { ydoc } = this.yjs;
110
+ this.permanentUserData = new Y.PermanentUserData(ydoc);
111
+ this.permanentUserData.setUserMapping(ydoc, ydoc.clientID, user.id);
112
+ }
113
+
114
+ this.provider.awareness.setLocalStateField('kerebron:user', user);
115
+ }
116
+
117
+ changeRoom(
118
+ roomId: string,
119
+ createYjsProvider: CreateYjsProvider,
120
+ tr: Transaction,
121
+ ) {
122
+ this.connectionState = 'joining';
123
+ this.hasImported = false;
124
+
125
+ if (this.provider) {
126
+ this.provider.removeEventListener('synced', this.syncedHandler);
127
+ this.provider.destroy();
128
+ this.provider = undefined;
129
+ }
130
+
131
+ const [provider, ydoc] = createYjsProvider(
132
+ roomId,
133
+ );
134
+
135
+ this.addToYjsHistory = true;
136
+ this.provider = provider;
137
+
138
+ this.bindingMetadata.mapping.clear();
139
+ this.bindingMetadata.isOverlappingMark.clear();
140
+ this.diffViewer.reset();
141
+
142
+ const fieldName = 'kerebron:' + this.editor.schema.topNodeType.name;
143
+ this.yjs = { ydoc, xmlFragment: ydoc.getXmlFragment(fieldName) };
144
+ this.permanentUserData = new Y.PermanentUserData(ydoc);
145
+ if (this.user?.id) {
146
+ this.permanentUserData.setUserMapping(ydoc, ydoc.clientID, this.user.id);
147
+ }
148
+
149
+ this.selectionStash = new SelectionStash(
150
+ this.yjs,
151
+ this.getMapping(),
152
+ this.editor,
153
+ );
154
+ this.yjs.xmlFragment.observeDeep(this._observeFunction);
155
+
156
+ this.provider.addEventListener('synced', this.syncedHandler);
157
+
158
+ tr.setMeta('yjs:setAwareness', provider.awareness);
159
+ tr.setMeta('setYjs', this.yjs);
160
+ }
161
+
162
+ leaveRoom(tr: Transaction) {
163
+ this.connectionState = 'leaving';
164
+ if (this.provider) {
165
+ this.provider.removeEventListener('synced', this.syncedHandler);
166
+ this.provider.destroy();
167
+ }
168
+
169
+ this.addToYjsHistory = true;
170
+ this.provider = undefined;
171
+
172
+ this.bindingMetadata.mapping.clear();
173
+ this.bindingMetadata.isOverlappingMark.clear();
174
+ this.diffViewer.reset();
175
+
176
+ this.selectionStash?.destroy();
177
+ this.selectionStash = undefined;
178
+ this.yjs?.xmlFragment.unobserveDeep(this._observeFunction);
179
+ this.yjs = undefined;
180
+ this.permanentUserData = undefined;
181
+
182
+ this.hasImported = false;
183
+
184
+ tr.setMeta('addToYjsHistory', false);
185
+ tr.setMeta('yjs:removeAwareness', true);
186
+ tr.setMeta('clearYjs', true);
187
+ }
188
+
189
+ importRemoteYdoc() {
190
+ if (!this.yjs) {
191
+ return;
192
+ }
193
+ if (this.diffViewer.isActive()) {
194
+ return;
195
+ }
196
+
197
+ this.addToYjsHistory = this.editor.state.doc.content.size > 2; // Non empty para
198
+
199
+ if (this.yjs.xmlFragment.length === 0) {
200
+ this.createFromProseMirror(this.yjs);
201
+ } else {
202
+ this.overwriteProseMirror(this.yjs.xmlFragment);
203
+ }
204
+
205
+ this.connectionState = 'synced';
206
+ this.hasImported = true;
207
+ }
208
+
209
+ yXmlChanged(events: Array<Y.YEvent<any>>, ytr: Y.Transaction) {
210
+ this.mux(() => {
211
+ if (!this.yjs) {
212
+ return;
213
+ }
214
+
215
+ if (this.diffViewer.isActive()) {
216
+ return;
217
+ }
218
+
219
+ const state = this.editor.state;
220
+
221
+ const { xmlFragment } = this.yjs;
222
+
223
+ const mapping = this.bindingMetadata.mapping;
224
+ const delType = (_: any, type: Y.AbstractType<any>) =>
225
+ mapping.delete(type);
226
+ Y.iterateDeletedStructs(
227
+ ytr,
228
+ ytr.deleteSet,
229
+ (struct) => {
230
+ if (struct.constructor === Y.Item) {
231
+ const type = (struct as Y.Item).content.type;
232
+ type && mapping.delete(type);
233
+ }
234
+ },
235
+ );
236
+ ytr.changed.forEach(delType);
237
+ ytr.changedParentTypes.forEach(delType);
238
+
239
+ const fragmentContent = xmlFragment.toArray().map((t) =>
240
+ createNodeIfNotExists(
241
+ t as Y.XmlElement,
242
+ state.schema,
243
+ this.bindingMetadata,
244
+ )
245
+ ).filter((n) => n !== null);
246
+
247
+ const tr = state.tr;
248
+ tr.setMeta('addToYjsHistory', false);
249
+ tr.replace(
250
+ 0,
251
+ state.doc.content.size,
252
+ new Slice(Fragment.from(fragmentContent), 0, 0),
253
+ );
254
+
255
+ this.selectionStash?.restore(tr);
256
+ this.editor.dispatchTransaction(tr);
257
+ });
258
+ }
259
+
260
+ pmChanged() {
261
+ if (!this.hasImported) {
262
+ return;
263
+ }
264
+
265
+ if (!this.yjs) {
266
+ return;
267
+ }
268
+
269
+ if (this.diffViewer.isActive()) {
270
+ return;
271
+ }
272
+
273
+ const doc = this.editor.state.doc;
274
+ const { ydoc, xmlFragment } = this.yjs;
275
+
276
+ this.mux(() => {
277
+ const origin = ySyncPluginKey;
278
+
279
+ ydoc.transact((ytr) => {
280
+ ytr.meta.set('addToYjsHistory', this.addToYjsHistory);
281
+ updateYFragment(
282
+ ydoc,
283
+ xmlFragment,
284
+ doc,
285
+ this.bindingMetadata,
286
+ this.addToYjsHistory,
287
+ );
288
+ this.selectionStash?.store();
289
+ }, origin);
290
+ });
291
+ }
292
+
293
+ createFromProseMirror(yjs: YjsData) {
294
+ const doc = this.editor.state.doc;
295
+ const { ydoc, xmlFragment } = yjs;
296
+ updateYFragment(
297
+ ydoc,
298
+ xmlFragment,
299
+ doc,
300
+ this.bindingMetadata,
301
+ this.addToYjsHistory,
302
+ );
303
+ }
304
+
305
+ overwriteProseMirror(yXmlFragment: Y.XmlFragment) {
306
+ const state = this.editor.state;
307
+ const newRoot = yXmlFragmentToProseMirrorRootNode(
308
+ yXmlFragment,
309
+ state.schema,
310
+ );
311
+
312
+ const tr = state.tr;
313
+ tr.setMeta('addToYjsHistory', false);
314
+ tr.replaceWith(
315
+ 0,
316
+ state.doc.content.size,
317
+ newRoot,
318
+ );
319
+
320
+ this.editor.dispatchTransaction(tr);
321
+ }
322
+
323
+ getYjs(): YjsData | undefined {
324
+ return this.yjs;
325
+ }
326
+
327
+ getMapping(): ProsemirrorMapping {
328
+ return this.bindingMetadata.mapping;
329
+ }
330
+
331
+ getSelectionStash(): SelectionStash | undefined {
332
+ return this.selectionStash;
333
+ }
334
+
335
+ isEditable() {
336
+ return !this.diffViewer.isActive();
337
+ }
338
+
339
+ setSnapshot(
340
+ snapshot: Uint8Array<ArrayBufferLike>,
341
+ prevSnapshot: Uint8Array<ArrayBufferLike> | undefined,
342
+ ) {
343
+ if (!this.yjs) {
344
+ return;
345
+ }
346
+ this.diffViewer.setSnapshot(this.yjs, snapshot, prevSnapshot);
347
+
348
+ // clear mapping because we are going to rerender
349
+ this.bindingMetadata.mapping.clear();
350
+ this.bindingMetadata.isOverlappingMark.clear();
351
+
352
+ this.mux(() => {
353
+ const historyDoc = this.diffViewer.getHistoryDoc();
354
+ if (!historyDoc) {
355
+ return;
356
+ }
357
+
358
+ historyDoc.transact((ytr) => {
359
+ const state = this.editor.state;
360
+ const fragmentContent = this.diffViewer.getFragmentContent(
361
+ state,
362
+ ytr,
363
+ this.permanentUserData,
364
+ );
365
+
366
+ if (!fragmentContent) {
367
+ return;
368
+ }
369
+
370
+ const tr = state.tr;
371
+ tr.replace(
372
+ 0,
373
+ state.doc.content.size,
374
+ new Slice(Fragment.from(fragmentContent), 0, 0),
375
+ );
376
+
377
+ tr.setMeta('addToHistory', false);
378
+ tr.setMeta(ySyncPluginKey, { isChangeOrigin: true }),
379
+ this.editor.dispatchTransaction(tr);
380
+ }, ySyncPluginKey);
381
+ });
382
+ }
383
+ }
@@ -0,0 +1,124 @@
1
+ import * as Y from 'yjs';
2
+
3
+ import { Fragment, Node, type Schema } from 'prosemirror-model';
4
+
5
+ import { TransactFunc } from '../lib.js';
6
+
7
+ import { updateYFragment } from './updateYFragment.js';
8
+ import { createNodeFromYElement } from './createNodeFromYElement.js';
9
+ import { BindingMetadata } from './BindingMetadata.js';
10
+
11
+ export const createEmptyMeta = (): BindingMetadata => ({
12
+ mapping: new Map(),
13
+ isOverlappingMark: new Map(),
14
+ });
15
+
16
+ /**
17
+ * Utility function for converting an Y.Fragment to a ProseMirror fragment.
18
+ */
19
+ export const yXmlFragmentToProseMirrorFragment = (
20
+ yXmlFragment: Y.XmlFragment,
21
+ schema: Schema,
22
+ ) => {
23
+ const elements: Y.XmlElement[] = yXmlFragment.toArray().filter((i) =>
24
+ i instanceof Y.XmlElement
25
+ );
26
+ const fragmentContent = elements.map((t) =>
27
+ createNodeFromYElement(
28
+ t,
29
+ schema,
30
+ createEmptyMeta(),
31
+ )
32
+ ).filter((n) => n !== null);
33
+ return Fragment.fromArray(fragmentContent);
34
+ };
35
+
36
+ /**
37
+ * Utility function for converting an Y.Fragment to a ProseMirror node.
38
+ */
39
+ export const yXmlFragmentToProseMirrorRootNode = (
40
+ yXmlFragment: Y.XmlFragment,
41
+ schema: Schema,
42
+ ) =>
43
+ schema.topNodeType.create(
44
+ null,
45
+ yXmlFragmentToProseMirrorFragment(yXmlFragment, schema),
46
+ );
47
+
48
+ /**
49
+ * Utility method to convert a Prosemirror Doc Node into a Y.Doc.
50
+ *
51
+ * This can be used when importing existing content to Y.Doc for the first time,
52
+ * note that this should not be used to rehydrate a Y.Doc from a database once
53
+ * collaboration has begun as all history will be lost
54
+ */
55
+ export function prosemirrorToYDoc(
56
+ doc: Node,
57
+ xmlFragment: string = 'prosemirror',
58
+ ): Y.Doc {
59
+ const ydoc = new Y.Doc();
60
+ const type: Y.XmlFragment = ydoc.get(xmlFragment, Y.XmlFragment);
61
+ if (!type.doc) {
62
+ return ydoc;
63
+ }
64
+
65
+ prosemirrorToYXmlFragment(doc, type);
66
+ return type.doc;
67
+ }
68
+
69
+ /**
70
+ * Utility method to update an empty Y.XmlFragment with content from a Prosemirror Doc Node.
71
+ *
72
+ * This can be used when importing existing content to Y.Doc for the first time,
73
+ * note that this should not be used to rehydrate a Y.Doc from a database once
74
+ * collaboration has begun as all history will be lost
75
+ *
76
+ * Note: The Y.XmlFragment does not need to be part of a Y.Doc document at the time that this
77
+ * method is called, but it must be added before any other operations are performed on it.
78
+ */
79
+ export function prosemirrorToYXmlFragment(
80
+ doc: Node,
81
+ xmlFragment: Y.XmlFragment,
82
+ ): Y.XmlFragment {
83
+ const type = xmlFragment || new Y.XmlFragment();
84
+ const ydoc: { transact: TransactFunc<void> } = type.doc
85
+ ? type.doc
86
+ : { transact: (transaction) => transaction(undefined) };
87
+ updateYFragment(ydoc, type, doc, {
88
+ mapping: new Map(),
89
+ isOverlappingMark: new Map(),
90
+ });
91
+ return type;
92
+ }
93
+
94
+ /**
95
+ * Utility method to convert Prosemirror compatible JSON into a Y.Doc.
96
+ *
97
+ * This can be used when importing existing content to Y.Doc for the first time,
98
+ * note that this should not be used to rehydrate a Y.Doc from a database once
99
+ * collaboration has begun as all history will be lost
100
+ */
101
+ export function prosemirrorJSONToYDoc(
102
+ schema: Schema,
103
+ state: any,
104
+ xmlFragment: string = 'prosemirror',
105
+ ): Y.Doc {
106
+ const doc = Node.fromJSON(schema, state);
107
+ return prosemirrorToYDoc(doc, xmlFragment);
108
+ }
109
+
110
+ /**
111
+ * Utility method to convert Prosemirror compatible JSON to a Y.XmlFragment
112
+ *
113
+ * This can be used when importing existing content to Y.Doc for the first time,
114
+ * note that this should not be used to rehydrate a Y.Doc from a database once
115
+ * collaboration has begun as all history will be lost
116
+ */
117
+ export function prosemirrorJSONToYXmlFragment(
118
+ schema: Schema,
119
+ state: any,
120
+ xmlFragment: Y.XmlFragment,
121
+ ): Y.XmlFragment {
122
+ const doc = Node.fromJSON(schema, state);
123
+ return prosemirrorToYXmlFragment(doc, xmlFragment);
124
+ }