-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcollabCursor.js
114 lines (96 loc) · 2.51 KB
/
collabCursor.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
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
import { Plugin, PluginKey } from 'prosemirror-state'
import { DecorationSet } from 'prosemirror-view'
import cursorWidgetDecoration from './cursorWidgetDecoration'
const key = new PluginKey('collabCursor')
const colors = [
'orange',
'palevioletred',
'mediumpurple',
'darkseagreen',
'seashell'
]
export const randID = () => 'cursor-' + Math.random().toString(36).slice(2)
const randColor = () => colors[Math.floor(Math.random() * colors.length)]
function cursorDecorationsFromState (state) {
if (!state.collabCursor$) {
return []
}
return Object.keys(state.collabCursor$.cursors)
.filter((cursorID) => {
return cursorID !== state.collabCursor$.id
})
.map((cursorID) => {
const { pos, color } = state.collabCursor$.cursors[cursorID]
return cursorWidgetDecoration(pos, color)
})
}
export function plugin (authority, cursorID) {
return new Plugin({
key,
state: {
init () {
return {
id: cursorID,
color: randColor(),
cursors: {}
}
},
apply (transaction, value, oldState, newState) {
const meta = transaction.getMeta('collabCursor')
if (meta) {
return {
...value,
cursors: {
...value.cursors,
...meta.cursors
}
}
} else {
return value
}
}
},
appendTransaction (transactions, oldState, newState) {
const transaction = newState.tr
if (!oldState.collabCursor$) {
return transaction
}
transaction.setMeta('collabCursor', {
cursors: {
[oldState.collabCursor$.id]: {
pos: newState.selection.$head.pos,
color: oldState.collabCursor$.color
}
}
})
return transaction
},
props: {
decorations: (state) => DecorationSet.create(
authority.doc,
cursorDecorationsFromState(state)
)
}
})
}
export function sendableData (state) {
if (!state.collabCursor$) {
return null
}
const cursorID = state.collabCursor$.id
const cursorData = state.collabCursor$.cursors[cursorID]
if (!cursorData) {
return null
}
return { id: cursorID, data: cursorData }
}
export function receiveTransaction (state, cursorData) {
const transaction = state.tr
if (!state.collabCursor$) {
return transaction
}
if (cursorData[state.collabCursor$.id] == null) {
transaction.setMeta('collabCursor', { cursors: cursorData })
}
return transaction
}