| bdb18c9 | | | 1 | const express = require("express"); |
| bdb18c9 | | | 2 | const http = require("http"); |
| bdb18c9 | | | 3 | const { Server } = require("socket.io"); |
| bdb18c9 | | | 4 | const path = require("path"); |
| bdb18c9 | | | 5 | const fs = require("fs"); |
| be59e71 | | | 6 | const fsp = fs.promises; |
| bdb18c9 | | | 7 | const Y = require("yjs"); |
| 515cc68 | | | 8 | const { requireAuth, optionalAuth, socketAuth } = require("./auth"); |
| bdb18c9 | | | 9 | |
| be59e71 | | | 10 | // Sanitize user-supplied IDs to prevent path traversal |
| be59e71 | | | 11 | function safeId(id) { |
| be59e71 | | | 12 | return String(id).replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 128); |
| be59e71 | | | 13 | } |
| be59e71 | | | 14 | |
| bdb18c9 | | | 15 | const app = express(); |
| bdb18c9 | | | 16 | const server = http.createServer(app); |
| bdb18c9 | | | 17 | const io = new Server(server, { cors: { origin: "*" } }); |
| bdb18c9 | | | 18 | |
| bdb18c9 | | | 19 | const PORT = process.env.PORT || 3333; |
| 2a9592c | | | 20 | const GROVE_API_URL = process.env.GROVE_API_URL || "http://localhost:4000"; |
| bdb18c9 | | | 21 | |
| 2a9592c | | | 22 | // Serve static files (JS, CSS, etc.) |
| bdb18c9 | | | 23 | app.use(express.static(path.join(__dirname, "public"))); |
| bdb18c9 | | | 24 | |
| 2a9592c | | | 25 | // In-memory store per room (keyed by "owner/repo") |
| 2a9592c | | | 26 | // { roomKey: { notes: { diagramId: [...] }, users: {}, ydocs: { diagramId: Y.Doc } } } |
| bdb18c9 | | | 27 | const rooms = {}; |
| bdb18c9 | | | 28 | |
| 2a9592c | | | 29 | function getRoom(roomKey) { |
| 2a9592c | | | 30 | if (!rooms[roomKey]) { |
| 2a9592c | | | 31 | rooms[roomKey] = { notes: {}, users: {}, ydocs: {} }; |
| bdb18c9 | | | 32 | } |
| 2a9592c | | | 33 | return rooms[roomKey]; |
| bdb18c9 | | | 34 | } |
| bdb18c9 | | | 35 | |
| 2a9592c | | | 36 | function roomKey(owner, repo) { |
| 2a9592c | | | 37 | return `${safeId(owner)}/${safeId(repo)}`; |
| 2a9592c | | | 38 | } |
| 2a9592c | | | 39 | |
| 2a9592c | | | 40 | // Persistence: repo-scoped data on disk |
| bdb18c9 | | | 41 | const DATA_DIR = process.env.DATA_DIR || path.join(__dirname, "data"); |
| bdb18c9 | | | 42 | if (!fs.existsSync(DATA_DIR)) fs.mkdirSync(DATA_DIR); |
| bdb18c9 | | | 43 | |
| 2a9592c | | | 44 | function repoDataDir(owner, repo) { |
| 2a9592c | | | 45 | return path.join(DATA_DIR, "repos", safeId(owner), safeId(repo)); |
| 2a9592c | | | 46 | } |
| 2a9592c | | | 47 | |
| 2a9592c | | | 48 | // ── Diagram catalog (per-repo) ── |
| 1e755c0 | | | 49 | const DIAGRAMS_DEFAULT_PATH = path.join(__dirname, "diagrams-default.json"); |
| 1e755c0 | | | 50 | |
| 2a9592c | | | 51 | function loadDiagrams(owner, repo) { |
| 2a9592c | | | 52 | const dir = repoDataDir(owner, repo); |
| 2a9592c | | | 53 | const repoPath = path.join(dir, "diagrams.json"); |
| 2a9592c | | | 54 | if (fs.existsSync(repoPath)) { |
| 1e755c0 | | | 55 | try { |
| 2a9592c | | | 56 | return JSON.parse(fs.readFileSync(repoPath, "utf-8")); |
| 1e755c0 | | | 57 | } catch (e) { |
| 2a9592c | | | 58 | console.error(`[diagrams] Failed to parse ${repoPath}:`, e.message); |
| 1e755c0 | | | 59 | } |
| 1e755c0 | | | 60 | } |
| 2a9592c | | | 61 | // Seed from default catalog for new repos |
| 1e755c0 | | | 62 | if (fs.existsSync(DIAGRAMS_DEFAULT_PATH)) { |
| 1e755c0 | | | 63 | const data = fs.readFileSync(DIAGRAMS_DEFAULT_PATH, "utf-8"); |
| 2a9592c | | | 64 | fs.mkdirSync(dir, { recursive: true }); |
| 2a9592c | | | 65 | fs.writeFileSync(repoPath, data); |
| 1e755c0 | | | 66 | return JSON.parse(data); |
| 1e755c0 | | | 67 | } |
| 1e755c0 | | | 68 | return { sections: [], diagrams: [] }; |
| 1e755c0 | | | 69 | } |
| 1e755c0 | | | 70 | |
| 2a9592c | | | 71 | function persistRoom(owner, repo) { |
| 2a9592c | | | 72 | const key = roomKey(owner, repo); |
| 2a9592c | | | 73 | const room = rooms[key]; |
| bdb18c9 | | | 74 | if (!room) return; |
| 2a9592c | | | 75 | const dir = repoDataDir(owner, repo); |
| 2a9592c | | | 76 | fs.mkdirSync(dir, { recursive: true }); |
| 2a9592c | | | 77 | const filePath = path.join(dir, "notes.json"); |
| be59e71 | | | 78 | fsp.writeFile(filePath, JSON.stringify(room.notes, null, 2)).catch((e) => |
| be59e71 | | | 79 | console.error(`[persist] Failed to write ${filePath}:`, e.message) |
| be59e71 | | | 80 | ); |
| bdb18c9 | | | 81 | } |
| bdb18c9 | | | 82 | |
| 2a9592c | | | 83 | function loadRoom(owner, repo) { |
| 2a9592c | | | 84 | const filePath = path.join(repoDataDir(owner, repo), "notes.json"); |
| bdb18c9 | | | 85 | if (fs.existsSync(filePath)) { |
| bdb18c9 | | | 86 | try { |
| bdb18c9 | | | 87 | return JSON.parse(fs.readFileSync(filePath, "utf-8")); |
| bdb18c9 | | | 88 | } catch { |
| bdb18c9 | | | 89 | return {}; |
| bdb18c9 | | | 90 | } |
| bdb18c9 | | | 91 | } |
| bdb18c9 | | | 92 | return {}; |
| bdb18c9 | | | 93 | } |
| bdb18c9 | | | 94 | |
| bdb18c9 | | | 95 | // ── Yjs document management ── |
| 2a9592c | | | 96 | function getYDoc(owner, repo, diagramId) { |
| 2a9592c | | | 97 | const key = roomKey(owner, repo); |
| 2a9592c | | | 98 | const room = getRoom(key); |
| bdb18c9 | | | 99 | if (!room.ydocs[diagramId]) { |
| bdb18c9 | | | 100 | const ydoc = new Y.Doc(); |
| bdb18c9 | | | 101 | room.ydocs[diagramId] = ydoc; |
| 2a9592c | | | 102 | const yFilePath = path.join(repoDataDir(owner, repo), `ydoc_${safeId(diagramId)}.bin`); |
| bdb18c9 | | | 103 | if (fs.existsSync(yFilePath)) { |
| bdb18c9 | | | 104 | try { |
| bdb18c9 | | | 105 | const data = fs.readFileSync(yFilePath); |
| bdb18c9 | | | 106 | Y.applyUpdate(ydoc, new Uint8Array(data)); |
| bdb18c9 | | | 107 | } catch (e) { |
| bdb18c9 | | | 108 | console.error(`[yjs] Failed to load ${yFilePath}:`, e.message); |
| bdb18c9 | | | 109 | } |
| bdb18c9 | | | 110 | } |
| bdb18c9 | | | 111 | } |
| bdb18c9 | | | 112 | return room.ydocs[diagramId]; |
| bdb18c9 | | | 113 | } |
| bdb18c9 | | | 114 | |
| 2a9592c | | | 115 | function persistYDoc(owner, repo, diagramId) { |
| 2a9592c | | | 116 | const key = roomKey(owner, repo); |
| 2a9592c | | | 117 | const room = rooms[key]; |
| bdb18c9 | | | 118 | if (!room || !room.ydocs[diagramId]) return; |
| bdb18c9 | | | 119 | const ydoc = room.ydocs[diagramId]; |
| 2a9592c | | | 120 | const dir = repoDataDir(owner, repo); |
| 2a9592c | | | 121 | fs.mkdirSync(dir, { recursive: true }); |
| 2a9592c | | | 122 | const yFilePath = path.join(dir, `ydoc_${safeId(diagramId)}.bin`); |
| bdb18c9 | | | 123 | const state = Y.encodeStateAsUpdate(ydoc); |
| be59e71 | | | 124 | fsp.writeFile(yFilePath, Buffer.from(state)).catch((e) => |
| be59e71 | | | 125 | console.error(`[persist] Failed to write ${yFilePath}:`, e.message) |
| be59e71 | | | 126 | ); |
| bdb18c9 | | | 127 | } |
| bdb18c9 | | | 128 | |
| 2a9592c | | | 129 | // ── Repo access control (delegated to grove-api) ── |
| 2a9592c | | | 130 | const accessCache = new Map(); |
| 2a9592c | | | 131 | const ACCESS_CACHE_TTL = 60 * 1000; |
| 2a9592c | | | 132 | |
| 2a9592c | | | 133 | async function canAccessRepo(owner, repo, token) { |
| 515cc68 | | | 134 | const cacheKey = `${token ? token.slice(-8) : "anon"}:${owner}/${repo}`; |
| 2a9592c | | | 135 | const cached = accessCache.get(cacheKey); |
| 2a9592c | | | 136 | if (cached && cached.expiresAt > Date.now()) return cached.allowed; |
| 2a9592c | | | 137 | try { |
| 515cc68 | | | 138 | const headers = token ? { Authorization: `Bearer ${token}` } : {}; |
| 2a9592c | | | 139 | const res = await fetch(`${GROVE_API_URL}/api/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`, { |
| 515cc68 | | | 140 | headers, |
| 2a9592c | | | 141 | }); |
| 2a9592c | | | 142 | const allowed = res.ok; |
| 2a9592c | | | 143 | accessCache.set(cacheKey, { allowed, expiresAt: Date.now() + ACCESS_CACHE_TTL }); |
| 2a9592c | | | 144 | return allowed; |
| 2a9592c | | | 145 | } catch (e) { |
| 2a9592c | | | 146 | console.error(`[access] Failed to check repo access:`, e.message); |
| 2a9592c | | | 147 | return false; |
| 2a9592c | | | 148 | } |
| 2a9592c | | | 149 | } |
| 2a9592c | | | 150 | |
| 2a9592c | | | 151 | // ── REST API (authenticated, repo-scoped) ── |
| 2a9592c | | | 152 | |
| 515cc68 | | | 153 | app.get("/api/repos/:owner/:repo/diagrams", optionalAuth, async (req, res) => { |
| 2a9592c | | | 154 | const { owner, repo } = req.params; |
| 2a9592c | | | 155 | if (!(await canAccessRepo(owner, repo, req.token))) { |
| 2a9592c | | | 156 | return res.status(404).json({ error: "Not found" }); |
| 2a9592c | | | 157 | } |
| 2a9592c | | | 158 | res.json(loadDiagrams(owner, repo)); |
| 2a9592c | | | 159 | }); |
| 2a9592c | | | 160 | |
| 2a9592c | | | 161 | app.get("/api/repos/:owner/:repo/notes", requireAuth, async (req, res) => { |
| 2a9592c | | | 162 | const { owner, repo } = req.params; |
| 2a9592c | | | 163 | if (!(await canAccessRepo(owner, repo, req.token))) { |
| 2a9592c | | | 164 | return res.status(404).json({ error: "Not found" }); |
| 2a9592c | | | 165 | } |
| 2a9592c | | | 166 | const room = getRoom(roomKey(owner, repo)); |
| bdb18c9 | | | 167 | res.json(room.notes); |
| bdb18c9 | | | 168 | }); |
| bdb18c9 | | | 169 | |
| 2a9592c | | | 170 | app.get("/api/repos/:owner/:repo/notes/llm", requireAuth, async (req, res) => { |
| 2a9592c | | | 171 | const { owner, repo } = req.params; |
| 2a9592c | | | 172 | if (!(await canAccessRepo(owner, repo, req.token))) { |
| 2a9592c | | | 173 | return res.status(404).json({ error: "Not found" }); |
| 2a9592c | | | 174 | } |
| 2a9592c | | | 175 | const room = getRoom(roomKey(owner, repo)); |
| 2a9592c | | | 176 | const repoName = `${owner}/${repo}`; |
| bdb18c9 | | | 177 | const timestamp = new Date().toISOString(); |
| 2a9592c | | | 178 | let output = `# Diagram Review Notes\n# Repo: ${repoName}\n# Exported: ${timestamp}\n\n`; |
| bdb18c9 | | | 179 | |
| bdb18c9 | | | 180 | for (const [diagramId, notes] of Object.entries(room.notes)) { |
| bdb18c9 | | | 181 | if (notes.length === 0) continue; |
| bdb18c9 | | | 182 | const diagramTitle = notes[0]?.diagramTitle || diagramId; |
| bdb18c9 | | | 183 | output += `## ${diagramTitle} (${diagramId})\n\n`; |
| bdb18c9 | | | 184 | for (const note of notes) { |
| bdb18c9 | | | 185 | const location = note.targetNode |
| bdb18c9 | | | 186 | ? ` [on: ${note.targetNode}]` |
| bdb18c9 | | | 187 | : note.x != null ? ` [pinned at (${Math.round(note.x)}, ${Math.round(note.y)})]` : ""; |
| bdb18c9 | | | 188 | output += `- **${note.author}** (${note.timestamp})${location}: ${note.text}\n`; |
| bdb18c9 | | | 189 | } |
| bdb18c9 | | | 190 | output += "\n"; |
| bdb18c9 | | | 191 | } |
| bdb18c9 | | | 192 | |
| 2a9592c | | | 193 | const filename = `collab-notes-${safeId(owner)}-${safeId(repo)}-${timestamp.slice(0, 10)}.md`; |
| bdb18c9 | | | 194 | res.setHeader("Content-Disposition", `attachment; filename="${filename}"`); |
| bdb18c9 | | | 195 | res.type("text/markdown").send(output); |
| bdb18c9 | | | 196 | }); |
| bdb18c9 | | | 197 | |
| 922dd18 | | | 198 | // Proxy repo list from grove-api for the homepage |
| 515cc68 | | | 199 | app.get("/api/repos", optionalAuth, async (req, res) => { |
| 922dd18 | | | 200 | try { |
| 515cc68 | | | 201 | const headers = req.token ? { Authorization: `Bearer ${req.token}` } : {}; |
| 515cc68 | | | 202 | const apiRes = await fetch(`${GROVE_API_URL}/api/repos`, { headers }); |
| 922dd18 | | | 203 | if (!apiRes.ok) return res.status(apiRes.status).json({ repos: [] }); |
| 922dd18 | | | 204 | const data = await apiRes.json(); |
| 922dd18 | | | 205 | res.json(data); |
| 922dd18 | | | 206 | } catch (e) { |
| 922dd18 | | | 207 | console.error("[proxy] Failed to fetch repos:", e.message); |
| 922dd18 | | | 208 | res.status(502).json({ repos: [] }); |
| 922dd18 | | | 209 | } |
| 922dd18 | | | 210 | }); |
| 922dd18 | | | 211 | |
| 922dd18 | | | 212 | // Homepage |
| 922dd18 | | | 213 | app.get("/", (req, res) => { |
| 922dd18 | | | 214 | res.sendFile(path.join(__dirname, "public", "index.html")); |
| 922dd18 | | | 215 | }); |
| 922dd18 | | | 216 | |
| 2a9592c | | | 217 | // SPA catch-all: serve index.html for /:owner/:repo routes |
| 2a9592c | | | 218 | app.get("/:owner/:repo", (req, res) => { |
| 2a9592c | | | 219 | res.sendFile(path.join(__dirname, "public", "index.html")); |
| 1e755c0 | | | 220 | }); |
| 1e755c0 | | | 221 | |
| bf6031c | | | 222 | // 404 catch-all |
| bf6031c | | | 223 | app.use((req, res) => { |
| bf6031c | | | 224 | res.status(404).sendFile(path.join(__dirname, "public", "404.html")); |
| bf6031c | | | 225 | }); |
| bf6031c | | | 226 | |
| 2a9592c | | | 227 | // ── Socket.IO collab namespace (authenticated) ── |
| be59e71 | | | 228 | const collabNs = io.of("/collab"); |
| 2a9592c | | | 229 | collabNs.use(socketAuth); |
| be59e71 | | | 230 | |
| be59e71 | | | 231 | collabNs.on("connection", (socket) => { |
| 2a9592c | | | 232 | let currentOwner = null; |
| 2a9592c | | | 233 | let currentRepo = null; |
| bdb18c9 | | | 234 | let userName = null; |
| bdb18c9 | | | 235 | |
| 2a9592c | | | 236 | socket.on("join-room", async ({ owner, repo }) => { |
| 2a9592c | | | 237 | // Verify repo access |
| 2a9592c | | | 238 | const allowed = await canAccessRepo(owner, repo, socket.token); |
| 2a9592c | | | 239 | if (!allowed) { |
| 2a9592c | | | 240 | socket.emit("error", { message: "Access denied" }); |
| 2a9592c | | | 241 | return; |
| 2a9592c | | | 242 | } |
| 2a9592c | | | 243 | |
| 2a9592c | | | 244 | currentOwner = owner; |
| 2a9592c | | | 245 | currentRepo = repo; |
| 2a9592c | | | 246 | userName = socket.user.display_name || socket.user.username || `User-${socket.id.slice(0, 4)}`; |
| bdb18c9 | | | 247 | |
| 2a9592c | | | 248 | const key = roomKey(owner, repo); |
| 2a9592c | | | 249 | socket.join(key); |
| bdb18c9 | | | 250 | |
| 2a9592c | | | 251 | const room = getRoom(key); |
| bdb18c9 | | | 252 | // Load persisted notes if room is fresh |
| bdb18c9 | | | 253 | if (Object.keys(room.notes).length === 0) { |
| 2a9592c | | | 254 | room.notes = loadRoom(owner, repo); |
| bdb18c9 | | | 255 | } |
| bdb18c9 | | | 256 | |
| bdb18c9 | | | 257 | room.users[socket.id] = { |
| bdb18c9 | | | 258 | id: socket.id, |
| bdb18c9 | | | 259 | name: userName, |
| bdb18c9 | | | 260 | color: pickColor(room), |
| bdb18c9 | | | 261 | cursor: null, |
| bdb18c9 | | | 262 | activeTab: null, |
| bdb18c9 | | | 263 | }; |
| bdb18c9 | | | 264 | |
| bdb18c9 | | | 265 | // Send current state to the joining user |
| bdb18c9 | | | 266 | socket.emit("room-state", { |
| bdb18c9 | | | 267 | notes: room.notes, |
| bdb18c9 | | | 268 | users: room.users, |
| bdb18c9 | | | 269 | }); |
| bdb18c9 | | | 270 | |
| bdb18c9 | | | 271 | // Notify others |
| 2a9592c | | | 272 | collabNs.to(key).emit("users-updated", room.users); |
| bdb18c9 | | | 273 | }); |
| bdb18c9 | | | 274 | |
| bdb18c9 | | | 275 | // ── Yjs sync protocol over socket.io ── |
| bdb18c9 | | | 276 | socket.on("yjs-sync", ({ diagramId }) => { |
| 2a9592c | | | 277 | if (!currentOwner) return; |
| 2a9592c | | | 278 | const ydoc = getYDoc(currentOwner, currentRepo, diagramId); |
| bdb18c9 | | | 279 | const state = Y.encodeStateAsUpdate(ydoc); |
| bdb18c9 | | | 280 | socket.emit("yjs-sync", { diagramId, update: Buffer.from(state).toString("base64") }); |
| bdb18c9 | | | 281 | }); |
| bdb18c9 | | | 282 | |
| bdb18c9 | | | 283 | socket.on("yjs-update", ({ diagramId, update }) => { |
| 2a9592c | | | 284 | if (!currentOwner) return; |
| 2a9592c | | | 285 | const key = roomKey(currentOwner, currentRepo); |
| 2a9592c | | | 286 | const ydoc = getYDoc(currentOwner, currentRepo, diagramId); |
| bdb18c9 | | | 287 | const buf = Buffer.from(update, "base64"); |
| bdb18c9 | | | 288 | Y.applyUpdate(ydoc, new Uint8Array(buf)); |
| 2a9592c | | | 289 | socket.to(key).emit("yjs-update", { diagramId, update }); |
| 2a9592c | | | 290 | // Persist (debounced per diagram) |
| 2a9592c | | | 291 | const owner = currentOwner, repo = currentRepo; |
| bdb18c9 | | | 292 | clearTimeout(ydoc._persistTimer); |
| 2a9592c | | | 293 | ydoc._persistTimer = setTimeout(() => persistYDoc(owner, repo, diagramId), 2000); |
| bdb18c9 | | | 294 | }); |
| bdb18c9 | | | 295 | |
| bdb18c9 | | | 296 | socket.on("cursor-move", ({ x, y, activeTab }) => { |
| 2a9592c | | | 297 | if (!currentOwner) return; |
| 2a9592c | | | 298 | const key = roomKey(currentOwner, currentRepo); |
| 2a9592c | | | 299 | const room = getRoom(key); |
| bdb18c9 | | | 300 | if (room.users[socket.id]) { |
| bdb18c9 | | | 301 | room.users[socket.id].cursor = { x, y }; |
| bdb18c9 | | | 302 | room.users[socket.id].activeTab = activeTab; |
| bdb18c9 | | | 303 | } |
| 2a9592c | | | 304 | socket.to(key).emit("cursor-updated", { |
| bdb18c9 | | | 305 | userId: socket.id, |
| bdb18c9 | | | 306 | x, |
| bdb18c9 | | | 307 | y, |
| bdb18c9 | | | 308 | activeTab, |
| bdb18c9 | | | 309 | name: userName, |
| bdb18c9 | | | 310 | color: room.users[socket.id]?.color, |
| bdb18c9 | | | 311 | }); |
| bdb18c9 | | | 312 | }); |
| bdb18c9 | | | 313 | |
| bdb18c9 | | | 314 | socket.on("add-note", (note) => { |
| 2a9592c | | | 315 | if (!currentOwner) return; |
| 2a9592c | | | 316 | const key = roomKey(currentOwner, currentRepo); |
| 2a9592c | | | 317 | const room = getRoom(key); |
| bdb18c9 | | | 318 | const diagramId = note.diagramId; |
| bdb18c9 | | | 319 | if (!room.notes[diagramId]) room.notes[diagramId] = []; |
| bdb18c9 | | | 320 | |
| bdb18c9 | | | 321 | const fullNote = { |
| bdb18c9 | | | 322 | id: `${Date.now()}-${Math.random().toString(36).slice(2, 7)}`, |
| bdb18c9 | | | 323 | author: userName, |
| bdb18c9 | | | 324 | text: note.text, |
| bdb18c9 | | | 325 | x: note.x, |
| bdb18c9 | | | 326 | y: note.y, |
| bdb18c9 | | | 327 | diagramId, |
| bdb18c9 | | | 328 | diagramTitle: note.diagramTitle || diagramId, |
| bdb18c9 | | | 329 | targetNode: note.targetNode || null, |
| bdb18c9 | | | 330 | timestamp: new Date().toISOString(), |
| bdb18c9 | | | 331 | }; |
| bdb18c9 | | | 332 | |
| bdb18c9 | | | 333 | room.notes[diagramId].push(fullNote); |
| 2a9592c | | | 334 | persistRoom(currentOwner, currentRepo); |
| 2a9592c | | | 335 | collabNs.to(key).emit("note-added", fullNote); |
| bdb18c9 | | | 336 | }); |
| bdb18c9 | | | 337 | |
| bdb18c9 | | | 338 | socket.on("edit-note", ({ noteId, diagramId, text }) => { |
| 2a9592c | | | 339 | if (!currentOwner) return; |
| 2a9592c | | | 340 | const key = roomKey(currentOwner, currentRepo); |
| 2a9592c | | | 341 | const room = getRoom(key); |
| bdb18c9 | | | 342 | const notes = room.notes[diagramId]; |
| bdb18c9 | | | 343 | if (!notes) return; |
| bdb18c9 | | | 344 | const note = notes.find((n) => n.id === noteId); |
| bdb18c9 | | | 345 | if (!note) return; |
| bdb18c9 | | | 346 | note.text = text; |
| bdb18c9 | | | 347 | note.editedAt = new Date().toISOString(); |
| 2a9592c | | | 348 | persistRoom(currentOwner, currentRepo); |
| 2a9592c | | | 349 | collabNs.to(key).emit("note-edited", { noteId, diagramId, text, editedAt: note.editedAt }); |
| bdb18c9 | | | 350 | }); |
| bdb18c9 | | | 351 | |
| bdb18c9 | | | 352 | socket.on("diagram-code", ({ diagramId, code }) => { |
| 2a9592c | | | 353 | if (!currentOwner) return; |
| 2a9592c | | | 354 | const key = roomKey(currentOwner, currentRepo); |
| 2a9592c | | | 355 | socket.to(key).emit("diagram-code", { diagramId, code, userId: socket.id }); |
| bdb18c9 | | | 356 | }); |
| bdb18c9 | | | 357 | |
| bdb18c9 | | | 358 | socket.on("delete-note", ({ noteId, diagramId }) => { |
| 2a9592c | | | 359 | if (!currentOwner) return; |
| 2a9592c | | | 360 | const key = roomKey(currentOwner, currentRepo); |
| 2a9592c | | | 361 | const room = getRoom(key); |
| bdb18c9 | | | 362 | if (!room.notes[diagramId]) return; |
| bdb18c9 | | | 363 | room.notes[diagramId] = room.notes[diagramId].filter((n) => n.id !== noteId); |
| 2a9592c | | | 364 | persistRoom(currentOwner, currentRepo); |
| 2a9592c | | | 365 | collabNs.to(key).emit("note-deleted", { noteId, diagramId }); |
| bdb18c9 | | | 366 | }); |
| bdb18c9 | | | 367 | |
| bdb18c9 | | | 368 | socket.on("disconnect", () => { |
| 2a9592c | | | 369 | if (!currentOwner) return; |
| 2a9592c | | | 370 | const key = roomKey(currentOwner, currentRepo); |
| 2a9592c | | | 371 | const room = getRoom(key); |
| bdb18c9 | | | 372 | delete room.users[socket.id]; |
| 2a9592c | | | 373 | collabNs.to(key).emit("users-updated", room.users); |
| 2a9592c | | | 374 | collabNs.to(key).emit("cursor-removed", { userId: socket.id }); |
| bdb18c9 | | | 375 | }); |
| bdb18c9 | | | 376 | }); |
| bdb18c9 | | | 377 | |
| bdb18c9 | | | 378 | const USER_COLORS = [ |
| bdb18c9 | | | 379 | "#e74c3c", "#3498db", "#2ecc71", "#f39c12", "#9b59b6", |
| bdb18c9 | | | 380 | "#1abc9c", "#e67e22", "#e84393", "#00b894", "#6c5ce7", |
| bdb18c9 | | | 381 | ]; |
| bdb18c9 | | | 382 | |
| bdb18c9 | | | 383 | function pickColor(room) { |
| bdb18c9 | | | 384 | const used = new Set(Object.values(room.users).map(u => u.color)); |
| bdb18c9 | | | 385 | for (const c of USER_COLORS) { |
| bdb18c9 | | | 386 | if (!used.has(c)) return c; |
| bdb18c9 | | | 387 | } |
| bdb18c9 | | | 388 | const counts = {}; |
| bdb18c9 | | | 389 | for (const c of USER_COLORS) counts[c] = 0; |
| bdb18c9 | | | 390 | for (const u of Object.values(room.users)) { |
| bdb18c9 | | | 391 | if (counts[u.color] != null) counts[u.color]++; |
| bdb18c9 | | | 392 | } |
| bdb18c9 | | | 393 | return USER_COLORS.reduce((a, b) => counts[a] <= counts[b] ? a : b); |
| bdb18c9 | | | 394 | } |
| bdb18c9 | | | 395 | |
| bdb18c9 | | | 396 | // Live reload: watch public/ for changes and notify all connected clients |
| bdb18c9 | | | 397 | const PUBLIC_DIR = path.join(__dirname, "public"); |
| bdb18c9 | | | 398 | fs.watch(PUBLIC_DIR, { recursive: true }, (eventType, filename) => { |
| bdb18c9 | | | 399 | if (!filename) return; |
| bdb18c9 | | | 400 | console.log(`[hot-reload] ${filename} changed`); |
| bdb18c9 | | | 401 | io.emit("hot-reload", { file: filename }); |
| bdb18c9 | | | 402 | }); |
| bdb18c9 | | | 403 | |
| bdb18c9 | | | 404 | server.listen(PORT, () => { |
| 2a9592c | | | 405 | console.log(`Grove Collab running on http://localhost:${PORT}`); |
| bdb18c9 | | | 406 | }); |