-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.js
395 lines (357 loc) · 10.9 KB
/
client.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
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
var sharedb = require('@teamwork/sharedb/lib/client');
var richText = require('rich-text');
var json0 = require('@houshuang/ot-json0');
var Quill = require('quill');
var QuillCursors = require('quill-cursors');
var Stringify = require('json-stable-stringify');
var HtmlTextCollabExt = require('@convergence/html-text-collab-ext');
var StringBinding = require('sharedb-string-binding');
Quill.register('modules/cursors', QuillCursors);
presence1 = {};
presence2 = {};
json0.type.registerSubtype(richText.type);
sharedb.types.register(json0.type);
const textarea = document.getElementById('example');
const textinput = document.getElementById('example2');
const car = document.getElementById('car');
const bike = document.getElementById('bike');
const carP = {};
const bikeP = {};
textarea.addEventListener('focus', function() {
window.setTimeout(
() =>
updateCursorText(
[textarea.selectionStart, textarea.selectionStart],
uid,
'example'
),
100
);
});
textinput.addEventListener('focus', function() {
window.setTimeout(
() =>
updateCursorText(
[textarea.selectionStart, textarea.selectionStart],
uid,
'example2'
),
100
);
});
const carPresence = document.getElementById('presenceCar');
const bikePresence = document.getElementById('presenceBike');
// Open WebSocket connection to ShareDB server
var socket = new WebSocket('ws://' + window.location.host);
var connection = new sharedb.Connection(socket);
// For testing reconnection
window.disconnect = function() {
connection.close();
};
window.connect = function() {
var socket = new WebSocket('ws://' + window.location.host);
connection.bindToSocket(socket);
};
var names = [
'Peter',
'Anna',
'John',
'Ole',
'Niels',
'Gregor',
'Chen Li',
'Ananda',
'Rupert',
'Ben'
];
// Helper functions for nicely displaying uid
function uidColor(uid) {
var colors = [
'red',
'blue',
'green',
'purple',
'orange',
'olive',
'maroon',
'yellow',
'lime',
'teal'
];
return colors[names.findIndex(x => x === uid)];
}
function renderNameplate(uid) {
var css = 'background-color: ' + uidColor(uid) + ';';
document.getElementById('nameplate').style = css;
document.getElementById('nameplate').innerText = uid;
}
// Create local Doc instance mapped to 'examples' collection document with id 'richtext'
var doc = connection.get('examples', 'stian5');
// can only create when document doesn't yet exist
// doc.create({ text: '', text2: '' });
// Generate a random uid and display it.
var uid = names[Math.floor(Math.random() * 10)];
renderNameplate(uid);
doc.requestReplyPresence = true;
doc.subscribe(function(err) {
if (err) throw err;
var quill = new Quill('#editor', {
theme: 'snow',
modules: {
cursors: { hideDelayMs: 999999999 }
}
});
var quill2 = new Quill('#editor2', {
theme: 'snow',
modules: {
cursors: { hideDelayMs: 999999999 }
}
});
var cursors = quill.getModule('cursors');
var cursors2 = quill2.getModule('cursors');
doc.submitPresence(
{
u: uid,
userInfo: { uid }
},
err => {
if (err) {
throw err;
}
doc.requestReplyPresence = false;
}
);
quill.setContents(doc.data.text);
quill2.setContents(doc.data.text2);
quill.on('text-change', function(delta, oldDelta, source) {
if (source !== 'user') return;
const op = { p: ['text'], t: 'rich-text', o: delta.ops };
doc.submitOp(op, { source: quill });
});
quill2.on('text-change', function(delta, oldDelta, source) {
if (source !== 'user') return;
const op = { p: ['text2'], t: 'rich-text', o: delta.ops };
doc.submitOp(op, { source: quill });
});
bike.addEventListener('change', function() {
checkboxSubmit('bike', this.checked);
});
car.addEventListener('change', function() {
checkboxSubmit('car', this.checked);
});
const binding = new StringBinding(textarea, doc, ['example']);
binding.setup();
const textEditor = new HtmlTextCollabExt.CollaborativeTextEditor({
control: textarea,
onSelectionChanged: selection =>
updateCursorText([selection.anchor, selection.target], uid, 'example')
});
const binding2 = new StringBinding(textinput, doc, ['example2']);
binding2.setup();
const textEditor2 = new HtmlTextCollabExt.CollaborativeTextEditor({
control: textinput,
onSelectionChanged: selection =>
updateCursorText([selection.anchor, selection.target], uid, 'example2')
});
const selectionManager = textEditor.selectionManager();
const selectionManager2 = textEditor2.selectionManager();
doc.on('op', function(ops, source) {
if (source === quill) return;
ops.forEach(op => {
if (op.p[0] === 'text') {
quill.updateContents(op.o);
} else {
quill2.updateContents(op.o);
}
});
});
// When we receive information about updated presences,
// update the locall QuillCursor(s).
doc.on('presence', function(srcList, submitted) {
document.getElementById('presence').innerHTML = Object.values(doc.presence)
.map(x => `<li><b>${x.u}</b> - ${Stringify(x)}</li>`)
.join('');
srcList.forEach(function(src) {
if (doc.presence[src] && doc.presence[src].u) {
var userid = doc.presence[src].u;
if (
userid !== uid &&
doc.presence[src].cursor &&
doc.presence[src].cursor.s &&
doc.presence[src].cursor.s.length > 0
) {
// TODO: Can QuillCursors support multiple selections?
var sel = doc.presence[src].cursor.s[0];
// Use Math.abs because the sharedb presence type
// supports reverse selections, but I don't think
// Quill Cursors does.
var len = Math.abs(sel[1] - sel[0]);
var min = Math.min(sel[0], sel[1]);
// Re-creating an existing cursor is a no-op
if (doc.presence[src].p && doc.presence[src].p[0] === 'text') {
cursors.createCursor(userid, userid, uidColor(userid));
cursors.moveCursor(userid, { index: min, length: len });
cursors2.removeCursor(userid);
if (presence1[userid]) {
selectionManager.removeCollaborator(userid);
presence1[userid] = null;
}
if (presence2[userid]) {
selectionManager.removeCollaborator(userid);
presence1[userid] = null;
}
} else if (
doc.presence[src].p &&
doc.presence[src].p[0] === 'text2'
) {
cursors2.createCursor(userid, userid, uidColor(userid));
cursors2.moveCursor(userid, { index: min, length: len });
cursors.removeCursor(userid);
} else if (
doc.presence[src].p &&
doc.presence[src].p[0] === 'example'
) {
cursors2.removeCursor(userid);
cursors.removeCursor(userid);
if (presence2[userid]) {
selectionManager2.removeCollaborator(userid);
presence2[userid] = null;
}
if (!presence1[userid]) {
presence1[userid] = selectionManager.addCollaborator(
userid,
userid,
uidColor(userid)
);
}
presence1[userid].setSelection({ anchor: sel[0], target: sel[1] });
presence1[userid].flashCursorToolTip(2);
} else if (
doc.presence[src].p &&
doc.presence[src].p[0] === 'example2'
) {
cursors2.removeCursor(userid);
cursors.removeCursor(userid);
if (presence1[userid]) {
selectionManager.removeCollaborator(userid);
presence1[userid] = null;
}
if (!presence2[userid]) {
presence2[userid] = selectionManager2.addCollaborator(
userid,
userid,
uidColor(userid)
);
}
presence2[userid].setSelection({ anchor: sel[0], target: sel[1] });
presence2[userid].flashCursorToolTip(2);
}
}
}
});
});
doc.on('presence', function(srcList, submitted) {
srcList.forEach(function(src) {
var userid = doc.presence[src].u;
if (doc.presence[src].p && doc.presence[src].p[0] === 'car') {
carP[userid] = true;
bikeP[userid] = false;
updateCarBikeP();
cursors2.removeCursor(userid);
cursors.removeCursor(userid);
if (presence1[userid]) {
selectionManager.removeCollaborator(userid);
presence1[userid] = null;
}
if (presence2[userid]) {
selectionManager.removeCollaborator(userid);
presence2[userid] = null;
}
} else if (doc.presence[src].p && doc.presence[src].p[0] === 'bike') {
carP[userid] = false;
bikeP[userid] = true;
updateCarBikeP();
cursors2.removeCursor(userid);
cursors.removeCursor(userid);
if (presence1[userid]) {
selectionManager.removeCollaborator(userid);
presence1[userid] = null;
}
if (presence2[userid]) {
selectionManager.removeCollaborator(userid);
presence2[userid] = null;
}
} else {
carP[userid] = false;
bikeP[userid] = false;
}
});
updateCarBikeP();
});
// When the local Quill selection changes, publish our new
// local presence data.
quill.on('selection-change', function(range, oldRange, source) {
if (source === 'user') {
updateCursor(range, uid, 'text');
} else {
debouncedUpdate(range, uid, 'text');
}
});
quill2.on('selection-change', function(range, oldRange, source) {
if (source === 'user') {
updateCursor(range, uid, 'text2');
} else {
debouncedUpdate(range, uid, 'text2');
}
});
});
function updateCursorText(range, uid, text) {
if (range) {
doc.submitPresence({
u: uid,
p: [text],
cursor: { c: 0, s: [range] }
});
}
}
function updateCursor(range, uid, text) {
if (range) {
doc.submitPresence({
u: uid,
p: [text],
t: 'rich-text',
cursor: { c: 0, s: [[range.index, range.index + range.length]] }
});
}
}
var debouncedUpdate = debounce(updateCursor, 500);
function debounce(func, wait) {
var timeout;
return function(...args) {
var context = this;
var later = function() {
timeout = null;
func.apply(context, args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
const checkboxSubmit = (field, value) => {
doc.submitPresence({
u: uid,
p: [field],
cursor: { s: [[]] }
});
doc.submitOp({ p: [field], oi: value });
};
const updateCarBikeP = () => {
carPresence.innerText =
Object.keys(carP)
.filter(x => carP[x])
.join(' - ') || '';
bikePresence.innerText =
Object.keys(bikeP)
.filter(x => bikeP[x])
.join(' - ') || '';
};