@vite-hub/realtime 0.0.4 → 0.1.0

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