// "loro-crdt/web" is the entry build.ts bundles for every "loro-crdt" import. Its init is the // default export of loro_wasm.js, the module web/index.js re-exports, so there is one WASM instance. import { LoroDoc, VersionVector } from "loro-crdt/web"; import init from "loro-crdt/web/loro_wasm.js"; import { CursorEphemeralStore, LoroEphemeralCursorPlugin, LoroSyncPlugin, LoroUndoPlugin, redo, undo, } from "loro-prosemirror"; import type { CursorUser, LoroDocType } from "loro-prosemirror"; import { Schema, type NodeSpec } from "prosemirror-model"; import { EditorState } from "prosemirror-state"; import { EditorView } from "prosemirror-view"; import { schema as basicSchema } from "prosemirror-schema-basic"; import { addListNodes, liftListItem, sinkListItem, splitListItem, } from "prosemirror-schema-list"; import { keymap } from "prosemirror-keymap"; import { baseKeymap, toggleMark } from "prosemirror-commands"; import { createEditing } from "./editing"; import { createFloating } from "./floating"; import { createNoteLinks } from "./noteLinks"; import { createToolbar } from "./toolbar"; import { h } from "./dom"; import { t, type Key } from "./i18n"; // Replaced at build time with the content-hashed name of the WASM file in assets/. declare const __LORO_WASM_NAME__: string; // The WASM ships as its own file so browsers can stream-compile and cache it. It must be // initialized before the first LoroDoc or ephemeral store exists. await init({ module_or_path: new URL(`/${__LORO_WASM_NAME__}`, location.origin) }); // ---- Wire protocol (must match the Rust server) ---- const TAG_SYNC_REQ = 0x01; const TAG_UPDATE = 0x02; const TAG_EPHEMERAL = 0x03; // ---- Schema: basic nodes/marks + lists ---- // Code blocks keep the fence language (```rust) so markdown round-trips. const codeBlock: NodeSpec = { ...basicSchema.spec.nodes.get("code_block")!, attrs: { language: { default: null } }, parseDOM: [ { tag: "pre", preserveWhitespace: "full", getAttrs: (dom) => ({ language: (dom as HTMLElement).dataset.language || null }), }, ], toDOM: (node) => [ "pre", node.attrs.language ? { "data-language": node.attrs.language } : {}, ["code", 0], ], }; const schema = new Schema({ nodes: addListNodes( basicSchema.spec.nodes.update("code_block", codeBlock), "paragraph block*", "block", ), marks: basicSchema.spec.marks, }); // ---- Per-tab peer identity for cursors ---- function peerIdentity(): CursorUser { const key = "project-note-peer"; let stored: CursorUser | null = null; try { const raw = sessionStorage.getItem(key); if (raw) stored = JSON.parse(raw) as CursorUser; } catch { stored = null; } if (!stored) { const n = 1000 + Math.floor(Math.random() * 9000); const hue = Math.floor(Math.random() * 360); stored = { name: `user-${n}`, color: `hsl(${hue} 70% 45%)` }; try { sessionStorage.setItem(key, JSON.stringify(stored)); } catch { // sessionStorage unavailable: identity just lasts for this load } } return stored; } // ---- Document, presence, editor ---- const mount = document.getElementById("editor"); if (!mount) throw new Error("#editor element not found"); const noteId = mount.dataset.noteId ?? ""; const noteTitle = mount.dataset.noteTitle?.trim() || document.querySelector("header span.truncate")?.textContent?.trim() || "Note"; const doc = new LoroDoc() as unknown as LoroDocType; const user = peerIdentity(); const presence = new CursorEphemeralStore((doc as unknown as LoroDoc).peerIdStr); const statusEl = ensureStatusElement(mount); const liveEl = ensureLiveRegion(); // Remote selections are tinted with the peer's color instead of loro's default yellow. function peerSelection(peer: string) { const all = presence.getAll() as Record; const color = all[peer]?.user?.color ?? "currentColor"; return { class: "loro-selection", "data-peer": peer, style: `background-color: color-mix(in srgb, ${color} 28%, transparent)`, }; } // Link commands open the floating popover; the floating UI is created right after. const editing = createEditing(schema, { requestLink: (v) => floating.openLink(v) }); const floating = createFloating(schema, editing); const toolbarPlugin = createToolbar(mount, schema, editing, { undo, redo }); const noteLinks = createNoteLinks(schema, { currentNoteId: noteId }); const listKeys = keymap({ Enter: splitListItem(schema.nodes.list_item), Tab: sinkListItem(schema.nodes.list_item), "Shift-Tab": liftListItem(schema.nodes.list_item), "Mod-b": toggleMark(schema.marks.strong), "Mod-i": toggleMark(schema.marks.em), "Mod-`": toggleMark(schema.marks.code), }); const state = EditorState.create({ schema, plugins: [ LoroSyncPlugin({ doc }), LoroUndoPlugin({ doc }), keymap({ "Mod-z": undo, "Mod-y": redo, "Shift-Mod-z": redo, }), ...floating.plugins, ...noteLinks.plugins, listKeys, ...editing.plugins, keymap(baseKeymap), toolbarPlugin, LoroEphemeralCursorPlugin(presence, { user, createSelection: peerSelection }), ], }); // The editor is created only after the server's state is imported. Creating it on an // empty doc makes loro-prosemirror write a fresh root that competes with the real one. let view: EditorView | null = null; let serverVersion: VersionVector | null = null; function maybeCreateEditor() { if (view || !serverVersion) return; const ours = (doc as unknown as LoroDoc).oplogVersion(); const cmp = serverVersion.compare(ours); if (cmp === undefined || cmp > 0) return; view = new EditorView(mount!, { state, attributes: { role: "textbox", "aria-multiline": "true", "aria-label": noteTitle, }, }); } // ---- Transport ---- const url = `${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/notes/${encodeURIComponent(noteId)}/ws`; const BASE_DELAY = 500; const MAX_DELAY = 5000; let socket: WebSocket | null = null; let retryDelay = BASE_DELAY; // False until this connection has sent our offline changes. Presence refers to // containers inside the doc, so it must not reach peers before those changes do. let presenceReady = false; function frame(tag: number, payload: Uint8Array): Uint8Array { const out = new Uint8Array(payload.length + 1); out[0] = tag; out.set(payload, 1); return out; } function isOpen(): boolean { return socket !== null && socket.readyState === WebSocket.OPEN; } function send(tag: number, payload: Uint8Array) { if (isOpen()) socket!.send(frame(tag, payload)); } // ---- Sync status ---- // "Saving…" is shown only when local changes stay unsent for more than 1.5s. A change is // confirmed sent once the socket's buffer is empty and 300ms have passed without edits. type SyncState = "connecting" | "reconnecting" | "saved" | "saving" | "local"; const STATUS_KEY: Record = { connecting: "statusConnecting", reconnecting: "statusReconnecting", saved: "statusSaved", saving: "statusSaving", local: "statusLocal", }; let connected = false; let everConnected = false; let dirty = false; let savingShown = false; let savingTimer: ReturnType | undefined; let flushTimer: ReturnType | undefined; function currentSyncState(): SyncState { if (navigator.onLine === false) return "local"; if (!connected) return everConnected ? "reconnecting" : "connecting"; return savingShown ? "saving" : "saved"; } function renderStatus() { const syncState = currentSyncState(); statusEl.dataset.state = syncState; statusEl.textContent = t(STATUS_KEY[syncState]); } function markLocalChange() { if (!dirty) { dirty = true; clearTimeout(savingTimer); savingTimer = setTimeout(() => { if (dirty) { savingShown = true; renderStatus(); } }, 1500); } clearTimeout(flushTimer); flushTimer = setTimeout(checkFlushed, 300); } function checkFlushed() { if (!dirty) return; if (isOpen() && socket!.bufferedAmount > 0) { flushTimer = setTimeout(checkFlushed, 100); return; } dirty = false; clearTimeout(savingTimer); savingShown = false; renderStatus(); } function setConnected(value: boolean) { connected = value; if (value) everConnected = true; renderStatus(); } // The pill lives in the note header's #sync-slot (right side, next to the actions menu). function ensureStatusElement(anchor: HTMLElement): HTMLElement { let el = document.getElementById("sync-status"); if (!el) { el = document.createElement("span"); el.id = "sync-status"; const slot = document.getElementById("sync-slot"); if (slot) slot.append(el); else anchor.before(el); } return el; } // Visually hidden; only offline/online transitions are announced. function ensureLiveRegion(): HTMLElement { const el = h("div", { class: "sr-only", role: "status", "aria-live": "polite" }); document.body.append(el); return el; } function announce(message: string) { liveEl.textContent = message; } window.addEventListener("offline", () => { renderStatus(); announce(t("announceOffline")); }); window.addEventListener("online", () => { renderStatus(); announce(t("announceOnline")); }); // Local doc changes: only sent while the socket is open. // Offline changes are delivered by the SYNC_REQ handshake on reconnect. (doc as unknown as LoroDoc).subscribeLocalUpdates((bytes: Uint8Array) => { send(TAG_UPDATE, bytes); markLocalChange(); }); // Local presence changes: sent while open. presence.subscribeLocalUpdates((bytes: Uint8Array) => { if (presenceReady) send(TAG_EPHEMERAL, bytes); }); function handleMessage(data: ArrayBuffer | string) { if (typeof data === "string") return; const bytes = new Uint8Array(data); if (bytes.length === 0) return; const tag = bytes[0]; const payload = bytes.subarray(1); switch (tag) { case TAG_SYNC_REQ: { // Peer asks for what we have beyond its version: reply with an update. const from = VersionVector.decode(payload); const update = (doc as unknown as LoroDoc).export({ mode: "update", from }); send(TAG_UPDATE, update); if (!presenceReady) { presenceReady = true; send(TAG_EPHEMERAL, presence.encodeAll()); } if (!serverVersion) { serverVersion = from; maybeCreateEditor(); } break; } case TAG_UPDATE: try { (doc as unknown as LoroDoc).import(payload); maybeCreateEditor(); } catch (err) { console.error("failed to import update", err); } break; case TAG_EPHEMERAL: try { presence.apply(payload); } catch (err) { console.error("failed to apply presence", err); } break; default: console.warn("unknown frame tag", tag); } } function connect() { const ws = new WebSocket(url); ws.binaryType = "arraybuffer"; socket = ws; ws.onopen = () => { retryDelay = BASE_DELAY; setConnected(true); // Handshake: ask the server for what we are missing. presenceReady = false; send(TAG_SYNC_REQ, (doc as unknown as LoroDoc).oplogVersion().encode()); }; ws.onmessage = (ev: MessageEvent) => handleMessage(ev.data); ws.onerror = () => { ws.close(); }; ws.onclose = () => { if (socket === ws) socket = null; if (detached) return; setConnected(false); setTimeout(connect, retryDelay); retryDelay = Math.min(retryDelay * 2, MAX_DELAY); }; } // Live search swaps the page content without a reload; it fires `note:detach` first so // this editor closes its socket instead of syncing a note that is no longer on screen. let detached = false; window.addEventListener("note:detach", () => { detached = true; socket?.close(); view?.destroy(); view = null; }); renderStatus(); connect();