@vite-hub/realtime 0.5.0 → 0.5.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.
- package/README.md +2 -2
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +1 -2
- package/dist/{bus-Bsdanf5O.js → bus-DJ3dOQAZ.js} +4 -6
- package/dist/{bus-protocol-wXkXW28q.d.ts → bus-protocol-juNrVJDF.d.ts} +0 -2
- package/dist/bus.d.ts +1 -3
- package/dist/bus.js +1 -2
- package/dist/client/browser.js +3 -3
- package/dist/client.d.ts +2 -4
- package/dist/client.js +5 -6
- package/dist/{conflict-DYC_qXzM.js → conflict-BqdKFrkE.js} +3 -5
- package/dist/{conflict-CmZizTYl.d.ts → conflict-C5KRv-J1.d.ts} +0 -2
- package/dist/{document-b1ShR2S1.d.ts → document-CbqgNO_0.d.ts} +2 -4
- package/dist/document-CfrQbB03.js +1736 -0
- package/dist/durability.d.ts +1 -3
- package/dist/durability.js +1 -2
- package/dist/{editor-IL2jHqn8.js → editor-DzhKM4Gt.js} +2 -4
- package/dist/{error-diagnostics-Cd-XWNf7.js → error-diagnostics-we8V1O-X.js} +1 -2
- package/dist/index.d.ts +3 -7
- package/dist/index.js +3 -3
- package/dist/internal/runtime/unavailable.d.ts +1 -3
- package/dist/internal/runtime/unavailable.js +1 -2
- package/dist/internal/server.d.ts +6 -6
- package/dist/internal/server.js +5 -5
- package/dist/{keepalive-B4ONG6AD.js → keepalive-BYkk6Ax8.js} +3 -5
- package/dist/{layout-DNaxppTZ.js → layout-BQwRLTH0.js} +1 -2
- package/dist/{layout-VHjYWa-M.d.ts → layout-BZtKNqiC.d.ts} +1 -3
- package/dist/{log-E-cH6xkd.js → log-NlQi6kow.js} +2 -4
- package/dist/{object-BgPPDLDE.js → object-DfrneieE.js} +2 -4
- package/dist/{presence-B6rvkHqd.js → presence-DZ21pPKm.js} +3 -4
- package/dist/{request-kM5epeSd.js → request-DM6xHTaU.js} +5 -9
- package/dist/{request-DAodIqZ8.d.ts → request-PrMHOYFK.d.ts} +1 -3
- package/dist/{server-Covbc24E.d.ts → server-CLdYV7Md.d.ts} +6 -20
- package/dist/{server-BSXJP45b.js → server-yQp02XNp.js} +17 -24
- package/dist/server.d.ts +3 -3
- package/dist/server.js +2 -2
- package/dist/{types-DdY7Vo1H.d.ts → types-oUyN-CJR.d.ts} +1 -5
- package/dist/vite.d.ts +2 -15
- package/dist/vite.js +20 -27
- package/dist/vue.d.ts +2 -6
- package/dist/vue.js +47 -26
- package/package.json +39 -39
- package/dist/document-U5rzg2vG.js +0 -2041
|
@@ -1,2041 +0,0 @@
|
|
|
1
|
-
import { n as isRecord } from "./object-BgPPDLDE.js";
|
|
2
|
-
import { n as realtimeDocumentLayout } from "./layout-DNaxppTZ.js";
|
|
3
|
-
import "y-protocols/awareness";
|
|
4
|
-
import * as Y from "yjs";
|
|
5
|
-
import { ContentType, Item, Text, UndoManager, XmlElement } from "yjs";
|
|
6
|
-
import { getSchema } from "@tiptap/core";
|
|
7
|
-
import { Decoration, DecorationSet } from "prosemirror-view";
|
|
8
|
-
import { AllSelection, NodeSelection, Plugin, PluginKey, Selection, TextSelection } from "prosemirror-state";
|
|
9
|
-
import { createMutex } from "lib0/mutex";
|
|
10
|
-
import * as PModel from "prosemirror-model";
|
|
11
|
-
import { Node as Node$1 } from "prosemirror-model";
|
|
12
|
-
import * as math from "lib0/math";
|
|
13
|
-
import * as object from "lib0/object";
|
|
14
|
-
import * as set from "lib0/set";
|
|
15
|
-
import { simpleDiff } from "lib0/diff";
|
|
16
|
-
import * as error from "lib0/error";
|
|
17
|
-
import * as random from "lib0/random";
|
|
18
|
-
import * as environment from "lib0/environment";
|
|
19
|
-
import * as dom from "lib0/dom";
|
|
20
|
-
import * as eventloop from "lib0/eventloop";
|
|
21
|
-
import * as map from "lib0/map";
|
|
22
|
-
import * as sha256 from "lib0/hash/sha256";
|
|
23
|
-
import * as buf from "lib0/buffer";
|
|
24
|
-
import { ReplaceStep } from "prosemirror-transform";
|
|
25
|
-
//#region ../../node_modules/.pnpm/@tiptap+y-tiptap@3.0.9_prosemirror-model@1.25.12_prosemirror-state@1.4.4_prosemirror-vi_94f322c849088dd0f92b6b80a0b1b30b/node_modules/@tiptap/y-tiptap/dist/y-tiptap.js
|
|
26
|
-
/**
|
|
27
|
-
* The unique prosemirror plugin key for syncPlugin
|
|
28
|
-
*
|
|
29
|
-
* @public
|
|
30
|
-
*/
|
|
31
|
-
const ySyncPluginKey = new PluginKey("y-sync");
|
|
32
|
-
/**
|
|
33
|
-
* The unique prosemirror plugin key for undoPlugin
|
|
34
|
-
*
|
|
35
|
-
* @public
|
|
36
|
-
*/
|
|
37
|
-
const yUndoPluginKey = new PluginKey("y-undo");
|
|
38
|
-
/**
|
|
39
|
-
* The unique prosemirror plugin key for cursorPlugin
|
|
40
|
-
*
|
|
41
|
-
* @public
|
|
42
|
-
*/
|
|
43
|
-
const yCursorPluginKey = new PluginKey("yjs-cursor");
|
|
44
|
-
/**
|
|
45
|
-
* Custom function to transform sha256 hash to N byte
|
|
46
|
-
*
|
|
47
|
-
* @param {Uint8Array} digest
|
|
48
|
-
*/
|
|
49
|
-
const _convolute = (digest) => {
|
|
50
|
-
const N = 6;
|
|
51
|
-
for (let i = N; i < digest.length; i++) digest[i % N] = digest[i % N] ^ digest[i];
|
|
52
|
-
return digest.slice(0, N);
|
|
53
|
-
};
|
|
54
|
-
/**
|
|
55
|
-
* @param {any} json
|
|
56
|
-
*/
|
|
57
|
-
const hashOfJSON = (json) => buf.toBase64(_convolute(sha256.digest(buf.encodeAny(json))));
|
|
58
|
-
/**
|
|
59
|
-
* @param {Y.Item} item
|
|
60
|
-
* @param {Y.Snapshot} [snapshot]
|
|
61
|
-
*/
|
|
62
|
-
const isVisible = (item, snapshot) => snapshot === void 0 ? !item.deleted : snapshot.sv.has(item.id.client) && snapshot.sv.get(item.id.client) > item.id.clock && !Y.isDeleted(snapshot.ds, item.id);
|
|
63
|
-
/**
|
|
64
|
-
* Either a node if type is YXmlElement or an Array of text nodes if YXmlText
|
|
65
|
-
* @typedef {Map<Y.AbstractType<any>, PModel.Node | Array<PModel.Node>>} ProsemirrorMapping
|
|
66
|
-
*/
|
|
67
|
-
/**
|
|
68
|
-
* @typedef {Object} ColorDef
|
|
69
|
-
* @property {string} ColorDef.light
|
|
70
|
-
* @property {string} ColorDef.dark
|
|
71
|
-
*/
|
|
72
|
-
/**
|
|
73
|
-
* @typedef {Object} YSyncOpts
|
|
74
|
-
* @property {Array<ColorDef>} [YSyncOpts.colors]
|
|
75
|
-
* @property {Map<string,ColorDef>} [YSyncOpts.colorMapping]
|
|
76
|
-
* @property {Y.PermanentUserData|null} [YSyncOpts.permanentUserData]
|
|
77
|
-
* @property {ProsemirrorMapping} [YSyncOpts.mapping]
|
|
78
|
-
* @property {function} [YSyncOpts.onFirstRender] Fired when the content from Yjs is initially rendered to ProseMirror
|
|
79
|
-
*/
|
|
80
|
-
/**
|
|
81
|
-
* @type {Array<ColorDef>}
|
|
82
|
-
*/
|
|
83
|
-
const defaultColors = [{
|
|
84
|
-
light: "#ecd44433",
|
|
85
|
-
dark: "#ecd444"
|
|
86
|
-
}];
|
|
87
|
-
/**
|
|
88
|
-
* @param {Map<string,ColorDef>} colorMapping
|
|
89
|
-
* @param {Array<ColorDef>} colors
|
|
90
|
-
* @param {string} user
|
|
91
|
-
* @return {ColorDef}
|
|
92
|
-
*/
|
|
93
|
-
const getUserColor = (colorMapping, colors, user) => {
|
|
94
|
-
if (!colorMapping.has(user)) {
|
|
95
|
-
if (colorMapping.size < colors.length) {
|
|
96
|
-
const usedColors = set.create();
|
|
97
|
-
colorMapping.forEach((color) => usedColors.add(color));
|
|
98
|
-
colors = colors.filter((color) => !usedColors.has(color));
|
|
99
|
-
}
|
|
100
|
-
colorMapping.set(user, random.oneOf(colors));
|
|
101
|
-
}
|
|
102
|
-
return colorMapping.get(user);
|
|
103
|
-
};
|
|
104
|
-
/**
|
|
105
|
-
* This plugin listens to changes in prosemirror view and keeps yXmlState and view in sync.
|
|
106
|
-
*
|
|
107
|
-
* This plugin also keeps references to the type and the shared document so other plugins can access it.
|
|
108
|
-
* @param {Y.XmlFragment} yXmlFragment
|
|
109
|
-
* @param {YSyncOpts} opts
|
|
110
|
-
* @return {any} Returns a prosemirror plugin that binds to this type
|
|
111
|
-
*/
|
|
112
|
-
const ySyncPlugin = (yXmlFragment, { colors = defaultColors, colorMapping = /* @__PURE__ */ new Map(), permanentUserData = null, onFirstRender = () => {}, mapping } = {}) => {
|
|
113
|
-
let initialContentChanged = false;
|
|
114
|
-
const binding = new ProsemirrorBinding(yXmlFragment, mapping);
|
|
115
|
-
const plugin = new Plugin({
|
|
116
|
-
props: { editable: (state) => {
|
|
117
|
-
const syncState = ySyncPluginKey.getState(state);
|
|
118
|
-
return syncState.snapshot == null && syncState.prevSnapshot == null;
|
|
119
|
-
} },
|
|
120
|
-
key: ySyncPluginKey,
|
|
121
|
-
state: {
|
|
122
|
-
/**
|
|
123
|
-
* @returns {any}
|
|
124
|
-
*/
|
|
125
|
-
init: (_initargs, _state) => {
|
|
126
|
-
return {
|
|
127
|
-
type: yXmlFragment,
|
|
128
|
-
doc: yXmlFragment.doc,
|
|
129
|
-
binding,
|
|
130
|
-
snapshot: null,
|
|
131
|
-
prevSnapshot: null,
|
|
132
|
-
isChangeOrigin: false,
|
|
133
|
-
isUndoRedoOperation: false,
|
|
134
|
-
addToHistory: true,
|
|
135
|
-
colors,
|
|
136
|
-
colorMapping,
|
|
137
|
-
permanentUserData
|
|
138
|
-
};
|
|
139
|
-
},
|
|
140
|
-
apply: (tr, pluginState) => {
|
|
141
|
-
const change = tr.getMeta(ySyncPluginKey);
|
|
142
|
-
if (change !== void 0) {
|
|
143
|
-
pluginState = Object.assign({}, pluginState);
|
|
144
|
-
for (const key in change) pluginState[key] = change[key];
|
|
145
|
-
}
|
|
146
|
-
if (tr.docChanged) pluginState.addToHistory = tr.getMeta("addToHistory") !== false;
|
|
147
|
-
pluginState.isChangeOrigin = change !== void 0 && !!change.isChangeOrigin;
|
|
148
|
-
pluginState.isUndoRedoOperation = change !== void 0 && !!change.isChangeOrigin && !!change.isUndoRedoOperation;
|
|
149
|
-
if (binding.prosemirrorView !== null) {
|
|
150
|
-
if (change !== void 0 && (change.snapshot != null || change.prevSnapshot != null)) eventloop.timeout(0, () => {
|
|
151
|
-
if (binding.prosemirrorView == null) return;
|
|
152
|
-
if (change.restore == null) binding._renderSnapshot(change.snapshot, change.prevSnapshot, pluginState);
|
|
153
|
-
else {
|
|
154
|
-
binding._renderSnapshot(change.snapshot, change.snapshot, pluginState);
|
|
155
|
-
delete pluginState.restore;
|
|
156
|
-
delete pluginState.snapshot;
|
|
157
|
-
delete pluginState.prevSnapshot;
|
|
158
|
-
binding.mux(() => {
|
|
159
|
-
binding._prosemirrorChanged(binding.prosemirrorView.state.doc);
|
|
160
|
-
});
|
|
161
|
-
}
|
|
162
|
-
});
|
|
163
|
-
}
|
|
164
|
-
return pluginState;
|
|
165
|
-
}
|
|
166
|
-
},
|
|
167
|
-
view: (view) => {
|
|
168
|
-
binding.initView(view);
|
|
169
|
-
if (mapping == null) binding._forceRerender();
|
|
170
|
-
onFirstRender();
|
|
171
|
-
return {
|
|
172
|
-
update: () => {
|
|
173
|
-
const pluginState = plugin.getState(view.state);
|
|
174
|
-
if (pluginState.snapshot == null && pluginState.prevSnapshot == null) {
|
|
175
|
-
if (initialContentChanged || view.state.doc.content.findDiffStart(view.state.doc.type.createAndFill().content) !== null) {
|
|
176
|
-
initialContentChanged = true;
|
|
177
|
-
if (pluginState.addToHistory === false && !pluginState.isChangeOrigin) {
|
|
178
|
-
const yUndoPluginState = yUndoPluginKey.getState(view.state);
|
|
179
|
-
/**
|
|
180
|
-
* @type {Y.UndoManager}
|
|
181
|
-
*/
|
|
182
|
-
const um = yUndoPluginState && yUndoPluginState.undoManager;
|
|
183
|
-
if (um) um.stopCapturing();
|
|
184
|
-
}
|
|
185
|
-
binding.mux(() => {
|
|
186
|
-
/** @type {Y.Doc} */ pluginState.doc.transact((tr) => {
|
|
187
|
-
tr.meta.set("addToHistory", pluginState.addToHistory);
|
|
188
|
-
binding._prosemirrorChanged(view.state.doc);
|
|
189
|
-
}, ySyncPluginKey);
|
|
190
|
-
});
|
|
191
|
-
}
|
|
192
|
-
}
|
|
193
|
-
},
|
|
194
|
-
destroy: () => {
|
|
195
|
-
binding.destroy();
|
|
196
|
-
}
|
|
197
|
-
};
|
|
198
|
-
}
|
|
199
|
-
});
|
|
200
|
-
return plugin;
|
|
201
|
-
};
|
|
202
|
-
/**
|
|
203
|
-
* Resolves one text-selection endpoint after a remote update. Falls back to
|
|
204
|
-
* content-based matching when the Yjs resolution is missing or lands in the
|
|
205
|
-
* wrong block, and keeps the Yjs resolution when the fallback finds nothing.
|
|
206
|
-
*
|
|
207
|
-
* @param {import('prosemirror-model').Node} newDoc
|
|
208
|
-
* @param {import('prosemirror-model').Node} oldDoc
|
|
209
|
-
* @param {number|null|undefined} oldAbs
|
|
210
|
-
* @param {number|null} resolved
|
|
211
|
-
* @return {number|null}
|
|
212
|
-
*/
|
|
213
|
-
const recoverSelectionEndpoint = (newDoc, oldDoc, oldAbs, resolved) => {
|
|
214
|
-
if (oldAbs == null) return resolved;
|
|
215
|
-
if (!(resolved === null || oldAbs > 1 && resolved <= 1 || isMisresolvedAfterStructuralChange(oldDoc, newDoc, oldAbs, resolved))) return resolved;
|
|
216
|
-
const recovered = findAbsolutePositionAfterStructuralChange(oldDoc, newDoc, oldAbs);
|
|
217
|
-
return recovered !== null ? recovered : resolved;
|
|
218
|
-
};
|
|
219
|
-
/**
|
|
220
|
-
* @param {import('prosemirror-state').Transaction} tr
|
|
221
|
-
* @param {ReturnType<typeof getRelativeSelection>} relSel
|
|
222
|
-
* @param {ProsemirrorBinding} binding
|
|
223
|
-
* @param {import('prosemirror-model').Node} [oldDoc]
|
|
224
|
-
*/
|
|
225
|
-
const restoreRelativeSelection = (tr, relSel, binding, oldDoc) => {
|
|
226
|
-
if (relSel !== null && relSel.anchor !== null && relSel.head !== null) {
|
|
227
|
-
if (relSel.type === "all") tr.setSelection(new AllSelection(tr.doc));
|
|
228
|
-
else if (relSel.type === "node") {
|
|
229
|
-
const anchor = relativePositionToAbsolutePosition(binding.doc, binding.type, relSel.anchor, binding.mapping);
|
|
230
|
-
if (anchor !== null) tr.setSelection(createSafeNodeSelection(tr, anchor));
|
|
231
|
-
} else if (relSel.type === "nodeRange") {
|
|
232
|
-
const anchor = relativePositionToAbsolutePosition(binding.doc, binding.type, relSel.anchor, binding.mapping);
|
|
233
|
-
const head = relativePositionToAbsolutePosition(binding.doc, binding.type, relSel.head, binding.mapping);
|
|
234
|
-
const selection = createSafeNodeRangeSelection(tr, anchor, head, relSel.depth);
|
|
235
|
-
if (selection !== null) tr.setSelection(selection);
|
|
236
|
-
} else {
|
|
237
|
-
let anchor = relativePositionToAbsolutePosition(binding.doc, binding.type, relSel.anchor, binding.mapping);
|
|
238
|
-
let head = relativePositionToAbsolutePosition(binding.doc, binding.type, relSel.head, binding.mapping);
|
|
239
|
-
if (oldDoc != null) {
|
|
240
|
-
anchor = recoverSelectionEndpoint(tr.doc, oldDoc, relSel.absAnchor, anchor);
|
|
241
|
-
head = recoverSelectionEndpoint(tr.doc, oldDoc, relSel.absHead, head);
|
|
242
|
-
}
|
|
243
|
-
if (anchor === null) anchor = head;
|
|
244
|
-
if (head === null) head = anchor;
|
|
245
|
-
if (anchor !== null && head !== null) tr.setSelection(TextSelection.between(tr.doc.resolve(anchor), tr.doc.resolve(head)));
|
|
246
|
-
}
|
|
247
|
-
}
|
|
248
|
-
};
|
|
249
|
-
/**
|
|
250
|
-
* @param {import('prosemirror-state').Transaction} tr
|
|
251
|
-
* @param {number} pos
|
|
252
|
-
* @returns {import('prosemirror-state').Selection}
|
|
253
|
-
*
|
|
254
|
-
* Creates a NodeSelection if the position points to a valid node, otherwise
|
|
255
|
-
* creates a TextSelection near the position.
|
|
256
|
-
*/
|
|
257
|
-
const createSafeNodeSelection = (tr, pos) => {
|
|
258
|
-
const $pos = tr.doc.resolve(pos);
|
|
259
|
-
if ($pos.nodeAfter) return NodeSelection.create(tr.doc, pos);
|
|
260
|
-
else return TextSelection.near($pos);
|
|
261
|
-
};
|
|
262
|
-
/**
|
|
263
|
-
* Safely reconstructs a NodeRangeSelection from resolved absolute positions.
|
|
264
|
-
*
|
|
265
|
-
* @param {import('prosemirror-state').Transaction} tr - The transaction whose document provides resolved positions.
|
|
266
|
-
* @param {number|null} anchor - Absolute document position marking the start (boundary) of the node range.
|
|
267
|
-
* Use `relativePositionToAbsolutePosition` before calling this function.
|
|
268
|
-
* @param {number|null} head - Absolute document position marking the end (boundary) of the node range.
|
|
269
|
-
* Use `relativePositionToAbsolutePosition` before calling this function.
|
|
270
|
-
* @param {number|undefined} depth - The nesting depth at which the range operates (e.g. 0 for
|
|
271
|
-
* top-level blocks, 1 for blocks nested inside a wrapper). Passed through to
|
|
272
|
-
* `Selection.fromJSON`; ignored by `@tiptap/extension-node-range` < v2.29 but
|
|
273
|
-
* properly stored starting from that version.
|
|
274
|
-
* @returns {import('prosemirror-state').Selection|null} Reconstructed selection, or null if
|
|
275
|
-
* anchor/head could not be resolved.
|
|
276
|
-
*/
|
|
277
|
-
const createSafeNodeRangeSelection = (tr, anchor, head, depth) => {
|
|
278
|
-
if (anchor === null || head === null) return null;
|
|
279
|
-
const clampedAnchor = Math.min(Math.max(anchor, 0), tr.doc.content.size);
|
|
280
|
-
const clampedHead = Math.min(Math.max(head, 0), tr.doc.content.size);
|
|
281
|
-
try {
|
|
282
|
-
const selection = Selection.fromJSON(tr.doc, {
|
|
283
|
-
type: "nodeRange",
|
|
284
|
-
anchor: clampedAnchor,
|
|
285
|
-
head: clampedHead,
|
|
286
|
-
depth
|
|
287
|
-
});
|
|
288
|
-
if (!selection.ranges.length) return TextSelection.near(tr.doc.resolve(clampedAnchor));
|
|
289
|
-
return selection;
|
|
290
|
-
} catch (e) {
|
|
291
|
-
return TextSelection.near(tr.doc.resolve(clampedAnchor));
|
|
292
|
-
}
|
|
293
|
-
};
|
|
294
|
-
/**
|
|
295
|
-
* @param {ProsemirrorBinding} pmbinding
|
|
296
|
-
* @param {import('prosemirror-state').EditorState} state
|
|
297
|
-
*/
|
|
298
|
-
const getRelativeSelection = (pmbinding, state) => {
|
|
299
|
-
const type = state.selection.jsonID;
|
|
300
|
-
return {
|
|
301
|
-
type,
|
|
302
|
-
depth: type === "nodeRange" ? state.selection.depth : void 0,
|
|
303
|
-
anchor: absolutePositionToRelativePosition(state.selection.anchor, pmbinding.type, pmbinding.mapping),
|
|
304
|
-
head: absolutePositionToRelativePosition(state.selection.head, pmbinding.type, pmbinding.mapping),
|
|
305
|
-
absAnchor: state.selection.anchor,
|
|
306
|
-
absHead: state.selection.head
|
|
307
|
-
};
|
|
308
|
-
};
|
|
309
|
-
/**
|
|
310
|
-
* Binding for prosemirror.
|
|
311
|
-
*
|
|
312
|
-
* @protected
|
|
313
|
-
*/
|
|
314
|
-
var ProsemirrorBinding = class {
|
|
315
|
-
/**
|
|
316
|
-
* @param {Y.XmlFragment} yXmlFragment The bind source
|
|
317
|
-
* @param {ProsemirrorMapping} mapping
|
|
318
|
-
*/
|
|
319
|
-
constructor(yXmlFragment, mapping = /* @__PURE__ */ new Map()) {
|
|
320
|
-
this.type = yXmlFragment;
|
|
321
|
-
/**
|
|
322
|
-
* this will be set once the view is created
|
|
323
|
-
* @type {any}
|
|
324
|
-
*/
|
|
325
|
-
this.prosemirrorView = null;
|
|
326
|
-
this.mux = createMutex();
|
|
327
|
-
this.mapping = mapping;
|
|
328
|
-
/**
|
|
329
|
-
* Is overlapping mark - i.e. mark does not exclude itself.
|
|
330
|
-
*
|
|
331
|
-
* @type {Map<import('prosemirror-model').MarkType, boolean>}
|
|
332
|
-
*/
|
|
333
|
-
this.isOMark = /* @__PURE__ */ new Map();
|
|
334
|
-
this._observeFunction = this._typeChanged.bind(this);
|
|
335
|
-
/**
|
|
336
|
-
* @type {Y.Doc}
|
|
337
|
-
*/
|
|
338
|
-
this.doc = yXmlFragment.doc;
|
|
339
|
-
/**
|
|
340
|
-
* current selection as relative positions in the Yjs model
|
|
341
|
-
*/
|
|
342
|
-
this.beforeTransactionSelection = null;
|
|
343
|
-
this.beforeAllTransactions = () => {
|
|
344
|
-
if (this.beforeTransactionSelection === null && this.prosemirrorView != null) this.beforeTransactionSelection = getRelativeSelection(this, this.prosemirrorView.state);
|
|
345
|
-
};
|
|
346
|
-
this.afterAllTransactions = () => {
|
|
347
|
-
this.beforeTransactionSelection = null;
|
|
348
|
-
};
|
|
349
|
-
this._domSelectionInView = null;
|
|
350
|
-
}
|
|
351
|
-
/**
|
|
352
|
-
* Create a transaction for changing the prosemirror state.
|
|
353
|
-
*
|
|
354
|
-
* @returns
|
|
355
|
-
*/
|
|
356
|
-
get _tr() {
|
|
357
|
-
return this.prosemirrorView.state.tr.setMeta("addToHistory", false);
|
|
358
|
-
}
|
|
359
|
-
_isLocalCursorInView() {
|
|
360
|
-
if (!this.prosemirrorView.hasFocus()) return false;
|
|
361
|
-
if (environment.isBrowser && this._domSelectionInView === null) {
|
|
362
|
-
eventloop.timeout(0, () => {
|
|
363
|
-
this._domSelectionInView = null;
|
|
364
|
-
});
|
|
365
|
-
this._domSelectionInView = this._isDomSelectionInView();
|
|
366
|
-
}
|
|
367
|
-
return this._domSelectionInView;
|
|
368
|
-
}
|
|
369
|
-
_isDomSelectionInView() {
|
|
370
|
-
const selection = this.prosemirrorView._root.getSelection();
|
|
371
|
-
if (selection == null || selection.anchorNode == null) return false;
|
|
372
|
-
const range = this.prosemirrorView._root.createRange();
|
|
373
|
-
range.setStart(selection.anchorNode, selection.anchorOffset);
|
|
374
|
-
range.setEnd(selection.focusNode, selection.focusOffset);
|
|
375
|
-
if (range.getClientRects().length === 0) {
|
|
376
|
-
if (range.startContainer && range.collapsed) range.selectNodeContents(range.startContainer);
|
|
377
|
-
}
|
|
378
|
-
const bounding = range.getBoundingClientRect();
|
|
379
|
-
const documentElement = dom.doc.documentElement;
|
|
380
|
-
return bounding.bottom >= 0 && bounding.right >= 0 && bounding.left <= (window.innerWidth || documentElement.clientWidth || 0) && bounding.top <= (window.innerHeight || documentElement.clientHeight || 0);
|
|
381
|
-
}
|
|
382
|
-
/**
|
|
383
|
-
* @param {Y.Snapshot} snapshot
|
|
384
|
-
* @param {Y.Snapshot} prevSnapshot
|
|
385
|
-
*/
|
|
386
|
-
renderSnapshot(snapshot, prevSnapshot) {
|
|
387
|
-
if (!prevSnapshot) prevSnapshot = Y.createSnapshot(Y.createDeleteSet(), /* @__PURE__ */ new Map());
|
|
388
|
-
this.prosemirrorView.dispatch(this._tr.setMeta(ySyncPluginKey, {
|
|
389
|
-
snapshot,
|
|
390
|
-
prevSnapshot
|
|
391
|
-
}));
|
|
392
|
-
}
|
|
393
|
-
unrenderSnapshot() {
|
|
394
|
-
this.mapping.clear();
|
|
395
|
-
this.mux(() => {
|
|
396
|
-
const fragmentContent = this.type.toArray().map((t) => createNodeFromYElement(t, this.prosemirrorView.state.schema, this)).filter((n) => n !== null);
|
|
397
|
-
const tr = this._tr.replace(0, this.prosemirrorView.state.doc.content.size, new PModel.Slice(PModel.Fragment.from(fragmentContent), 0, 0));
|
|
398
|
-
tr.setMeta(ySyncPluginKey, {
|
|
399
|
-
snapshot: null,
|
|
400
|
-
prevSnapshot: null
|
|
401
|
-
});
|
|
402
|
-
this.prosemirrorView.dispatch(tr);
|
|
403
|
-
});
|
|
404
|
-
}
|
|
405
|
-
_forceRerender() {
|
|
406
|
-
this.mapping.clear();
|
|
407
|
-
this.mux(() => {
|
|
408
|
-
const sel = this.beforeTransactionSelection !== null ? null : this.prosemirrorView.state.selection;
|
|
409
|
-
const fragmentContent = this.type.toArray().map((t) => createNodeFromYElement(t, this.prosemirrorView.state.schema, this)).filter((n) => n !== null);
|
|
410
|
-
const tr = this._tr.replace(0, this.prosemirrorView.state.doc.content.size, new PModel.Slice(PModel.Fragment.from(fragmentContent), 0, 0));
|
|
411
|
-
if (sel) {
|
|
412
|
-
/**
|
|
413
|
-
* If the Prosemirror document we just created from this.type is
|
|
414
|
-
* smaller than the previous document, the selection might be
|
|
415
|
-
* out of bound, which would make Prosemirror throw an error.
|
|
416
|
-
*/
|
|
417
|
-
const clampedAnchor = math.min(math.max(sel.anchor, 0), tr.doc.content.size);
|
|
418
|
-
const clampedHead = math.min(math.max(sel.head, 0), tr.doc.content.size);
|
|
419
|
-
tr.setSelection(TextSelection.create(tr.doc, clampedAnchor, clampedHead));
|
|
420
|
-
}
|
|
421
|
-
this.prosemirrorView.dispatch(tr.setMeta(ySyncPluginKey, {
|
|
422
|
-
isChangeOrigin: true,
|
|
423
|
-
binding: this
|
|
424
|
-
}));
|
|
425
|
-
});
|
|
426
|
-
}
|
|
427
|
-
/**
|
|
428
|
-
* @param {Y.Snapshot|Uint8Array} snapshot
|
|
429
|
-
* @param {Y.Snapshot|Uint8Array} prevSnapshot
|
|
430
|
-
* @param {Object} pluginState
|
|
431
|
-
*/
|
|
432
|
-
_renderSnapshot(snapshot, prevSnapshot, pluginState) {
|
|
433
|
-
/**
|
|
434
|
-
* The document that contains the full history of this document.
|
|
435
|
-
* @type {Y.Doc}
|
|
436
|
-
*/
|
|
437
|
-
let historyDoc = this.doc;
|
|
438
|
-
let historyType = this.type;
|
|
439
|
-
if (!snapshot) snapshot = Y.snapshot(this.doc);
|
|
440
|
-
if (snapshot instanceof Uint8Array || prevSnapshot instanceof Uint8Array) {
|
|
441
|
-
if (!(snapshot instanceof Uint8Array) || !(prevSnapshot instanceof Uint8Array)) error.unexpectedCase();
|
|
442
|
-
historyDoc = new Y.Doc({ gc: false });
|
|
443
|
-
Y.applyUpdateV2(historyDoc, prevSnapshot);
|
|
444
|
-
prevSnapshot = Y.snapshot(historyDoc);
|
|
445
|
-
Y.applyUpdateV2(historyDoc, snapshot);
|
|
446
|
-
snapshot = Y.snapshot(historyDoc);
|
|
447
|
-
if (historyType._item === null) {
|
|
448
|
-
/**
|
|
449
|
-
* If is a root type, we need to find the root key in the initial document
|
|
450
|
-
* and use it to get the history type.
|
|
451
|
-
*/
|
|
452
|
-
const rootKey = Array.from(this.doc.share.keys()).find((key) => this.doc.share.get(key) === this.type);
|
|
453
|
-
historyType = historyDoc.getXmlFragment(rootKey);
|
|
454
|
-
} else {
|
|
455
|
-
/**
|
|
456
|
-
* If it is a sub type, we use the item id to find the history type.
|
|
457
|
-
*/
|
|
458
|
-
const historyStructs = historyDoc.store.clients.get(historyType._item.id.client) ?? [];
|
|
459
|
-
historyType = historyStructs[Y.findIndexSS(historyStructs, historyType._item.id.clock)].content.type;
|
|
460
|
-
}
|
|
461
|
-
}
|
|
462
|
-
this.mapping.clear();
|
|
463
|
-
this.mux(() => {
|
|
464
|
-
historyDoc.transact((transaction) => {
|
|
465
|
-
/**
|
|
466
|
-
* @type {Y.PermanentUserData}
|
|
467
|
-
*/
|
|
468
|
-
const pud = pluginState.permanentUserData;
|
|
469
|
-
if (pud) pud.dss.forEach((ds) => {
|
|
470
|
-
Y.iterateDeletedStructs(transaction, ds, (_item) => {});
|
|
471
|
-
});
|
|
472
|
-
/**
|
|
473
|
-
* @param {'removed'|'added'} type
|
|
474
|
-
* @param {Y.ID} id
|
|
475
|
-
*/
|
|
476
|
-
const computeYChange = (type, id) => {
|
|
477
|
-
const user = type === "added" ? pud.getUserByClientId(id.client) : pud.getUserByDeletedId(id);
|
|
478
|
-
return {
|
|
479
|
-
user,
|
|
480
|
-
type,
|
|
481
|
-
color: getUserColor(pluginState.colorMapping, pluginState.colors, user)
|
|
482
|
-
};
|
|
483
|
-
};
|
|
484
|
-
const fragmentContent = Y.typeListToArraySnapshot(historyType, new Y.Snapshot(prevSnapshot.ds, snapshot.sv)).map((t) => {
|
|
485
|
-
if (!t._item.deleted || isVisible(t._item, snapshot) || isVisible(t._item, prevSnapshot)) return createNodeFromYElement(t, this.prosemirrorView.state.schema, {
|
|
486
|
-
mapping: /* @__PURE__ */ new Map(),
|
|
487
|
-
isOMark: /* @__PURE__ */ new Map()
|
|
488
|
-
}, snapshot, prevSnapshot, computeYChange);
|
|
489
|
-
else return null;
|
|
490
|
-
}).filter((n) => n !== null);
|
|
491
|
-
const tr = this._tr.replace(0, this.prosemirrorView.state.doc.content.size, new PModel.Slice(PModel.Fragment.from(fragmentContent), 0, 0));
|
|
492
|
-
this.prosemirrorView.dispatch(tr.setMeta(ySyncPluginKey, { isChangeOrigin: true }));
|
|
493
|
-
}, ySyncPluginKey);
|
|
494
|
-
});
|
|
495
|
-
}
|
|
496
|
-
/**
|
|
497
|
-
* @param {Array<Y.YEvent<any>>} events
|
|
498
|
-
* @param {Y.Transaction} transaction
|
|
499
|
-
*/
|
|
500
|
-
_typeChanged(events, transaction) {
|
|
501
|
-
if (this.prosemirrorView == null) return;
|
|
502
|
-
const syncState = ySyncPluginKey.getState(this.prosemirrorView.state);
|
|
503
|
-
if (events.length === 0 || syncState.snapshot != null || syncState.prevSnapshot != null) {
|
|
504
|
-
this.renderSnapshot(syncState.snapshot, syncState.prevSnapshot);
|
|
505
|
-
return;
|
|
506
|
-
}
|
|
507
|
-
this.mux(() => {
|
|
508
|
-
/**
|
|
509
|
-
* @param {any} _
|
|
510
|
-
* @param {Y.AbstractType<any>} type
|
|
511
|
-
*/
|
|
512
|
-
const delType = (_, type) => this.mapping.delete(type);
|
|
513
|
-
Y.iterateDeletedStructs(transaction, transaction.deleteSet, (struct) => {
|
|
514
|
-
if (struct.constructor === Y.Item) {
|
|
515
|
-
const type = struct.content.type;
|
|
516
|
-
type && this.mapping.delete(type);
|
|
517
|
-
}
|
|
518
|
-
});
|
|
519
|
-
transaction.changed.forEach(delType);
|
|
520
|
-
transaction.changedParentTypes.forEach(delType);
|
|
521
|
-
this.mapping.clear();
|
|
522
|
-
const fragmentContent = this.type.toArray().map((t) => createNodeIfNotExists(t, this.prosemirrorView.state.schema, this)).filter((n) => n !== null);
|
|
523
|
-
const oldDoc = this.prosemirrorView.state.doc;
|
|
524
|
-
let tr = this._tr.replace(0, this.prosemirrorView.state.doc.content.size, new PModel.Slice(PModel.Fragment.from(fragmentContent), 0, 0));
|
|
525
|
-
restoreRelativeSelection(tr, this.beforeTransactionSelection, this, oldDoc);
|
|
526
|
-
tr = tr.setMeta(ySyncPluginKey, {
|
|
527
|
-
isChangeOrigin: true,
|
|
528
|
-
isUndoRedoOperation: transaction.origin instanceof Y.UndoManager
|
|
529
|
-
});
|
|
530
|
-
if (this.beforeTransactionSelection !== null && this._isLocalCursorInView()) tr.scrollIntoView();
|
|
531
|
-
this.prosemirrorView.dispatch(tr);
|
|
532
|
-
});
|
|
533
|
-
}
|
|
534
|
-
/**
|
|
535
|
-
* @param {import('prosemirror-model').Node} doc
|
|
536
|
-
*/
|
|
537
|
-
_prosemirrorChanged(doc) {
|
|
538
|
-
this.doc.transact(() => {
|
|
539
|
-
updateYFragment(this.doc, this.type, doc, this);
|
|
540
|
-
this.beforeTransactionSelection = getRelativeSelection(this, this.prosemirrorView.state);
|
|
541
|
-
}, ySyncPluginKey);
|
|
542
|
-
}
|
|
543
|
-
/**
|
|
544
|
-
* View is ready to listen to changes. Register observers.
|
|
545
|
-
* @param {any} prosemirrorView
|
|
546
|
-
*/
|
|
547
|
-
initView(prosemirrorView) {
|
|
548
|
-
if (this.prosemirrorView != null) this.destroy();
|
|
549
|
-
this.prosemirrorView = prosemirrorView;
|
|
550
|
-
this.doc.on("beforeAllTransactions", this.beforeAllTransactions);
|
|
551
|
-
this.doc.on("afterAllTransactions", this.afterAllTransactions);
|
|
552
|
-
this.type.observeDeep(this._observeFunction);
|
|
553
|
-
}
|
|
554
|
-
destroy() {
|
|
555
|
-
if (this.prosemirrorView == null) return;
|
|
556
|
-
this.prosemirrorView = null;
|
|
557
|
-
this.type.unobserveDeep(this._observeFunction);
|
|
558
|
-
this.doc.off("beforeAllTransactions", this.beforeAllTransactions);
|
|
559
|
-
this.doc.off("afterAllTransactions", this.afterAllTransactions);
|
|
560
|
-
}
|
|
561
|
-
};
|
|
562
|
-
/**
|
|
563
|
-
* @private
|
|
564
|
-
* @param {Y.XmlElement | Y.XmlHook} el
|
|
565
|
-
* @param {PModel.Schema} schema
|
|
566
|
-
* @param {BindingMetadata} meta
|
|
567
|
-
* @param {Y.Snapshot} [snapshot]
|
|
568
|
-
* @param {Y.Snapshot} [prevSnapshot]
|
|
569
|
-
* @param {function('removed' | 'added', Y.ID):any} [computeYChange]
|
|
570
|
-
* @return {PModel.Node | null}
|
|
571
|
-
*/
|
|
572
|
-
const createNodeIfNotExists = (el, schema, meta, snapshot, prevSnapshot, computeYChange) => {
|
|
573
|
-
const node = meta.mapping.get(el);
|
|
574
|
-
if (node === void 0) {
|
|
575
|
-
if (el instanceof Y.XmlElement) return createNodeFromYElement(el, schema, meta, snapshot, prevSnapshot, computeYChange);
|
|
576
|
-
else throw error.methodUnimplemented();
|
|
577
|
-
}
|
|
578
|
-
return node;
|
|
579
|
-
};
|
|
580
|
-
/**
|
|
581
|
-
* @private
|
|
582
|
-
* @param {Y.XmlElement} el
|
|
583
|
-
* @param {any} schema
|
|
584
|
-
* @param {BindingMetadata} meta
|
|
585
|
-
* @param {Y.Snapshot} [snapshot]
|
|
586
|
-
* @param {Y.Snapshot} [prevSnapshot]
|
|
587
|
-
* @param {function('removed' | 'added', Y.ID):any} [computeYChange]
|
|
588
|
-
* @return {PModel.Node | null} Returns node if node could be created. Otherwise it deletes the yjs type and returns null
|
|
589
|
-
*/
|
|
590
|
-
const createNodeFromYElement = (el, schema, meta, snapshot, prevSnapshot, computeYChange) => {
|
|
591
|
-
const children = [];
|
|
592
|
-
/**
|
|
593
|
-
* @param {Y.XmlElement | Y.XmlText} type
|
|
594
|
-
*/
|
|
595
|
-
const createChildren = (type) => {
|
|
596
|
-
if (type instanceof Y.XmlElement) {
|
|
597
|
-
const n = createNodeIfNotExists(type, schema, meta, snapshot, prevSnapshot, computeYChange);
|
|
598
|
-
if (n !== null) children.push(n);
|
|
599
|
-
} else {
|
|
600
|
-
const nextytext = (type._item.right?.content)?.type;
|
|
601
|
-
if (nextytext instanceof Y.Text && !nextytext._item.deleted && nextytext._item.id.client === nextytext.doc.clientID) {
|
|
602
|
-
type.applyDelta([{ retain: type.length }, ...nextytext.toDelta()]);
|
|
603
|
-
nextytext.doc.transact((tr) => {
|
|
604
|
-
nextytext._item.delete(tr);
|
|
605
|
-
});
|
|
606
|
-
}
|
|
607
|
-
const ns = createTextNodesFromYText(type, schema, meta, snapshot, prevSnapshot, computeYChange);
|
|
608
|
-
if (ns !== null) ns.forEach((textchild) => {
|
|
609
|
-
if (textchild !== null) children.push(textchild);
|
|
610
|
-
});
|
|
611
|
-
}
|
|
612
|
-
};
|
|
613
|
-
if (snapshot === void 0 || prevSnapshot === void 0) el.toArray().forEach(createChildren);
|
|
614
|
-
else Y.typeListToArraySnapshot(el, new Y.Snapshot(prevSnapshot.ds, snapshot.sv)).forEach(createChildren);
|
|
615
|
-
try {
|
|
616
|
-
const attrs = el.getAttributes(snapshot);
|
|
617
|
-
if (snapshot !== void 0) {
|
|
618
|
-
if (!isVisible(el._item, snapshot)) attrs.ychange = computeYChange ? computeYChange(
|
|
619
|
-
"removed",
|
|
620
|
-
/** @type {Y.Item} */
|
|
621
|
-
el._item.id
|
|
622
|
-
) : { type: "removed" };
|
|
623
|
-
else if (!isVisible(el._item, prevSnapshot)) attrs.ychange = computeYChange ? computeYChange(
|
|
624
|
-
"added",
|
|
625
|
-
/** @type {Y.Item} */
|
|
626
|
-
el._item.id
|
|
627
|
-
) : { type: "added" };
|
|
628
|
-
}
|
|
629
|
-
const node = schema.node(el.nodeName, attrs, children);
|
|
630
|
-
meta.mapping.set(el, node);
|
|
631
|
-
return node;
|
|
632
|
-
} catch (e) {
|
|
633
|
-
/** @type {Y.Doc} */ el.doc.transact((transaction) => {
|
|
634
|
-
/** @type {Y.Item} */ el._item.delete(transaction);
|
|
635
|
-
}, ySyncPluginKey);
|
|
636
|
-
meta.mapping.delete(el);
|
|
637
|
-
return null;
|
|
638
|
-
}
|
|
639
|
-
};
|
|
640
|
-
/**
|
|
641
|
-
* @private
|
|
642
|
-
* @param {Y.XmlText} text
|
|
643
|
-
* @param {import('prosemirror-model').Schema} schema
|
|
644
|
-
* @param {BindingMetadata} _meta
|
|
645
|
-
* @param {Y.Snapshot} [snapshot]
|
|
646
|
-
* @param {Y.Snapshot} [prevSnapshot]
|
|
647
|
-
* @param {function('removed' | 'added', Y.ID):any} [computeYChange]
|
|
648
|
-
* @return {Array<PModel.Node>|null}
|
|
649
|
-
*/
|
|
650
|
-
const createTextNodesFromYText = (text, schema, _meta, snapshot, prevSnapshot, computeYChange) => {
|
|
651
|
-
const nodes = [];
|
|
652
|
-
const deltas = text.toDelta(snapshot, prevSnapshot, computeYChange);
|
|
653
|
-
try {
|
|
654
|
-
for (let i = 0; i < deltas.length; i++) {
|
|
655
|
-
const delta = deltas[i];
|
|
656
|
-
nodes.push(schema.text(delta.insert, attributesToMarks(delta.attributes, schema)));
|
|
657
|
-
}
|
|
658
|
-
} catch (e) {
|
|
659
|
-
/** @type {Y.Doc} */ text.doc.transact((transaction) => {
|
|
660
|
-
/** @type {Y.Item} */ text._item.delete(transaction);
|
|
661
|
-
}, ySyncPluginKey);
|
|
662
|
-
return null;
|
|
663
|
-
}
|
|
664
|
-
return nodes;
|
|
665
|
-
};
|
|
666
|
-
/**
|
|
667
|
-
* @private
|
|
668
|
-
* @param {Array<any>} nodes prosemirror node
|
|
669
|
-
* @param {BindingMetadata} meta
|
|
670
|
-
* @return {Y.XmlText}
|
|
671
|
-
*/
|
|
672
|
-
const createTypeFromTextNodes = (nodes, meta) => {
|
|
673
|
-
const type = new Y.XmlText();
|
|
674
|
-
const delta = nodes.map((node) => ({
|
|
675
|
-
insert: node.text,
|
|
676
|
-
attributes: marksToAttributes(node.marks, meta)
|
|
677
|
-
}));
|
|
678
|
-
type.applyDelta(delta);
|
|
679
|
-
meta.mapping.set(type, nodes);
|
|
680
|
-
return type;
|
|
681
|
-
};
|
|
682
|
-
/**
|
|
683
|
-
* @private
|
|
684
|
-
* @param {any} node prosemirror node
|
|
685
|
-
* @param {BindingMetadata} meta
|
|
686
|
-
* @return {Y.XmlElement}
|
|
687
|
-
*/
|
|
688
|
-
const createTypeFromElementNode = (node, meta) => {
|
|
689
|
-
const type = new Y.XmlElement(node.type.name);
|
|
690
|
-
for (const key in node.attrs) {
|
|
691
|
-
const val = node.attrs[key];
|
|
692
|
-
if (val !== null && key !== "ychange") type.setAttribute(key, val);
|
|
693
|
-
}
|
|
694
|
-
type.insert(0, normalizePNodeContent(node).map((n) => createTypeFromTextOrElementNode(n, meta)));
|
|
695
|
-
meta.mapping.set(type, node);
|
|
696
|
-
return type;
|
|
697
|
-
};
|
|
698
|
-
/**
|
|
699
|
-
* @private
|
|
700
|
-
* @param {PModel.Node|Array<PModel.Node>} node prosemirror text node
|
|
701
|
-
* @param {BindingMetadata} meta
|
|
702
|
-
* @return {Y.XmlElement|Y.XmlText}
|
|
703
|
-
*/
|
|
704
|
-
const createTypeFromTextOrElementNode = (node, meta) => node instanceof Array ? createTypeFromTextNodes(node, meta) : createTypeFromElementNode(node, meta);
|
|
705
|
-
/**
|
|
706
|
-
* @param {any} val
|
|
707
|
-
*/
|
|
708
|
-
const isObject = (val) => typeof val === "object" && val !== null;
|
|
709
|
-
/**
|
|
710
|
-
* @param {any} pattrs
|
|
711
|
-
* @param {any} yattrs
|
|
712
|
-
*/
|
|
713
|
-
const equalAttrs = (pattrs, yattrs) => {
|
|
714
|
-
const keys = Object.keys(pattrs).filter((key) => pattrs[key] !== null);
|
|
715
|
-
let eq = keys.length === Object.keys(yattrs).filter((key) => yattrs[key] !== null).length;
|
|
716
|
-
for (let i = 0; i < keys.length && eq; i++) {
|
|
717
|
-
const key = keys[i];
|
|
718
|
-
const l = pattrs[key];
|
|
719
|
-
const r = yattrs[key];
|
|
720
|
-
eq = key === "ychange" || l === r || isObject(l) && isObject(r) && equalAttrs(l, r);
|
|
721
|
-
}
|
|
722
|
-
return eq;
|
|
723
|
-
};
|
|
724
|
-
/**
|
|
725
|
-
* @typedef {Array<Array<PModel.Node>|PModel.Node>} NormalizedPNodeContent
|
|
726
|
-
*/
|
|
727
|
-
/**
|
|
728
|
-
* @param {any} pnode
|
|
729
|
-
* @return {NormalizedPNodeContent}
|
|
730
|
-
*/
|
|
731
|
-
const normalizePNodeContent = (pnode) => {
|
|
732
|
-
const c = pnode.content.content;
|
|
733
|
-
const res = [];
|
|
734
|
-
for (let i = 0; i < c.length; i++) {
|
|
735
|
-
const n = c[i];
|
|
736
|
-
if (n.isText) {
|
|
737
|
-
const textNodes = [];
|
|
738
|
-
for (let tnode = c[i]; i < c.length && tnode.isText; tnode = c[++i]) textNodes.push(tnode);
|
|
739
|
-
i--;
|
|
740
|
-
res.push(textNodes);
|
|
741
|
-
} else res.push(n);
|
|
742
|
-
}
|
|
743
|
-
return res;
|
|
744
|
-
};
|
|
745
|
-
/**
|
|
746
|
-
* @param {Y.XmlText} ytext
|
|
747
|
-
* @param {Array<any>} ptexts
|
|
748
|
-
*/
|
|
749
|
-
const equalYTextPText = (ytext, ptexts) => {
|
|
750
|
-
const delta = ytext.toDelta();
|
|
751
|
-
return delta.length === ptexts.length && delta.every(
|
|
752
|
-
/** @type {(d:any,i:number) => boolean} */
|
|
753
|
-
(d, i) => d.insert === ptexts[i].text && object.keys(d.attributes || {}).length === ptexts[i].marks.length && object.every(d.attributes, (attr, yattrname) => {
|
|
754
|
-
const markname = yattr2markname(yattrname);
|
|
755
|
-
const pmarks = ptexts[i].marks;
|
|
756
|
-
if (!pmarks.find(
|
|
757
|
-
/** @param {any} mark */
|
|
758
|
-
(mark) => mark.type.name === markname
|
|
759
|
-
)) return false;
|
|
760
|
-
return equalAttrs(attr, pmarks.find(
|
|
761
|
-
/** @param {any} mark */
|
|
762
|
-
(mark) => mark.type.name === markname
|
|
763
|
-
)?.attrs);
|
|
764
|
-
})
|
|
765
|
-
);
|
|
766
|
-
};
|
|
767
|
-
/**
|
|
768
|
-
* @param {Y.XmlElement|Y.XmlText|Y.XmlHook} ytype
|
|
769
|
-
* @param {any|Array<any>} pnode
|
|
770
|
-
*/
|
|
771
|
-
const equalYTypePNode = (ytype, pnode) => {
|
|
772
|
-
if (ytype instanceof Y.XmlElement && !(pnode instanceof Array) && matchNodeName(ytype, pnode)) {
|
|
773
|
-
const normalizedContent = normalizePNodeContent(pnode);
|
|
774
|
-
return ytype._length === normalizedContent.length && equalAttrs(ytype.getAttributes(), pnode.attrs) && ytype.toArray().every((ychild, i) => equalYTypePNode(ychild, normalizedContent[i]));
|
|
775
|
-
}
|
|
776
|
-
return ytype instanceof Y.XmlText && pnode instanceof Array && equalYTextPText(ytype, pnode);
|
|
777
|
-
};
|
|
778
|
-
/**
|
|
779
|
-
* For a given Y type and ProseMirror node content, check if the ProseMirror node content is the same as the mapped ProseMirror node content.
|
|
780
|
-
*
|
|
781
|
-
* @param {PModel.Node | Array<PModel.Node> | undefined} mapped The ProseMirror node content that is mapped to the Y type.
|
|
782
|
-
* @param {PModel.Node | Array<PModel.Node>} pcontent The ProseMirror node content to compare against the mapped content.
|
|
783
|
-
* @returns {boolean} Returns true if the mapped content is the same as the ProseMirror node content, false otherwise.
|
|
784
|
-
*/
|
|
785
|
-
const mappedIdentity = (mapped, pcontent) => mapped === pcontent || mapped instanceof Array && pcontent instanceof Array && mapped.length === pcontent.length && mapped.every((a, i) => pcontent[i] === a);
|
|
786
|
-
/**
|
|
787
|
-
* @typedef {{ yIndex: number, pIndex: number, yChild: Y.XmlElement | Y.XmlText | Y.XmlHook }} MappedChildAnchor
|
|
788
|
-
*/
|
|
789
|
-
/**
|
|
790
|
-
* Find mapped children that retain their relative order after a move.
|
|
791
|
-
*
|
|
792
|
-
* @param {Array<Y.XmlElement | Y.XmlText | Y.XmlHook>} yChildren
|
|
793
|
-
* @param {NormalizedPNodeContent} pChildren
|
|
794
|
-
* @param {BindingMetadata} meta
|
|
795
|
-
* @return {Array<MappedChildAnchor>}
|
|
796
|
-
*/
|
|
797
|
-
const findMappedChildAnchors = (yChildren, pChildren, meta) => {
|
|
798
|
-
const pChildIndices = /* @__PURE__ */ new Map();
|
|
799
|
-
pChildren.forEach((pChild, index) => {
|
|
800
|
-
if (!pChildIndices.has(pChild)) pChildIndices.set(pChild, index);
|
|
801
|
-
});
|
|
802
|
-
const candidates = [];
|
|
803
|
-
yChildren.forEach((yChild, yIndex) => {
|
|
804
|
-
const mapped = meta.mapping.get(yChild);
|
|
805
|
-
const pIndex = pChildIndices.get(mapped);
|
|
806
|
-
if (pIndex !== void 0 && mappedIdentity(mapped, pChildren[pIndex])) candidates.push({
|
|
807
|
-
yIndex,
|
|
808
|
-
pIndex,
|
|
809
|
-
yChild
|
|
810
|
-
});
|
|
811
|
-
});
|
|
812
|
-
if (candidates.length === 0) return [];
|
|
813
|
-
const predecessors = new Array(candidates.length);
|
|
814
|
-
const tails = [];
|
|
815
|
-
for (let index = 0; index < candidates.length; index++) {
|
|
816
|
-
let low = 0;
|
|
817
|
-
let high = tails.length;
|
|
818
|
-
while (low < high) {
|
|
819
|
-
const middle = low + high >> 1;
|
|
820
|
-
if (candidates[tails[middle]].pIndex < candidates[index].pIndex) low = middle + 1;
|
|
821
|
-
else high = middle;
|
|
822
|
-
}
|
|
823
|
-
predecessors[index] = low > 0 ? tails[low - 1] : -1;
|
|
824
|
-
tails[low] = index;
|
|
825
|
-
}
|
|
826
|
-
const anchors = [];
|
|
827
|
-
for (let index = tails[tails.length - 1]; index !== -1; index = predecessors[index]) anchors.push(candidates[index]);
|
|
828
|
-
return anchors.reverse();
|
|
829
|
-
};
|
|
830
|
-
/**
|
|
831
|
-
* @param {Y.XmlFragment} yDomFragment
|
|
832
|
-
* @param {number} index
|
|
833
|
-
* @param {number} length
|
|
834
|
-
* @param {BindingMetadata} meta
|
|
835
|
-
*/
|
|
836
|
-
const deleteYChildren = (yDomFragment, index, length, meta) => {
|
|
837
|
-
if (length > 0) {
|
|
838
|
-
yDomFragment.slice(index, index + length).forEach((type) => meta.mapping.delete(type));
|
|
839
|
-
yDomFragment.delete(index, length);
|
|
840
|
-
}
|
|
841
|
-
};
|
|
842
|
-
/**
|
|
843
|
-
* @param {Y.XmlFragment} yDomFragment
|
|
844
|
-
* @param {number} index
|
|
845
|
-
* @param {NormalizedPNodeContent} pChildren
|
|
846
|
-
* @param {number} start
|
|
847
|
-
* @param {number} end
|
|
848
|
-
* @param {BindingMetadata} meta
|
|
849
|
-
*/
|
|
850
|
-
const insertPChildren = (yDomFragment, index, pChildren, start, end, meta) => {
|
|
851
|
-
if (start < end) {
|
|
852
|
-
const children = [];
|
|
853
|
-
for (let childIndex = start; childIndex < end; childIndex++) children.push(createTypeFromTextOrElementNode(pChildren[childIndex], meta));
|
|
854
|
-
yDomFragment.insert(index, children);
|
|
855
|
-
}
|
|
856
|
-
};
|
|
857
|
-
/**
|
|
858
|
-
* Updates a Y child in place when it still lines up with the ProseMirror child.
|
|
859
|
-
* Recreating it instead would drop concurrent remote edits on that child.
|
|
860
|
-
*
|
|
861
|
-
* @param {{ transact: Function }} y
|
|
862
|
-
* @param {Y.XmlElement | Y.XmlText | Y.XmlHook} yChild
|
|
863
|
-
* @param {PModel.Node | Array<PModel.Node>} pChild
|
|
864
|
-
* @param {BindingMetadata} meta
|
|
865
|
-
* @return {boolean}
|
|
866
|
-
*/
|
|
867
|
-
const updateMatchingYChild = (y, yChild, pChild, meta) => {
|
|
868
|
-
if (yChild instanceof Y.XmlText && pChild instanceof Array) {
|
|
869
|
-
if (equalYTextPText(yChild, pChild)) meta.mapping.set(yChild, pChild);
|
|
870
|
-
else updateYText(yChild, pChild, meta);
|
|
871
|
-
return true;
|
|
872
|
-
}
|
|
873
|
-
if (yChild instanceof Y.XmlElement && !(pChild instanceof Array) && matchNodeName(yChild, pChild)) {
|
|
874
|
-
if (equalYTypePNode(yChild, pChild)) meta.mapping.set(yChild, pChild);
|
|
875
|
-
else updateYFragment(y, yChild, pChild, meta);
|
|
876
|
-
return true;
|
|
877
|
-
}
|
|
878
|
-
return false;
|
|
879
|
-
};
|
|
880
|
-
/**
|
|
881
|
-
* Reconciles the children between two anchors by position, then deletes or
|
|
882
|
-
* inserts to make up the length difference.
|
|
883
|
-
*
|
|
884
|
-
* @param {{ transact: Function }} y
|
|
885
|
-
* @param {Y.XmlFragment} yDomFragment
|
|
886
|
-
* @param {NormalizedPNodeContent} pChildren
|
|
887
|
-
* @param {Array<Y.XmlElement | Y.XmlText | Y.XmlHook>} yChildren
|
|
888
|
-
* @param {number} yStart
|
|
889
|
-
* @param {number} yEnd
|
|
890
|
-
* @param {number} pStart
|
|
891
|
-
* @param {number} pEnd
|
|
892
|
-
* @param {BindingMetadata} meta
|
|
893
|
-
*/
|
|
894
|
-
const reconcileUnanchoredChildren = (y, yDomFragment, pChildren, yChildren, yStart, yEnd, pStart, pEnd, meta) => {
|
|
895
|
-
const matchingChildren = math.min(yEnd - yStart, pEnd - pStart);
|
|
896
|
-
for (let index = 0; index < matchingChildren; index++) {
|
|
897
|
-
const yChild = yChildren[yStart + index];
|
|
898
|
-
const pChild = pChildren[pStart + index];
|
|
899
|
-
if (!updateMatchingYChild(y, yChild, pChild, meta)) {
|
|
900
|
-
deleteYChildren(yDomFragment, pStart + index, 1, meta);
|
|
901
|
-
insertPChildren(yDomFragment, pStart + index, pChildren, pStart + index, pStart + index + 1, meta);
|
|
902
|
-
}
|
|
903
|
-
}
|
|
904
|
-
deleteYChildren(yDomFragment, pStart + matchingChildren, yEnd - yStart - matchingChildren, meta);
|
|
905
|
-
insertPChildren(yDomFragment, pStart + matchingChildren, pChildren, pStart + matchingChildren, pEnd, meta);
|
|
906
|
-
};
|
|
907
|
-
/**
|
|
908
|
-
* Reconciles a fragment whose children were reordered, keeping the Y types of the
|
|
909
|
-
* anchors. The left/right diff in `updateYFragment` mismatches on both ends after
|
|
910
|
-
* a move, so it rebuilds the middle and drops text that is still being edited.
|
|
911
|
-
*
|
|
912
|
-
* @param {{ transact: Function }} y
|
|
913
|
-
* @param {Y.XmlFragment} yDomFragment
|
|
914
|
-
* @param {NormalizedPNodeContent} pChildren
|
|
915
|
-
* @param {Array<Y.XmlElement | Y.XmlText | Y.XmlHook>} yChildren
|
|
916
|
-
* @param {BindingMetadata} meta
|
|
917
|
-
* @return {boolean}
|
|
918
|
-
*/
|
|
919
|
-
const reconcileMappedChildren = (y, yDomFragment, pChildren, yChildren, meta) => {
|
|
920
|
-
const anchors = findMappedChildAnchors(yChildren, pChildren, meta);
|
|
921
|
-
if (anchors.length < 2 || !anchors.some((anchor) => anchor.yIndex !== anchor.pIndex) || anchors.some((anchor) => {
|
|
922
|
-
const pChild = pChildren[anchor.pIndex];
|
|
923
|
-
return !(anchor.yChild instanceof Y.XmlText && pChild instanceof Array || anchor.yChild instanceof Y.XmlElement && !(pChild instanceof Array));
|
|
924
|
-
})) return false;
|
|
925
|
-
let yIndex = 0;
|
|
926
|
-
let pIndex = 0;
|
|
927
|
-
for (const anchor of anchors) {
|
|
928
|
-
reconcileUnanchoredChildren(y, yDomFragment, pChildren, yChildren, yIndex, anchor.yIndex, pIndex, anchor.pIndex, meta);
|
|
929
|
-
const pChild = pChildren[anchor.pIndex];
|
|
930
|
-
updateMatchingYChild(y, anchor.yChild, pChild, meta);
|
|
931
|
-
yIndex = anchor.yIndex + 1;
|
|
932
|
-
pIndex = anchor.pIndex + 1;
|
|
933
|
-
}
|
|
934
|
-
reconcileUnanchoredChildren(y, yDomFragment, pChildren, yChildren, yIndex, yChildren.length, pIndex, pChildren.length, meta);
|
|
935
|
-
return true;
|
|
936
|
-
};
|
|
937
|
-
/**
|
|
938
|
-
* @param {Y.XmlElement} ytype
|
|
939
|
-
* @param {PModel.Node} pnode
|
|
940
|
-
* @param {BindingMetadata} meta
|
|
941
|
-
* @return {{ foundMappedChild: boolean, equalityFactor: number }}
|
|
942
|
-
*/
|
|
943
|
-
const computeChildEqualityFactor = (ytype, pnode, meta) => {
|
|
944
|
-
const yChildren = ytype.toArray();
|
|
945
|
-
const pChildren = normalizePNodeContent(pnode);
|
|
946
|
-
const pChildCnt = pChildren.length;
|
|
947
|
-
const yChildCnt = yChildren.length;
|
|
948
|
-
const minCnt = math.min(yChildCnt, pChildCnt);
|
|
949
|
-
let left = 0;
|
|
950
|
-
let right = 0;
|
|
951
|
-
let foundMappedChild = false;
|
|
952
|
-
for (; left < minCnt; left++) {
|
|
953
|
-
const leftY = yChildren[left];
|
|
954
|
-
const leftP = pChildren[left];
|
|
955
|
-
if (mappedIdentity(meta.mapping.get(leftY), leftP)) foundMappedChild = true;
|
|
956
|
-
else if (!equalYTypePNode(leftY, leftP)) break;
|
|
957
|
-
}
|
|
958
|
-
for (; left + right < minCnt; right++) {
|
|
959
|
-
const rightY = yChildren[yChildCnt - right - 1];
|
|
960
|
-
const rightP = pChildren[pChildCnt - right - 1];
|
|
961
|
-
if (mappedIdentity(meta.mapping.get(rightY), rightP)) foundMappedChild = true;
|
|
962
|
-
else if (!equalYTypePNode(rightY, rightP)) break;
|
|
963
|
-
}
|
|
964
|
-
return {
|
|
965
|
-
equalityFactor: left + right,
|
|
966
|
-
foundMappedChild
|
|
967
|
-
};
|
|
968
|
-
};
|
|
969
|
-
/**
|
|
970
|
-
* @param {Y.Text} ytext
|
|
971
|
-
*/
|
|
972
|
-
const ytextTrans = (ytext) => {
|
|
973
|
-
let str = "";
|
|
974
|
-
/**
|
|
975
|
-
* @type {Y.Item|null}
|
|
976
|
-
*/
|
|
977
|
-
let n = ytext._start;
|
|
978
|
-
const nAttrs = {};
|
|
979
|
-
while (n !== null) {
|
|
980
|
-
if (!n.deleted) {
|
|
981
|
-
if (n.countable && n.content instanceof Y.ContentString) str += n.content.str;
|
|
982
|
-
else if (n.content instanceof Y.ContentFormat) nAttrs[n.content.key] = null;
|
|
983
|
-
}
|
|
984
|
-
n = n.right;
|
|
985
|
-
}
|
|
986
|
-
return {
|
|
987
|
-
str,
|
|
988
|
-
nAttrs
|
|
989
|
-
};
|
|
990
|
-
};
|
|
991
|
-
/**
|
|
992
|
-
* @todo test this more
|
|
993
|
-
*
|
|
994
|
-
* @param {Y.Text} ytext
|
|
995
|
-
* @param {Array<any>} ptexts
|
|
996
|
-
* @param {BindingMetadata} meta
|
|
997
|
-
*/
|
|
998
|
-
const updateYText = (ytext, ptexts, meta) => {
|
|
999
|
-
meta.mapping.set(ytext, ptexts);
|
|
1000
|
-
const { nAttrs, str } = ytextTrans(ytext);
|
|
1001
|
-
const content = ptexts.map((p) => ({
|
|
1002
|
-
insert: /** @type {any} */ p.text,
|
|
1003
|
-
attributes: Object.assign({}, nAttrs, marksToAttributes(p.marks, meta))
|
|
1004
|
-
}));
|
|
1005
|
-
const { insert, remove, index } = simpleDiff(str, content.map((c) => c.insert).join(""));
|
|
1006
|
-
ytext.delete(index, remove);
|
|
1007
|
-
ytext.insert(index, insert);
|
|
1008
|
-
ytext.applyDelta(content.map((c) => ({
|
|
1009
|
-
retain: c.insert.length,
|
|
1010
|
-
attributes: c.attributes
|
|
1011
|
-
})));
|
|
1012
|
-
};
|
|
1013
|
-
const hashedMarkNameRegex = /(.*)(--[a-zA-Z0-9+/=]{8})$/;
|
|
1014
|
-
/**
|
|
1015
|
-
* @param {string} attrName
|
|
1016
|
-
*/
|
|
1017
|
-
const yattr2markname = (attrName) => hashedMarkNameRegex.exec(attrName)?.[1] ?? attrName;
|
|
1018
|
-
/**
|
|
1019
|
-
* @todo move this to markstoattributes
|
|
1020
|
-
*
|
|
1021
|
-
* @param {Object<string, any>} attrs
|
|
1022
|
-
* @param {import('prosemirror-model').Schema} schema
|
|
1023
|
-
*/
|
|
1024
|
-
const attributesToMarks = (attrs, schema) => {
|
|
1025
|
-
/**
|
|
1026
|
-
* @type {Array<import('prosemirror-model').Mark>}
|
|
1027
|
-
*/
|
|
1028
|
-
const marks = [];
|
|
1029
|
-
for (const markName in attrs) marks.push(schema.mark(yattr2markname(markName), attrs[markName]));
|
|
1030
|
-
return marks;
|
|
1031
|
-
};
|
|
1032
|
-
/**
|
|
1033
|
-
* @param {Array<import('prosemirror-model').Mark>} marks
|
|
1034
|
-
* @param {BindingMetadata} meta
|
|
1035
|
-
*/
|
|
1036
|
-
const marksToAttributes = (marks, meta) => {
|
|
1037
|
-
const pattrs = {};
|
|
1038
|
-
marks.forEach((mark) => {
|
|
1039
|
-
if (mark.type.name !== "ychange") {
|
|
1040
|
-
const isOverlapping = map.setIfUndefined(meta.isOMark, mark.type, () => !mark.type.excludes(mark.type));
|
|
1041
|
-
pattrs[isOverlapping ? `${mark.type.name}--${hashOfJSON(mark.toJSON())}` : mark.type.name] = mark.attrs;
|
|
1042
|
-
}
|
|
1043
|
-
});
|
|
1044
|
-
return pattrs;
|
|
1045
|
-
};
|
|
1046
|
-
/**
|
|
1047
|
-
* Update a yDom node by syncing the current content of the prosemirror node.
|
|
1048
|
-
*
|
|
1049
|
-
* This is a y-prosemirror internal feature that you can use at your own risk.
|
|
1050
|
-
*
|
|
1051
|
-
* @private
|
|
1052
|
-
* @unstable
|
|
1053
|
-
*
|
|
1054
|
-
* @param {{transact: Function}} y
|
|
1055
|
-
* @param {Y.XmlFragment} yDomFragment
|
|
1056
|
-
* @param {any} pNode
|
|
1057
|
-
* @param {BindingMetadata} meta
|
|
1058
|
-
*/
|
|
1059
|
-
const updateYFragment = (y, yDomFragment, pNode, meta) => {
|
|
1060
|
-
if (yDomFragment instanceof Y.XmlElement && yDomFragment.nodeName !== pNode.type.name) throw new Error("node name mismatch!");
|
|
1061
|
-
meta.mapping.set(yDomFragment, pNode);
|
|
1062
|
-
if (yDomFragment instanceof Y.XmlElement) {
|
|
1063
|
-
const yDomAttrs = yDomFragment.getAttributes();
|
|
1064
|
-
const pAttrs = pNode.attrs;
|
|
1065
|
-
for (const key in pAttrs) if (pAttrs[key] !== null) {
|
|
1066
|
-
if (yDomAttrs[key] !== pAttrs[key] && key !== "ychange") yDomFragment.setAttribute(key, pAttrs[key]);
|
|
1067
|
-
} else yDomFragment.removeAttribute(key);
|
|
1068
|
-
for (const key in yDomAttrs) if (pAttrs[key] === void 0) yDomFragment.removeAttribute(key);
|
|
1069
|
-
}
|
|
1070
|
-
const pChildren = normalizePNodeContent(pNode);
|
|
1071
|
-
const pChildCnt = pChildren.length;
|
|
1072
|
-
const yChildren = yDomFragment.toArray();
|
|
1073
|
-
const yChildCnt = yChildren.length;
|
|
1074
|
-
const minCnt = math.min(pChildCnt, yChildCnt);
|
|
1075
|
-
if (reconcileMappedChildren(y, yDomFragment, pChildren, yChildren, meta)) return;
|
|
1076
|
-
let left = 0;
|
|
1077
|
-
let right = 0;
|
|
1078
|
-
for (; left < minCnt; left++) {
|
|
1079
|
-
const leftY = yChildren[left];
|
|
1080
|
-
const leftP = pChildren[left];
|
|
1081
|
-
if (!mappedIdentity(meta.mapping.get(leftY), leftP)) {
|
|
1082
|
-
if (equalYTypePNode(leftY, leftP)) meta.mapping.set(leftY, leftP);
|
|
1083
|
-
else break;
|
|
1084
|
-
}
|
|
1085
|
-
}
|
|
1086
|
-
for (; right + left + 1 < minCnt; right++) {
|
|
1087
|
-
const rightY = yChildren[yChildCnt - right - 1];
|
|
1088
|
-
const rightP = pChildren[pChildCnt - right - 1];
|
|
1089
|
-
if (!mappedIdentity(meta.mapping.get(rightY), rightP)) {
|
|
1090
|
-
if (equalYTypePNode(rightY, rightP)) meta.mapping.set(rightY, rightP);
|
|
1091
|
-
else break;
|
|
1092
|
-
}
|
|
1093
|
-
}
|
|
1094
|
-
y.transact(() => {
|
|
1095
|
-
while (yChildCnt - left - right > 0 && pChildCnt - left - right > 0) {
|
|
1096
|
-
const leftY = yChildren[left];
|
|
1097
|
-
const leftP = pChildren[left];
|
|
1098
|
-
const rightY = yChildren[yChildCnt - right - 1];
|
|
1099
|
-
const rightP = pChildren[pChildCnt - right - 1];
|
|
1100
|
-
if (leftY instanceof Y.XmlText && leftP instanceof Array) {
|
|
1101
|
-
if (!equalYTextPText(leftY, leftP)) updateYText(leftY, leftP, meta);
|
|
1102
|
-
left += 1;
|
|
1103
|
-
} else {
|
|
1104
|
-
let updateLeft = leftY instanceof Y.XmlElement && matchNodeName(leftY, leftP);
|
|
1105
|
-
let updateRight = rightY instanceof Y.XmlElement && matchNodeName(rightY, rightP);
|
|
1106
|
-
if (updateLeft && updateRight) {
|
|
1107
|
-
const equalityLeft = computeChildEqualityFactor(leftY, leftP, meta);
|
|
1108
|
-
const equalityRight = computeChildEqualityFactor(rightY, rightP, meta);
|
|
1109
|
-
if (equalityLeft.foundMappedChild && !equalityRight.foundMappedChild) updateRight = false;
|
|
1110
|
-
else if (!equalityLeft.foundMappedChild && equalityRight.foundMappedChild) updateLeft = false;
|
|
1111
|
-
else if (equalityLeft.equalityFactor < equalityRight.equalityFactor) updateLeft = false;
|
|
1112
|
-
else updateRight = false;
|
|
1113
|
-
}
|
|
1114
|
-
if (updateLeft) {
|
|
1115
|
-
updateYFragment(y, leftY, leftP, meta);
|
|
1116
|
-
left += 1;
|
|
1117
|
-
} else if (updateRight) {
|
|
1118
|
-
updateYFragment(y, rightY, rightP, meta);
|
|
1119
|
-
right += 1;
|
|
1120
|
-
} else {
|
|
1121
|
-
meta.mapping.delete(yDomFragment.get(left));
|
|
1122
|
-
yDomFragment.delete(left, 1);
|
|
1123
|
-
yDomFragment.insert(left, [createTypeFromTextOrElementNode(leftP, meta)]);
|
|
1124
|
-
left += 1;
|
|
1125
|
-
}
|
|
1126
|
-
}
|
|
1127
|
-
}
|
|
1128
|
-
const yDelLen = yChildCnt - left - right;
|
|
1129
|
-
if (yChildCnt === 1 && pChildCnt === 0 && yChildren[0] instanceof Y.XmlText) {
|
|
1130
|
-
meta.mapping.delete(yChildren[0]);
|
|
1131
|
-
yChildren[0].delete(0, yChildren[0].length);
|
|
1132
|
-
} else if (yDelLen > 0) {
|
|
1133
|
-
yDomFragment.slice(left, left + yDelLen).forEach((type) => meta.mapping.delete(type));
|
|
1134
|
-
yDomFragment.delete(left, yDelLen);
|
|
1135
|
-
}
|
|
1136
|
-
if (left + right < pChildCnt) {
|
|
1137
|
-
const ins = [];
|
|
1138
|
-
for (let i = left; i < pChildCnt - right; i++) ins.push(createTypeFromTextOrElementNode(pChildren[i], meta));
|
|
1139
|
-
yDomFragment.insert(left, ins);
|
|
1140
|
-
}
|
|
1141
|
-
}, ySyncPluginKey);
|
|
1142
|
-
};
|
|
1143
|
-
/**
|
|
1144
|
-
* @function
|
|
1145
|
-
* @param {Y.XmlElement} yElement
|
|
1146
|
-
* @param {any} pNode Prosemirror Node
|
|
1147
|
-
*/
|
|
1148
|
-
const matchNodeName = (yElement, pNode) => !(pNode instanceof Array) && yElement.nodeName === pNode.type.name;
|
|
1149
|
-
/**
|
|
1150
|
-
* Either a node if type is YXmlElement or an Array of text nodes if YXmlText
|
|
1151
|
-
* @typedef {Map<Y.AbstractType, Node | Array<Node>>} ProsemirrorMapping
|
|
1152
|
-
*/
|
|
1153
|
-
/**
|
|
1154
|
-
* Is null if no timeout is in progress.
|
|
1155
|
-
* Is defined if a timeout is in progress.
|
|
1156
|
-
* Maps from view
|
|
1157
|
-
* @type {Map<EditorView, Map<any, any>>|null}
|
|
1158
|
-
*/
|
|
1159
|
-
let viewsToUpdate = null;
|
|
1160
|
-
var MetaEntry = class {
|
|
1161
|
-
/**
|
|
1162
|
-
* @param {EditorView} view
|
|
1163
|
-
* @param {any} key
|
|
1164
|
-
* @param {any} value
|
|
1165
|
-
*/
|
|
1166
|
-
constructor(view, key, value) {
|
|
1167
|
-
this.view = view;
|
|
1168
|
-
this.key = key;
|
|
1169
|
-
this.value = value;
|
|
1170
|
-
}
|
|
1171
|
-
apply() {
|
|
1172
|
-
const syncState = ySyncPluginKey.getState(this.view.state);
|
|
1173
|
-
if (syncState && syncState.binding && !syncState.binding.isDestroyed) {
|
|
1174
|
-
const tr = this.view.state.tr;
|
|
1175
|
-
tr.setMeta(this.key, this.value);
|
|
1176
|
-
this.view.dispatch(tr);
|
|
1177
|
-
}
|
|
1178
|
-
}
|
|
1179
|
-
};
|
|
1180
|
-
var MetaEntriesQueue = class MetaEntriesQueue {
|
|
1181
|
-
/**
|
|
1182
|
-
* @param {Array<MetaEntry>} [entries=[]]
|
|
1183
|
-
*/
|
|
1184
|
-
constructor(entries = []) {
|
|
1185
|
-
this.entries = entries;
|
|
1186
|
-
}
|
|
1187
|
-
/**
|
|
1188
|
-
* @return {MetaEntry|undefined}
|
|
1189
|
-
*/
|
|
1190
|
-
getFirst() {
|
|
1191
|
-
return this.entries[0];
|
|
1192
|
-
}
|
|
1193
|
-
/**
|
|
1194
|
-
* @return {MetaEntry|undefined}
|
|
1195
|
-
*/
|
|
1196
|
-
dequeueFirst() {
|
|
1197
|
-
return this.entries.shift();
|
|
1198
|
-
}
|
|
1199
|
-
/**
|
|
1200
|
-
* @return {boolean}
|
|
1201
|
-
*/
|
|
1202
|
-
isEmpty() {
|
|
1203
|
-
return this.entries.length === 0;
|
|
1204
|
-
}
|
|
1205
|
-
static fromViewsToUpdate() {
|
|
1206
|
-
const ups = viewsToUpdate;
|
|
1207
|
-
viewsToUpdate = null;
|
|
1208
|
-
const entries = [];
|
|
1209
|
-
ups.forEach((metas, view) => {
|
|
1210
|
-
metas.forEach((value, key) => {
|
|
1211
|
-
entries.push(new MetaEntry(view, key, value));
|
|
1212
|
-
});
|
|
1213
|
-
});
|
|
1214
|
-
return new MetaEntriesQueue(entries);
|
|
1215
|
-
}
|
|
1216
|
-
};
|
|
1217
|
-
/**
|
|
1218
|
-
* Dispatch queued plugin metadata in order, retrying only the remaining
|
|
1219
|
-
* entries if a transaction becomes stale while the async queue is flushing.
|
|
1220
|
-
*
|
|
1221
|
-
* Cursor awareness updates are decoration-only refreshes. If a real document
|
|
1222
|
-
* transaction lands before one of these queued meta transactions is applied,
|
|
1223
|
-
* ProseMirror can reject it with a RangeError. In that case we reschedule the
|
|
1224
|
-
* remaining entries on the next tick. If the first remaining entry fails again
|
|
1225
|
-
* on retry, we drop that entry and continue with the rest of the queue instead
|
|
1226
|
-
* of retrying forever or crashing the editor.
|
|
1227
|
-
*
|
|
1228
|
-
* @param {MetaEntriesQueue} [metaEntries=MetaEntriesQueue.fromViewsToUpdate()]
|
|
1229
|
-
* @param {boolean} [isRetry=false]
|
|
1230
|
-
*/
|
|
1231
|
-
const updateMetas = (metaEntries = MetaEntriesQueue.fromViewsToUpdate(), isRetry = false) => {
|
|
1232
|
-
let isFirst = true;
|
|
1233
|
-
while (!metaEntries.isEmpty()) {
|
|
1234
|
-
const metaEntry = metaEntries.getFirst();
|
|
1235
|
-
try {
|
|
1236
|
-
metaEntry.apply();
|
|
1237
|
-
} catch (err) {
|
|
1238
|
-
if (err instanceof RangeError) {
|
|
1239
|
-
if (isRetry && isFirst) metaEntries.dequeueFirst();
|
|
1240
|
-
if (!metaEntries.isEmpty()) eventloop.timeout(0, () => updateMetas(metaEntries, true));
|
|
1241
|
-
return;
|
|
1242
|
-
}
|
|
1243
|
-
throw err;
|
|
1244
|
-
}
|
|
1245
|
-
isFirst = false;
|
|
1246
|
-
metaEntries.dequeueFirst();
|
|
1247
|
-
}
|
|
1248
|
-
};
|
|
1249
|
-
const setMeta = (view, key, value) => {
|
|
1250
|
-
if (!viewsToUpdate) {
|
|
1251
|
-
viewsToUpdate = /* @__PURE__ */ new Map();
|
|
1252
|
-
eventloop.timeout(0, updateMetas);
|
|
1253
|
-
}
|
|
1254
|
-
map.setIfUndefined(viewsToUpdate, view, map.create).set(key, value);
|
|
1255
|
-
};
|
|
1256
|
-
/**
|
|
1257
|
-
* Transforms a Prosemirror based absolute position to a Yjs Cursor (relative position in the Yjs model).
|
|
1258
|
-
*
|
|
1259
|
-
* @param {number} pos
|
|
1260
|
-
* @param {Y.XmlFragment} type
|
|
1261
|
-
* @param {ProsemirrorMapping} mapping
|
|
1262
|
-
* @return {any} relative position
|
|
1263
|
-
*/
|
|
1264
|
-
const absolutePositionToRelativePosition = (pos, type, mapping) => {
|
|
1265
|
-
if (pos === 0) return Y.createRelativePositionFromTypeIndex(type, 0, -1);
|
|
1266
|
-
/**
|
|
1267
|
-
* @type {any}
|
|
1268
|
-
*/
|
|
1269
|
-
let n = type._first === null ? null : /** @type {Y.ContentType} */ type._first.content.type;
|
|
1270
|
-
while (n !== null && type !== n) {
|
|
1271
|
-
if (n instanceof Y.XmlText) {
|
|
1272
|
-
if (n._length >= pos) return Y.createRelativePositionFromTypeIndex(n, pos, -1);
|
|
1273
|
-
else pos -= n._length;
|
|
1274
|
-
if (n._item !== null && n._item.next !== null) n = n._item.next.content.type;
|
|
1275
|
-
else {
|
|
1276
|
-
do {
|
|
1277
|
-
n = n._item === null ? null : n._item.parent;
|
|
1278
|
-
pos--;
|
|
1279
|
-
} while (n !== type && n !== null && n._item !== null && n._item.next === null);
|
|
1280
|
-
if (n !== null && n !== type) n = n._item === null ? null : /** @type {Y.ContentType} */ n._item.next.content.type;
|
|
1281
|
-
}
|
|
1282
|
-
} else {
|
|
1283
|
-
const pNodeSize = (mapping.get(n) || { nodeSize: 0 }).nodeSize;
|
|
1284
|
-
if (n._first !== null && pos < pNodeSize) {
|
|
1285
|
-
n = n._first.content.type;
|
|
1286
|
-
pos--;
|
|
1287
|
-
} else {
|
|
1288
|
-
if (pos === 1 && n._length === 0 && pNodeSize > 1) return new Y.RelativePosition(n._item === null ? null : n._item.id, n._item === null ? Y.findRootTypeKey(n) : null, null);
|
|
1289
|
-
pos -= pNodeSize;
|
|
1290
|
-
if (n._item !== null && n._item.next !== null) n = n._item.next.content.type;
|
|
1291
|
-
else {
|
|
1292
|
-
if (pos === 0) {
|
|
1293
|
-
n = n._item === null ? n : n._item.parent;
|
|
1294
|
-
return new Y.RelativePosition(n._item === null ? null : n._item.id, n._item === null ? Y.findRootTypeKey(n) : null, null);
|
|
1295
|
-
}
|
|
1296
|
-
do {
|
|
1297
|
-
n = n._item.parent;
|
|
1298
|
-
pos--;
|
|
1299
|
-
} while (n !== type && n._item.next === null);
|
|
1300
|
-
if (n !== type) n = n._item.next.content.type;
|
|
1301
|
-
}
|
|
1302
|
-
}
|
|
1303
|
-
}
|
|
1304
|
-
if (n === null) throw error.unexpectedCase();
|
|
1305
|
-
if (pos === 0 && n.constructor !== Y.XmlText && n !== type) return createRelativePosition(n._item.parent, n._item);
|
|
1306
|
-
}
|
|
1307
|
-
return Y.createRelativePositionFromTypeIndex(type, type._length, -1);
|
|
1308
|
-
};
|
|
1309
|
-
/**
|
|
1310
|
-
* Item-id based relative positions can misresolve to the document start after
|
|
1311
|
-
* block reorder during collaborative drag-and-drop.
|
|
1312
|
-
*
|
|
1313
|
-
* @param {Y.Doc} y
|
|
1314
|
-
* @param {Y.RelativePosition} relPos
|
|
1315
|
-
* @param {number|null} absPos
|
|
1316
|
-
* @return {boolean}
|
|
1317
|
-
*/
|
|
1318
|
-
const isMisresolvedTextPosition = (y, relPos, absPos) => {
|
|
1319
|
-
if (absPos === null) return false;
|
|
1320
|
-
const decoded = Y.createAbsolutePositionFromRelativePosition(relPos, y);
|
|
1321
|
-
return decoded !== null && decoded.type instanceof Y.XmlText && relPos.item !== null && absPos <= 1;
|
|
1322
|
-
};
|
|
1323
|
-
const createRelativePosition = (type, item) => {
|
|
1324
|
-
let typeid = null;
|
|
1325
|
-
let tname = null;
|
|
1326
|
-
if (type._item === null) tname = Y.findRootTypeKey(type);
|
|
1327
|
-
else typeid = Y.createID(type._item.id.client, type._item.id.clock);
|
|
1328
|
-
return new Y.RelativePosition(typeid, tname, item.id);
|
|
1329
|
-
};
|
|
1330
|
-
/**
|
|
1331
|
-
* @param {Y.Doc} y
|
|
1332
|
-
* @param {Y.XmlFragment} documentType Top level type that is bound to pView
|
|
1333
|
-
* @param {any} relPos Encoded Yjs based relative position
|
|
1334
|
-
* @param {ProsemirrorMapping} mapping
|
|
1335
|
-
* @return {null|number}
|
|
1336
|
-
*/
|
|
1337
|
-
const relativePositionToAbsolutePosition = (y, documentType, relPos, mapping) => {
|
|
1338
|
-
const decodedPos = Y.createAbsolutePositionFromRelativePosition(relPos, y);
|
|
1339
|
-
if (decodedPos === null || decodedPos.type !== documentType && !Y.isParentOf(documentType, decodedPos.type._item)) return null;
|
|
1340
|
-
let type = decodedPos.type;
|
|
1341
|
-
let pos = 0;
|
|
1342
|
-
if (type.constructor === Y.XmlText) pos = decodedPos.index;
|
|
1343
|
-
else if (type._item === null || !type._item.deleted) {
|
|
1344
|
-
let n = type._first;
|
|
1345
|
-
let i = 0;
|
|
1346
|
-
while (i < type._length && i < decodedPos.index && n !== null) {
|
|
1347
|
-
if (!n.deleted) {
|
|
1348
|
-
const t = n.content.type;
|
|
1349
|
-
i++;
|
|
1350
|
-
if (t instanceof Y.XmlText) pos += t._length;
|
|
1351
|
-
else {
|
|
1352
|
-
const mapped = mapping.get(t);
|
|
1353
|
-
if (mapped == null) return null;
|
|
1354
|
-
pos += mapped.nodeSize;
|
|
1355
|
-
}
|
|
1356
|
-
}
|
|
1357
|
-
n = n.right;
|
|
1358
|
-
}
|
|
1359
|
-
pos += 1;
|
|
1360
|
-
}
|
|
1361
|
-
while (type !== documentType && type._item !== null) {
|
|
1362
|
-
const parent = type._item.parent;
|
|
1363
|
-
if (parent._item === null || !parent._item.deleted) {
|
|
1364
|
-
pos += 1;
|
|
1365
|
-
let n = parent._first;
|
|
1366
|
-
while (n !== null) {
|
|
1367
|
-
const contentType = n.content.type;
|
|
1368
|
-
if (contentType === type) break;
|
|
1369
|
-
if (!n.deleted) {
|
|
1370
|
-
if (contentType instanceof Y.XmlText) pos += contentType._length;
|
|
1371
|
-
else {
|
|
1372
|
-
const mapped = mapping.get(contentType);
|
|
1373
|
-
if (mapped == null) return null;
|
|
1374
|
-
pos += mapped.nodeSize;
|
|
1375
|
-
}
|
|
1376
|
-
}
|
|
1377
|
-
n = n.right;
|
|
1378
|
-
}
|
|
1379
|
-
}
|
|
1380
|
-
type = parent;
|
|
1381
|
-
}
|
|
1382
|
-
const absPos = pos - 1;
|
|
1383
|
-
if (isMisresolvedTextPosition(y, relPos, absPos)) return null;
|
|
1384
|
-
return absPos;
|
|
1385
|
-
};
|
|
1386
|
-
/**
|
|
1387
|
-
* Shallow attrs comparison. Attr values are primitives in most schemas;
|
|
1388
|
-
* non-primitive values fail the check and callers fall back to text matching.
|
|
1389
|
-
*
|
|
1390
|
-
* @param {Object<string, any>} a
|
|
1391
|
-
* @param {Object<string, any>} b
|
|
1392
|
-
* @return {boolean}
|
|
1393
|
-
*/
|
|
1394
|
-
const attrsEqual = (a, b) => {
|
|
1395
|
-
if (a === b) return true;
|
|
1396
|
-
const aKeys = Object.keys(a);
|
|
1397
|
-
return aKeys.length === Object.keys(b).length && aKeys.every((k) => a[k] === b[k]);
|
|
1398
|
-
};
|
|
1399
|
-
/**
|
|
1400
|
-
* Returns true when any attr deviates from its spec default or has none.
|
|
1401
|
-
* Default-only attrs cannot tell same-type siblings apart.
|
|
1402
|
-
*
|
|
1403
|
-
* @param {import('prosemirror-model').Node} node
|
|
1404
|
-
* @return {boolean}
|
|
1405
|
-
*/
|
|
1406
|
-
const hasDistinctiveAttrs = (node) => {
|
|
1407
|
-
const specAttrs = node.type.spec.attrs || {};
|
|
1408
|
-
return Object.keys(node.attrs).some((key) => {
|
|
1409
|
-
const spec = specAttrs[key];
|
|
1410
|
-
return spec == null || !Object.prototype.hasOwnProperty.call(spec, "default") || spec.default !== node.attrs[key];
|
|
1411
|
-
});
|
|
1412
|
-
};
|
|
1413
|
-
/**
|
|
1414
|
-
* Remaps a position into a matched block by walking the same child-index path
|
|
1415
|
-
* it had in the old block. A raw byte offset would overshoot into a sibling
|
|
1416
|
-
* inner textblock when the old block contains local keystrokes that are not
|
|
1417
|
-
* yet part of the rebuilt document.
|
|
1418
|
-
*
|
|
1419
|
-
* @param {import('prosemirror-model').ResolvedPos} $oldPos
|
|
1420
|
-
* @param {number} newBlockStart
|
|
1421
|
-
* @param {import('prosemirror-model').Node} newBlock
|
|
1422
|
-
* @return {number|null}
|
|
1423
|
-
*/
|
|
1424
|
-
const remapIntoBlock = ($oldPos, newBlockStart, newBlock) => {
|
|
1425
|
-
let pos = newBlockStart + 1;
|
|
1426
|
-
let node = newBlock;
|
|
1427
|
-
for (let depth = 1; depth < $oldPos.depth; depth++) {
|
|
1428
|
-
const idx = $oldPos.index(depth);
|
|
1429
|
-
if (idx >= node.childCount) return null;
|
|
1430
|
-
for (let i = 0; i < idx; i++) pos += node.child(i).nodeSize;
|
|
1431
|
-
pos += 1;
|
|
1432
|
-
node = node.child(idx);
|
|
1433
|
-
if (node.type !== $oldPos.node(depth + 1).type) return null;
|
|
1434
|
-
}
|
|
1435
|
-
if (!node.isTextblock) return null;
|
|
1436
|
-
return pos + Math.min($oldPos.parentOffset, node.content.size);
|
|
1437
|
-
};
|
|
1438
|
-
/**
|
|
1439
|
-
* @param {import('prosemirror-model').Node} oldDoc
|
|
1440
|
-
* @param {import('prosemirror-model').Node} newDoc
|
|
1441
|
-
* @param {number} absPos
|
|
1442
|
-
* @return {number|null}
|
|
1443
|
-
*/
|
|
1444
|
-
const findAbsolutePositionAfterStructuralChange = (oldDoc, newDoc, absPos) => {
|
|
1445
|
-
let pos = 0;
|
|
1446
|
-
let targetIdx = 0;
|
|
1447
|
-
for (; targetIdx < oldDoc.childCount; targetIdx++) {
|
|
1448
|
-
const child = oldDoc.child(targetIdx);
|
|
1449
|
-
if (pos + child.nodeSize > absPos) break;
|
|
1450
|
-
pos += child.nodeSize;
|
|
1451
|
-
}
|
|
1452
|
-
if (targetIdx >= oldDoc.childCount) return null;
|
|
1453
|
-
const targetChild = oldDoc.child(targetIdx);
|
|
1454
|
-
const $oldPos = oldDoc.resolve(absPos);
|
|
1455
|
-
/**
|
|
1456
|
-
* @param {number} newBlockStart
|
|
1457
|
-
* @param {import('prosemirror-model').Node} newBlock
|
|
1458
|
-
* @return {number|null}
|
|
1459
|
-
*/
|
|
1460
|
-
const place = (newBlockStart, newBlock) => {
|
|
1461
|
-
if ($oldPos.depth === 0) {
|
|
1462
|
-
const remapped = newBlockStart + (absPos - pos);
|
|
1463
|
-
const contentStart = newBlockStart + 1;
|
|
1464
|
-
const contentEnd = newBlockStart + newBlock.nodeSize - 1;
|
|
1465
|
-
return Math.max(contentStart, Math.min(remapped, contentEnd));
|
|
1466
|
-
}
|
|
1467
|
-
return remapIntoBlock($oldPos, newBlockStart, newBlock);
|
|
1468
|
-
};
|
|
1469
|
-
/**
|
|
1470
|
-
* Finds the Nth block in newDoc matching `pred`, where N is the number of
|
|
1471
|
-
* matching blocks in oldDoc up to and including the target block.
|
|
1472
|
-
*
|
|
1473
|
-
* @param {function(import('prosemirror-model').Node): boolean} pred
|
|
1474
|
-
* @param {boolean} requireUnique
|
|
1475
|
-
* @return {number|null}
|
|
1476
|
-
*/
|
|
1477
|
-
const findByPredicate = (pred, requireUnique = false) => {
|
|
1478
|
-
let occurrence = 0;
|
|
1479
|
-
for (let i = 0; i <= targetIdx; i++) if (pred(oldDoc.child(i))) occurrence++;
|
|
1480
|
-
let matchCount = 0;
|
|
1481
|
-
let matchStart = -1;
|
|
1482
|
-
let matchBlock = null;
|
|
1483
|
-
let newPos = 0;
|
|
1484
|
-
for (let i = 0; i < newDoc.childCount; i++) {
|
|
1485
|
-
const child = newDoc.child(i);
|
|
1486
|
-
if (pred(child)) {
|
|
1487
|
-
matchCount++;
|
|
1488
|
-
if (matchCount === occurrence) {
|
|
1489
|
-
matchStart = newPos;
|
|
1490
|
-
matchBlock = child;
|
|
1491
|
-
}
|
|
1492
|
-
}
|
|
1493
|
-
newPos += child.nodeSize;
|
|
1494
|
-
}
|
|
1495
|
-
if (matchBlock === null || requireUnique && (occurrence !== 1 || matchCount !== 1)) return null;
|
|
1496
|
-
return place(matchStart, matchBlock);
|
|
1497
|
-
};
|
|
1498
|
-
/**
|
|
1499
|
-
* @param {import('prosemirror-model').Node} child
|
|
1500
|
-
* @return {boolean}
|
|
1501
|
-
*/
|
|
1502
|
-
const sameTypeAndAttrs = (child) => child.type === targetChild.type && attrsEqual(child.attrs, targetChild.attrs);
|
|
1503
|
-
const oldText = targetChild.textContent;
|
|
1504
|
-
const byAll = findByPredicate((child) => sameTypeAndAttrs(child) && child.textContent === oldText);
|
|
1505
|
-
if (byAll !== null) return byAll;
|
|
1506
|
-
const byText = findByPredicate((child) => child.type === targetChild.type && child.textContent === oldText);
|
|
1507
|
-
if (byText !== null) return byText;
|
|
1508
|
-
if (hasDistinctiveAttrs(targetChild)) {
|
|
1509
|
-
const byAttrs = findByPredicate(sameTypeAndAttrs, true);
|
|
1510
|
-
if (byAttrs !== null) return byAttrs;
|
|
1511
|
-
}
|
|
1512
|
-
return findByPredicate((child) => sameTypeAndAttrs(child) && oldText !== "" && child.textContent !== "" && (oldText.startsWith(child.textContent) || child.textContent.startsWith(oldText)), true);
|
|
1513
|
-
};
|
|
1514
|
-
/**
|
|
1515
|
-
* Returns true when a transaction changes block structure rather than only
|
|
1516
|
-
* editing inline content inside existing blocks.
|
|
1517
|
-
*
|
|
1518
|
-
* @param {import('prosemirror-state').Transaction} tr
|
|
1519
|
-
* @param {import('prosemirror-model').Node} oldDoc
|
|
1520
|
-
* @return {boolean}
|
|
1521
|
-
*/
|
|
1522
|
-
const isStructuralTransaction = (tr, oldDoc) => {
|
|
1523
|
-
if (!tr.docChanged) return false;
|
|
1524
|
-
if (tr.doc.childCount !== oldDoc.childCount) return true;
|
|
1525
|
-
for (const step of tr.steps) if (step instanceof ReplaceStep) {
|
|
1526
|
-
if (step.from === 0 && step.to === oldDoc.content.size) return true;
|
|
1527
|
-
if (step.slice.content.size > 0) {
|
|
1528
|
-
let hasBlock = false;
|
|
1529
|
-
step.slice.content.forEach((node) => {
|
|
1530
|
-
if (node.isBlock) hasBlock = true;
|
|
1531
|
-
});
|
|
1532
|
-
if (hasBlock) return true;
|
|
1533
|
-
} else if (step.to > step.from) {
|
|
1534
|
-
const $from = oldDoc.resolve(step.from);
|
|
1535
|
-
const $to = oldDoc.resolve(step.to);
|
|
1536
|
-
if ($from.depth === 0 && $to.depth === 0 && $from.index() !== $to.index()) return true;
|
|
1537
|
-
}
|
|
1538
|
-
}
|
|
1539
|
-
return false;
|
|
1540
|
-
};
|
|
1541
|
-
/**
|
|
1542
|
-
* Detect stale relative positions after structural changes that resolve to the
|
|
1543
|
-
* wrong text block or to the start of the correct block.
|
|
1544
|
-
*
|
|
1545
|
-
* @param {import('prosemirror-model').Node} oldDoc
|
|
1546
|
-
* @param {import('prosemirror-model').Node} newDoc
|
|
1547
|
-
* @param {number} oldAbs
|
|
1548
|
-
* @param {number|null} resolvedAbs
|
|
1549
|
-
* @return {boolean}
|
|
1550
|
-
*/
|
|
1551
|
-
const isMisresolvedAfterStructuralChange = (oldDoc, newDoc, oldAbs, resolvedAbs) => {
|
|
1552
|
-
if (resolvedAbs === null) return false;
|
|
1553
|
-
const $old = oldDoc.resolve(oldAbs);
|
|
1554
|
-
const $new = newDoc.resolve(resolvedAbs);
|
|
1555
|
-
if (!$old.parent.isTextblock) return false;
|
|
1556
|
-
if (!$new.parent.isTextblock) return true;
|
|
1557
|
-
if ($old.parent.textContent !== $new.parent.textContent) return true;
|
|
1558
|
-
if ($old.parentOffset !== 0 && $new.parentOffset === 0) return true;
|
|
1559
|
-
const bothAtStart = $old.parentOffset === 0 && $new.parentOffset === 0;
|
|
1560
|
-
const suspicious = $old.parentOffset !== $new.parentOffset || $old.parent.type !== $new.parent.type || !attrsEqual($old.parent.attrs, $new.parent.attrs);
|
|
1561
|
-
if (bothAtStart || suspicious) {
|
|
1562
|
-
const expected = findAbsolutePositionAfterStructuralChange(oldDoc, newDoc, oldAbs);
|
|
1563
|
-
return expected !== null && expected !== resolvedAbs;
|
|
1564
|
-
}
|
|
1565
|
-
return false;
|
|
1566
|
-
};
|
|
1567
|
-
/**
|
|
1568
|
-
* Utility method to update an empty Y.XmlFragment with content from a Prosemirror Doc Node.
|
|
1569
|
-
*
|
|
1570
|
-
* This can be used when importing existing content to Y.Doc for the first time,
|
|
1571
|
-
* note that this should not be used to rehydrate a Y.Doc from a database once
|
|
1572
|
-
* collaboration has begun as all history will be lost
|
|
1573
|
-
*
|
|
1574
|
-
* Note: The Y.XmlFragment does not need to be part of a Y.Doc document at the time that this
|
|
1575
|
-
* method is called, but it must be added before any other operations are performed on it.
|
|
1576
|
-
*
|
|
1577
|
-
* @param {Node} doc prosemirror document.
|
|
1578
|
-
* @param {Y.XmlFragment} [xmlFragment] If supplied, an xml fragment to be
|
|
1579
|
-
* populated from the prosemirror state; otherwise a new XmlFragment will be created.
|
|
1580
|
-
* @return {Y.XmlFragment}
|
|
1581
|
-
*/
|
|
1582
|
-
function prosemirrorToYXmlFragment(doc, xmlFragment) {
|
|
1583
|
-
const type = xmlFragment || new Y.XmlFragment();
|
|
1584
|
-
const ydoc = type.doc ? type.doc : { transact: (transaction) => transaction(void 0) };
|
|
1585
|
-
updateYFragment(ydoc, type, doc, {
|
|
1586
|
-
mapping: /* @__PURE__ */ new Map(),
|
|
1587
|
-
isOMark: /* @__PURE__ */ new Map()
|
|
1588
|
-
});
|
|
1589
|
-
return type;
|
|
1590
|
-
}
|
|
1591
|
-
/**
|
|
1592
|
-
* Utility method to convert Prosemirror compatible JSON to a Y.XmlFragment
|
|
1593
|
-
*
|
|
1594
|
-
* This can be used when importing existing content to Y.Doc for the first time,
|
|
1595
|
-
* note that this should not be used to rehydrate a Y.Doc from a database once
|
|
1596
|
-
* collaboration has begun as all history will be lost
|
|
1597
|
-
*
|
|
1598
|
-
* @param {Schema} schema
|
|
1599
|
-
* @param {any} state
|
|
1600
|
-
* @param {Y.XmlFragment} [xmlFragment] If supplied, an xml fragment to be
|
|
1601
|
-
* populated from the prosemirror state; otherwise a new XmlFragment will be created.
|
|
1602
|
-
* @return {Y.XmlFragment}
|
|
1603
|
-
*/
|
|
1604
|
-
function prosemirrorJSONToYXmlFragment(schema, state, xmlFragment) {
|
|
1605
|
-
return prosemirrorToYXmlFragment(Node$1.fromJSON(schema, state), xmlFragment);
|
|
1606
|
-
}
|
|
1607
|
-
/**
|
|
1608
|
-
* @deprecated Use `yXmlFragmentToProseMirrorRootNode` instead
|
|
1609
|
-
*
|
|
1610
|
-
* Utility method to convert a Y.Doc to Prosemirror compatible JSON.
|
|
1611
|
-
*
|
|
1612
|
-
* @param {Y.XmlFragment} xmlFragment The fragment, which must be part of a Y.Doc.
|
|
1613
|
-
* @return {Record<string, any>}
|
|
1614
|
-
*/
|
|
1615
|
-
function yXmlFragmentToProsemirrorJSON(xmlFragment) {
|
|
1616
|
-
const items = xmlFragment.toArray();
|
|
1617
|
-
/**
|
|
1618
|
-
* @param {Y.AbstractType} item
|
|
1619
|
-
*/
|
|
1620
|
-
const serialize = (item) => {
|
|
1621
|
-
/**
|
|
1622
|
-
* @type {Object} NodeObject
|
|
1623
|
-
* @property {string} NodeObject.type
|
|
1624
|
-
* @property {Record<string, string>=} NodeObject.attrs
|
|
1625
|
-
* @property {Array<NodeObject>=} NodeObject.content
|
|
1626
|
-
*/
|
|
1627
|
-
let response;
|
|
1628
|
-
if (item instanceof Y.XmlText) response = item.toDelta().map(
|
|
1629
|
-
/** @param {any} d */
|
|
1630
|
-
(d) => {
|
|
1631
|
-
const text = {
|
|
1632
|
-
type: "text",
|
|
1633
|
-
text: d.insert
|
|
1634
|
-
};
|
|
1635
|
-
if (d.attributes) text.marks = Object.keys(d.attributes).map((type_) => {
|
|
1636
|
-
const attrs = d.attributes[type_];
|
|
1637
|
-
const mark = { type: yattr2markname(type_) };
|
|
1638
|
-
if (Object.keys(attrs)) mark.attrs = attrs;
|
|
1639
|
-
return mark;
|
|
1640
|
-
});
|
|
1641
|
-
return text;
|
|
1642
|
-
}
|
|
1643
|
-
);
|
|
1644
|
-
else if (item instanceof Y.XmlElement) {
|
|
1645
|
-
response = { type: item.nodeName };
|
|
1646
|
-
const attrs = item.getAttributes();
|
|
1647
|
-
if (Object.keys(attrs).length) response.attrs = attrs;
|
|
1648
|
-
const children = item.toArray();
|
|
1649
|
-
if (children.length) response.content = children.map(serialize).flat();
|
|
1650
|
-
} else error.unexpectedCase();
|
|
1651
|
-
return response;
|
|
1652
|
-
};
|
|
1653
|
-
return {
|
|
1654
|
-
type: "doc",
|
|
1655
|
-
content: items.map(serialize)
|
|
1656
|
-
};
|
|
1657
|
-
}
|
|
1658
|
-
/**
|
|
1659
|
-
* Default awareness state filter
|
|
1660
|
-
*
|
|
1661
|
-
* @param {number} currentClientId current client id
|
|
1662
|
-
* @param {number} userClientId user client id
|
|
1663
|
-
* @param {any} _user user data
|
|
1664
|
-
* @return {boolean}
|
|
1665
|
-
*/
|
|
1666
|
-
const defaultAwarenessStateFilter = (currentClientId, userClientId, _user) => currentClientId !== userClientId;
|
|
1667
|
-
/**
|
|
1668
|
-
* Default generator for a cursor element
|
|
1669
|
-
*
|
|
1670
|
-
* @param {any} user user data
|
|
1671
|
-
* @return {HTMLElement}
|
|
1672
|
-
*/
|
|
1673
|
-
const defaultCursorBuilder = (user) => {
|
|
1674
|
-
const cursor = document.createElement("span");
|
|
1675
|
-
cursor.classList.add("ProseMirror-yjs-cursor");
|
|
1676
|
-
cursor.setAttribute("style", `border-color: ${user.color}`);
|
|
1677
|
-
const userDiv = document.createElement("div");
|
|
1678
|
-
userDiv.setAttribute("style", `background-color: ${user.color}`);
|
|
1679
|
-
userDiv.insertBefore(document.createTextNode(user.name), null);
|
|
1680
|
-
const nonbreakingSpace1 = document.createTextNode("");
|
|
1681
|
-
const nonbreakingSpace2 = document.createTextNode("");
|
|
1682
|
-
cursor.insertBefore(nonbreakingSpace1, null);
|
|
1683
|
-
cursor.insertBefore(userDiv, null);
|
|
1684
|
-
cursor.insertBefore(nonbreakingSpace2, null);
|
|
1685
|
-
return cursor;
|
|
1686
|
-
};
|
|
1687
|
-
/**
|
|
1688
|
-
* Default generator for the selection attributes
|
|
1689
|
-
*
|
|
1690
|
-
* @param {any} user user data
|
|
1691
|
-
* @return {import('prosemirror-view').DecorationAttrs}
|
|
1692
|
-
*/
|
|
1693
|
-
const defaultSelectionBuilder = (user) => {
|
|
1694
|
-
return {
|
|
1695
|
-
style: `background-color: ${user.color}70`,
|
|
1696
|
-
class: "ProseMirror-yjs-selection"
|
|
1697
|
-
};
|
|
1698
|
-
};
|
|
1699
|
-
const rxValidColor = /^#[0-9a-fA-F]{6}$/;
|
|
1700
|
-
/**
|
|
1701
|
-
* @param {any} state
|
|
1702
|
-
* @param {Awareness} awareness
|
|
1703
|
-
* @param {function(number, number, any):boolean} awarenessFilter
|
|
1704
|
-
* @param {(user: { name: string, color: string }, clientId: number) => Element} createCursor
|
|
1705
|
-
* @param {(user: { name: string, color: string }, clientId: number) => import('prosemirror-view').DecorationAttrs} createSelection
|
|
1706
|
-
* @return {any} DecorationSet
|
|
1707
|
-
*/
|
|
1708
|
-
const createDecorations = (state, awareness, awarenessFilter, createCursor, createSelection) => {
|
|
1709
|
-
const ystate = ySyncPluginKey.getState(state);
|
|
1710
|
-
if (ystate == null || ystate.doc == null || ystate.binding == null) return DecorationSet.create(state.doc, []);
|
|
1711
|
-
const y = ystate.doc;
|
|
1712
|
-
const decorations = [];
|
|
1713
|
-
if (ystate.snapshot != null || ystate.prevSnapshot != null || ystate.binding.mapping.size === 0) return DecorationSet.create(state.doc, []);
|
|
1714
|
-
awareness.getStates().forEach((aw, clientId) => {
|
|
1715
|
-
if (!awarenessFilter(y.clientID, clientId, aw)) return;
|
|
1716
|
-
if (aw && aw.cursor != null) {
|
|
1717
|
-
const user = aw.user || {};
|
|
1718
|
-
if (user.color == null) user.color = "#ffa500";
|
|
1719
|
-
else if (!rxValidColor.test(user.color)) console.warn("A user uses an unsupported color format", user);
|
|
1720
|
-
if (user.name == null) user.name = `User: ${clientId}`;
|
|
1721
|
-
let anchor = relativePositionToAbsolutePosition(y, ystate.type, Y.createRelativePositionFromJSON(aw.cursor.anchor), ystate.binding.mapping);
|
|
1722
|
-
let head = relativePositionToAbsolutePosition(y, ystate.type, Y.createRelativePositionFromJSON(aw.cursor.head), ystate.binding.mapping);
|
|
1723
|
-
if (anchor !== null && head !== null) {
|
|
1724
|
-
const maxsize = math.max(state.doc.content.size - 1, 0);
|
|
1725
|
-
anchor = math.min(anchor, maxsize);
|
|
1726
|
-
head = math.min(head, maxsize);
|
|
1727
|
-
decorations.push(Decoration.widget(head, () => createCursor(user, clientId), {
|
|
1728
|
-
key: clientId + "",
|
|
1729
|
-
side: 10
|
|
1730
|
-
}));
|
|
1731
|
-
const from = math.min(anchor, head);
|
|
1732
|
-
const to = math.max(anchor, head);
|
|
1733
|
-
decorations.push(Decoration.inline(from, to, createSelection(user, clientId), {
|
|
1734
|
-
inclusiveEnd: true,
|
|
1735
|
-
inclusiveStart: false
|
|
1736
|
-
}));
|
|
1737
|
-
}
|
|
1738
|
-
}
|
|
1739
|
-
});
|
|
1740
|
-
return DecorationSet.create(state.doc, decorations);
|
|
1741
|
-
};
|
|
1742
|
-
/**
|
|
1743
|
-
* A prosemirror plugin that listens to awareness information on Yjs.
|
|
1744
|
-
* This requires that a `prosemirrorPlugin` is also bound to the prosemirror.
|
|
1745
|
-
*
|
|
1746
|
-
* @public
|
|
1747
|
-
* @param {Awareness} awareness
|
|
1748
|
-
* @param {object} opts
|
|
1749
|
-
* @param {function(any, any, any):boolean} [opts.awarenessStateFilter]
|
|
1750
|
-
* @param {(user: any, clientId: number) => HTMLElement} [opts.cursorBuilder]
|
|
1751
|
-
* @param {(user: any, clientId: number) => import('prosemirror-view').DecorationAttrs} [opts.selectionBuilder]
|
|
1752
|
-
* @param {function(any):any} [opts.getSelection]
|
|
1753
|
-
* @param {string} [cursorStateField] By default all editor bindings use the awareness 'cursor' field to propagate cursor information.
|
|
1754
|
-
* @return {any}
|
|
1755
|
-
*/
|
|
1756
|
-
const yCursorPlugin = (awareness, { awarenessStateFilter = defaultAwarenessStateFilter, cursorBuilder = defaultCursorBuilder, selectionBuilder = defaultSelectionBuilder, getSelection = (state) => state.selection } = {}, cursorStateField = "cursor") => new Plugin({
|
|
1757
|
-
key: yCursorPluginKey,
|
|
1758
|
-
state: {
|
|
1759
|
-
init(_, state) {
|
|
1760
|
-
return createDecorations(state, awareness, awarenessStateFilter, cursorBuilder, selectionBuilder);
|
|
1761
|
-
},
|
|
1762
|
-
apply(tr, prevState, oldState, newState) {
|
|
1763
|
-
const ystate = ySyncPluginKey.getState(newState);
|
|
1764
|
-
const yCursorState = tr.getMeta(yCursorPluginKey);
|
|
1765
|
-
const isRemoteChange = ystate && ystate.isChangeOrigin;
|
|
1766
|
-
if (tr.docChanged && !isRemoteChange && isStructuralTransaction(tr, oldState.doc)) return DecorationSet.empty;
|
|
1767
|
-
if (isRemoteChange || yCursorState && yCursorState.awarenessUpdated) return createDecorations(newState, awareness, awarenessStateFilter, cursorBuilder, selectionBuilder);
|
|
1768
|
-
if (tr.docChanged) return prevState.map(tr.mapping, tr.doc);
|
|
1769
|
-
return prevState;
|
|
1770
|
-
}
|
|
1771
|
-
},
|
|
1772
|
-
props: { decorations: (state) => {
|
|
1773
|
-
return yCursorPluginKey.getState(state);
|
|
1774
|
-
} },
|
|
1775
|
-
view: (view) => {
|
|
1776
|
-
const awarenessListener = () => {
|
|
1777
|
-
if (view.docView) setMeta(view, yCursorPluginKey, { awarenessUpdated: true });
|
|
1778
|
-
};
|
|
1779
|
-
/**
|
|
1780
|
-
* @param {import('prosemirror-view').EditorView} editorView
|
|
1781
|
-
* @param {{ force?: boolean }} [opts]
|
|
1782
|
-
*/
|
|
1783
|
-
const updateCursorInfo = (editorView, opts = {}) => {
|
|
1784
|
-
const ystate = ySyncPluginKey.getState(editorView.state);
|
|
1785
|
-
if (!ystate || !ystate.binding) return;
|
|
1786
|
-
const current = awareness.getLocalState() || {};
|
|
1787
|
-
if (editorView.hasFocus()) {
|
|
1788
|
-
const selection = getSelection(editorView.state);
|
|
1789
|
-
/**
|
|
1790
|
-
* @type {Y.RelativePosition}
|
|
1791
|
-
*/
|
|
1792
|
-
const anchor = absolutePositionToRelativePosition(selection.anchor, ystate.type, ystate.binding.mapping);
|
|
1793
|
-
/**
|
|
1794
|
-
* @type {Y.RelativePosition}
|
|
1795
|
-
*/
|
|
1796
|
-
const head = absolutePositionToRelativePosition(selection.head, ystate.type, ystate.binding.mapping);
|
|
1797
|
-
if (opts.force || current.cursor == null || !Y.compareRelativePositions(Y.createRelativePositionFromJSON(current.cursor.anchor), anchor) || !Y.compareRelativePositions(Y.createRelativePositionFromJSON(current.cursor.head), head)) awareness.setLocalStateField(cursorStateField, {
|
|
1798
|
-
anchor,
|
|
1799
|
-
head
|
|
1800
|
-
});
|
|
1801
|
-
} else if (current.cursor != null && relativePositionToAbsolutePosition(ystate.doc, ystate.type, Y.createRelativePositionFromJSON(current.cursor.anchor), ystate.binding.mapping) !== null) awareness.setLocalStateField(cursorStateField, null);
|
|
1802
|
-
};
|
|
1803
|
-
const onFocusChange = () => updateCursorInfo(view);
|
|
1804
|
-
awareness.on("change", awarenessListener);
|
|
1805
|
-
view.dom.addEventListener("focusin", onFocusChange);
|
|
1806
|
-
view.dom.addEventListener("focusout", onFocusChange);
|
|
1807
|
-
return {
|
|
1808
|
-
update: (editorView, prevState) => {
|
|
1809
|
-
const forceAwarenessUpdate = !!(ySyncPluginKey.getState(editorView.state)?.isChangeOrigin && prevState?.doc && !prevState.doc.eq(editorView.state.doc));
|
|
1810
|
-
updateCursorInfo(editorView, { force: forceAwarenessUpdate });
|
|
1811
|
-
},
|
|
1812
|
-
destroy: () => {
|
|
1813
|
-
view.dom.removeEventListener("focusin", onFocusChange);
|
|
1814
|
-
view.dom.removeEventListener("focusout", onFocusChange);
|
|
1815
|
-
awareness.off("change", awarenessListener);
|
|
1816
|
-
awareness.setLocalStateField(cursorStateField, null);
|
|
1817
|
-
}
|
|
1818
|
-
};
|
|
1819
|
-
}
|
|
1820
|
-
});
|
|
1821
|
-
const undo = (state) => {
|
|
1822
|
-
const undoManager = yUndoPluginKey.getState(state).undoManager;
|
|
1823
|
-
if (undoManager != null) {
|
|
1824
|
-
undoManager.undo();
|
|
1825
|
-
return true;
|
|
1826
|
-
}
|
|
1827
|
-
};
|
|
1828
|
-
const redo = (state) => {
|
|
1829
|
-
const undoManager = yUndoPluginKey.getState(state).undoManager;
|
|
1830
|
-
if (undoManager != null) {
|
|
1831
|
-
undoManager.redo();
|
|
1832
|
-
return true;
|
|
1833
|
-
}
|
|
1834
|
-
};
|
|
1835
|
-
const defaultProtectedNodes = /* @__PURE__ */ new Set(["paragraph"]);
|
|
1836
|
-
const defaultDeleteFilter = (item, protectedNodes) => !(item instanceof Item) || !(item.content instanceof ContentType) || !(item.content.type instanceof Text || item.content.type instanceof XmlElement && protectedNodes.has(item.content.type.nodeName)) || item.content.type._length === 0;
|
|
1837
|
-
const yUndoPlugin = ({ protectedNodes = defaultProtectedNodes, trackedOrigins = [], undoManager = null } = {}) => new Plugin({
|
|
1838
|
-
key: yUndoPluginKey,
|
|
1839
|
-
state: {
|
|
1840
|
-
init: (initargs, state) => {
|
|
1841
|
-
const ystate = ySyncPluginKey.getState(state);
|
|
1842
|
-
let _undoManager = undoManager;
|
|
1843
|
-
if (!_undoManager) {
|
|
1844
|
-
const doc = ystate.doc;
|
|
1845
|
-
const destroyListenersBefore = new Set(doc ? doc._observers.get("destroy") : []);
|
|
1846
|
-
_undoManager = new UndoManager(ystate.type, {
|
|
1847
|
-
trackedOrigins: new Set([ySyncPluginKey].concat(trackedOrigins)),
|
|
1848
|
-
deleteFilter: (item) => defaultDeleteFilter(item, protectedNodes),
|
|
1849
|
-
captureTransaction: (tr) => tr.meta.get("addToHistory") !== false
|
|
1850
|
-
});
|
|
1851
|
-
const destroyListenersAfter = doc ? doc._observers.get("destroy") : /* @__PURE__ */ new Set();
|
|
1852
|
-
_undoManager._yTiptapDocDestroyListeners = Array.from(destroyListenersAfter || []).filter((listener) => !destroyListenersBefore.has(listener));
|
|
1853
|
-
}
|
|
1854
|
-
return {
|
|
1855
|
-
undoManager: _undoManager,
|
|
1856
|
-
prevSel: null,
|
|
1857
|
-
hasUndoOps: _undoManager.undoStack.length > 0,
|
|
1858
|
-
hasRedoOps: _undoManager.redoStack.length > 0
|
|
1859
|
-
};
|
|
1860
|
-
},
|
|
1861
|
-
/**
|
|
1862
|
-
* @returns {any}
|
|
1863
|
-
*/
|
|
1864
|
-
apply: (tr, val, oldState, state) => {
|
|
1865
|
-
const binding = ySyncPluginKey.getState(state).binding;
|
|
1866
|
-
const undoManager = val.undoManager;
|
|
1867
|
-
const hasUndoOps = undoManager.undoStack.length > 0;
|
|
1868
|
-
const hasRedoOps = undoManager.redoStack.length > 0;
|
|
1869
|
-
if (binding) return {
|
|
1870
|
-
undoManager,
|
|
1871
|
-
prevSel: getRelativeSelection(binding, oldState),
|
|
1872
|
-
hasUndoOps,
|
|
1873
|
-
hasRedoOps
|
|
1874
|
-
};
|
|
1875
|
-
else if (hasUndoOps !== val.hasUndoOps || hasRedoOps !== val.hasRedoOps) return Object.assign({}, val, {
|
|
1876
|
-
hasUndoOps: undoManager.undoStack.length > 0,
|
|
1877
|
-
hasRedoOps: undoManager.redoStack.length > 0
|
|
1878
|
-
});
|
|
1879
|
-
else return val;
|
|
1880
|
-
}
|
|
1881
|
-
},
|
|
1882
|
-
view: (view) => {
|
|
1883
|
-
const ystate = ySyncPluginKey.getState(view.state);
|
|
1884
|
-
const undoManager = yUndoPluginKey.getState(view.state).undoManager;
|
|
1885
|
-
undoManager.on("stack-item-added", ({ stackItem }) => {
|
|
1886
|
-
const binding = ystate.binding;
|
|
1887
|
-
if (binding) stackItem.meta.set(binding, yUndoPluginKey.getState(view.state).prevSel);
|
|
1888
|
-
});
|
|
1889
|
-
undoManager.on("stack-item-popped", ({ stackItem }) => {
|
|
1890
|
-
const binding = ystate.binding;
|
|
1891
|
-
if (binding) binding.beforeTransactionSelection = stackItem.meta.get(binding) || binding.beforeTransactionSelection;
|
|
1892
|
-
});
|
|
1893
|
-
return { destroy: () => {
|
|
1894
|
-
undoManager.destroy();
|
|
1895
|
-
const leakedDestroyListeners = undoManager._yTiptapDocDestroyListeners;
|
|
1896
|
-
if (leakedDestroyListeners && undoManager.doc) {
|
|
1897
|
-
leakedDestroyListeners.forEach((listener) => undoManager.doc.off("destroy", listener));
|
|
1898
|
-
undoManager._yTiptapDocDestroyListeners = null;
|
|
1899
|
-
}
|
|
1900
|
-
} };
|
|
1901
|
-
}
|
|
1902
|
-
});
|
|
1903
|
-
//#endregion
|
|
1904
|
-
//#region src/document.ts
|
|
1905
|
-
const schemas = /* @__PURE__ */ new WeakMap();
|
|
1906
|
-
function realtimeEditorSchema(editor) {
|
|
1907
|
-
let schema = schemas.get(editor);
|
|
1908
|
-
if (!schema) {
|
|
1909
|
-
schema = getSchema(editor.extensions());
|
|
1910
|
-
schemas.set(editor, schema);
|
|
1911
|
-
}
|
|
1912
|
-
return schema;
|
|
1913
|
-
}
|
|
1914
|
-
function stableJson(value) {
|
|
1915
|
-
if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
|
|
1916
|
-
if (isRecord(value)) {
|
|
1917
|
-
const record = value;
|
|
1918
|
-
return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${stableJson(record[key])}`).join(",")}}`;
|
|
1919
|
-
}
|
|
1920
|
-
return JSON.stringify(value ?? null);
|
|
1921
|
-
}
|
|
1922
|
-
function realtimeJsonEqual(left, right) {
|
|
1923
|
-
return stableJson(left) === stableJson(right);
|
|
1924
|
-
}
|
|
1925
|
-
/** Writes fields into a document's field map, inserting, replacing, and deleting only what differs. */
|
|
1926
|
-
function writeRealtimeFields(map, fields) {
|
|
1927
|
-
const next = fields ?? {};
|
|
1928
|
-
for (const key of map.keys()) if (!Object.hasOwn(next, key)) map.delete(key);
|
|
1929
|
-
for (const [key, value] of Object.entries(next)) {
|
|
1930
|
-
if (value === void 0) continue;
|
|
1931
|
-
if (!map.has(key) || !realtimeJsonEqual(map.get(key), value)) map.set(key, structuredClone(value));
|
|
1932
|
-
}
|
|
1933
|
-
}
|
|
1934
|
-
/** Builds a new room document from a stored snapshot. Only use it for rooms no client holds yet. */
|
|
1935
|
-
async function createRealtimeYDoc(editor, snapshot) {
|
|
1936
|
-
const content = await editor.fromMarkdown(snapshot.body);
|
|
1937
|
-
const document = new Y.Doc();
|
|
1938
|
-
try {
|
|
1939
|
-
document.transact(() => {
|
|
1940
|
-
prosemirrorJSONToYXmlFragment(realtimeEditorSchema(editor), content, document.getXmlFragment(realtimeDocumentLayout.body));
|
|
1941
|
-
writeRealtimeFields(document.getMap(realtimeDocumentLayout.fields), snapshot.fields);
|
|
1942
|
-
});
|
|
1943
|
-
return document;
|
|
1944
|
-
} catch (error) {
|
|
1945
|
-
document.destroy();
|
|
1946
|
-
throw error;
|
|
1947
|
-
}
|
|
1948
|
-
}
|
|
1949
|
-
function readRealtimeFields(document) {
|
|
1950
|
-
return document.getMap(realtimeDocumentLayout.fields).toJSON();
|
|
1951
|
-
}
|
|
1952
|
-
function readRealtimeBody(editor, document) {
|
|
1953
|
-
return {
|
|
1954
|
-
...yXmlFragmentToProsemirrorJSON(document.getXmlFragment(realtimeDocumentLayout.body)),
|
|
1955
|
-
type: realtimeEditorSchema(editor).topNodeType.name
|
|
1956
|
-
};
|
|
1957
|
-
}
|
|
1958
|
-
async function readRealtimeYDoc(editor, document) {
|
|
1959
|
-
const content = readRealtimeBody(editor, document);
|
|
1960
|
-
const fields = readRealtimeFields(document);
|
|
1961
|
-
return {
|
|
1962
|
-
body: await editor.toMarkdown(content),
|
|
1963
|
-
fields
|
|
1964
|
-
};
|
|
1965
|
-
}
|
|
1966
|
-
/**
|
|
1967
|
-
* Throws when the body of `document` does not fit the editor schema, such as a node type the schema does not know.
|
|
1968
|
-
* A codec that builds an editor from such JSON writes an empty or partial document.
|
|
1969
|
-
*/
|
|
1970
|
-
function checkRealtimeBody(editor, document) {
|
|
1971
|
-
realtimeEditorSchema(editor).nodeFromJSON(readRealtimeBody(editor, document)).check();
|
|
1972
|
-
}
|
|
1973
|
-
/** Whether `fromMarkdown(body)` gives back the body of `document`, where `body` is what `toMarkdown` wrote for it. */
|
|
1974
|
-
async function realtimeCodecReadsBack(editor, document, body) {
|
|
1975
|
-
const schema = realtimeEditorSchema(editor);
|
|
1976
|
-
try {
|
|
1977
|
-
return schema.nodeFromJSON(readRealtimeBody(editor, document)).eq(schema.nodeFromJSON(await editor.fromMarkdown(body)));
|
|
1978
|
-
} catch {
|
|
1979
|
-
return false;
|
|
1980
|
-
}
|
|
1981
|
-
}
|
|
1982
|
-
/** Adds the final newline that a codec dropped when the stored body ends with one. */
|
|
1983
|
-
function keepRealtimeFinalNewline(body, finalNewline) {
|
|
1984
|
-
return finalNewline && !body.endsWith("\n") ? `${body}\n` : body;
|
|
1985
|
-
}
|
|
1986
|
-
function sameBody(left, right) {
|
|
1987
|
-
return left === right || keepRealtimeFinalNewline(left, true) === keepRealtimeFinalNewline(right, true);
|
|
1988
|
-
}
|
|
1989
|
-
/**
|
|
1990
|
-
* Returns the Yjs update that turns `base` into `target` as a structural diff. Applying it to a
|
|
1991
|
-
* room that has moved on since `base` keeps concurrent edits instead of duplicating content.
|
|
1992
|
-
*/
|
|
1993
|
-
async function diffRealtimeYDoc(editor, base, target) {
|
|
1994
|
-
const current = await readRealtimeYDoc(editor, base);
|
|
1995
|
-
const next = sameBody(target.body, current.body) ? void 0 : await editor.fromMarkdown(target.body);
|
|
1996
|
-
const fieldsChanged = target.fields !== void 0 && !realtimeJsonEqual(current.fields, target.fields);
|
|
1997
|
-
if (!next && !fieldsChanged) return /* @__PURE__ */ new Uint8Array();
|
|
1998
|
-
const clone = new Y.Doc({ gc: false });
|
|
1999
|
-
try {
|
|
2000
|
-
Y.applyUpdate(clone, Y.encodeStateAsUpdate(base));
|
|
2001
|
-
const state = Y.encodeStateVector(clone);
|
|
2002
|
-
clone.transact(() => {
|
|
2003
|
-
if (next) updateYFragment(clone, clone.getXmlFragment(realtimeDocumentLayout.body), realtimeEditorSchema(editor).nodeFromJSON(next), {
|
|
2004
|
-
isOMark: /* @__PURE__ */ new Map(),
|
|
2005
|
-
mapping: /* @__PURE__ */ new Map()
|
|
2006
|
-
});
|
|
2007
|
-
if (fieldsChanged) writeRealtimeFields(clone.getMap(realtimeDocumentLayout.fields), target.fields);
|
|
2008
|
-
});
|
|
2009
|
-
return Y.encodeStateAsUpdate(clone, state);
|
|
2010
|
-
} finally {
|
|
2011
|
-
clone.destroy();
|
|
2012
|
-
}
|
|
2013
|
-
}
|
|
2014
|
-
function writeRealtimeStatus(document, status, origin) {
|
|
2015
|
-
const map = document.getMap(realtimeDocumentLayout.status);
|
|
2016
|
-
document.transact(() => {
|
|
2017
|
-
for (const [key, value] of Object.entries(status)) {
|
|
2018
|
-
if (value === void 0) continue;
|
|
2019
|
-
if (!map.has(key) || !realtimeJsonEqual(map.get(key), value)) map.set(key, value === null ? null : structuredClone(value));
|
|
2020
|
-
}
|
|
2021
|
-
}, origin);
|
|
2022
|
-
}
|
|
2023
|
-
/** Compact fingerprint used to reject client updates that touch the server-written status. */
|
|
2024
|
-
function realtimeStatusFingerprint(document) {
|
|
2025
|
-
return stableJson(document.getMap(realtimeDocumentLayout.status).toJSON());
|
|
2026
|
-
}
|
|
2027
|
-
/** Whether `document` already contains every insertion and deletion in `state`. */
|
|
2028
|
-
function containsRealtimeState(document, state) {
|
|
2029
|
-
const candidate = new Y.Doc({ gc: false });
|
|
2030
|
-
try {
|
|
2031
|
-
Y.applyUpdate(candidate, Y.encodeStateAsUpdate(document));
|
|
2032
|
-
const before = Y.snapshot(candidate);
|
|
2033
|
-
Y.applyUpdate(candidate, state);
|
|
2034
|
-
if (candidate.store.pendingStructs || candidate.store.pendingDs) return false;
|
|
2035
|
-
return Y.equalSnapshots(before, Y.snapshot(candidate));
|
|
2036
|
-
} finally {
|
|
2037
|
-
candidate.destroy();
|
|
2038
|
-
}
|
|
2039
|
-
}
|
|
2040
|
-
//#endregion
|
|
2041
|
-
export { yCursorPlugin as _, keepRealtimeFinalNewline as a, yUndoPlugin as b, realtimeJsonEqual as c, writeRealtimeStatus as d, absolutePositionToRelativePosition as f, undo as g, relativePositionToAbsolutePosition as h, diffRealtimeYDoc as i, realtimeStatusFingerprint as l, redo as m, containsRealtimeState as n, readRealtimeYDoc as o, defaultSelectionBuilder as p, createRealtimeYDoc as r, realtimeCodecReadsBack as s, checkRealtimeBody as t, writeRealtimeFields as u, ySyncPlugin as v, yUndoPluginKey as x, ySyncPluginKey as y };
|