-
Notifications
You must be signed in to change notification settings - Fork 94
/
Collaboration.js
77 lines (67 loc) · 1.48 KB
/
Collaboration.js
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
import { Extension } from '@tiptap/core'
import { Step } from 'prosemirror-transform'
import {
collab,
sendableSteps,
getVersion,
receiveTransaction,
} from 'prosemirror-collab'
let timeout
const debounce = (fn, delay) => (...args) => {
if (timeout) {
clearTimeout(timeout)
}
timeout = setTimeout(() => {
fn(...args)
timeout = null
}, delay)
}
const Collaboration = Extension.create({
name: 'collaboration',
onCreate() {
this.getSendableSteps = debounce(state => {
const sendable = sendableSteps(state)
if (sendable) {
this.options.onSendable({
editor: this.editor,
sendable: {
version: sendable.version,
steps: sendable.steps.map(step => step.toJSON()),
clientID: sendable.clientID,
},
})
}
}, this.options.debounce)
this.editor.on('transaction', ({ editor }) => {
this.getSendableSteps(editor.state)
})
},
addOptions() {
return {
version: 0,
clientID: Math.floor(Math.random() * 0xFFFFFFFF),
debounce: 250,
onSendable: () => { },
update: ({ steps, version }) => {
const { state, view, schema } = this.editor
if (getVersion(state) > version) {
return
}
view.dispatch(receiveTransaction(
state,
steps.map(item => Step.fromJSON(schema, item.step)),
steps.map(item => item.clientID),
))
},
}
},
addProseMirrorPlugins() {
return [
collab({
version: this.options.version,
clientID: this.options.clientID,
}),
]
},
})
export default Collaboration