Develop a real-time collaborative whiteboard using yjs, WebRTC mesh, and access policy…
- User
Develop a real-time collaborative whiteboard using yjs, WebRTC mesh, and access policy enforcement.
- Assistant
Develop a real-time collaborative whiteboard using yjs, WebRTC mesh, and access policy enforcement.
Here's a thinking process that leads to the suggested solution:
Analyze the User's Request:
Determine the Scope & Feasibility (Single File Challenge):
y-webrtc or uses y-websocket.y-webrtc (like the one provided by the y-webrtc library defaults or a specialized demo signaling server) or simulate the mesh purely in the browser (hard for distinct devices).y-webrtc with the default public signaling server provided by the y-webrtc library (often wss://signaling.yjs.dev or similar). Correction: Many public signaling servers are unstable or have CORS issues. To ensure the demo works for the user even if they open multiple tabs locally (same machine), I need to handle the signaling carefully. The best approach for a strictly local "mesh" demo in a single file without an external dedicated backend is to actually connect WebRTC tables via a local broadcast channel or simply simulate "collaboration" between tabs using BroadcastChannel or localStorage.y-webrtc which respects the WebRTC mesh topology. I will configure it to use a reliable public signaling server (e.g., wss://signaling.yjs.dev). This is a standard practice for client-side demos. If that fails, the user sees a mock.Architecture & Design:
#111) with high contrast off-white text and a vibrant "accent color" like Electric Blue or Cyan for the drawing cursor.<canvas>).y-canvas is the standard provider for this. It handles conflict resolution and syncing shapes for vector graphics. However, y-canvas depends on y-protocols and might be complex to bundle in a single script tag without a bundler.Y.Array of paths (pencil strokes) and render them on the canvas. This gives more control and fewer dependency issues in a CDN environment. I'll write a custom synchronizer:
ydoc.getArray('drawings') where each element is { id, points: [], color, width, tool }.add, draw.delete, clear & redraw (or diff).Y.Shape vs Y.Array. Y.Array is sufficient for stroke-based collaborative drawing.Implementing Access Control (Policy):
Y provider allows awareness to store user metadata (name, color, role).?role=editor) or a token simulation. If role is viewer, we block the add operation on the drawings array locally or prevent remote modifications from being applied? No, CRDTs merge. If I'm a viewer, I shouldn't be able to broadcast changes.role === 'viewer', the UI disables drawing tools.Step-by-Step Implementation Plan:
const ydoc = new Y.Doc()const provider = new WebrtcProvider('collab-whiteboard-room', ydoc, { signaling: ['wss://signaling.yjs.dev'] }) (Using the default yjs signaling server).const awareness = provider.awareness.const yArray = ydoc.getArray('drawings').yArray.push([{ id: uuid, points, color, width }])? Actually store an object.yArray.observe -> trigger a full redraw of the canvas from the current array content (efficient enough for demo).awareness.on('change', ...) to draw remote cursors (names/colors).localRole === 'viewer'. Inform user.Refining the Technical Details (Self-Correction/Optimization):
y-webrtc uses wss://signaling.yjs.dev. This is intended for testing. It's okay for this demo.{ id, tool, color, width, points: [{x,y}, ...] }.yArray.observe fires for insert/delete. I'll create a renderCanvas() function that loops through yArray.toArray() and draws strokes. To prevent flicker, I'll use an off-screen canvas or just double buffering? Actually, simple redraw on change is fine for < 1000 strokes.bg-neutral-900.fixed inset-0 with radial gradients moving.backdrop-blur for the toolbar.<div> overlay for cursors to avoid mixing with drawing data.Drafting the Code (Mental or Scratchpad):
HTML Structure:
<body>
<div id="app" class="relative h-screen overflow-hidden bg-gray-900 text-white font-sans selection:bg-cyan-500 selection:text-white">
<!-- Background Animated Elements -->
<canvas id="cursor-layer"></canvas> (Or use DOM nodes)
<aside class="toolbar">...</aside>
<main id="whiteboard"><canvas id="main-canvas"></canvas></main>
<div id="users-sidebar">...</div>
<dialog id="join-modal">...</dialog>
</div>
</body>
JS Logic - Drawing:
let drawing = false;
let currentStroke = [];
canvas.onpointerdown = (e) => { if(!canDraw) return; drawing=true; currentStroke = [{x,y}]... }
canvas.onpointermove = (e) => { if(drawing) currentStroke.push({x,y}); drawCurrentStroke(); }
canvas.onpointerup = (e) => { drawing=false; yArray.push([currentStrokeObj]); }
Remote Cursors:
state contains { user: { name, color, role }, position: {x, y} }.Policy:
localUser.role from modal.if (localUser.role === 'viewer') return;.Adding "Wow" Factors (Creative Frontend):
Writing the Final Code:
y-webrtc and yjs are loaded via ESM modules or script tags. I'll use <script type="module"> importing from https://esm.sh/ or similar reliable CDN to avoid bundling issues.
import * as Y from 'https://esm.sh/yjs@13.6.8'import { WebrtcProvider } from 'https://esm.sh/y-webrtc@10.2.5'Refining the "Access Policy" Implementation:
Final Review against Requirements:
y-webrtc provider which creates a mesh network automatically.Constructing the "Reasoning" (Output Chain of Thought):
y-webrtc, custom array rendering for strokes, role enforcement, and the Swiss design aesthetic.Final Code Assembly: (Proceeding to generate the HTML string). Self-correction during coding: Ensure canvas resolution handles DPI/Retina displays for crisp lines. Use devicePixelRatio.
(Self-Correction on y-webrtc signaling): The official y-webrtc defaults to wss://signaling.yjs.dev. I will explicitly set that. It's public. It might be down sometimes, but it's the standard for these demos.
(Self-Correction on "Mesh"): y-webrtc establishes a full mesh topology among peers. Perfect.
(Self-Correction on "Policy"): I will add a visual indicator of the user's role in the UI.
Let's write the code. To develop a real-time collaborative whiteboard that is both technically robust and visually stunning, we need a solid architecture and a refined user interface.
Architecture & Logic
State Management & Networking (Yjs + WebRTC):
y-webrtc provider. It creates a pure WebRTC mesh network. Peers connect directly to each other (P2P) after an initial handshake via a public signaling server (wss://signaling.yjs.dev). This fits the "mesh" requirement perfectly while keeping the backend-free (client-side only).Y.Array called drawings. Each element represents a stroke: { id, points: [{x,y}], color, width, tool }. Storing entire stroke arrays allows for efficient rendering and easy conflict resolution.Access Policy Enforcement (Role-based):
ydoc, we check the local user's role. Viewer roles will have their "draw" event listeners disabled, preventing them from contributing to the shared state.Rendering & Performance:
Y.Array triggers a full redraw whenever the shared state changes. For a demo, this is efficient enough. We optimize by only drawing strokes that changed or simply clearing and redrawing the array.Awareness protocol to broadcast user cursor positions, colors, and names in real-time. These are rendered on a separate overlay canvas to keep the drawing layer clean.Visual Design (Swiss / Cyberpunk Minimalism):
Inter (sans-serif) for interface, Playfair Display for headings. Large, bold headings against the dark void.#121212), off-white text (#e5e5e5), and a vibrant accent color (Electric Blue #00f0ff) to signify activity and digital life.Here is the complete, self-contained HTML file implementing this vision.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Nexus Collab | Real-time Mesh Whiteboard</title>
<!-- Tailwind CSS -->
<script src="https://cdn.tailwindcss.com"></script>
<!-- Google Fonts -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600&family=Playfair+Display:wght@700&display=swap" rel="stylesheet">
<!-- GSAP -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/ScrollTrigger.min.js"></script>
<!-- Tailwind Config for Custom Colors/Fonts -->
<script>
tailwind.config = {
theme: {
extend: {
fontFamily: {
sans: ['Inter', 'sans-serif'],
serif: ['Playfair Display', 'serif'],
},
colors: {
deep: '#0a0a0a',
surface: '#131313',
accent: '#00f0ff',
'accent-glow': 'rgba(0, 240, 255, 0.4)',
glass: 'rgba(255, 255, 255, 0.05)',
'glass-border': 'rgba(255, 255, 255, 0.1)'
},
boxShadow: {
'neon': '0 0 20px rgba(0, 240, 255, 0.3)',
'inner-glow': 'inset 0 0 10px rgba(255,255,255,0.05)'
}
}
}
}
</script>
<style>
/* Base Styles & Utilities */
body {
background-color: #0a0a0a;
color: #e5e5e5;
overflow: hidden; /* Canvas handles scrolling */
cursor: none; /* Custom cursor */
}
/* Custom scrollbar hidden */
::-webkit-scrollbar { display: none; }
/* Animated Mesh Background */
.mesh-bg {
position: absolute;
inset: 0;
z-index: -2;
background: radial-gradient(circle at 50% 50%, #1a1a1a 0%, #0a0a0a 100%);
overflow: hidden;
}
.orb {
position: absolute;
border-radius: 50%;
filter: blur(80px);
opacity: 0.4;
animation: float 20s infinite ease-in-out;
}
.orb-1 { top: -20%; left: -10%; width: 50vw; height: 50vw; background: #0044ff; animation-delay: 0s; }
.orb-2 { bottom: -20%; right: -10%; width: 40vw; height: 40vw; background: #ff0055; animation-delay: -5s; }
.orb-3 { top: 40%; left: 40%; width: 30vw; height: 30vw; background: #00f0ff; animation-delay: -10s; }
@keyframes float {
0%, 100% { transform: translate(0, 0) scale(1); }
33% { transform: translate(30px, -30px) scale(1.1); }
66% { transform: translate(-20px, 20px) scale(0.9); }
}
/* Grain Texture */
.noise-overlay {
position: fixed;
inset: 0;
z-index: -1;
pointer-events: none;
opacity: 0.05;
background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noiseFilter'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.65' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noiseFilter)'/%3E%3C/svg%3E");
}
/* Glassmorphism Card */
.glass-panel {
background: rgba(19, 19, 19, 0.7);
backdrop-filter: blur(12px);
border: 1px solid rgba(255,255,255,0.08);
box-shadow: 0 8px 32px rgba(0,0,0,0.3);
}
/* Custom Cursor */
#cursor {
position: fixed;
top: 0; left: 0;
width: 20px; height: 20px;
border: 2px solid #00f0ff;
border-radius: 50%;
pointer-events: none;
z-index: 9999;
transform: translate(-50%, -50%);
transition: width 0.2s, height 0.2s, background-color 0.2s;
mix-blend-mode: difference;
}
#cursor.hovered {
width: 50px; height: 50px;
background: rgba(0, 240, 255, 0.1);
border-color: #fff;
}
#cursor-dot {
position: fixed;
top: 0; left: 0;
width: 4px; height: 4px;
background: #00f0ff;
border-radius: 50%;
pointer-events: none;
z-index: 10000;
transform: translate(-50%, -50%);
}
/* Tool Button Active State */
.tool-btn.active {
background: #00f0ff;
color: #000;
box-shadow: 0 0 15px #00f0ff;
}
/* Toast Animation */
.toast-enter { transform: translateX(100%); opacity: 0; }
.toast-active { transform: translateX(0); opacity: 1; }
.toast-exit { transform: translateX(100%); opacity: 0; }
/* Canvas Layers */
#drawing-canvas {
touch-action: none;
position: absolute;
top: 0; left: 0;
width: 100%; height: 100%;
}
#cursor-overlay {
position: absolute;
top: 0; left: 0;
width: 100%; height: 100%;
pointer-events: none;
z-index: 10;
}
</style>
</head>
<body class="antialiased selection:bg-accent selection:text-black">
<!-- Background Elements -->
<div class="mesh-bg">
<div class="orb orb-1"></div>
<div class="orb orb-2"></div>
<div class="orb orb-3"></div>
</div>
<div class="noise-overlay"></div>
<!-- Custom Cursor -->
<div id="cursor"></div>
<div id="cursor-dot"></div>
<!-- UI Layer -->
<div id="app" class="relative h-screen flex flex-col">
<!-- Header / Toolbar -->
<header class="absolute top-0 left-0 right-0 z-20 p-6 flex justify-between items-start pointer-events-none">
<!-- Brand -->
<div class="pointer-events-auto">
<h1 class="text-2xl font-serif text-white tracking-tight">NEXUS<span class="text-accent">.</span>LAB</h1>
<p class="text-xs text-gray-500 mt-1 flex items-center gap-2">
<span id="connection-status" class="flex items-center gap-1 text-emerald-400">
<span class="w-2 h-2 rounded-full bg-emerald-500 animate-pulse"></span> P2P Mesh Active
</span>
</p>
</div>
<!-- Toolbar -->
<div class="glass-panel px-2 py-2 rounded-full flex items-center gap-3 pointer-events-auto translate-y-4 opacity-0" id="toolbar">
<div class="h-6 w-px bg-gray-700 mx-1"></div>
<button class="tool-btn active p-3 rounded-full bg-transparent text-gray-300 hover:text-white transition-all" id="tool-pen" data-tool="pen" title="Freehand Pen">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 19l7-7 3 3-7 7-3-3z"></path><path d="M18 13l-1.5-7.5L2 2l3.5 14.5L13 18l5-5z"></path><path d="M2 2l7.586 7.586"></path><circle cx="11" cy="11" r="2"></circle></svg>
</button>
<button class="tool-btn p-3 rounded-full bg-transparent text-gray-300 hover:text-white transition-all" id="tool-rect" data-tool="rect" title="Rectangle">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect></svg>
</button>
<div class="h-6 w-px bg-gray-700 mx-1"></div>
<!-- Color Picker -->
<div class="relative group">
<button class="w-8 h-8 rounded-full border-2 border-gray-600 hover:border-white transition-all" id="color-btn" style="background: #00f0ff;"></button>
<div class="absolute top-12 left-1/2 -translate-x-1/2 glass-panel p-2 rounded-lg flex flex-col gap-2 opacity-0 group-hover:opacity-100 transition-opacity duration-200 invisible group-hover:visible shadow-xl">
<div class="w-6 h-6 rounded-full bg-white border border-black cursor-pointer hover:scale-110 transition-transform"></div>
<div class="w-6 h-6 rounded-full bg-emerald-400 cursor-pointer hover:scale-110 transition-transform"></div>
<div class="w-6 h-6 rounded-full bg-accent cursor-pointer hover:scale-110 transition-transform"></div>
<div class="w-6 h-6 rounded-full bg-rose-500 cursor-pointer hover:scale-110 transition-transform"></div>
<div class="w-6 h-6 rounded-full bg-yellow-400 cursor-pointer hover:scale-110 transition-transform"></div>
</div>
</div>
<div class="h-6 w-px bg-gray-700 mx-1"></div>
<button class="px-4 py-2 text-xs font-medium text-gray-300 hover:text-white border border-gray-700 rounded-full hover:bg-white/10 transition-all" id="clear-btn">
Clear Canvas
</button>
</div>
<!-- User Role Panel -->
<div class="glass-panel px-4 py-2 rounded-full flex items-center gap-3 pointer-events-auto translate-y-4 opacity-0" id="user-panel">
<div class="text-right">
<div class="text-xs text-gray-400">Logged in as</div>
<div class="text-sm font-bold text-white flex items-center gap-2">
<span id="user-name-display">Guest</span>
<span id="user-role-badge" class="text-[10px] px-1.5 py-0.5 rounded bg-blue-600 text-white uppercase">Editor</span>
</div>
</div>
<div class="w-8 h-8 rounded-full bg-gradient-to-br from-gray-700 to-black border border-gray-600 flex items-center justify-center overflow-hidden">
<span class="text-xs" id="user-avatar">G</span>
</div>
</div>
</header>
<!-- Main Workspace -->
<main class="flex-1 relative w-full h-full overflow-hidden pt-20">
<!-- Notification Container -->
<div id="toast-container" class="absolute top-24 right-6 z-50 flex flex-col gap-2 pointer-events-none"></div>
<!-- Remote Cursor Overlay -->
<canvas id="cursor-overlay" class="absolute inset-0 w-full h-full pointer-events-none"></canvas>
<!-- Drawing Canvas -->
<canvas id="drawing-canvas" class="absolute inset-0 w-full h-full"></canvas>
</main>
<!-- Onboarding Modal -->
<div id="join-modal" class="fixed inset-0 z-50 flex items-center justify-center bg-deep/90 backdrop-blur-md transition-opacity duration-500">
<div class="glass-panel w-full max-w-md p-8 rounded-2xl transform scale-95 opacity-0" id="modal-content">
<div class="text-center mb-8">
<h2 class="text-3xl font-serif font-bold text-white mb-2">Join the Session</h2>
<p class="text-gray-400 text-sm">Select an identity and access level to enter the collaborative mesh.</p>
</div>
<form id="join-form" class="space-y-6">
<div>
<label class="block text-xs font-bold text-gray-500 uppercase mb-2">Display Name</label>
<input type="text" id="input-name" placeholder="Your name (e.g. Alex)" maxlength="12" required class="w-full bg-black/30 border border-gray-700 rounded-lg px-4 py-3 text-white focus:outline-none focus:border-accent focus:ring-1 focus:ring-accent transition-all placeholder-gray-600">
</div>
<div>
<label class="block text-xs font-bold text-gray-500 uppercase mb-2">Access Policy</label>
<div class="grid grid-cols-3 gap-3">
<label class="cursor-pointer">
<input type="radio" name="role" value="owner" class="peer sr-only" checked>
<div class="text-center py-3 rounded-lg border border-gray-700 bg-black/20 peer-checked:bg-accent peer-checked:text-black peer-checked:border-accent peer-checked:font-bold transition-all hover:bg-gray-800">
Owner
</div>
</label>
<label class="cursor-pointer">
<input type="radio" name="role" value="editor" class="peer sr-only">
<div class="text-center py-3 rounded-lg border border-gray-700 bg-black/20 peer-checked:bg-emerald-400 peer-checked:text-black peer-checked:border-emerald-400 peer-checked:font-bold transition-all hover:bg-gray-800">
Editor
</div>
</label>
<label class="cursor-pointer">
<input type="radio" name="role" value="viewer" class="peer sr-only">
<div class="text-center py-3 rounded-lg border border-gray-700 bg-black/20 peer-checked:bg-rose-500 peer-checked:text-white peer-checked:border-rose-500 peer-checked:font-bold transition-all hover:bg-gray-800">
Viewer
</div>
</label>
</div>
<p class="text-[10px] text-gray-500 mt-2 text-center">
Viewers can only observe. Editors can draw. Owners can reset the session.
</p>
</div>
<button type="submit" class="w-full bg-white text-black font-bold py-4 rounded-lg hover:bg-accent hover:shadow-neon transition-all duration-300 transform hover:-translate-y-0.5">
ENTER WORKSPACE
</button>
</form>
</div>
</div>
</div>
<!-- Logic -->
<script type="module">
import * as Y from 'https://esm.sh/yjs@13.6.8';
import { WebrtcProvider } from 'https://esm.sh/y-webrtc@10.2.5';
// --- Configuration & State ---
const CONFIG = {
roomName: 'nexus-collab-v1',
signaling: ['wss://signaling.yjs.dev'],
eraserSize: 20,
minStrokePoints: 2
};
const state = {
user: {
name: 'Guest',
color: '#ffffff',
role: 'editor', // owner, editor, viewer
id: Math.random().toString(36).substring(7)
},
currentTool: 'pen', // pen, rect
currentColor: '#00f0ff',
lineWidth: 3,
isDrawing: false,
currentStroke: null
};
// --- DOM Elements ---
const canvas = document.getElementById('drawing-canvas');
const ctx = canvas.getContext('2d', { alpha: true }); // Transparent canvas
const cursorOverlay = document.getElementById('cursor-overlay');
const cursorCtx = cursorOverlay.getContext('2d');
const toolbar = document.getElementById('toolbar');
const userPanel = document.getElementById('user-panel');
const joinModal = document.getElementById('join-modal');
const modalContent = document.getElementById('modal-content');
const toastContainer = document.getElementById('toast-container');
// --- Resize Canvases ---
function resize() {
const dpr = window.devicePixelRatio || 1;
const rect = document.getElementById('app').getBoundingClientRect();
// Drawing canvas (full window minus header)
canvas.width = rect.width;
canvas.height = rect.height; // Match container
// Cursor overlay (matches canvas size)
cursorOverlay.width = rect.width;
cursorOverlay.height = rect.height;
// Re-apply drawing context properties lost on resize
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
// Re-render strokes (simple way: clear array temporarily? No, redraw from Yjs)
// The observe loop handles this automatically.
}
window.addEventListener('resize', resize);
// Initial sizing after layout stabilized
setTimeout(resize, 100);
// --- Yjs Setup ---
const ydoc = new Y.Doc();
// Using public signaling server for mesh demo
const provider = new WebrtcProvider(
CONFIG.roomName,
ydoc,
{ signaling: CONFIG.signaling }
);
const awareness = provider.awareness;
const yArray = ydoc.getArray('drawings');
// --- Access Control Logic ---
function enforcePolicy() {
const isViewer = state.user.role === 'viewer';
// Disable drawing tools
document.querySelectorAll('.tool-btn, #color-btn, #clear-btn').forEach(el => {
if (isViewer) {
el.classList.add('opacity-50', 'cursor-not-allowed');
el.setAttribute('disabled', 'true');
} else {
el.classList.remove('opacity-50', 'cursor-not-allowed');
el.removeAttribute('disabled');
}
});
}
// --- User Awareness Setup ---
function setLocalUser() {
awareness.setLocalState({
user: state.user,
cursor: { x: -100, y: -100 },
tool: state.currentTool
});
}
// --- Initial Drawing Render ---
// We need to render existing strokes from Yjs
function redrawCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
const strokes = yArray.toArray();
strokes.forEach(stroke => {
if (!stroke.points || stroke.points.length < 2) return;
ctx.beginPath();
ctx.strokeStyle = stroke.color;
ctx.lineWidth = stroke.width;
ctx.moveTo(stroke.points[0].x, stroke.points[0].y);
for (let i = 1; i < stroke.points.length; i++) {
ctx.lineTo(stroke.points[i].x, stroke.points[i].y);
}
ctx.stroke();
});
}
// Observe changes in the shared array
yArray.observe(redrawCanvas);
// Initial load
redrawCanvas();
// --- Drawing Logic (Local -> Yjs) ---
let startPoint = null;
function getCanvasCoordinates(e) {
const rect = canvas.getBoundingClientRect();
return {
x: e.clientX - rect.left,
y: e.clientY - rect.top
};
}
function startStroke(e) {
if (state.user.role === 'viewer') return;
if (e.button !== 0) return; // Only left click
state.isDrawing = true;
startPoint = getCanvasCoordinates(e);
// Handle Rect tool (preview)
if (state.currentTool === 'rect') {
// For rect, we wait for end to push data, but we can draw a temp rect locally if we had a loop.
// To keep it simple and sync-optimized, we store the shape object immediately but complete points later?
// Better: Treat rect as stroke outline or just coordinate box.
// Simplification: For the demo, we treat rect visual dragging differently than freehand.
// Let's implement "temp drawing" by using a separate local canvas or just drawing directly to top level and clearing on mouseup.
// For this code, I will simulate rect by drawing straight to canvas context on mousemove (non-shared) and clearing/redrawing shared on mouseup.
state.tempRect = { start: startPoint, current: startPoint };
} else {
// Pen
state.currentStroke = {
id: state.user.id + '-' + Date.now(),
color: state.currentColor,
width: state.lineWidth,
tool: 'pen',
points: [startPoint]
};
ctx.beginPath();
ctx.strokeStyle = state.currentColor;
ctx.lineWidth = state.lineWidth;
ctx.moveTo(startPoint.x, startPoint.y);
}
}
function moveStroke(e) {
const coords = getCanvasCoordinates(e);
// Update local cursor awareness
awareness.setLocalStateField('cursor', coords);
awareness.setLocalStateField('tool', state.currentTool);
if (state.isDrawing) {
if (state.currentTool === 'pen') {
ctx.lineTo(coords.x, coords.y);
ctx.stroke();
state.currentStroke.points.push(coords);
} else if (state.currentTool === 'rect' && state.tempRect) {
// Re-draw to clear previous temp rect
// We essentially temporarily draw on canvas, but need to not conflict with final strokes.
// The 'redrawCanvas' clears everything. So we can't just draw on top.
// Strategy: We use a flag "isDrawingRect" and we simulate the drawing by NOT using the shared observer during drag,
// but relying on direct drawing to canvas, then clearing shared before final push.
// To avoid complex layering, we will simply draw the preview rect on the canvas.
// 1. Redraw shared strokes (redrawCanvas)
// 2. Draw current temp rect
redrawCanvas();
drawRectPreview(startPoint, coords);
}
}
}
function endStroke(e) {
if (!state.isDrawing || state.user.role === 'viewer') return;
state.isDrawing = false;
if (state.currentTool === 'pen') {
if (state.currentStroke.points.length >= CONFIG.minStrokePoints) {
yDocPush(state.currentStroke);
}
state.currentStroke = null;
} else if (state.currentTool === 'rect' && state.tempRect) {
const endPoint = getCanvasCoordinates(e);
const rectStroke = {
id: state.user.id + '-' + Date.now(),
color: state.currentColor,
width: state.lineWidth,
tool: 'rect',
points: [startPoint, endPoint] // Store two points to define rect
};
yDocPush(rectStroke);
state.tempRect = null;
}
}
// Helper to push data to Yjs
function yDocPush(stroke) {
// Policy enforcement double-check
if (state.user.role === 'viewer') return;
yArray.push([stroke]);
}
// Helper to draw rect preview locally (not shared)
function drawRectPreview(p1, p2) {
ctx.strokeStyle = state.currentColor;
ctx.lineWidth = state.lineWidth;
ctx.strokeRect(
p1.x,
p1.y,
p2.x - p1.x,
p2.y - p1.y
);
}
canvas.addEventListener('pointerdown', startStroke);
canvas.addEventListener('pointermove', moveStroke);
canvas.addEventListener('pointerup', endStroke);
canvas.addEventListener('pointerleave', endStroke);
// --- Remote Cursors & Awareness Rendering ---
// Store separate states for cursors to draw after strokes redraw
const remoteUsers = new Map();
awareness.on('change', () => {
// Iterate through all connected users
for (const [clientId, state] of awareness.getStates()) {
if (clientId === awareness.clientID) continue; // Skip self
const user = state.user;
const cursor = state.cursor;
if (cursor) {
remoteUsers.set(clientId, user);
} else {
remoteUsers.delete(clientId);
}
}
requestAnimationFrame(renderRemoteCursors);
});
// On removal
awareness.on('remove', (clientId) => {
remoteUsers.delete(clientId);
requestAnimationFrame(renderRemoteCursors);
showToast('User disconnected');
});
function renderRemoteCursors() {
cursorCtx.clearRect(0, 0, cursorOverlay.width, cursorOverlay.height);
// Get all states again to draw cursors
const states = awareness.getStates();
const rect = canvas.getBoundingClientRect();
for (const [clientId, state] of states) {
if (clientId === awareness.clientID) continue;
const user = state.user;
const cursor = state.cursor;
if (cursor) {
// Convert page coords to canvas coords (roughly, assuming canvas is full screen)
const x = cursor.x; // These are already page coords typically depending on how we send them
const y = cursor.y;
// Draw Cursor Triangle
drawCursor(cursorCtx, x, y, user.color);
// Draw Name Tag
cursorCtx.font = '12px Inter';
cursorCtx.textAlign = 'center';
const text = user.name;
const textWidth = cursorCtx.measureText(text).width;
// Background for name
cursorCtx.fillStyle = 'rgba(0,0,0,0.7)';
cursorCtx.beginPath();
cursorCtx.roundRect(x - textWidth/2 - 4, y - 24, textWidth + 8, 18, 4);
cursorCtx.fill();
cursorCtx.fillStyle = '#fff';
cursorCtx.fillText(text, x, y - 10);
}
}
}
function drawCursor(ctx, x, y, color) {
ctx.save();
ctx.translate(x, y);
ctx.fillStyle = color;
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(-10, -10);
ctx.lineTo(0, -5);
ctx.lineTo(10, -10);
ctx.closePath();
ctx.fill();
ctx.restore();
}
// --- UI Interactions & Setup ---
// Magnetic Button Effect (Simple Implementation)
document.querySelectorAll('.tool-btn:not([disabled])').forEach(btn => {
btn.addEventListener('mousemove', (e) => {
const rect = btn.getBoundingClientRect();
const x = e.clientX - rect.left - rect.width / 2;
const y = e.clientY - rect.top - rect.height / 2;
btn.style.transform = `translate(${x * 0.2}px, ${y * 0.2}px)`;
});
btn.addEventListener('mouseleave', () => {
btn.style.transform = 'translate(0px, 0px)';
});
});
// Tool Selection
document.querySelectorAll('.tool-btn').forEach(btn => {
btn.addEventListener('click', () => {
if (btn.hasAttribute('disabled')) return;
document.querySelectorAll('.tool-btn').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
state.currentTool = btn.dataset.tool;
// Update awareness
awareness.setLocalStateField('tool', state.currentTool);
showToast(`Switched to ${state.currentTool}`);
});
});
// Color Selection
const colorBtn = document.getElementById('color-btn');
const colors = {
white: '#ffffff',
emerald: '#10b981',
cyan: '#00f0ff',
rose: '#f43f5e',
yellow: '#fbbf24'
};
// Build color picker dynamically
const picker = colorBtn.nextElementSibling;
Object.entries(colors).forEach(([name, val]) => {
// Already in HTML, we need to bind clicks to those divs.
// Since we generated via HTML earlier, let's query those new divs.
// Actually the HTML inside the picker div has hardcoded colors. Let's keep it simple.
});
// Re-binding color click logic quickly:
const colorDots = picker.querySelectorAll('div');
colorDots.forEach(dot => {
dot.addEventListener('click', () => {
state.currentColor = dot.style.backgroundColor;
// Convert rgb to hex for consistency
colorBtn.style.backgroundColor = state.currentColor;
showToast(`Color set`);
});
});
// Clear Canvas
document.getElementById('clear-btn').addEventListener('click', () => {
if (state.user.role === 'viewer') return;
if (confirm('Are you sure you want to clear the whiteboard for everyone?')) {
yArray.delete(0, yArray.length);
showToast('Canvas cleared');
}
});
// Custom Cursor Logic
const cursor = document.getElementById('cursor');
const cursorDot = document.getElementById('cursor-dot');
document.addEventListener('mousemove', (e) => {
cursorDot.style.left = e.clientX + 'px';
cursorDot.style.top = e.clientY + 'px';
gsap.to(cursor, {
x: e.clientX,
y: e.clientY,
duration: 0.1,
ease: 'power2.out'
});
// Hover effect on interactive elements
const target = e.target;
if (target.closest('button') || target.closest('a') || target.closest('input')) {
cursor.classList.add('hovered');
} else {
cursor.classList.remove('hovered');
}
});
// --- Notifications (Toast) ---
function showToast(message, type = 'info') {
const el = document.createElement('div');
el.className = `glass-panel px-4 py-2 rounded text-sm text-white shadow-lg border-l-4 ${type === 'error' ? 'border-red-500' : 'border-accent'} toast-enter`;
el.textContent = message;
toastContainer.appendChild(el);
// GSAP entry
gsap.to(el, { x: 0, opacity: 1, duration: 0.3, ease: 'back.out', onComplete: () => {
// Auto remove
setTimeout(() => {
gsap.to(el, { x: '100%', opacity: 0, duration: 0.3, onComplete: () => el.remove() });
}, 3000);
}});
}
// --- Initialization & Modal Handling ---
const joinForm = document.getElementById('join-form');
const inputName = document.getElementById('input-name');
const roleRadios = document.getElementsByName('role');
// Check for URL params to prefill (simulating deep link)
const params = new URLSearchParams(window.location.search);
const prefillName = params.get('name') || '';
inputName.value = prefillName;
joinForm.addEventListener('submit', (e) => {
e.preventDefault();
const name = inputName.value.trim() || 'Anonymous';
let roleVal = 'editor';
for (const radio of roleRadios) {
if (radio.checked) roleVal = radio.value;
}
// Update state
state.user.name = name;
state.user.role = roleVal;
// Generate a color based on name hash or fixed palette
const palettes = ['#00f0ff', '#ff0055', '#ffd700', '#10b981', '#8b5cf6'];
state.user.color = palettes[Math.floor(Math.random() * palettes.length)];
// Set UI Text
document.getElementById('user-name-display').textContent = name;
document.getElementById('user-avatar').textContent = name.charAt(0).toUpperCase();
const badge = document.getElementById('user-role-badge');
badge.textContent = roleVal;
// Badge styling
if (roleVal === 'owner') badge.className = 'text-[10px] px-1.5 py-0.5 rounded bg-blue-600 text-white uppercase';
else if (roleVal === 'editor') badge.className = 'text-[10px] px-1.5 py-0.5 rounded bg-emerald-500 text-white uppercase';
else badge.className = 'text-[10px] px-1.5 py-0.5 rounded bg-rose-600 text-white uppercase';
// Animate UI Entry
gsap.to([toolbar, userPanel], {
y: 0,
opacity: 1,
duration: 0.6,
stagger: 0.1,
ease: 'power3.out'
});
gsap.to(modalContent, {
scale: 0.95,
opacity: 0,
duration: 0.3,
onComplete: () => joinModal.style.display = 'none'
});
// Init Yjs Awareness
setLocalUser();
enforcePolicy();
showToast(`Connected to mesh as ${roleVal}`);
// Pulse effect on cursor
gsap.to(cursor, { scale: 1.5, duration: 0.5, yoyo: true, repeat: 1 });
});
// --- Intro Sequence (Exists regardless of modal, to populate background) ---
window.addEventListener('load', () => {
gsap.from("header>div:first-child", { y: -50, opacity: 0, duration: 1, ease: 'power3.out' });
});
</script>
</body>
</html>