<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Collab Editor - CRDT + WebRTC</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
:root {
--bg-primary: #0a0f1a;
--bg-secondary: #111827;
--bg-tertiary: #1e293b;
--text-primary: #f1f5f9;
--text-secondary: #94a3b8;
--accent-cyan: #22d3ee;
--accent-orange: #fb923c;
--accent-pink: #f472b6;
--accent-green: #4ade80;
--border-color: #334155;
}
body {
font-family: 'Segoe UI', system-ui, sans-serif;
background: var(--bg-primary);
color: var(--text-primary);
min-height: 100vh;
overflow-x: hidden;
}
#bg-canvas {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 0;
opacity: 0.6;
}
.app-container {
position: relative;
z-index: 1;
max-width: 1400px;
margin: 0 auto;
padding: 20px;
min-height: 100vh;
}
header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 20px 0;
border-bottom: 1px solid var(--border-color);
margin-bottom: 20px;
}
.logo {
display: flex;
align-items: center;
gap: 12px;
}
.logo-icon {
width: 48px;
height: 48px;
background: linear-gradient(135deg, var(--accent-cyan), var(--accent-orange));
border-radius: 12px;
display: flex;
align-items: center;
justify-content: center;
font-size: 24px;
font-weight: bold;
animation: pulse 2s ease-in-out infinite;
}
@keyframes pulse {
0%, 100% { transform: scale(1); }
50% { transform: scale(1.05); }
}
.logo h1 {
font-size: 1.5rem;
font-weight: 600;
background: linear-gradient(90deg, var(--accent-cyan), var(--text-primary));
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
.users-panel {
display: flex;
align-items: center;
gap: 12px;
}
.user-avatar {
width: 36px;
height: 36px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
font-weight: 600;
font-size: 14px;
border: 2px solid transparent;
transition: all 0.3s ease;
position: relative;
}
.user-avatar.local {
border-color: var(--accent-cyan);
box-shadow: 0 0 15px rgba(34, 211, 238, 0.4);
}
.user-avatar.remote {
animation: fadeIn 0.5s ease;
}
@keyframes fadeIn {
from { transform: scale(0); opacity: 0; }
to { transform: scale(1); opacity: 1; }
}
.connection-status {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 16px;
background: var(--bg-secondary);
border-radius: 20px;
font-size: 0.85rem;
}
.status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--accent-orange);
animation: blink 1.5s ease-in-out infinite;
}
.status-dot.connected {
background: var(--accent-green);
animation: none;
}
@keyframes blink {
0%, 100% { opacity: 1; }
50% { opacity: 0.3; }
}
.main-content {
display: grid;
grid-template-columns: 1fr 320px;
gap: 20px;
}
@media (max-width: 900px) {
.main-content {
grid-template-columns: 1fr;
}
}
.editor-container {
background: var(--bg-secondary);
border-radius: 16px;
border: 1px solid var(--border-color);
overflow: hidden;
display: flex;
flex-direction: column;
min-height: 500px;
}
.editor-toolbar {
display: flex;
align-items: center;
gap: 8px;
padding: 12px 16px;
background: var(--bg-tertiary);
border-bottom: 1px solid var(--border-color);
}
.toolbar-btn {
padding: 8px 12px;
background: var(--bg-secondary);
border: 1px solid var(--border-color);
border-radius: 8px;
color: var(--text-primary);
cursor: pointer;
transition: all 0.2s ease;
font-size: 0.85rem;
}
.toolbar-btn:hover {
background: var(--accent-cyan);
color: var(--bg-primary);
transform: translateY(-2px);
}
.toolbar-separator {
width: 1px;
height: 24px;
background: var(--border-color);
margin: 0 8px;
}
.editor-wrapper {
flex: 1;
position: relative;
overflow: hidden;
}
#editor {
width: 100%;
height: 100%;
min-height: 400px;
padding: 20px;
font-family: 'JetBrains Mono', 'Fira Code', monospace;
font-size: 15px;
line-height: 1.7;
color: var(--text-primary);
background: transparent;
border: none;
outline: none;
resize: none;
overflow-y: auto;
white-space: pre-wrap;
word-wrap: break-word;
}
#editor::placeholder {
color: var(--text-secondary);
}
.line-numbers {
position: absolute;
left: 0;
top: 0;
width: 50px;
height: 100%;
padding: 20px 10px;
text-align: right;
font-family: 'JetBrains Mono', monospace;
font-size: 13px;
color: var(--text-secondary);
opacity: 0.5;
pointer-events: none;
overflow: hidden;
}
.sidebar {
display: flex;
flex-direction: column;
gap: 16px;
}
.panel {
background: var(--bg-secondary);
border-radius: 16px;
border: 1px solid var(--border-color);
overflow: hidden;
}
.panel-header {
padding: 16px;
background: var(--bg-tertiary);
border-bottom: 1px solid var(--border-color);
font-weight: 600;
display: flex;
align-items: center;
gap: 8px;
}
.panel-header::before {
content: '';
width: 4px;
height: 16px;
background: var(--accent-cyan);
border-radius: 2px;
}
.panel-content {
padding: 16px;
}
.webrtc-section {
margin-bottom: 16px;
}
.webrtc-section h4 {
font-size: 0.85rem;
color: var(--text-secondary);
margin-bottom: 8px;
}
.webrtc-textarea {
width: 100%;
height: 80px;
padding: 10px;
background: var(--bg-primary);
border: 1px solid var(--border-color);
border-radius: 8px;
color: var(--text-primary);
font-family: monospace;
font-size: 11px;
resize: none;
margin-bottom: 8px;
}
.btn {
padding: 10px 16px;
border: none;
border-radius: 8px;
cursor: pointer;
font-weight: 500;
transition: all 0.2s ease;
font-size: 0.85rem;
}
.btn-primary {
background: linear-gradient(135deg, var(--accent-cyan), #06b6d4);
color: var(--bg-primary);
}
.btn-primary:hover {
transform: translateY(-2px);
box-shadow: 0 5px 20px rgba(34, 211, 238, 0.3);
}
.btn-secondary {
background: var(--bg-tertiary);
color: var(--text-primary);
border: 1px solid var(--border-color);
}
.btn-secondary:hover {
background: var(--accent-orange);
color: var(--bg-primary);
}
.btn-group {
display: flex;
gap: 8px;
}
.connection-list {
max-height: 200px;
overflow-y: auto;
}
.connection-item {
display: flex;
align-items: center;
justify-content: space-between;
padding: 10px;
background: var(--bg-primary);
border-radius: 8px;
margin-bottom: 8px;
transition: all 0.3s ease;
}
.connection-item:hover {
background: var(--bg-tertiary);
}
.connection-info {
display: flex;
align-items: center;
gap: 10px;
}
.connection-icon {
width: 32px;
height: 32px;
border-radius: 8px;
background: linear-gradient(135deg, var(--accent-pink), var(--accent-orange));
display: flex;
align-items: center;
justify-content: center;
}
.stats-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
}
.stat-item {
background: var(--bg-primary);
padding: 12px;
border-radius: 8px;
text-align: center;
}
.stat-value {
font-size: 1.5rem;
font-weight: 700;
background: linear-gradient(135deg, var(--accent-cyan), var(--accent-green));
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
.stat-label {
font-size: 0.75rem;
color: var(--text-secondary);
margin-top: 4px;
}
.remote-cursor {
position: absolute;
pointer-events: none;
transition: all 0.1s ease;
}
.remote-cursor-line {
width: 2px;
height: 20px;
animation: cursorBlink 1s ease-in-out infinite;
}
.remote-cursor-label {
position: absolute;
top: -20px;
left: 0;
padding: 2px 6px;
border-radius: 4px;
font-size: 11px;
font-weight: 600;
white-space: nowrap;
}
@keyframes cursorBlink {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
}
.char-insertion {
animation: charAppear 0.2s ease;
}
@keyframes charAppear {
from {
opacity: 0;
transform: scale(1.5);
color: var(--accent-cyan);
}
to {
opacity: 1;
transform: scale(1);
}
}
.toast {
position: fixed;
bottom: 20px;
left: 50%;
transform: translateX(-50%) translateY(100px);
padding: 12px 24px;
background: var(--bg-tertiary);
border: 1px solid var(--accent-cyan);
border-radius: 8px;
color: var(--text-primary);
font-size: 0.9rem;
z-index: 1000;
opacity: 0;
transition: all 0.3s ease;
}
.toast.show {
transform: translateX(-50%) translateY(0);
opacity: 1;
}
.version-history {
max-height: 150px;
overflow-y: auto;
}
.version-item {
padding: 8px;
background: var(--bg-primary);
border-radius: 6px;
margin-bottom: 6px;
font-size: 0.8rem;
display: flex;
justify-content: space-between;
align-items: center;
}
.version-time {
color: var(--text-secondary);
}
.version-op {
padding: 2px 8px;
border-radius: 4px;
font-size: 0.75rem;
font-weight: 600;
}
.version-op.insert {
background: rgba(74, 222, 128, 0.2);
color: var(--accent-green);
}
.version-op.delete {
background: rgba(251, 146, 60, 0.2);
color: var(--accent-orange);
}
</style>
</head>
<body>
<canvas id="bg-canvas"></canvas>
<div class="app-container">
<header>
<div class="logo">
<div class="logo-icon">C</div>
<h1>Collab Editor</h1>
</div>
<div class="users-panel">
<div id="user-avatars"></div>
<div class="connection-status">
<div class="status-dot" id="status-dot"></div>
<span id="status-text">Waiting for peers</span>
</div>
</div>
</header>
<div class="main-content">
<div class="editor-container">
<div class="editor-toolbar">
<button class="toolbar-btn" onclick="editorAction('bold')">Bold</button>
<button class="toolbar-btn" onclick="editorAction('italic')">Italic</button>
<div class="toolbar-separator"></div>
<button class="toolbar-btn" onclick="editorAction('clear')">Clear</button>
<button class="toolbar-btn" onclick="editorAction('export')">Export</button>
<div class="toolbar-separator"></div>
<button class="toolbar-btn" onclick="editorAction('insert-demo')">Insert Demo</button>
</div>
<div class="editor-wrapper">
<div class="line-numbers" id="line-numbers">1</div>
<textarea id="editor" placeholder="Start typing here... Your changes will sync in real-time with connected peers."></textarea>
</div>
</div>
<div class="sidebar">
<div class="panel">
<div class="panel-header">WebRTC Connection</div>
<div class="panel-content">
<div class="webrtc-section">
<h4>Create Offer (Tab 1)</h4>
<button class="btn btn-primary" onclick="createOffer()">Generate Offer</button>
<div id="offer-output" style="margin-top: 10px;"></div>
</div>
<div class="webrtc-section">
<h4>Paste Offer (Tab 2)</h4>
<textarea class="webrtc-textarea" id="offer-input" placeholder="Paste offer here..."></textarea>
<div class="btn-group">
<button class="btn btn-secondary" onclick="acceptOffer()">Accept Offer</button>
</div>
</div>
<div class="webrtc-section">
<h4>Paste Answer (Tab 1)</h4>
<textarea class="webrtc-textarea" id="answer-input" placeholder="Paste answer here..."></textarea>
<button class="btn btn-secondary" onclick="acceptAnswer()">Accept Answer</button>
</div>
</div>
</div>
<div class="panel">
<div class="panel-header">Connected Peers</div>
<div class="panel-content">
<div class="connection-list" id="connection-list">
<div style="color: var(--text-secondary); text-align: center; padding: 20px;">
No peers connected yet
</div>
</div>
</div>
</div>
<div class="panel">
<div class="panel-header">Statistics</div>
<div class="panel-content">
<div class="stats-grid">
<div class="stat-item">
<div class="stat-value" id="stat-chars">0</div>
<div class="stat-label">Characters</div>
</div>
<div class="stat-item">
<div class="stat-value" id="stat-lines">1</div>
<div class="stat-label">Lines</div>
</div>
<div class="stat-item">
<div class="stat-value" id="stat-ops">0</div>
<div class="stat-label">Operations</div>
</div>
<div class="stat-item">
<div class="stat-value" id="stat-peers">0</div>
<div class="stat-label">Peers</div>
</div>
</div>
</div>
</div>
<div class="panel">
<div class="panel-header">Recent Operations</div>
<div class="panel-content">
<div class="version-history" id="version-history"></div>
</div>
</div>
</div>
</div>
</div>
<div class="toast" id="toast"></div>
<script>
// ============== BACKGROUND ANIMATION ==============
const bgCanvas = document.getElementById('bg-canvas');
const bgCtx = bgCanvas.getContext('2d');
function resizeCanvas() {
bgCanvas.width = window.innerWidth;
bgCanvas.height = window.innerHeight;
}
resizeCanvas();
window.addEventListener('resize', resizeCanvas);
class Particle {
constructor() {
this.reset();
}
reset() {
this.x = Math.random() * bgCanvas.width;
this.y = Math.random() * bgCanvas.height;
this.size = Math.random() * 2 + 0.5;
this.speedX = (Math.random() - 0.5) * 0.5;
this.speedY = (Math.random() - 0.5) * 0.5;
this.opacity = Math.random() * 0.5 + 0.2;
this.hue = Math.random() * 60 + 170; // cyan to blue range
}
update() {
this.x += this.speedX;
this.y += this.speedY;
if (this.x < 0 || this.x > bgCanvas.width) this.speedX *= -1;
if (this.y < 0 || this.y > bgCanvas.height) this.speedY *= -1;
}
draw() {
bgCtx.beginPath();
bgCtx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
bgCtx.fillStyle = `hsla(${this.hue}, 80%, 60%, ${this.opacity})`;
bgCtx.fill();
}
}
const particles = Array.from({ length: 80 }, () => new Particle());
function animateBackground() {
bgCtx.fillStyle = 'rgba(10, 15, 26, 0.1)';
bgCtx.fillRect(0, 0, bgCanvas.width, bgCanvas.height);
particles.forEach(p => {
p.update();
p.draw();
});
// Draw connections
for (let i = 0; i < particles.length; i++) {
for (let j = i + 1; j < particles.length; j++) {
const dx = particles[i].x - particles[j].x;
const dy = particles[i].y - particles[j].y;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < 100) {
bgCtx.beginPath();
bgCtx.moveTo(particles[i].x, particles[i].y);
bgCtx.lineTo(particles[j].x, particles[j].y);
bgCtx.strokeStyle = `rgba(34, 211, 238, ${0.1 * (1 - dist / 100)})`;
bgCtx.stroke();
}
}
}
requestAnimationFrame(animateBackground);
}
animateBackground();
// ============== CRDT IMPLEMENTATION ==============
class Char {
constructor(id, leftOrigin, rightOrigin, char, siteId) {
this.id = id;
this.leftOrigin = leftOrigin;
this.rightOrigin = rightOrigin;
this.char = char;
this.siteId = siteId;
}
static compare(a, b) {
if (a.id.siteId !== b.id.siteId) {
return a.id.siteId < b.id.siteId ? -1 : 1;
}
return a.id.clock - b.id.clock;
}
}
class CRDTDocument {
constructor(siteId) {
this.siteId = siteId;
this.clock = 0;
this.chars = [];
this.ops = [];
}
generateId() {
return { siteId: this.siteId, clock: this.clock++ };
}
localInsert(index, char) {
const left = index > 0 ? this.chars[index - 1] : null;
const right = index < this.chars.length ? this.chars[index] : null;
const newChar = new Char(
this.generateId(),
left ? left.id : null,
right ? right.id : null,
char,
this.siteId
);
this.insertChar(newChar, left, right);
this.ops.push({ type: 'insert', char: newChar, timestamp: Date.now() });
return { type: 'insert', char: newChar };
}
localDelete(index) {
if (index < 0 || index >= this.chars.length) return null;
const deletedChar = this.chars[index];
this.chars.splice(index, 1);
this.ops.push({ type: 'delete', char: deletedChar, timestamp: Date.now() });
return { type: 'delete', charId: deletedChar.id };
}
insertChar(newChar, left, right) {
let insertIndex = 0;
if (left) {
const leftIndex = this.chars.findIndex(c =>
c.id.siteId === left.id.siteId && c.id.clock === left.id.clock
);
if (leftIndex !== -1) {
insertIndex = leftIndex + 1;
}
}
if (right) {
const rightIndex = this.chars.findIndex(c =>
c.id.siteId === right.id.siteId && c.id.clock === right.id.clock
);
if (rightIndex !== -1 && rightIndex < insertIndex) {
insertIndex = rightIndex;
}
}
// Check for duplicates
const exists = this.chars.some(c =>
c.id.siteId === newChar.id.siteId && c.id.clock === newChar.id.clock
);
if (!exists) {
this.chars.splice(insertIndex, 0, newChar);
}
return insertIndex;
}
remoteInsert(op) {
const newChar = op.char;
const left = newChar.leftOrigin ?
this.chars.find(c =>
c.id.siteId === newChar.leftOrigin.siteId &&
c.id.clock === newChar.leftOrigin.clock
) : null;
const right = newChar.rightOrigin ?
this.chars.find(c =>
c.id.siteId === newChar.rightOrigin.siteId &&
c.id.clock === newChar.rightOrigin.clock
) : null;
const index = this.insertChar(newChar, left, right);
this.ops.push({ type: 'insert', char: newChar, timestamp: Date.now() });
return { index, char: newChar.char };
}
remoteDelete(op) {
const index = this.chars.findIndex(c =>
c.id.siteId === op.charId.siteId && c.id.clock === op.charId.clock
);
if (index !== -1) {
const deleted = this.chars.splice(index, 1)[0];
this.ops.push({ type: 'delete', char: deleted, timestamp: Date.now() });
return index;
}
return -1;
}
getText() {
return this.chars.map(c => c.char).join('');
}
getLength() {
return this.chars.length;
}
}
// ============== WEBRTC & SYNC MANAGER ==============
class SyncManager {
constructor(crdt, editor) {
this.crdt = crdt;
this.editor = editor;
this.peers = new Map();
this.peerConnections = new Map();
this.pendingCandidates = [];
this.isInitiator = false;
this.broadcastChannel = null;
this.userId = Math.random().toString(36).substr(2, 9);
this.userColors = {};
this.colorIndex = 0;
this.colors = ['#22d3ee', '#fb923c', '#f472b6', '#4ade80', '#a78bfa', '#fbbf24'];
this.initBroadcastChannel();
this.initWebRTC();
}
getUserColor(userId) {
if (!this.userColors[userId]) {
this.userColors[userId] = this.colors[this.colorIndex % this.colors.length];
this.colorIndex++;
}
return this.userColors[userId];
}
initBroadcastChannel() {
try {
this.broadcastChannel = new BroadcastChannel('collab-editor-sync');
this.broadcastChannel.onmessage = (event) => {
const { type, data, userId } = event.data;
if (userId === this.userId) return;
switch (type) {
case 'join':
this.handlePeerJoin(userId);
// Send current state to new peer
this.broadcastChannel.postMessage({
type: 'sync',
data: {
text: this.crdt.getText(),
chars: this.crdt.chars
},
userId: this.userId
});
break;
case 'leave':
this.handlePeerLeave(userId);
break;
case 'operation':
this.handleRemoteOperation(data);
break;
case 'sync':
this.handleSync(data);
break;
case 'cursor':
this.handleRemoteCursor(data, userId);
break;
}
};
// Announce presence
this.broadcastChannel.postMessage({
type: 'join',
userId: this.userId
});
window.addEventListener('beforeunload', () => {
this.broadcastChannel.postMessage({
type: 'leave',
userId: this.userId
});
});
} catch (e) {
console.log('BroadcastChannel not supported');
}
}
handlePeerJoin(userId) {
this.peers.set(userId, { connected: true, type: 'broadcast' });
this.updatePeerUI();
this.showToast(`Peer connected (${userId.slice(0, 4)})`);
}
handlePeerLeave(userId) {
this.peers.delete(userId);
this.updatePeerUI();
}
handleSync(data) {
if (this.crdt.chars.length === 0 && data.chars) {
this.crdt.chars = data.chars;
this.crdt.clock = data.chars.reduce((max, c) =>
Math.max(max, c.id.clock + 1), 0);
this.editor.value = data.text;
this.updateStats();
}
}
handleRemoteOperation(data) {
let result;
if (data.type === 'insert') {
result = this.crdt.remoteInsert(data);
if (result) {
const pos = result.index;
const text = this.editor.value;
this.editor.value = text.slice(0, pos) + result.char + text.slice(pos);
this.showToast('Remote change received');
}
} else if (data.type === 'delete') {
result = this.crdt.remoteDelete(data);
if (result >= 0) {
const text = this.editor.value;
this.editor.value = text.slice(0, result) + text.slice(result + 1);
}
}
this.updateStats();
this.updateVersionHistory();
}
handleRemoteCursor(data, userId) {
// Visual feedback for remote cursor (simplified)
const color = this.getUserColor(userId);
// Could implement cursor rendering here
}
broadcastOperation(op) {
if (this.broadcastChannel) {
this.broadcastChannel.postMessage({
type: 'operation',
data: op,
userId: this.userId
});
}
// Also send via WebRTC if connected
this.peerConnections.forEach((conn) => {
if (conn.dataChannel && conn.dataChannel.readyState === 'open') {
conn.dataChannel.send(JSON.stringify({ type: 'operation', data: op }));
}
});
}
initWebRTC() {
this.rtcConfig = {
iceServers: [
{ urls: 'stun:stun.l.google.com:19302' },
{ urls: 'stun:stun1.l.google.com:19302' }
]
};
}
async createOffer() {
const pc = new RTCPeerConnection(this.rtcConfig);
const connectionId = Date.now().toString();
const dataChannel = pc.createDataChannel('collab');
this.setupDataChannel(dataChannel, connectionId);
pc.onicecandidate = (event) => {
if (event.candidate === null) {
const offer = btoa(JSON.stringify({
type: 'offer',
sdp: pc.localDescription
}));
document.getElementById('offer-output').innerHTML = `
<textarea class="webrtc-textarea" id="generated-offer" readonly>${offer}</textarea>
<button class="btn btn-secondary" onclick="navigator.clipboard.writeText(document.getElementById('generated-offer').value)">Copy Offer</button>
`;
}
};
pc.onconnectionstatechange = () => {
this.updateConnectionStatus(pc.connectionState, connectionId);
};
const offer = await pc.createOffer();
await pc.setLocalDescription(offer);
this.peerConnections.set(connectionId, { pc, dataChannel });
this.isInitiator = true;
this.currentConnectionId = connectionId;
this.showToast('Offer created! Copy and share it.');
}
async acceptOffer() {
const offerText = document.getElementById('offer-input').value.trim();
if (!offerText) {
this.showToast('Please paste an offer first');
return;
}
try {
const offerData = JSON.parse(atob(offerText));
const pc = new RTCPeerConnection(this.rtcConfig);
const connectionId = Date.now().toString();
pc.ondatachannel = (event) => {
this.setupDataChannel(event.channel, connectionId);
};
pc.onicecandidate = (event) => {
if (event.candidate === null) {
const answer = btoa(JSON.stringify({
type: 'answer',
sdp: pc.localDescription
}));
document.getElementById('offer-input').value = '';
document.getElementById('offer-input').placeholder = 'Answer generated below:';
document.getElementById('offer-input').value = answer;
this.showToast('Answer created! Copy and send it back.');
}
};
pc.onconnectionstatechange = () => {
this.updateConnectionStatus(pc.connectionState, connectionId);
};
await pc.setRemoteDescription(new RTCSessionDescription(offerData.sdp));
const answer = await pc.createAnswer();
await pc.setLocalDescription(answer);
this.peerConnections.set(connectionId, { pc });
this.currentConnectionId = connectionId;
} catch (e) {
this.showToast('Invalid offer format');
console.error(e);
}
}
async acceptAnswer() {
const answerText = document.getElementById('answer-input').value.trim();
if (!answerText) {
this.showToast('Please paste an answer first');
return;
}
try {
const answerData = JSON.parse(atob(answerText));
const connection = this.peerConnections.get(this.currentConnectionId);
if (connection && connection.pc) {
await connection.pc.setRemoteDescription(new RTCSessionDescription(answerData.sdp));
this.showToast('Connection established!');
document.getElementById('answer-input').value = '';
}
} catch (e) {
this.showToast('Invalid answer format');
console.error(e);
}
}
setupDataChannel(channel, connectionId) {
channel.onopen = () => {
this.peers.set(connectionId, { connected: true, type: 'webrtc' });
this.updatePeerUI();
this.showToast('Peer connected via WebRTC');
// Sync current state
channel.send(JSON.stringify({
type: 'sync',
data: {
text: this.crdt.getText(),
chars: this.crdt.chars
}
}));
};
channel.onmessage = (event) => {
const message = JSON.parse(event.data);
if (message.type === 'operation') {
this.handleRemoteOperation(message.data);
} else if (message.type === 'sync') {
this.handleSync(message.data);
}
};
channel.onclose = () => {
this.peers.delete(connectionId);
this.updatePeerUI();
};
const connection = this.peerConnections.get(connectionId);
if (connection) {
connection.dataChannel = channel;
}
}
updateConnectionStatus(state, connectionId) {
if (state === 'connected') {
this.peers.set(connectionId, { connected: true, type: 'webrtc' });
this.updatePeerUI();
} else if (state === 'disconnected' || state === 'failed') {
this.peers.delete(connectionId);
this.updatePeerUI();
}
}
updatePeerUI() {
const statusDot = document.getElementById('status-dot');
const statusText = document.getElementById('status-text');
const peerCount = this.peers.size;
if (peerCount > 0) {
statusDot.classList.add('connected');
statusText.textContent = `${peerCount} peer${peerCount > 1 ? 's' : ''} connected`;
} else {
statusDot.classList.remove('connected');
statusText.textContent = 'Waiting for peers';
}
// Update connection list
const listEl = document.getElementById('connection-list');
if (peerCount === 0) {
listEl.innerHTML = '<div style="color: var(--text-secondary); text-align: center; padding: 20px;">No peers connected yet</div>';
} else {
listEl.innerHTML = Array.from(this.peers.entries()).map(([id, peer]) => `
<div class="connection-item">
<div class="connection-info">
<div class="connection-icon">
<svg width="16" height="16" viewBox="0 0 24 24" fill="white">
<path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/>
</svg>
</div>
<div>
<div style="font-weight: 500;">Peer ${id.slice(-4)}</div>
<div style="font-size: 0.75rem; color: var(--text-secondary);">${peer.type}</div>
</div>
</div>
<div class="status-dot connected"></div>
</div>
`).join('');
}
// Update avatars
const avatarsEl = document.getElementById('user-avatars');
avatarsEl.innerHTML = `
<div class="user-avatar local" style="background: ${this.getUserColor(this.userId)}">
${this.userId.slice(0, 2).toUpperCase()}
</div>
` + Array.from(this.peers.keys()).map(id => `
<div class="user-avatar remote" style="background: ${this.getUserColor(id)}">
${id.slice(0, 2).toUpperCase()}
</div>
`).join('');
document.getElementById('stat-peers').textContent = peerCount;
}
updateStats() {
document.getElementById('stat-chars').textContent = this.crdt.getLength();
document.getElementById('stat-lines').textContent =
(this.editor.value.match(/\n/g) || []).length + 1;
document.getElementById('stat-ops').textContent = this.crdt.ops.length;
}
updateVersionHistory() {
const historyEl = document.getElementById('version-history');
const recentOps = this.crdt.ops.slice(-10).reverse();
historyEl.innerHTML = recentOps.map(op => `
<div class="version-item">
<span class="version-time">${new Date(op.timestamp).toLocaleTimeString()}</span>
<span class="version-op ${op.type}">
${op.type} "${op.char ? (op.char.char || '') : ''}"
</span>
</div>
`).join('');
}
showToast(message) {
const toast = document.getElementById('toast');
toast.textContent = message;
toast.classList.add('show');
setTimeout(() => toast.classList.remove('show'), 2500);
}
}
// ============== EDITOR SETUP ==============
const editor = document.getElementById('editor');
const crdt = new CRDTDocument(Math.random().toString(36).substr(2, 9));
const syncManager = new SyncManager(crdt, editor);
let lastText = '';
let isUpdating = false;
editor.addEventListener('input', (e) => {
if (isUpdating) return;
const newText = editor.value;
const oldLength = lastText.length;
const newLength = newText.length;
if (newLength > oldLength) {
// Characters inserted
const diff = newLength - oldLength;
let insertPos = -1;
for (let i = 0; i <= newLength - diff; i++) {
const before = lastText.slice(0, i) + lastText.slice(i);
if (newText.slice(0, i) + newText.slice(i + diff) === lastText) {
insertPos = i;
break;
}
}
if (insertPos === -1) {
// Simple end insertion detection
for (let i = 0; i < newLength; i++) {
if (newText[i] !== lastText[i]) {
insertPos = i;
break;
}
}
if (insertPos === -1) insertPos = oldLength;
}
for (let i = 0; i < diff; i++) {
const char = newText[insertPos + i];
const adjustedPos = insertPos + i;
const op = crdt.localInsert(adjustedPos, char);
syncManager.broadcastOperation(op);
}
} else if (newLength < oldLength) {
// Characters deleted
const diff = oldLength - newLength;
let deletePos = -1;
for (let i = 0; i <= newLength; i++) {
if (lastText.slice(0, i) + lastText.slice(i + diff) === newText) {
deletePos = i;
break;
}
}
if (deletePos === -1) {
for (let i = 0; i < oldLength; i++) {
if (lastText[i] !== newText[i]) {
deletePos = i;
break;
}
}
}
for (let i = 0; i < diff; i++) {
const op = crdt.localDelete(deletePos);
if (op) syncManager.broadcastOperation(op);
}
}
lastText = newText;
syncManager.updateStats();
syncManager.updateVersionHistory();
updateLineNumbers();
});
editor.addEventListener('select', () => {
// Could track cursor position for remote cursors
});
function updateLineNumbers() {
const lines = (editor.value.match(/\n/g) || []).length + 1;
const lineNumbers = Array.from({ length: lines }, (_, i) => i + 1).join('\n');
document.getElementById('line-numbers').textContent = lineNumbers;
}
// ============== TOOLBAR ACTIONS ==============
function editorAction(action) {
switch (action) {
case 'clear':
if (confirm('Clear all content?')) {
editor.value = '';
lastText = '';
crdt.chars = [];
crdt.ops = [];
syncManager.updateStats();
syncManager.updateVersionHistory();
updateLineNumbers();
}
break;
case 'export':
const blob = new Blob([editor.value], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'collab-document.txt';
a.click();
URL.revokeObjectURL(url);
syncManager.showToast('Document exported');
break;
case 'insert-demo':
const demoText = `// Welcome to Collab Editor!
// This is a real-time collaborative text editor
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("World"));
// Try editing this text in another tab!`;
demoText.split('').forEach((char, i) => {
setTimeout(() => {
const pos = editor.value.length;
const op = crdt.localInsert(pos, char);
editor.value += char;
lastText = editor.value;
syncManager.broadcastOperation(op);
syncManager.updateStats();
updateLineNumbers();
}, i * 20);
});
break;
}
}
// Global functions for WebRTC
window.createOffer = () => syncManager.createOffer();
window.acceptOffer = () => syncManager.acceptOffer();
window.acceptAnswer = () => syncManager.acceptAnswer();
window.editorAction = editorAction;
// Initial stats
syncManager.updateStats();
syncManager.updateVersionHistory();
// Periodic sync check
setInterval(() => {
if (syncManager.broadcastChannel) {
syncManager.broadcastChannel.postMessage({
type: 'join',
userId: syncManager.userId
});
}
}, 5000);
</script>
</body>
</html>