forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksJavaScript3.6 MiBe100df4Tahinli1 month ago1 commit

editor.ts394 lines, 11.7 KiBHistoryRawDownload
1// "loro-crdt/web" is the entry build.ts bundles for every "loro-crdt" import. Its init is the
2// default export of loro_wasm.js, the module web/index.js re-exports, so there is one WASM instance.
3import { LoroDoc, VersionVector } from "loro-crdt/web";
4import init from "loro-crdt/web/loro_wasm.js";
5import {
6 CursorEphemeralStore,
7 LoroEphemeralCursorPlugin,
8 LoroSyncPlugin,
9 LoroUndoPlugin,
10 redo,
11 undo,
12} from "loro-prosemirror";
13import type { CursorUser, LoroDocType } from "loro-prosemirror";
14import { Schema, type NodeSpec } from "prosemirror-model";
15import { EditorState } from "prosemirror-state";
16import { EditorView } from "prosemirror-view";
17import { schema as basicSchema } from "prosemirror-schema-basic";
18import {
19 addListNodes,
20 liftListItem,
21 sinkListItem,
22 splitListItem,
23} from "prosemirror-schema-list";
24import { keymap } from "prosemirror-keymap";
25import { baseKeymap, toggleMark } from "prosemirror-commands";
26import { createEditing } from "./editing";
27import { createFloating } from "./floating";
28import { createNoteLinks } from "./noteLinks";
29import { createToolbar } from "./toolbar";
30import { h } from "./dom";
31import { t, type Key } from "./i18n";
32
33// Replaced at build time with the content-hashed name of the WASM file in assets/.
34declare const __LORO_WASM_NAME__: string;
35
36// The WASM ships as its own file so browsers can stream-compile and cache it. It must be
37// initialized before the first LoroDoc or ephemeral store exists.
38await init({ module_or_path: new URL(`/${__LORO_WASM_NAME__}`, location.origin) });
39
40// ---- Wire protocol (must match the Rust server) ----
41const TAG_SYNC_REQ = 0x01;
42const TAG_UPDATE = 0x02;
43const TAG_EPHEMERAL = 0x03;
44
45// ---- Schema: basic nodes/marks + lists ----
46// Code blocks keep the fence language (```rust) so markdown round-trips.
47const codeBlock: NodeSpec = {
48 ...basicSchema.spec.nodes.get("code_block")!,
49 attrs: { language: { default: null } },
50 parseDOM: [
51 {
52 tag: "pre",
53 preserveWhitespace: "full",
54 getAttrs: (dom) => ({ language: (dom as HTMLElement).dataset.language || null }),
55 },
56 ],
57 toDOM: (node) => [
58 "pre",
59 node.attrs.language ? { "data-language": node.attrs.language } : {},
60 ["code", 0],
61 ],
62};
63
64const schema = new Schema({
65 nodes: addListNodes(
66 basicSchema.spec.nodes.update("code_block", codeBlock),
67 "paragraph block*",
68 "block",
69 ),
70 marks: basicSchema.spec.marks,
71});
72
73// ---- Per-tab peer identity for cursors ----
74function peerIdentity(): CursorUser {
75 const key = "project-note-peer";
76 let stored: CursorUser | null = null;
77 try {
78 const raw = sessionStorage.getItem(key);
79 if (raw) stored = JSON.parse(raw) as CursorUser;
80 } catch {
81 stored = null;
82 }
83 if (!stored) {
84 const n = 1000 + Math.floor(Math.random() * 9000);
85 const hue = Math.floor(Math.random() * 360);
86 stored = { name: `user-${n}`, color: `hsl(${hue} 70% 45%)` };
87 try {
88 sessionStorage.setItem(key, JSON.stringify(stored));
89 } catch {
90 // sessionStorage unavailable: identity just lasts for this load
91 }
92 }
93 return stored;
94}
95
96// ---- Document, presence, editor ----
97const mount = document.getElementById("editor");
98if (!mount) throw new Error("#editor element not found");
99const noteId = mount.dataset.noteId ?? "";
100const noteTitle =
101 mount.dataset.noteTitle?.trim() ||
102 document.querySelector<HTMLElement>("header span.truncate")?.textContent?.trim() ||
103 "Note";
104
105const doc = new LoroDoc() as unknown as LoroDocType;
106const user = peerIdentity();
107const presence = new CursorEphemeralStore((doc as unknown as LoroDoc).peerIdStr);
108
109const statusEl = ensureStatusElement(mount);
110const liveEl = ensureLiveRegion();
111
112// Remote selections are tinted with the peer's color instead of loro's default yellow.
113function peerSelection(peer: string) {
114 const all = presence.getAll() as Record<string, { user?: { color?: string } } | undefined>;
115 const color = all[peer]?.user?.color ?? "currentColor";
116 return {
117 class: "loro-selection",
118 "data-peer": peer,
119 style: `background-color: color-mix(in srgb, ${color} 28%, transparent)`,
120 };
121}
122
123// Link commands open the floating popover; the floating UI is created right after.
124const editing = createEditing(schema, { requestLink: (v) => floating.openLink(v) });
125const floating = createFloating(schema, editing);
126const toolbarPlugin = createToolbar(mount, schema, editing, { undo, redo });
127
128const noteLinks = createNoteLinks(schema, { currentNoteId: noteId });
129
130const listKeys = keymap({
131 Enter: splitListItem(schema.nodes.list_item),
132 Tab: sinkListItem(schema.nodes.list_item),
133 "Shift-Tab": liftListItem(schema.nodes.list_item),
134 "Mod-b": toggleMark(schema.marks.strong),
135 "Mod-i": toggleMark(schema.marks.em),
136 "Mod-`": toggleMark(schema.marks.code),
137});
138
139const state = EditorState.create({
140 schema,
141 plugins: [
142 LoroSyncPlugin({ doc }),
143 LoroUndoPlugin({ doc }),
144 keymap({
145 "Mod-z": undo,
146 "Mod-y": redo,
147 "Shift-Mod-z": redo,
148 }),
149 ...floating.plugins,
150 ...noteLinks.plugins,
151 listKeys,
152 ...editing.plugins,
153 keymap(baseKeymap),
154 toolbarPlugin,
155 LoroEphemeralCursorPlugin(presence, { user, createSelection: peerSelection }),
156 ],
157});
158
159// The editor is created only after the server's state is imported. Creating it on an
160// empty doc makes loro-prosemirror write a fresh root that competes with the real one.
161let view: EditorView | null = null;
162let serverVersion: VersionVector | null = null;
163
164function maybeCreateEditor() {
165 if (view || !serverVersion) return;
166 const ours = (doc as unknown as LoroDoc).oplogVersion();
167 const cmp = serverVersion.compare(ours);
168 if (cmp === undefined || cmp > 0) return;
169 view = new EditorView(mount!, {
170 state,
171 attributes: {
172 role: "textbox",
173 "aria-multiline": "true",
174 "aria-label": noteTitle,
175 },
176 });
177}
178
179// ---- Transport ----
180const url = `${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/notes/${encodeURIComponent(noteId)}/ws`;
181const BASE_DELAY = 500;
182const MAX_DELAY = 5000;
183let socket: WebSocket | null = null;
184let retryDelay = BASE_DELAY;
185// False until this connection has sent our offline changes. Presence refers to
186// containers inside the doc, so it must not reach peers before those changes do.
187let presenceReady = false;
188
189function frame(tag: number, payload: Uint8Array): Uint8Array<ArrayBuffer> {
190 const out = new Uint8Array(payload.length + 1);
191 out[0] = tag;
192 out.set(payload, 1);
193 return out;
194}
195
196function isOpen(): boolean {
197 return socket !== null && socket.readyState === WebSocket.OPEN;
198}
199
200function send(tag: number, payload: Uint8Array) {
201 if (isOpen()) socket!.send(frame(tag, payload));
202}
203
204// ---- Sync status ----
205// "Saving…" is shown only when local changes stay unsent for more than 1.5s. A change is
206// confirmed sent once the socket's buffer is empty and 300ms have passed without edits.
207type SyncState = "connecting" | "reconnecting" | "saved" | "saving" | "local";
208const STATUS_KEY: Record<SyncState, Key> = {
209 connecting: "statusConnecting",
210 reconnecting: "statusReconnecting",
211 saved: "statusSaved",
212 saving: "statusSaving",
213 local: "statusLocal",
214};
215
216let connected = false;
217let everConnected = false;
218let dirty = false;
219let savingShown = false;
220let savingTimer: ReturnType<typeof setTimeout> | undefined;
221let flushTimer: ReturnType<typeof setTimeout> | undefined;
222
223function currentSyncState(): SyncState {
224 if (navigator.onLine === false) return "local";
225 if (!connected) return everConnected ? "reconnecting" : "connecting";
226 return savingShown ? "saving" : "saved";
227}
228
229function renderStatus() {
230 const syncState = currentSyncState();
231 statusEl.dataset.state = syncState;
232 statusEl.textContent = t(STATUS_KEY[syncState]);
233}
234
235function markLocalChange() {
236 if (!dirty) {
237 dirty = true;
238 clearTimeout(savingTimer);
239 savingTimer = setTimeout(() => {
240 if (dirty) {
241 savingShown = true;
242 renderStatus();
243 }
244 }, 1500);
245 }
246 clearTimeout(flushTimer);
247 flushTimer = setTimeout(checkFlushed, 300);
248}
249
250function checkFlushed() {
251 if (!dirty) return;
252 if (isOpen() && socket!.bufferedAmount > 0) {
253 flushTimer = setTimeout(checkFlushed, 100);
254 return;
255 }
256 dirty = false;
257 clearTimeout(savingTimer);
258 savingShown = false;
259 renderStatus();
260}
261
262function setConnected(value: boolean) {
263 connected = value;
264 if (value) everConnected = true;
265 renderStatus();
266}
267
268// The pill lives in the note header's #sync-slot (right side, next to the actions menu).
269function ensureStatusElement(anchor: HTMLElement): HTMLElement {
270 let el = document.getElementById("sync-status");
271 if (!el) {
272 el = document.createElement("span");
273 el.id = "sync-status";
274 const slot = document.getElementById("sync-slot");
275 if (slot) slot.append(el);
276 else anchor.before(el);
277 }
278 return el;
279}
280
281// Visually hidden; only offline/online transitions are announced.
282function ensureLiveRegion(): HTMLElement {
283 const el = h("div", { class: "sr-only", role: "status", "aria-live": "polite" });
284 document.body.append(el);
285 return el;
286}
287
288function announce(message: string) {
289 liveEl.textContent = message;
290}
291
292window.addEventListener("offline", () => {
293 renderStatus();
294 announce(t("announceOffline"));
295});
296window.addEventListener("online", () => {
297 renderStatus();
298 announce(t("announceOnline"));
299});
300
301// Local doc changes: only sent while the socket is open.
302// Offline changes are delivered by the SYNC_REQ handshake on reconnect.
303(doc as unknown as LoroDoc).subscribeLocalUpdates((bytes: Uint8Array) => {
304 send(TAG_UPDATE, bytes);
305 markLocalChange();
306});
307
308// Local presence changes: sent while open.
309presence.subscribeLocalUpdates((bytes: Uint8Array) => {
310 if (presenceReady) send(TAG_EPHEMERAL, bytes);
311});
312
313function handleMessage(data: ArrayBuffer | string) {
314 if (typeof data === "string") return;
315 const bytes = new Uint8Array(data);
316 if (bytes.length === 0) return;
317 const tag = bytes[0];
318 const payload = bytes.subarray(1);
319 switch (tag) {
320 case TAG_SYNC_REQ: {
321 // Peer asks for what we have beyond its version: reply with an update.
322 const from = VersionVector.decode(payload);
323 const update = (doc as unknown as LoroDoc).export({ mode: "update", from });
324 send(TAG_UPDATE, update);
325 if (!presenceReady) {
326 presenceReady = true;
327 send(TAG_EPHEMERAL, presence.encodeAll());
328 }
329 if (!serverVersion) {
330 serverVersion = from;
331 maybeCreateEditor();
332 }
333 break;
334 }
335 case TAG_UPDATE:
336 try {
337 (doc as unknown as LoroDoc).import(payload);
338 maybeCreateEditor();
339 } catch (err) {
340 console.error("failed to import update", err);
341 }
342 break;
343 case TAG_EPHEMERAL:
344 try {
345 presence.apply(payload);
346 } catch (err) {
347 console.error("failed to apply presence", err);
348 }
349 break;
350 default:
351 console.warn("unknown frame tag", tag);
352 }
353}
354
355function connect() {
356 const ws = new WebSocket(url);
357 ws.binaryType = "arraybuffer";
358 socket = ws;
359
360 ws.onopen = () => {
361 retryDelay = BASE_DELAY;
362 setConnected(true);
363 // Handshake: ask the server for what we are missing.
364 presenceReady = false;
365 send(TAG_SYNC_REQ, (doc as unknown as LoroDoc).oplogVersion().encode());
366 };
367
368 ws.onmessage = (ev: MessageEvent) => handleMessage(ev.data);
369
370 ws.onerror = () => {
371 ws.close();
372 };
373
374 ws.onclose = () => {
375 if (socket === ws) socket = null;
376 if (detached) return;
377 setConnected(false);
378 setTimeout(connect, retryDelay);
379 retryDelay = Math.min(retryDelay * 2, MAX_DELAY);
380 };
381}
382
383// Live search swaps the page content without a reload; it fires `note:detach` first so
384// this editor closes its socket instead of syncing a note that is no longer on screen.
385let detached = false;
386window.addEventListener("note:detach", () => {
387 detached = true;
388 socket?.close();
389 view?.destroy();
390 view = null;
391});
392
393renderStatus();
394connect();