This repository has been archived by the owner on Sep 30, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
78 lines (65 loc) · 2 KB
/
app.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
import { createClient } from "@liveblocks/client";
const client = createClient({
authEndpoint: "/auth",
});
const room = client.enter("node-js-example", { cursor: null });
const cursorsContainer = document.getElementById("cursors-container");
/**
* Subscribe to every others presence updates.
* The callback will be called if you or someone else enters or leaves the room
* or when someone presence is updated
*/
room.subscribe("others", (others, event) => {
switch (event.type) {
case "reset": {
// Clear all cursors
cursorsContainer.innerHTML = "";
for (const user of others.toArray()) {
updateCursor(user);
}
break;
}
case "leave": {
deleteCursor(event.user);
break;
}
case "enter":
case "update": {
updateCursor(event.user);
break;
}
}
});
document.addEventListener("pointermove", (e) => {
room.updatePresence({ cursor: { x: e.clientX, y: e.clientY } });
});
document.addEventListener("pointerleave", (e) => {
room.updatePresence({ cursor: null });
});
const COLORS = ["#DC2626", "#D97706", "#059669", "#7C3AED", "#DB2777"];
// Update cursor position based on user presence
function updateCursor(user) {
const cursor = getCursorOrCreate(user.connectionId);
if (user.presence?.cursor) {
cursor.style.transform = `translateX(${user.presence.cursor.x}px) translateY(${user.presence.cursor.y}px)`;
cursor.style.opacity = "1";
} else {
cursor.style.opacity = "0";
}
}
function getCursorOrCreate(connectionId) {
let cursor = document.getElementById(`cursor-${connectionId}`);
if (cursor == null) {
cursor = document.getElementById("cursor-template").cloneNode(true);
cursor.id = `cursor-${connectionId}`;
cursor.style.fill = COLORS[connectionId % COLORS.length];
cursorsContainer.appendChild(cursor);
}
return cursor;
}
function deleteCursor(user) {
const cursor = document.getElementById(`cursor-${user.connectionId}`);
if (cursor) {
cursor.parentNode.removeChild(cursor);
}
}