1class CollaborativeEngine {
2 constructor(wsUrl, store) {
3 this.wsUrl = wsUrl;
4 this.store = store;
5 this.socket = null;
6 this.clientId = 'client_' + crypto.randomUUID().slice(0, 8);
7 this.remotePresences = new Map();
8
9 this.connect();
10 this.initMouseTracking();
11 }
12
13 connect() {
14 this.socket = new WebSocket(this.wsUrl);
15
16 this.socket.onopen = () => {
17 console.log(`[Collab] Connected as ${this.clientId}`);
18 // Broadcast join presence
19 this.broadcast({
20 type: 'PEER_JOIN',
21 clientId: this.clientId,
22 color: this.getRandomColor()
23 });
24 };
25
26 this.socket.onmessage = (event) => {
27 const message = JSON.parse(event.data);
28 // Ignore self-broadcasts
29 if (message.clientId === this.clientId) return;
30
31 this.handleRemoteMessage(message);
32 };
33 }
34
35 initMouseTracking() {
36 // Throttle cursor broadcasts to 50ms (20fps) to conserve network
37 let lastSent = 0;
38
39 window.addEventListener('pointermove', (e) => {
40 const now = Date.now();
41 if (now - lastSent > 50) {
42 lastSent = now;
43 this.broadcast({
44 type: 'CURSOR_UPDATE',
45 clientId: this.clientId,
46 x: e.clientX,
47 y: e.clientY
48 });
49 }
50 });
51 }
52
53 broadcast(action) {
54 if (this.socket && this.socket.readyState === WebSocket.OPEN) {
55 this.socket.send(JSON.stringify(action));
56 }
57 }
58
59 handleRemoteMessage(msg) {
60 switch (msg.type) {
61 case 'CURSOR_UPDATE':
62 this.updateRemoteCursor(msg.clientId, msg.x, msg.y);
63 break;
64
65 case 'DASHBOARD_MUTATION':
66 // Dispatch remote mutation directly to local store!
67 this.store.dispatch(msg.action);
68 break;
69
70 case 'PEER_LEAVE':
71 this.removeRemoteCursor(msg.clientId);
72 break;
73 }
74 }
75
76 updateRemoteCursor(peerId, x, y) {
77 let cursorEl = document.querySelector(`#cursor-${peerId}`);
78 if (!cursorEl) {
79 cursorEl = document.createElement('div');
80 cursorEl.id = `cursor-${peerId}`;
81 cursorEl.className = 'remote-cursor';
82 cursorEl.innerHTML = `
83 <svg class="cursor-pointer" width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
84 <polygon points="0,0 0,20 6,15 11,24 14,22 9,13 18,13" />
85 </svg>
86 <span class="peer-label">${peerId}</span>
87 `;
88 document.body.appendChild(cursorEl);
89 }
90
91 // High performance GPU translate
92 cursorEl.style.transform = `translate3d(${x}px, ${y}px, 0)`;
93 }
94
95 removeRemoteCursor(peerId) {
96 const el = document.querySelector(`#cursor-${peerId}`);
97 if (el) el.remove();
98 }
99
100 getRandomColor() {
101 return ['#ef4444', '#3b82f6', '#10b981', '#f59e0b', '#8b5cf6'][Math.floor(Math.random() * 5)];
102 }
103}