collab-editor
A collaborative text editor in the browser, served by a ygo server: the
stock Yjs stack (yjs, y-websocket, y-codemirror.next) in one web page,
loaded from esm.sh, with no npm and no build step.
go run ./examples/collab-editor
Open http://127.0.0.1:8080/#notes in two windows and type in either: the text and each user's cursor show up in the other. Another name after # (letters, digits, - and _) opens another document; the page reloads for it. The server listens on loopback by default (-addr to change it), since this example has no authentication.
How it fits together:
- The server (
main.go) is server.New with Handler mounted at /ws/, so ws://host/ws/notes is the document notes. A new document starts with a welcome line (OnLoadDocument). Documents live in memory; pass a persist.Store (such as persist/sqlite) to keep them.
- The page (
index.html, embedded in the binary) binds a CodeMirror 6 editor to a Y.Text with y-codemirror.next, the official binding: it turns edits into Yjs updates, applies remote ones with the selection kept, and draws other users' cursors from the awareness. y-websocket's WebsocketProvider connects to the server.
- No JavaScript on the server. ygo reads and writes the same updates as yjs, so the browser and the Go server sync directly.
Things to copy right:
- One yjs. Every import in the page's import map pins the same versions (
?deps=yjs@13.6.33,...), so y-websocket, y-codemirror.next and the page share one yjs module. Two copies break Yjs's type checks (yjs warns "Yjs was already imported").
- Pinned versions: yjs 13.6.33 and y-websocket 3.1.0, the versions ygo's end-to-end tests run, and y-codemirror.next 0.3.6 with @codemirror/state 6.7.6 and @codemirror/view 6.43.15, checked in a browser by hand. For production, vendor or bundle them rather than loading them from a CDN.
- Document names go into the WebSocket URL, so the page takes only letters, digits,
- and _ (a ? or / in a name would open another document).
disableBc: true: without it, tabs of one browser also sync through a BroadcastChannel, past the server.
- A real editor binding. A hand-written textarea diff is easy to get wrong: it must not split a UTF-16 surrogate pair (an emoji) and must keep each user's selection where remote edits move the text. y-codemirror.next does both.
How it is checked: main_test.go checks the served page and its pins, and that two clients of /ws/notes get the welcome line and each other's edits. The page itself was driven in headless Chrome (two tabs typing, an emoji replaced, cursors and presence, no duplicate yjs); that run is not part of CI.
Hocuspocus providers connect to the same server: mount HocuspocusHandler (or use yserve) and point @hocuspocus/provider at it.