import * as awarenessProtocol from "y-protocols/awareness.js"; import * as Y from "yjs"; import { MessageCode } from "./types"; import * as SocketIOClient from "socket.io-client"; import throttle from "lodash.throttle"; import { createMutex } from "lib0/mutex.js"; type OnSubscribe = () => void; type OnConnect = () => void; type OnUpdateCursors = (any) => void; interface WavingClientOpts { socket: SocketIOClient.Socket; onConnect?: OnConnect; onSubscribe?: OnSubscribe; onDisconnect?: OnConnect; } export class WavingClient { private connected = false; public isActive: boolean; public isSubscribed: boolean; public onConnect?: OnConnect; public onSubscribe?: OnSubscribe; public onDisconnect?: OnConnect; public mux = createMutex(); private socket: SocketIOClient.Socket; private docId?: string; private doc?: Y.Doc; private awareness?: awarenessProtocol.Awareness; private communicatedDoc?: Y.Doc; public user?: any = {}; constructor({ socket, onConnect, onSubscribe, onDisconnect, }: WavingClientOpts) { this.isActive = socket.connected; this.isSubscribed = false; this.socket = socket; this.onConnect = onConnect; this.onSubscribe = onSubscribe; this.onDisconnect = onDisconnect; socket.on("connect", () => { this.connected = true; this.isActive = socket.connected; if (this.onConnect) this.onConnect(); }); socket.on("disconnect", () => { this.connected = false; this.isActive = socket.connected; if (this.onDisconnect) this.onDisconnect(); this.doc?.off("update", this.commitChanges.bind(this)); delete this.communicatedDoc; delete this.awareness; }); socket.on(MessageCode.updateVector, (docId, vectors) => { this.mux(() => { if (vectors && vectors.length && this.doc && this.communicatedDoc) { for (const vector of vectors) { const vec = new Uint8Array(vector); Y.applyUpdate(this.communicatedDoc, vec, "remote"); Y.applyUpdate(this.doc, vec, "remote"); } this.onAwarenessChange(null, "remote"); } }); }); socket.on(MessageCode.awareness, (docId, update) => { if (update.cursor && (update.cursor.anchor || update.cursor.head)) { this.awareness!.states.set(update.id, update); } else { this.awareness!.states.delete(update.id); } this.awareness!.emit("change", [{ updated: [update.id] }, "remote"]); }); } private commitChanges = throttle(this._commitChanges, 700, { leading: false, trailing: true, }); _commitChanges(update, origin) { if (!this.doc || !this.communicatedDoc) throw new Error(`No local doc`); if (origin !== "remote") { Y.applyUpdate(this.communicatedDoc, Y.encodeStateAsUpdate(this.doc)); } } auth(token: string) { if (!this.connected) throw new Error(`Socket not open`); this.socket.emit("auth", token); } subscribeToDoc( docId: string, yDoc: Y.Doc, awareness: awarenessProtocol.Awareness ) { if (this.isSubscribed) throw new Error(`Socket already subscribed`); this.docId = docId; return new Promise((resolve, reject) => { this.socket.emit( "subscribe", docId, [], (docId, vector, awarenessItems) => { this.doc = yDoc; this.awareness = awareness; this.communicatedDoc = new Y.Doc(); Y.applyUpdate(this.doc, Uint8Array.from(vector), "remote"); this.doc.on("update", this.commitChanges.bind(this)); this.communicatedDoc.on("update", (update, origin) => { if (origin === null) { (this.socket as any).emit(MessageCode.updateVector, this.docId, [ update, ]); } }); this.awareness.on("change", this.onAwarenessChange.bind(this)); for (const aw of awarenessItems) { if (aw.anchor || aw.head) { this.awareness!.states.set(aw.id, { ...aw }); } else { this.awareness!.states.delete(aw.id); } } this.isSubscribed = true; if (awarenessItems.length) { this.awareness!.emit("change", [{}, "remote"]); } this.onSubscribe ? this.onSubscribe() : null; resolve(undefined); } ); }); } unsubscribeFromDoc(docId: string) { if (!this.isActive) throw new Error(`Socket not subscribed`); return new Promise((resolve) => { this.socket.emit("unsubscribe", docId, () => { this.doc?.off("update", this.commitChanges.bind(this)); delete this.docId; this.isSubscribed = false; resolve(undefined); }); }); } onAwarenessChange(arg, source) { if (this.isActive) { // TODO only update modified cursors (using arg) if (source !== "local") { // const cursors = Array.from( // this.awareness! // .getStates() // .entries() // ) // .filter(([id, val]: any) => !!val.cursor && id !== this.doc?.clientID) // .map(([id, val]: any) => { // const cursor = val.cursor; // const anchor = Y.createAbsolutePositionFromRelativePosition(Y.createRelativePositionFromJSON(cursor.anchor as any), this.doc!) // const head = Y.createAbsolutePositionFromRelativePosition(Y.createRelativePositionFromJSON(cursor.head), this.doc!) // return { id, ...cursor, head, anchor }; // }); } else if (source === "local") { this.socket.emit(MessageCode.awareness, this.docId, { id: this.doc!.clientID, user: this.user, ...this.awareness?.getLocalState(), }); } } } }