"use client";
import Editor, { type OnMount } from "@monaco-editor/react";
import { memo, useCallback, useEffect, useRef, useState } from "react";
import type { editor as MonacoEditor } from "monaco-editor";
import * as Y from "yjs";
import * as awarenessProtocol from "y-protocols/awareness.js";
import type { Language } from "@/lib/config";
import { defineEditorTheme, editorTheme } from "@/lib/monaco-theme";
const editorOptions: MonacoEditor.IStandaloneEditorConstructionOptions = {
minimap: { enabled: false }, glyphMargin: false, lineNumbersMinChars: 3,
lineDecorationsWidth: 14, folding: false,
fontFamily: "var(--font-jetbrains-mono), monospace", fontSize: 14, lineHeight: 20,
padding: { top: 10, bottom: 22 }, scrollBeyondLastLine: false,
wordWrap: "on", renderLineHighlight: "line", overviewRulerBorder: false,
automaticLayout: true, readOnly: true, tabSize: 2,
};
const encode = (bytes: Uint8Array) => {
let binary = "";
for (const byte of bytes) binary += String.fromCharCode(byte);
return btoa(binary);
};
const decode = (value: string) => Uint8Array.from(atob(value), (char) => char.charCodeAt(0));
const animalEmojis = ["🦊", "🐼", "🐨", "🐸", "🐱", "🐰", "🐻", "🐯", "🦁", "🦉"] as const;
export const participantColors = [
"#FF206E", "#41EAD4", "#4CC9F0", "#4361EE", "#F72585",
"#FB5607", "#FEE440", "#9B5DE5", "#16DB65", "#70E000",
"#FF4800", "#2D3142", "#FF66D8", "#D58936", "#00A896",
] as const;
const guestNames = [
"Кракозябра", "Шушпанчик", "Бумбурум", "Хрумзик", "Плюмпик", "Чудобряк",
"Фырфыр", "Ляпсик", "Кувыркун", "Зюзяка", "Дрындуль", "Бубнилка",
"Пыхтелка", "Шмякозавр", "Трындюля", "Крошкобум", "Чупырчик", "Брякуша",
"Мурчалка", "Жужелка", "Фантазюк", "Шалабум", "Пушкодрыг", "Хохотунчик",
"Карамбуль", "Топотун", "Бульбозик", "Чудилкин", "Прыгоскок", "Шуршун",
] as const;
function participantHash(identity: string) {
let hash = 2166136261;
for (const char of identity) hash = Math.imul(hash ^ char.charCodeAt(0), 16777619);
return hash >>> 0;
}
function participantColor(identity: string) {
return participantColors[participantHash(identity) % participantColors.length];
}
function savedParticipantColor(userId?: number) {
try {
const color = localStorage.getItem(`trycode:participant-color:${userId ? `user:${userId}` : "guest"}`);
return participantColors.find((option) => option === color) ?? null;
} catch { return null; }
}
function participantForeground(color: string) {
if (["#FF206E", "#F72585", "#FB5607", "#FF4800", "#D58936", "#00A896"].includes(color.toUpperCase())) return "#ffffff";
const channels = [1, 3, 5].map((index) => {
const value = parseInt(color.slice(index, index + 2), 16) / 255;
return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
});
const luminance = channels[0] * 0.2126 + channels[1] * 0.7152 + channels[2] * 0.0722;
return luminance > 0.22 ? "#111827" : "#ffffff";
}
export type PresenceUser = { id: number; name: string; emoji: string; color: string; foreground: string; background: string; isLocal: boolean };
function guestIdentity() {
const storageKey = "trycode:guest-identity-v3";
try {
const saved = JSON.parse(sessionStorage.getItem(storageKey) || "null") as { nameIndex?: number; colorId?: string } | null;
if (saved && Number.isInteger(saved.nameIndex) && saved.nameIndex! >= 0 && saved.nameIndex! < guestNames.length) {
const colorId = saved.colorId || crypto.randomUUID();
if (!saved.colorId) sessionStorage.setItem(storageKey, JSON.stringify({ ...saved, colorId }));
return { name: guestNames[saved.nameIndex!], colorId };
}
} catch { /* Private browsing may block storage. */ }
const nameIndex = Math.floor(Math.random() * guestNames.length);
const colorId = crypto.randomUUID();
try { sessionStorage.setItem(storageKey, JSON.stringify({ nameIndex, colorId })); } catch { /* The generated name still works for this visit. */ }
return { name: guestNames[nameIndex], colorId };
}
function presenceUsers(awareness: awarenessProtocol.Awareness): PresenceUser[] {
const states = [...awareness.getStates()].filter(([id, state]) => id === awareness.clientID || (state.user && typeof state.user.name === "string"));
const guestCounts = new Map<string, number>();
for (const [, state] of states) {
const guestName = state.user?.guestName as string | undefined;
if (guestName && (state.user?.name === guestName || !state.user?.name)) guestCounts.set(guestName, (guestCounts.get(guestName) ?? 0) + 1);
}
const guestNumbers = new Map<string, number>();
const usedEmojis = new Set<string>();
const usedColors = new Set<string>();
return states.sort(([a], [b]) => a - b).map(([id, state]) => {
const user = state.user as { name?: string; guestName?: string; emoji?: string; color?: string; background?: string; customColor?: boolean } | undefined;
const preferred = animalEmojis.indexOf(user?.emoji as typeof animalEmojis[number]);
const start = preferred >= 0 ? preferred : id % animalEmojis.length;
const emoji = Array.from({ length: animalEmojis.length }, (_, offset) => animalEmojis[(start + offset) % animalEmojis.length]).find((candidate) => !usedEmojis.has(candidate)) ?? animalEmojis[start];
usedEmojis.add(emoji);
const preferredColor = participantColors.findIndex((color) => color.toLowerCase() === user?.color?.toLowerCase());
const colorStart = preferredColor >= 0 ? preferredColor : id % participantColors.length;
const color = user?.customColor && preferredColor >= 0
? participantColors[preferredColor]
: Array.from({ length: participantColors.length }, (_, offset) => participantColors[(colorStart + offset) % participantColors.length]).find((candidate) => !usedColors.has(candidate)) ?? participantColors[colorStart];
usedColors.add(color);
const baseName = user?.name || user?.guestName || guestNames[id % guestNames.length];
const isGuest = !user?.name || user.name === user.guestName;
let duplicateNumber: number | null = null;
if (isGuest && (guestCounts.get(baseName) ?? 0) > 1) {
duplicateNumber = (guestNumbers.get(baseName) ?? 0) + 1;
guestNumbers.set(baseName, duplicateNumber);
}
return {
id,
name: duplicateNumber ? `${baseName} ${duplicateNumber}` : baseName,
emoji,
color,
foreground: participantForeground(color),
background: color,
isLocal: id === awareness.clientID,
};
}).sort((a, b) => Number(b.isLocal) - Number(a.isLocal) || a.id - b.id);
}
function bindEditor(editor: MonacoEditor.IStandaloneCodeEditor, text: Y.Text, awareness: awarenessProtocol.Awareness, onPresence: (users: PresenceUser[]) => void) {
const model = editor.getModel()!;
const localOrigin = Symbol("monaco");
let applyingRemote = false;
const onModelChange = editor.onDidChangeModelContent((event) => {
if (applyingRemote) return;
text.doc?.transact(() => {
for (const change of [...event.changes].sort((a, b) => b.rangeOffset - a.rangeOffset)) {
if (change.rangeLength) text.delete(change.rangeOffset, change.rangeLength);
if (change.text) text.insert(change.rangeOffset, change.text);
}
}, localOrigin);
});
const onTextChange = (event: Y.YTextEvent) => {
if (event.transaction.origin === localOrigin) return;
let offset = 0;
const edits: MonacoEditor.IIdentifiedSingleEditOperation[] = [];
for (const part of event.delta) {
if (part.retain) offset += part.retain;
if (part.delete) {
const start = model.getPositionAt(offset);
const end = model.getPositionAt(offset + part.delete);
edits.push({ range: { startLineNumber: start.lineNumber, startColumn: start.column, endLineNumber: end.lineNumber, endColumn: end.column }, text: "" });
offset += part.delete;
}
if (part.insert) {
const start = model.getPositionAt(offset);
edits.push({ range: { startLineNumber: start.lineNumber, startColumn: start.column, endLineNumber: start.lineNumber, endColumn: start.column }, text: String(part.insert) });
}
}
if (edits.length) {
applyingRemote = true;
try { model.applyEdits(edits); } finally { applyingRemote = false; }
}
};
text.observe(onTextChange);
const localSelection = editor.onDidChangeCursorSelection((event) => {
awareness.setLocalStateField("selection", {
anchor: model.getOffsetAt(event.selection.getStartPosition()),
head: model.getOffsetAt(event.selection.getEndPosition()),
});
});
const decorations = editor.createDecorationsCollection();
const style = document.createElement("style");
document.head.appendChild(style);
const cursorLabels = new Map<number, { widget: MonacoEditor.IContentWidget; element: HTMLDivElement }>();
const cursorActivity = new Map<number, { anchor: number; head: number; timer: ReturnType<typeof setTimeout> }>();
const updateRemoteCursors = () => {
const changes: MonacoEditor.IModelDeltaDecoration[] = [];
let rules = "";
const visible = new Set<number>();
for (const [clientId, state] of awareness.getStates()) {
if (clientId === awareness.clientID) continue;
const selection = state.selection as { anchor?: number; head?: number } | undefined;
if (!selection || !Number.isFinite(selection.anchor) || !Number.isFinite(selection.head)) continue;
visible.add(clientId);
const user = presenceUsers(awareness).find((entry) => entry.id === clientId)!;
rules += `.remote-selection-${clientId}{background:${user.color}33}.remote-caret-${clientId}{border-left:2px solid ${user.color};margin-left:-1px}`;
const anchor = Math.min(selection.anchor!, selection.head!);
const head = Math.max(selection.anchor!, selection.head!);
const start = model.getPositionAt(Math.max(0, Math.min(anchor, model.getValueLength())));
const end = model.getPositionAt(Math.max(0, Math.min(head, model.getValueLength())));
const caret = model.getPositionAt(Math.max(0, Math.min(selection.head!, model.getValueLength())));
let label = cursorLabels.get(clientId);
if (!label) {
const element = document.createElement("div");
element.className = "remote-cursor-label";
const widget: MonacoEditor.IContentWidget = {
getId: () => `remote-cursor-label-${clientId}`,
getDomNode: () => element,
getPosition: () => ({ position: caret, preference: [0] }),
};
label = { widget, element };
cursorLabels.set(clientId, label);
editor.addContentWidget(widget);
}
const previousActivity = cursorActivity.get(clientId);
if (!previousActivity || previousActivity.anchor !== selection.anchor || previousActivity.head !== selection.head) {
if (previousActivity) clearTimeout(previousActivity.timer);
label.element.classList.remove("is-idle");
const timer = setTimeout(() => label.element.classList.add("is-idle"), 5000);
cursorActivity.set(clientId, { anchor: selection.anchor!, head: selection.head!, timer });
}
label.widget.getPosition = () => ({ position: caret, preference: [0] });
label.element.style.backgroundColor = user.color;
label.element.style.color = user.foreground;
label.element.textContent = `${user.emoji} ${user.name}`;
editor.layoutContentWidget(label.widget);
if (anchor !== head) changes.push({ range: { startLineNumber: start.lineNumber, startColumn: start.column, endLineNumber: end.lineNumber, endColumn: end.column }, options: { inlineClassName: `remote-selection-${clientId}` } });
changes.push({ range: { startLineNumber: caret.lineNumber, startColumn: caret.column, endLineNumber: caret.lineNumber, endColumn: caret.column }, options: { beforeContentClassName: `remote-caret-${clientId}` } });
}
for (const [clientId, label] of cursorLabels) if (!visible.has(clientId)) {
editor.removeContentWidget(label.widget);
cursorLabels.delete(clientId);
const activity = cursorActivity.get(clientId);
if (activity) clearTimeout(activity.timer);
cursorActivity.delete(clientId);
}
style.textContent = rules;
decorations.set(changes);
onPresence(presenceUsers(awareness));
};
awareness.on("change", updateRemoteCursors);
text.observe(updateRemoteCursors);
updateRemoteCursors();
return () => {
onModelChange.dispose(); localSelection.dispose();
text.unobserve(onTextChange); text.unobserve(updateRemoteCursors);
awareness.off("change", updateRemoteCursors);
for (const activity of cursorActivity.values()) clearTimeout(activity.timer);
for (const label of cursorLabels.values()) editor.removeContentWidget(label.widget);
decorations.clear(); style.remove();
};
}
function CollaborativeEditorView({ id, language, canEdit, initialDraft, userName, userId, selectedColor, saveSignal, onSaveResult, onSavedContent, onContent, onConnection, onPresence, onMountEditor }: {
id: string; language: Language; canEdit: boolean; initialDraft?: string;
userName?: string; userId?: number; selectedColor?: string | null; saveSignal: number; onSaveResult: (saved: boolean) => void; onSavedContent: (value: string) => void; onPresence: (users: PresenceUser[]) => void;
onContent: (value: string) => void; onConnection: (connected: boolean) => void;
onMountEditor?: (editor: MonacoEditor.IStandaloneCodeEditor) => void;
}) {
const editorRef = useRef<MonacoEditor.IStandaloneCodeEditor | null>(null);
const canEditRef = useRef(canEdit);
const onContentRef = useRef(onContent);
const onConnectionRef = useRef(onConnection);
const onPresenceRef = useRef(onPresence);
const onSaveResultRef = useRef(onSaveResult);
const onSavedContentRef = useRef(onSavedContent);
const requestSaveRef = useRef<(() => void) | null>(null);
const userNameRef = useRef(userName);
const userIdRef = useRef(userId);
const selectedColorRef = useRef(selectedColor);
selectedColorRef.current = selectedColor;
const guestColorIdRef = useRef<string | null>(null);
const awarenessRef = useRef<awarenessProtocol.Awareness | null>(null);
const [mounted, setMounted] = useState(false);
const draftAppliedRef = useRef(false);
const [connectedLocal, setConnectedLocal] = useState(false);
useEffect(() => { canEditRef.current = canEdit; editorRef.current?.updateOptions({ readOnly: !canEdit || !connectedLocal }); }, [canEdit, connectedLocal]);
useEffect(() => { onContentRef.current = onContent; onConnectionRef.current = onConnection; onPresenceRef.current = onPresence; onSaveResultRef.current = onSaveResult; onSavedContentRef.current = onSavedContent; }, [onContent, onConnection, onPresence, onSaveResult, onSavedContent]);
useEffect(() => { if (saveSignal > 0) requestSaveRef.current?.(); }, [saveSignal]);
useEffect(() => {
userNameRef.current = userName;
userIdRef.current = userId;
const awareness = awarenessRef.current;
if (awareness) {
const guestName = awareness.getLocalState()?.user?.guestName;
const identity = userId ? `user:${userId}` : `guest:${guestColorIdRef.current}`;
const savedColor = savedParticipantColor(userId);
const color = selectedColorRef.current || savedColor || participantColor(identity);
awareness.setLocalStateField("user", { ...awareness.getLocalState()?.user, name: userName || guestName, emoji: animalEmojis[participantHash(identity) % animalEmojis.length], color, background: color, customColor: !!(selectedColorRef.current || savedColor) });
}
}, [userName, userId]);
useEffect(() => {
if (!selectedColor || !participantColors.some((color) => color === selectedColor)) return;
try { localStorage.setItem(`trycode:participant-color:${userId ? `user:${userId}` : "guest"}`, selectedColor); }
catch { /* The color still applies for this visit. */ }
const awareness = awarenessRef.current;
if (awareness) awareness.setLocalStateField("user", { ...awareness.getLocalState()?.user, color: selectedColor, background: selectedColor, customColor: true });
}, [selectedColor, userId]);
const onMount: OnMount = useCallback((editor) => {
editorRef.current = editor;
onMountEditor?.(editor);
editor.updateOptions({ readOnly: true });
setMounted(true);
}, [onMountEditor]);
useEffect(() => {
if (!mounted || !editorRef.current) return;
const editor = editorRef.current;
const model = editor.getModel();
if (!model) return;
const doc = new Y.Doc();
const text = doc.getText("content");
const awareness = new awarenessProtocol.Awareness(doc);
awarenessRef.current = awareness;
const { name, colorId } = guestIdentity();
guestColorIdRef.current = colorId;
const guestName = name;
const identity = userIdRef.current ? `user:${userIdRef.current}` : `guest:${colorId}`;
const savedColor = savedParticipantColor(userIdRef.current);
const color = selectedColorRef.current || savedColor || participantColor(identity);
awareness.setLocalStateField("user", { name: userNameRef.current || guestName, guestName, emoji: animalEmojis[participantHash(identity) % animalEmojis.length], color, background: color, customColor: !!(selectedColorRef.current || savedColor) });
const unbind = bindEditor(editor, text, awareness, (users) => onPresenceRef.current(users));
const base = process.env.NEXT_PUBLIC_REALTIME_URL || `${location.protocol === "https:" ? "wss:" : "ws:"}//${location.hostname}:3001`;
let socket: WebSocket;
let disposed = false;
let retryTimer: ReturnType<typeof setTimeout> | undefined;
let synced = false;
let pendingSave = false;
let localRevision = 0;
let acknowledgedRevision = 0;
const reportSaved = () => {
if (synced && acknowledgedRevision === localRevision) onSavedContentRef.current(text.toString());
};
requestSaveRef.current = () => {
if (!synced || socket?.readyState !== WebSocket.OPEN) { onSaveResultRef.current(false); return; }
pendingSave = true;
socket.send(JSON.stringify({ type: "save", seq: localRevision }));
};
const handleUpdate = (update: Uint8Array, origin: unknown) => {
if (origin !== "remote") localRevision += 1;
onContentRef.current(text.toString());
if (origin === "remote") {
reportSaved();
} else {
if (synced && socket?.readyState === WebSocket.OPEN) socket.send(JSON.stringify({ type: "update", payload: encode(update), seq: localRevision }));
}
};
doc.on("update", handleUpdate);
const handleAwareness = ({ added, updated, removed }: { added: number[]; updated: number[]; removed: number[] }, origin: unknown) => {
if (origin === "remote" || socket?.readyState !== WebSocket.OPEN) return;
const ids = [...added, ...updated, ...removed];
socket.send(JSON.stringify({ type: "awareness", payload: encode(awarenessProtocol.encodeAwarenessUpdate(awareness, ids)) }));
};
awareness.on("update", handleAwareness);
const connect = () => {
if (disposed) return;
synced = false;
socket = new WebSocket(`${base}/${id}`);
socket.onmessage = (event) => {
const message = JSON.parse(event.data) as { type: string; payload?: string; stateVector?: string; seq?: number; kind?: string; canEdit?: boolean };
if (message.type === "sync" && message.payload) {
const serverStateVector = message.stateVector ? decode(message.stateVector) : (() => {
const serverDoc = new Y.Doc();
Y.applyUpdate(serverDoc, decode(message.payload!));
const vector = Y.encodeStateVector(serverDoc);
serverDoc.destroy();
return vector;
})();
Y.applyUpdate(doc, decode(message.payload), "remote");
synced = true;
if (localRevision > acknowledgedRevision) {
socket.send(JSON.stringify({ type: "update", payload: encode(Y.encodeStateAsUpdate(doc, serverStateVector)), seq: localRevision }));
}
if (initialDraft && !draftAppliedRef.current && canEditRef.current) {
if (text.toString() !== initialDraft) doc.transact(() => { text.delete(0, text.length); text.insert(0, initialDraft); });
draftAppliedRef.current = true;
}
editor.updateOptions({ readOnly: !canEditRef.current });
setConnectedLocal(true);
onContentRef.current(text.toString());
reportSaved();
onConnectionRef.current(true);
const ids = [doc.clientID];
socket.send(JSON.stringify({ type: "awareness", payload: encode(awarenessProtocol.encodeAwarenessUpdate(awareness, ids)) }));
} else if (message.type === "update" && message.payload) {
Y.applyUpdate(doc, decode(message.payload), "remote");
reportSaved();
} else if (message.type === "awareness" && message.payload) {
awarenessProtocol.applyAwarenessUpdate(awareness, decode(message.payload), "remote");
} else if (message.type === "saved") {
if (Number.isSafeInteger(message.seq) && message.seq! <= localRevision) acknowledgedRevision = Math.max(acknowledgedRevision, message.seq!);
reportSaved();
if (message.kind === "manual" && pendingSave) {
pendingSave = false;
onSaveResultRef.current(true);
}
} else if (message.type === "denied") {
if (pendingSave) { pendingSave = false; onSaveResultRef.current(false); }
editor.updateOptions({ readOnly: true });
setConnectedLocal(false);
}
};
socket.onclose = () => {
if (pendingSave) { pendingSave = false; onSaveResultRef.current(false); }
onConnectionRef.current(false);
editor.updateOptions({ readOnly: true });
setConnectedLocal(false);
awarenessProtocol.removeAwarenessStates(awareness, [...awareness.getStates().keys()].filter((key) => key !== doc.clientID), "remote");
if (!disposed) retryTimer = setTimeout(connect, 1800);
};
socket.onerror = () => socket.close();
};
connect();
return () => {
disposed = true;
if (retryTimer) clearTimeout(retryTimer);
socket?.close();
requestSaveRef.current = null;
unbind();
awareness.destroy();
awarenessRef.current = null;
guestColorIdRef.current = null;
onPresenceRef.current([]);
doc.destroy();
onConnectionRef.current(false);
};
}, [id, mounted, initialDraft]);
return <Editor height="100%" language={language} defaultValue="" theme={editorTheme} beforeMount={defineEditorTheme} loading={null} onMount={onMount}
options={editorOptions} />;
}
export const CollaborativeEditor = memo(CollaborativeEditorView);
Code will run automatically after changes.
Code runs in an isolated environment.
Code runs in an isolated environment.