-
Notifications
You must be signed in to change notification settings - Fork 0
/
socket.js
60 lines (52 loc) · 1.47 KB
/
socket.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
const { Server } = require('socket.io');
const getRandomColor = () => {
const randomColor = Math.floor(Math.random() * 16777215).toString(16);
return '#' + randomColor;
};
const getUniqueRandomColor = () => {
let color = getRandomColor();
while (Color.includes(color)) {
color = getRandomColor();
}
Color.push(color);
return color;
};
let Color = [];
const socketInit = (server, app) => {
const io = new Server(server, {
cors: {
origin: '*',
methods: ['GET', 'POST'],
credentials: true,
},
transports: ['websocket'],
});
app.set('io', io);
io.on('connection', (socket) => {
console.log(socket);
socket.on('get-document', async (docId) => {
console.log(docId);
// const document = await findOrCreateDocument(docId);
let cursors = {};
socket.join(docId);
socket.emit('load-document', '');
socket.on('send-changes', (delta) => {
socket.broadcast.to(docId).emit('receive-changes', delta);
});
socket.on('send-cursor-changes', (rangemap) => {
const color =
cursors[socket.id]?.color === undefined
? getUniqueRandomColor(Color)
: cursors[socket.id]?.color;
cursors[socket.id] = {
range: rangemap.range,
color,
id: rangemap.id,
};
socket.broadcast.to(docId).emit('receive-cursor-changes', cursors);
});
});
});
};
// exports.SocketMap = SocketMap;
exports.socketInit = socketInit;