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