<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CRDT Collaborative Engine</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
:root {
--bg-primary: #0a0e17;
--bg-secondary: #111827;
--bg-tertiary: #1f2937;
--accent-cyan: #06b6d4;
--accent-emerald: #10b981;
--accent-amber: #f59e0b;
--accent-rose: #f43f5e;
--accent-violet: #8b5cf6;
--text-primary: #f9fafb;
--text-secondary: #9ca3af;
--border-color: #374151;
}
body {
font-family: 'Segoe UI', system-ui, sans-serif;
background: var(--bg-primary);
color: var(--text-primary);
min-height: 100vh;
overflow-x: hidden;
}
.background-canvas {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: -1;
opacity: 0.6;
}
.app-container {
display: grid;
grid-template-columns: 280px 1fr 320px;
grid-template-rows: auto 1fr auto;
gap: 16px;
padding: 16px;
min-height: 100vh;
}
.header {
grid-column: 1 / -1;
display: flex;
justify-content: space-between;
align-items: center;
padding: 16px 24px;
background: linear-gradient(135deg, var(--bg-secondary) 0%, var(--bg-tertiary) 100%);
border-radius: 12px;
border: 1px solid var(--border-color);
}
.header h1 {
font-size: 1.5rem;
font-weight: 600;
background: linear-gradient(135deg, var(--accent-cyan), var(--accent-emerald));
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
.header-status {
display: flex;
gap: 20px;
align-items: center;
}
.status-item {
display: flex;
align-items: center;
gap: 8px;
font-size: 0.875rem;
color: var(--text-secondary);
}
.status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--accent-emerald);
animation: pulse 2s ease-in-out infinite;
}
.status-dot.warning { background: var(--accent-amber); }
.status-dot.error { background: var(--accent-rose); }
@keyframes pulse {
0%, 100% { opacity: 1; transform: scale(1); }
50% { opacity: 0.6; transform: scale(1.2); }
}
.panel {
background: var(--bg-secondary);
border-radius: 12px;
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;
font-size: 0.875rem;
text-transform: uppercase;
letter-spacing: 0.05em;
color: var(--text-secondary);
}
.panel-content {
padding: 16px;
}
/* Peers Panel */
.peers-panel { grid-row: 1 / 3; }
.peer-item {
display: flex;
align-items: center;
gap: 12px;
padding: 12px;
background: var(--bg-tertiary);
border-radius: 8px;
margin-bottom: 8px;
transition: all 0.2s ease;
border: 1px solid transparent;
}
.peer-item:hover {
border-color: var(--accent-cyan);
transform: translateX(4px);
}
.peer-item.local {
border-color: var(--accent-emerald);
}
.peer-avatar {
width: 36px;
height: 36px;
border-radius: 8px;
display: flex;
align-items: center;
justify-content: center;
font-weight: 600;
font-size: 0.875rem;
color: white;
}
.peer-info {
flex: 1;
}
.peer-name {
font-size: 0.875rem;
font-weight: 500;
}
.peer-status {
font-size: 0.75rem;
color: var(--text-secondary);
}
.peer-reputation {
font-size: 0.75rem;
padding: 2px 8px;
border-radius: 4px;
background: var(--bg-primary);
}
.peer-reputation.good { color: var(--accent-emerald); }
.peer-reputation.warning { color: var(--accent-amber); }
.peer-reputation.bad { color: var(--accent-rose); }
/* Editor */
.editor-panel {
display: flex;
flex-direction: column;
}
.editor-toolbar {
display: flex;
gap: 8px;
padding: 12px 16px;
background: var(--bg-tertiary);
border-bottom: 1px solid var(--border-color);
}
.toolbar-btn {
padding: 8px 16px;
background: var(--bg-primary);
border: 1px solid var(--border-color);
border-radius: 6px;
color: var(--text-secondary);
font-size: 0.8rem;
cursor: pointer;
transition: all 0.2s ease;
}
.toolbar-btn:hover {
background: var(--accent-cyan);
color: var(--bg-primary);
border-color: var(--accent-cyan);
}
.editor-container {
flex: 1;
position: relative;
min-height: 400px;
}
.editor-textarea {
width: 100%;
height: 100%;
min-height: 400px;
background: transparent;
border: none;
color: var(--text-primary);
font-family: 'JetBrains Mono', 'Fira Code', monospace;
font-size: 14px;
line-height: 1.6;
padding: 20px;
resize: none;
outline: none;
}
.cursor-overlay {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
pointer-events: none;
padding: 20px;
font-family: 'JetBrains Mono', 'Fira Code', monospace;
font-size: 14px;
line-height: 1.6;
white-space: pre-wrap;
overflow: hidden;
}
.remote-cursor {
position: absolute;
width: 2px;
height: 22px;
animation: cursorBlink 1s ease-in-out infinite;
}
@keyframes cursorBlink {
0%, 100% { opacity: 1; }
50% { opacity: 0.4; }
}
.cursor-label {
position: absolute;
top: -20px;
left: 0;
font-size: 10px;
padding: 2px 6px;
border-radius: 3px;
white-space: nowrap;
color: white;
}
/* Right Panel */
.info-panel {
grid-row: 1 / 3;
display: flex;
flex-direction: column;
gap: 16px;
}
.network-graph {
height: 200px;
position: relative;
background: var(--bg-primary);
border-radius: 8px;
overflow: hidden;
}
.network-canvas {
width: 100%;
height: 100%;
}
.stats-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
}
.stat-card {
background: var(--bg-tertiary);
border-radius: 8px;
padding: 12px;
text-align: center;
}
.stat-value {
font-size: 1.5rem;
font-weight: 700;
color: var(--accent-cyan);
}
.stat-label {
font-size: 0.7rem;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.05em;
}
.operations-log {
max-height: 200px;
overflow-y: auto;
font-family: monospace;
font-size: 0.75rem;
}
.log-entry {
padding: 8px;
border-bottom: 1px solid var(--border-color);
display: flex;
justify-content: space-between;
align-items: center;
}
.log-entry:last-child {
border-bottom: none;
}
.log-type {
padding: 2px 6px;
border-radius: 3px;
font-size: 0.65rem;
text-transform: uppercase;
}
.log-type.insert { background: rgba(16, 185, 129, 0.2); color: var(--accent-emerald); }
.log-type.delete { background: rgba(244, 63, 94, 0.2); color: var(--accent-rose); }
.log-type.sync { background: rgba(6, 182, 212, 0.2); color: var(--accent-cyan); }
/* Footer */
.footer {
grid-column: 1 / -1;
display: flex;
justify-content: space-between;
align-items: center;
padding: 12px 20px;
background: var(--bg-secondary);
border-radius: 12px;
border: 1px solid var(--border-color);
font-size: 0.8rem;
}
.vector-clock {
display: flex;
gap: 8px;
align-items: center;
}
.clock-item {
padding: 4px 8px;
background: var(--bg-tertiary);
border-radius: 4px;
font-family: monospace;
font-size: 0.75rem;
}
.connection-status {
display: flex;
gap: 16px;
}
.conn-item {
display: flex;
align-items: center;
gap: 6px;
color: var(--text-secondary);
}
.conn-value {
color: var(--text-primary);
font-weight: 500;
}
/* Scrollbar */
::-webkit-scrollbar {
width: 6px;
}
::-webkit-scrollbar-track {
background: var(--bg-primary);
}
::-webkit-scrollbar-thumb {
background: var(--border-color);
border-radius: 3px;
}
::-webkit-scrollbar-thumb:hover {
background: var(--text-secondary);
}
.empty-state {
text-align: center;
padding: 24px;
color: var(--text-secondary);
font-size: 0.875rem;
}
.warning-banner {
background: rgba(245, 158, 11, 0.1);
border: 1px solid var(--accent-amber);
border-radius: 8px;
padding: 12px;
margin-bottom: 12px;
font-size: 0.8rem;
color: var(--accent-amber);
}
.sim-mode {
font-size: 0.75rem;
padding: 4px 8px;
background: var(--accent-violet);
color: white;
border-radius: 4px;
}
</style>
</head>
<body>
<canvas class="background-canvas" id="bgCanvas"></canvas>
<div class="app-container">
<header class="header">
<h1>CRDT Collaborative Engine</h1>
<div class="header-status">
<span class="sim-mode">SIMULATION MODE</span>
<div class="status-item">
<span class="status-dot" id="statusDot"></span>
<span id="statusText">Initializing</span>
</div>
<div class="status-item">
<span>Site ID:</span>
<span id="siteIdDisplay">-</span>
</div>
</div>
</header>
<!-- Peers Panel -->
<div class="panel peers-panel">
<div class="panel-header">Connected Peers</div>
<div class="panel-content" id="peersList">
<div class="empty-state">Discovering peers...</div>
</div>
</div>
<!-- Editor Panel -->
<div class="panel editor-panel">
<div class="editor-toolbar">
<button class="toolbar-btn" onclick="editor.syncAll()">Sync All</button>
<button class="toolbar-btn" onclick="editor.simulateOffline()">Toggle Offline</button>
<button class="toolbar-btn" onclick="editor.simulateConflict()">Simulate Conflict</button>
<button class="toolbar-btn" onclick="editor.clearDocument()">Clear</button>
</div>
<div class="warning-banner" id="offlineBanner" style="display: none;">
Offline Mode: Operations will be buffered and synced when reconnected
</div>
<div class="editor-container">
<textarea class="editor-textarea" id="editor" placeholder="Start typing to collaborate..."></textarea>
<div class="cursor-overlay" id="cursorOverlay"></div>
</div>
</div>
<!-- Info Panel -->
<div class="info-panel">
<div class="panel">
<div class="panel-header">Network Topology</div>
<div class="network-graph">
<canvas class="network-canvas" id="networkCanvas"></canvas>
</div>
</div>
<div class="panel">
<div class="panel-header">Statistics</div>
<div class="panel-content">
<div class="stats-grid">
<div class="stat-card">
<div class="stat-value" id="statOps">0</div>
<div class="stat-label">Operations</div>
</div>
<div class="stat-card">
<div class="stat-value" id="statBytes">0</div>
<div class="stat-label">Bytes Sent</div>
</div>
<div class="stat-card">
<div class="stat-value" id="statLatency">0</div>
<div class="stat-label">Avg Latency</div>
</div>
<div class="stat-card">
<div class="stat-value" id="statCompression">0%</div>
<div class="stat-label">Compression</div>
</div>
</div>
</div>
</div>
<div class="panel" style="flex: 1;">
<div class="panel-header">Operation Log</div>
<div class="operations-log" id="operationsLog">
<div class="empty-state">No operations yet</div>
</div>
</div>
</div>
<!-- Footer -->
<footer class="footer">
<div class="vector-clock">
<span style="color: var(--text-secondary);">Vector Clock:</span>
<div id="vectorClockDisplay"></div>
</div>
<div class="connection-status">
<div class="conn-item">
Peers: <span class="conn-value" id="peerCount">0</span>
</div>
<div class="conn-item">
Pending: <span class="conn-value" id="pendingOps">0</span>
</div>
<div class="conn-item">
Buffer: <span class="conn-value" id="bufferSize">0</span>
</div>
</div>
</footer>
</div>
<script>
// ===========================================
// CRDT Implementation - RGA (Replicated Growable Array)
// ===========================================
class Char {
constructor(id, leftOrigin, rightOrigin, value, deleted = false) {
this.id = id; // {site: number, clock: number}
this.leftOrigin = leftOrigin;
this.rightOrigin = rightOrigin;
this.value = value;
this.deleted = deleted;
}
static compareId(a, b) {
if (a.clock !== b.clock) return a.clock - b.clock;
return a.site - b.site;
}
}
class VectorClock {
constructor() {
this.clocks = new Map();
}
increment(siteId) {
const current = this.clocks.get(siteId) || 0;
this.clocks.set(siteId, current + 1);
return current + 1;
}
get(siteId) {
return this.clocks.get(siteId) || 0;
}
merge(other) {
for (const [site, clock] of other.clocks) {
const current = this.clocks.get(site) || 0;
this.clocks.set(site, Math.max(current, clock));
}
}
happensBefore(other) {
let atLeastOneLess = false;
for (const [site, clock] of this.clocks) {
const otherClock = other.get(site);
if (clock > otherClock) return false;
if (clock < otherClock) atLeastOneLess = true;
}
return atLeastOneLess;
}
toJson() {
return Object.fromEntries(this.clocks);
}
static fromJson(json) {
const vc = new VectorClock();
for (const [site, clock] of Object.entries(json)) {
vc.clocks.set(parseInt(site), clock);
}
return vc;
}
}
class RGACRDT {
constructor(siteId) {
this.siteId = siteId;
this.clock = 0;
this.vectorClock = new VectorClock();
this.chars = [];
this.tombstones = [];
this.operationBuffer = [];
this.pendingOperations = [];
}
generateId() {
this.clock++;
this.vectorClock.increment(this.siteId);
return { site: this.siteId, clock: this.clock };
}
// Insert at visible position
insert(position, value) {
const left = this.findCharAtPosition(position - 1);
const right = this.findCharAtPosition(position);
const leftOrigin = left ? left.id : null;
const rightOrigin = right ? right.id : null;
const char = new Char(
this.generateId(),
leftOrigin,
rightOrigin,
value
);
this.insertChar(char);
return this.createOperation('insert', char);
}
delete(position) {
const char = this.findCharAtPosition(position);
if (!char || char.deleted) return null;
char.deleted = true;
this.tombstones.push(char.id);
return this.createOperation('delete', { id: char.id });
}
findCharAtPosition(position) {
let visiblePos = -1;
for (const char of this.chars) {
if (!char.deleted) {
visiblePos++;
if (visiblePos === position) return char;
}
}
return null;
}
findCharById(id) {
return this.chars.find(c =>
c.id.site === id.site && c.id.clock === id.clock
);
}
insertChar(char) {
// Find insertion position using RGA algorithm
let insertIndex = 0;
// Find the left bound
if (char.leftOrigin) {
const leftIndex = this.chars.findIndex(c =>
c.id.site === char.leftOrigin.site &&
c.id.clock === char.leftOrigin.clock
);
if (leftIndex !== -1) {
insertIndex = leftIndex + 1;
}
}
// Scan right until we find proper position
while (insertIndex < this.chars.length) {
const current = this.chars[insertIndex];
// Check if we've passed the right bound
if (char.rightOrigin &&
current.id.site === char.rightOrigin.site &&
current.id.clock === char.rightOrigin.clock) {
break;
}
// Check if current char should come before our new char
if (current.leftOrigin &&
char.leftOrigin &&
current.leftOrigin.site === char.leftOrigin.site &&
current.leftOrigin.clock === char.leftOrigin.clock) {
// Tie-breaker: compare IDs
if (Char.compareId(current.id, char.id) < 0) {
insertIndex++;
continue;
}
}
break;
}
this.chars.splice(insertIndex, 0, char);
}
createOperation(type, data) {
return {
type,
data,
id: this.generateId(),
vectorClock: this.vectorClock.toJson(),
timestamp: Date.now()
};
}
applyOperation(operation) {
// Causality check
const opVC = VectorClock.fromJson(operation.vectorClock);
if (operation.type === 'insert') {
const char = new Char(
operation.data.id,
operation.data.leftOrigin,
operation.data.rightOrigin,
operation.data.value,
operation.data.deleted
);
// Check if already applied
if (this.findCharById(char.id)) return false;
this.insertChar(char);
this.vectorClock.merge(opVC);
return true;
}
if (operation.type === 'delete') {
const char = this.findCharById(operation.data.id);
if (char && !char.deleted) {
char.deleted = true;
this.tombstones.push(char.id);
this.vectorClock.merge(opVC);
return true;
}
return false;
}
return false;
}
getText() {
return this.chars
.filter(c => !c.deleted)
.map(c => c.value)
.join('');
}
getPositionFromIndex(charIndex) {
let visiblePos = -1;
for (let i = 0; i < this.chars.length; i++) {
if (!this.chars[i].deleted) {
visiblePos++;
if (visiblePos === charIndex) return i;
}
}
return -1;
}
}
// ===========================================
// Delta Compression
// ===========================================
class DeltaCompressor {
static compress(operations) {
if (operations.length === 0) return { ops: [], saved: 0 };
// Run-length encode consecutive operations from same site
const compressed = [];
let current = null;
let saved = 0;
for (const op of operations) {
if (current &&
current.type === op.type &&
current.id.site === op.id.site &&
op.type === 'delete') {
// Batch deletes
current.batch = current.batch || [];
current.batch.push(op.data);
saved += JSON.stringify(op).length;
} else {
if (current) compressed.push(current);
current = { ...op };
}
}
if (current) compressed.push(current);
return { ops: compressed, saved };
}
static decompress(compressedOps) {
const operations = [];
for (const op of compressedOps) {
if (op.batch) {
// Expand batched operations
for (const data of op.batch) {
operations.push({
type: op.type,
data,
id: op.id,
vectorClock: op.vectorClock,
timestamp: op.timestamp
});
}
} else {
operations.push(op);
}
}
return operations;
}
}
// ===========================================
// Abuse Mitigation
// ===========================================
class AbuseMitigator {
constructor() {
this.rates = new Map(); // siteId -> { count, lastReset }
this.reputations = new Map(); // siteId -> score (0-100)
this.blockedSites = new Set();
this.config = {
maxOpsPerSecond: 50,
maxOpsPerMinute: 500,
maxDocSize: 100000,
maxOpSize: 10000,
reputationDecay: 0.99
};
}
checkRateLimit(siteId) {
const now = Date.now();
let rate = this.rates.get(siteId);
if (!rate || now - rate.lastReset > 60000) {
rate = { count: 0, lastReset: now };
this.rates.set(siteId, rate);
}
rate.count++;
if (rate.count > this.config.maxOpsPerMinute) {
this.decreaseReputation(siteId, 10);
return { allowed: false, reason: 'Rate limit exceeded' };
}
return { allowed: true };
}
validateOperation(operation, docSize) {
// Size checks
const opSize = JSON.stringify(operation).length;
if (opSize > this.config.maxOpSize) {
return { valid: false, reason: 'Operation too large' };
}
if (operation.type === 'insert') {
if (docSize + operation.data.value.length > this.config.maxDocSize) {
return { valid: false, reason: 'Document size limit exceeded' };
}
// Check for suspicious content
if (this.containsSuspiciousContent(operation.data.value)) {
this.decreaseReputation(operation.id.site, 20);
return { valid: false, reason: 'Suspicious content detected' };
}
}
return { valid: true };
}
containsSuspiciousContent(value) {
// Check for potential script injection or excessive repetition
if (/<script|javascript:|data:/i.test(value)) return true;
if (/(.)\1{100,}/.test(value)) return true; // 100+ same chars
return false;
}
getReputation(siteId) {
return this.reputations.get(siteId) || 50;
}
decreaseReputation(siteId, amount) {
const current = this.getReputation(siteId);
const newValue = Math.max(0, current - amount);
this.reputations.set(siteId, newValue);
if (newValue < 10) {
this.blockedSites.add(siteId);
}
}
increaseReputation(siteId, amount) {
const current = this.getReputation(siteId);
this.reputations.set(siteId, Math.min(100, current + amount));
}
isBlocked(siteId) {
return this.blockedSites.has(siteId);
}
}
// ===========================================
// P2P Communication Layer
// ===========================================
class P2PLayer {
constructor(siteId) {
this.siteId = siteId;
this.peers = new Map();
this.channel = null;
this.onMessage = null;
this.isOffline = false;
this.messageQueue = [];
this.initBroadcastChannel();
}
initBroadcastChannel() {
// Use BroadcastChannel for same-browser tab communication
this.channel = new BroadcastChannel('crdt-collab');
this.channel.onmessage = (event) => {
if (this.isOffline) {
this.messageQueue.push(event.data);
return;
}
if (event.data.sender !== this.siteId && this.onMessage) {
this.onMessage(event.data);
}
};
}
broadcast(message) {
const fullMessage = {
...message,
sender: this.siteId,
timestamp: Date.now()
};
if (this.isOffline) {
this.messageQueue.push(fullMessage);
return;
}
this.channel.postMessage(fullMessage);
}
sendToPeer(peerId, message) {
this.broadcast({ ...message, target: peerId });
}
setOffline(offline) {
this.isOffline = offline;
if (!offline && this.messageQueue.length > 0) {
// Flush queued messages
const queue = [...this.messageQueue];
this.messageQueue = [];
setTimeout(() => {
queue.forEach(msg => {
if (msg.sender === this.siteId) {
this.channel.postMessage(msg);
} else if (this.onMessage) {
this.onMessage(msg);
}
});
}, 100);
}
}
getPendingCount() {
return this.messageQueue.length;
}
}
// ===========================================
// Main Editor Controller
// ===========================================
class CollaborativeEditor {
constructor() {
this.siteId = Math.floor(Math.random() * 10000);
this.crdt = new RGACRDT(this.siteId);
this.p2p = new P2PLayer(this.siteId);
this.abuseMitigator = new AbuseMitigator();
this.peers = new Map();
this.remoteCursors = new Map();
this.stats = {
ops: 0,
bytesSent: 0,
latencies: [],
compressionSaved: 0
};
this.isOffline = false;
this.pendingOps = [];
this.initUI();
this.initEventListeners();
this.announcePresence();
this.startBackgroundAnimation();
this.startNetworkVisualization();
}
initUI() {
this.editorEl = document.getElementById('editor');
this.cursorOverlay = document.getElementById('cursorOverlay');
this.statusDot = document.getElementById('statusDot');
this.statusText = document.getElementById('statusText');
this.siteIdDisplay = document.getElementById('siteIdDisplay');
this.peersList = document.getElementById('peersList');
this.operationsLog = document.getElementById('operationsLog');
this.vectorClockDisplay = document.getElementById('vectorClockDisplay');
this.offlineBanner = document.getElementById('offlineBanner');
this.siteIdDisplay.textContent = this.siteId;
this.statusText.textContent = 'Connected';
this.statusDot.classList.remove('error', 'warning');
}
initEventListeners() {
let lastText = '';
let isApplyingRemote = false;
this.editorEl.addEventListener('input', (e) => {
if (isApplyingRemote) return;
const newText = this.editorEl.value;
const oldText = lastText;
lastText = newText;
// Calculate diff
const diff = this.computeDiff(oldText, newText);
if (diff) {
this.handleLocalChange(diff);
}
});
this.editorEl.addEventListener('selectionchange', () => {
this.broadcastCursor();
});
// Handle P2P messages
this.p2p.onMessage = (message) => {
this.handleRemoteMessage(message);
};
// Periodic sync
setInterval(() => this.syncPending(), 1000);
setInterval(() => this.updateStats(), 500);
}
computeDiff(oldText, newText) {
const oldLen = oldText.length;
const newLen = newText.length;
if (newLen > oldLen) {
// Insertion
let pos = 0;
while (pos < oldLen && oldText[pos] === newText[pos]) pos++;
const inserted = newText.slice(pos, pos + (newLen - oldLen));
return { type: 'insert', position: pos, value: inserted };
} else if (newLen < oldLen) {
// Deletion
let start = 0;
while (start < newLen && oldText[start] === newText[start]) start++;
return { type: 'delete', position: start, length: oldLen - newLen };
}
return null;
}
handleLocalChange(diff) {
// Rate limiting
const rateCheck = this.abuseMitigator.checkRateLimit(this.siteId);
if (!rateCheck.allowed) {
console.warn('Rate limited:', rateCheck.reason);
return;
}
const operations = [];
if (diff.type === 'insert') {
for (let i = 0; i < diff.value.length; i++) {
const op = this.crdt.insert(diff.position + i, diff.value[i]);
if (op) {
const validation = this.abuseMitigator.validateOperation(
op, this.crdt.getText().length
);
if (validation.valid) {
operations.push(op);
}
}
}
} else if (diff.type === 'delete') {
for (let i = 0; i < diff.length; i++) {
const op = this.crdt.delete(diff.position);
if (op) operations.push(op);
}
}
// Broadcast operations with compression
const { ops: compressed, saved } = DeltaCompressor.compress(operations);
this.p2p.broadcast({
type: 'operations',
operations: compressed,
compressed: operations.length !== compressed.length
});
this.stats.ops += operations.length;
this.stats.bytesSent += JSON.stringify(compressed).length;
this.stats.compressionSaved += saved;
this.logOperations(operations);
this.updateVectorClockDisplay();
}
handleRemoteMessage(message) {
if (this.abuseMitigator.isBlocked(message.sender)) {
return;
}
switch (message.type) {
case 'presence':
this.handlePresence(message);
break;
case 'operations':
this.handleRemoteOperations(message);
break;
case 'cursor':
this.handleRemoteCursor(message);
break;
case 'sync-request':
this.handleSyncRequest(message);
break;
case 'sync-response':
this.handleSyncResponse(message);
break;
case 'disconnect':
this.handleDisconnect(message);
break;
}
}
handleRemoteOperations(message) {
const operations = message.compressed
? DeltaCompressor.decompress(message.operations)
: message.operations;
for (const op of operations) {
const validation = this.abuseMitigator.validateOperation(
op, this.crdt.getText().length
);
if (!validation.valid) {
this.abuseMitigator.decreaseReputation(message.sender, 5);
continue;
}
const applied = this.crdt.applyOperation(op);
if (applied) {
this.stats.ops++;
this.abuseMitigator.increaseReputation(message.sender, 1);
}
}
// Update editor
this.updateEditorContent();
this.logOperations(operations.slice(-5), message.sender);
this.updateVectorClockDisplay();
}
updateEditorContent() {
const newText = this.crdt.getText();
const oldText = this.editorEl.value;
if (newText !== oldText) {
const selectionStart = this.editorEl.selectionStart;
const selectionEnd = this.editorEl.selectionEnd;
this.editorEl.value = newText;
// Try to preserve cursor position
this.editorEl.setSelectionRange(selectionStart, selectionEnd);
}
}
handlePresence(message) {
if (message.sender === this.siteId) return;
this.peers.set(message.sender, {
id: message.sender,
name: message.name || `Peer ${message.sender}`,
color: message.color || this.generatePeerColor(message.sender),
lastSeen: Date.now(),
reputation: this.abuseMitigator.getReputation(message.sender)
});
this.updatePeersList();
}
handleRemoteCursor(message) {
if (message.sender === this.siteId) return;
this.remoteCursors.set(message.sender, {
position: message.position,
color: this.generatePeerColor(message.sender),
name: `Peer ${message.sender}`,
timestamp: Date.now()
});
this.renderRemoteCursors();
}
handleSyncRequest(message) {
// Send full document state
this.p2p.sendToPeer(message.sender, {
type: 'sync-response',
chars: this.crdt.chars,
vectorClock: this.crdt.vectorClock.toJson()
});
}
handleSyncResponse(message) {
// Reconstruct document from sync
if (message.chars) {
this.crdt.chars = message.chars.map(c => {
const char = new Char(c.id, c.leftOrigin, c.rightOrigin, c.value, c.deleted);
return char;
});
this.crdt.vectorClock = VectorClock.fromJson(message.vectorClock);
this.updateEditorContent();
}
}
handleDisconnect(message) {
this.peers.delete(message.sender);
this.remoteCursors.delete(message.sender);
this.updatePeersList();
this.renderRemoteCursors();
}
announcePresence() {
this.p2p.broadcast({
type: 'presence',
name: `Peer ${this.siteId}`,
color: this.generatePeerColor(this.siteId)
});
// Periodic presence announcements
setInterval(() => {
this.p2p.broadcast({ type: 'presence' });
}, 5000);
}
broadcastCursor() {
const position = this.editorEl.selectionStart;
this.p2p.broadcast({
type: 'cursor',
position
});
}
generatePeerColor(siteId) {
const hue = (siteId * 137.508) % 360; // Golden angle
return `hsl(${hue}, 70%, 50%)`;
}
updatePeersList() {
const html = [];
// Local peer
html.push(`
<div class="peer-item local">
<div class="peer-avatar" style="background: ${this.generatePeerColor(this.siteId)}">
${this.siteId}
</div>
<div class="peer-info">
<div class="peer-name">You (Local)</div>
<div class="peer-status">Site ID: ${this.siteId}</div>
</div>
<div class="peer-reputation good">100</div>
</div>
`);
// Remote peers
for (const [id, peer] of this.peers) {
const rep = this.abuseMitigator.getReputation(id);
const repClass = rep > 70 ? 'good' : rep > 30 ? 'warning' : 'bad';
html.push(`
<div class="peer-item">
<div class="peer-avatar" style="background: ${peer.color}">
${id}
</div>
<div class="peer-info">
<div class="peer-name">${peer.name}</div>
<div class="peer-status">Last seen: ${Math.round((Date.now() - peer.lastSeen) / 1000)}s ago</div>
</div>
<div class="peer-reputation ${repClass}">${rep}</div>
</div>
`);
}
this.peersList.innerHTML = html.join('') || '<div class="empty-state">No peers connected</div>';
document.getElementById('peerCount').textContent = this.peers.size;
}
renderRemoteCursors() {
let html = '';
for (const [id, cursor] of this.remoteCursors) {
// Approximate cursor position (simplified)
const lineHeight = 22;
const charWidth = 8.4;
const lines = this.editorEl.value.substring(0, cursor.position).split('\n');
const line = lines.length - 1;
const col = lines[lines.length - 1].length;
const top = line * lineHeight + 20;
const left = col * charWidth + 20;
html += `
<div class="remote-cursor" style="background: ${cursor.color}; top: ${top}px; left: ${left}px;">
<div class="cursor-label" style="background: ${cursor.color}">${cursor.name}</div>
</div>
`;
}
this.cursorOverlay.innerHTML = html;
}
logOperations(operations, sender = null) {
const html = operations.map(op => {
const typeClass = op.type;
const detail = op.type === 'insert'
? `"${op.data.value}"`
: `del ${op.data.id.site}:${op.data.id.clock}`;
return `
<div class="log-entry">
<span>${sender || this.siteId} - ${detail}</span>
<span class="log-type ${typeClass}">${op.type}</span>
</div>
`;
}).join('');
this.operationsLog.innerHTML = html + this.operationsLog.innerHTML;
// Keep only last 50 entries
const entries = this.operationsLog.querySelectorAll('.log-entry');
if (entries.length > 50) {
for (let i = 50; i < entries.length; i++) {
entries[i].remove();
}
}
}
updateVectorClockDisplay() {
const vc = this.crdt.vectorClock.toJson();
const html = Object.entries(vc)
.slice(-5)
.map(([site, clock]) => `<span class="clock-item">${site}: ${clock}</span>`)
.join('');
this.vectorClockDisplay.innerHTML = html;
}
updateStats() {
document.getElementById('statOps').textContent = this.stats.ops;
document.getElementById('statBytes').textContent = this.formatBytes(this.stats.bytesSent);
const avgLatency = this.stats.latencies.length > 0
? Math.round(this.stats.latencies.reduce((a, b) => a + b, 0) / this.stats.latencies.length)
: 0;
document.getElementById('statLatency').textContent = `${avgLatency}ms`;
const compressionRate = this.stats.bytesSent > 0
? Math.round((this.stats.compressionSaved / this.stats.bytesSent) * 100)
: 0;
document.getElementById('statCompression').textContent = `${compressionRate}%`;
document.getElementById('pendingOps').textContent = this.p2p.getPendingCount();
document.getElementById('bufferSize').textContent = this.crdt.chars.length;
}
formatBytes(bytes) {
if (bytes < 1024) return bytes;
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + 'KB';
return (bytes / (1024 * 1024)).toFixed(1) + 'MB';
}
// Public API
syncAll() {
this.p2p.broadcast({ type: 'sync-request' });
}
simulateOffline() {
this.isOffline = !this.isOffline;
this.p2p.setOffline(this.isOffline);
this.offlineBanner.style.display = this.isOffline ? 'block' : 'none';
this.statusDot.className = 'status-dot ' + (this.isOffline ? 'warning' : '');
this.statusText.textContent = this.isOffline ? 'Offline' : 'Connected';
}
simulateConflict() {
// Simulate concurrent edits from different sites
const testOps = [
{ type: 'insert', position: 0, value: 'A' },
{ type: 'insert', position: 0, value: 'B' },
{ type: 'insert', position: 0, value: 'C' }
];
const remoteSite = 9999;
for (const op of testOps) {
const remoteOp = {
type: 'insert',
data: {
id: { site: remoteSite, clock: Math.random() * 10000 },
leftOrigin: null,
rightOrigin: null,
value: op.value
},
id: { site: remoteSite, clock: Date.now() },
vectorClock: { [remoteSite]: 1 },
timestamp: Date.now()
};
this.crdt.applyOperation(remoteOp);
}
this.updateEditorContent();
}
clearDocument() {
this.crdt = new RGACRDT(this.siteId);
this.editorEl.value = '';
this.remoteCursors.clear();
this.renderRemoteCursors();
}
startBackgroundAnimation() {
const canvas = document.getElementById('bgCanvas');
const ctx = canvas.getContext('2d');
const resize = () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
};
resize();
window.addEventListener('resize', resize);
const particles = [];
for (let i = 0; i < 50; i++) {
particles.push({
x: Math.random() * canvas.width,
y: Math.random() * canvas.height,
vx: (Math.random() - 0.5) * 0.5,
vy: (Math.random() - 0.5) * 0.5,
size: Math.random() * 2 + 1,
opacity: Math.random() * 0.5 + 0.1
});
}
const animate = () => {
ctx.fillStyle = 'rgba(10, 14, 23, 0.1)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
particles.forEach(p => {
p.x += p.vx;
p.y += p.vy;
if (p.x < 0 || p.x > canvas.width) p.vx *= -1;
if (p.y < 0 || p.y > canvas.height) p.vy *= -1;
ctx.beginPath();
ctx.arc(p.x, p.y, p.size, 0, Math.PI * 2);
ctx.fillStyle = `rgba(6, 182, 212, ${p.opacity})`;
ctx.fill();
});
// Draw connections
ctx.strokeStyle = 'rgba(6, 182, 212, 0.05)';
ctx.lineWidth = 1;
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 < 150) {
ctx.beginPath();
ctx.moveTo(particles[i].x, particles[i].y);
ctx.lineTo(particles[j].x, particles[j].y);
ctx.stroke();
}
}
}
requestAnimationFrame(animate);
};
animate();
}
startNetworkVisualization() {
const canvas = document.getElementById('networkCanvas');
const ctx = canvas.getContext('2d');
const resize = () => {
const rect = canvas.parentElement.getBoundingClientRect();
canvas.width = rect.width;
canvas.height = rect.height;
};
resize();
window.addEventListener('resize', resize);
const nodes = new Map();
nodes.set(this.siteId, {
x: canvas.width / 2,
y: canvas.height / 2,
vx: 0,
vy: 0,
color: this.generatePeerColor(this.siteId)
});
const animate = () => {
ctx.fillStyle = '#0a0e17';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Update nodes
for (const [id, peer] of this.peers) {
if (!nodes.has(id)) {
nodes.set(id, {
x: Math.random() * canvas.width,
y: Math.random() * canvas.height,
vx: (Math.random() - 0.5) * 2,
vy: (Math.random() - 0.5) * 2,
color: this.generatePeerColor(id)
});
}
}
// Remove disconnected nodes
for (const [id] of nodes) {
if (id !== this.siteId && !this.peers.has(id)) {
nodes.delete(id);
}
}
// Update positions
for (const [id, node] of nodes) {
node.x += node.vx;
node.y += node.vy;
// Bounce off edges
if (node.x < 20 || node.x > canvas.width - 20) node.vx *= -1;
if (node.y < 20 || node.y > canvas.height - 20) node.vy *= -1;
node.x = Math.max(20, Math.min(canvas.width - 20, node.x));
node.y = Math.max(20, Math.min(canvas.height - 20, node.y));
}
// Draw connections
const localNode = nodes.get(this.siteId);
ctx.strokeStyle = 'rgba(6, 182, 212, 0.3)';
ctx.lineWidth = 1;
for (const [id, node] of nodes) {
if (id !== this.siteId) {
ctx.beginPath();
ctx.moveTo(localNode.x, localNode.y);
ctx.lineTo(node.x, node.y);
ctx.stroke();
}
}
// Draw nodes
for (const [id, node] of nodes) {
ctx.beginPath();
ctx.arc(node.x, node.y, id === this.siteId ? 10 : 8, 0, Math.PI * 2);
ctx.fillStyle = node.color;
ctx.fill();
// Glow effect for local node
if (id === this.siteId) {
ctx.beginPath();
ctx.arc(node.x, node.y, 15, 0, Math.PI * 2);
ctx.strokeStyle = node.color;
ctx.lineWidth = 2;
ctx.stroke();
}
}
requestAnimationFrame(animate);
};
animate();
}
syncPending() {
// Process any pending operations during offline mode
if (!this.isOffline && this.p2p.messageQueue.length > 0) {
// Operations will be processed by P2PLayer
}
}
}
// ===========================================
// Initialize
// ===========================================
let editor;
document.addEventListener('DOMContentLoaded', () => {
editor = new CollaborativeEditor();
});
</script>
</body>
</html>