forked from facebook/lexical
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSyncEditorStates.ts
244 lines (215 loc) · 7.38 KB
/
SyncEditorStates.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import type {EditorState, NodeKey} from 'lexical';
import {
$createParagraphNode,
$getNodeByKey,
$getRoot,
$getSelection,
$isRangeSelection,
$isTextNode,
} from 'lexical';
import invariant from 'shared/invariant';
import {Text as YText, YEvent, YMapEvent, YTextEvent, YXmlEvent} from 'yjs';
import {Binding, Provider} from '.';
import {CollabDecoratorNode} from './CollabDecoratorNode';
import {CollabElementNode} from './CollabElementNode';
import {CollabTextNode} from './CollabTextNode';
import {
$syncLocalCursorPosition,
syncCursorPositions,
syncLexicalSelectionToYjs,
} from './SyncCursors';
import {
$getOrInitCollabNodeFromSharedType,
$moveSelectionToPreviousNode,
doesSelectionNeedRecovering,
syncWithTransaction,
} from './Utils';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function $syncEvent(binding: Binding, event: any): void {
const {target} = event;
const collabNode = $getOrInitCollabNodeFromSharedType(binding, target);
if (collabNode instanceof CollabElementNode && event instanceof YTextEvent) {
// @ts-expect-error We need to access the private property of the class
const {keysChanged, childListChanged, delta} = event;
// Update
if (keysChanged.size > 0) {
collabNode.syncPropertiesFromYjs(binding, keysChanged);
}
if (childListChanged) {
collabNode.applyChildrenYjsDelta(binding, delta);
collabNode.syncChildrenFromYjs(binding);
}
} else if (
collabNode instanceof CollabTextNode &&
event instanceof YMapEvent
) {
const {keysChanged} = event;
// Update
if (keysChanged.size > 0) {
collabNode.syncPropertiesAndTextFromYjs(binding, keysChanged);
}
} else if (
collabNode instanceof CollabDecoratorNode &&
event instanceof YXmlEvent
) {
const {attributesChanged} = event;
// Update
if (attributesChanged.size > 0) {
collabNode.syncPropertiesFromYjs(binding, attributesChanged);
}
} else {
invariant(false, 'Expected text, element, or decorator event');
}
}
export function syncYjsChangesToLexical(
binding: Binding,
provider: Provider,
events: Array<YEvent<YText>>,
isFromUndoManger: boolean,
): void {
const editor = binding.editor;
const currentEditorState = editor._editorState;
// This line precompute the delta before editor update. The reason is
// delta is computed when it is accessed. Note that this can only be
// safely computed during the event call. If it is accessed after event
// call it might result in unexpected behavior.
// https://github.com/yjs/yjs/blob/00ef472d68545cb260abd35c2de4b3b78719c9e4/src/utils/YEvent.js#L132
events.forEach((event) => event.delta);
editor.update(
() => {
for (let i = 0; i < events.length; i++) {
const event = events[i];
$syncEvent(binding, event);
}
// If there was a collision on the top level paragraph
// we need to re-add a paragraph
if ($getRoot().getChildrenSize() === 0) {
$getRoot().append($createParagraphNode());
}
const selection = $getSelection();
if ($isRangeSelection(selection)) {
if (doesSelectionNeedRecovering(selection)) {
const prevSelection = currentEditorState._selection;
if ($isRangeSelection(prevSelection)) {
$syncLocalCursorPosition(binding, provider);
if (doesSelectionNeedRecovering(selection)) {
// If the selected node is deleted, move the selection to the previous or parent node.
const anchorNodeKey = selection.anchor.key;
$moveSelectionToPreviousNode(anchorNodeKey, currentEditorState);
}
}
syncLexicalSelectionToYjs(
binding,
provider,
prevSelection,
$getSelection(),
);
} else {
$syncLocalCursorPosition(binding, provider);
}
}
},
{
onUpdate: () => {
syncCursorPositions(binding, provider);
},
skipTransforms: true,
tag: isFromUndoManger ? 'historic' : 'collaboration',
},
);
}
function $handleNormalizationMergeConflicts(
binding: Binding,
normalizedNodes: Set<NodeKey>,
): void {
// We handle the merge operations here
const normalizedNodesKeys = Array.from(normalizedNodes);
const collabNodeMap = binding.collabNodeMap;
const mergedNodes = [];
for (let i = 0; i < normalizedNodesKeys.length; i++) {
const nodeKey = normalizedNodesKeys[i];
const lexicalNode = $getNodeByKey(nodeKey);
const collabNode = collabNodeMap.get(nodeKey);
if (collabNode instanceof CollabTextNode) {
if ($isTextNode(lexicalNode)) {
// We mutate the text collab nodes after removing
// all the dead nodes first, otherwise offsets break.
mergedNodes.push([collabNode, lexicalNode.__text]);
} else {
const offset = collabNode.getOffset();
if (offset === -1) {
continue;
}
const parent = collabNode._parent;
collabNode._normalized = true;
parent._xmlText.delete(offset, 1);
collabNodeMap.delete(nodeKey);
const parentChildren = parent._children;
const index = parentChildren.indexOf(collabNode);
parentChildren.splice(index, 1);
}
}
}
for (let i = 0; i < mergedNodes.length; i++) {
const [collabNode, text] = mergedNodes[i];
if (collabNode instanceof CollabTextNode && typeof text === 'string') {
collabNode._text = text;
}
}
}
type IntentionallyMarkedAsDirtyElement = boolean;
export function syncLexicalUpdateToYjs(
binding: Binding,
provider: Provider,
prevEditorState: EditorState,
currEditorState: EditorState,
dirtyElements: Map<NodeKey, IntentionallyMarkedAsDirtyElement>,
dirtyLeaves: Set<NodeKey>,
normalizedNodes: Set<NodeKey>,
tags: Set<string>,
): void {
syncWithTransaction(binding, () => {
currEditorState.read(() => {
// We check if the update has come from a origin where the origin
// was the collaboration binding previously. This can help us
// prevent unnecessarily re-diffing and possible re-applying
// the same change editor state again. For example, if a user
// types a character and we get it, we don't want to then insert
// the same character again. The exception to this heuristic is
// when we need to handle normalization merge conflicts.
if (tags.has('collaboration') || tags.has('historic')) {
if (normalizedNodes.size > 0) {
$handleNormalizationMergeConflicts(binding, normalizedNodes);
}
return;
}
if (dirtyElements.has('root')) {
const prevNodeMap = prevEditorState._nodeMap;
const nextLexicalRoot = $getRoot();
const collabRoot = binding.root;
collabRoot.syncPropertiesFromLexical(
binding,
nextLexicalRoot,
prevNodeMap,
);
collabRoot.syncChildrenFromLexical(
binding,
nextLexicalRoot,
prevNodeMap,
dirtyElements,
dirtyLeaves,
);
}
const selection = $getSelection();
const prevSelection = prevEditorState._selection;
syncLexicalSelectionToYjs(binding, provider, prevSelection, selection);
});
});
}