CodeMirror
This is a real-time collaborative example of the CodeMirror 6 editor. It uses the Text, a custom CRDT type from Yorkie.
main.ts
1import type { EditOpInfo, OpInfo } from '@yorkie-js/sdk';2import yorkie, { DocEventType } from '@yorkie-js/sdk';3import { basicSetup, EditorView } from 'codemirror';4import { Transaction, TransactionSpec } from '@codemirror/state';5import { keymap } from '@codemirror/view';6import { displayError, displayStatus, statusListener } from './network';7import { createPeer, displayPeers, getDocKey, linkToDoc } from './utils';8import { remoteCursors, setRemoteCursors } from './cursors';9import { YorkieDoc, YorkiePresence } from './type';10import './style.css';1112const statusElem = document.getElementById('network-status')!;13const peersElem = document.getElementById('peers')!;14const errorElem = document.getElementById('error')!;15const editorParentElem = document.getElementById('editor')!;16const shareLinkElem = document.getElementById(17 'share-link',18) as HTMLAnchorElement;1920const rpcAddr = import.meta.env.VITE_YORKIE_API_ADDR;21const docKey = getDocKey('codemirror6');22linkToDoc(shareLinkElem, docKey);2324async function main() {25 displayStatus(statusElem, 'connecting');2627 // 01. create client with RPCAddr then activate it.28 const client = new yorkie.Client({29 rpcAddr,30 apiKey: import.meta.env.VITE_YORKIE_API_KEY,31 });32 await client.activate();3334 // 02-1. create a document then attach it into the client.35 const doc = new yorkie.Document<YorkieDoc, YorkiePresence>(docKey, {36 enableDevtools: import.meta.env.DEV,37 });38 doc.subscribe('connection', statusListener(statusElem));39 doc.subscribe('presence', (event) => {40 // Names and colours never change, so only joins and leaves redraw the41 // avatars. Presences are keyed by the client's actor ID.42 if (event.type !== DocEventType.PresenceChanged) {43 displayPeers(peersElem, doc.getPresences(), client.getActorID()!);44 }45 });46 await client.attach(doc, {47 initialPresence: createPeer(client.getActorID()!),48 });49 doc.update((root) => {50 if (!root.content) {51 root.content = new yorkie.Text();52 }53 }, 'create content if not exists');5455 await client.sync();5657 // 03-1. define function that bind the document with the codemirror(broadcast local changes to peers)58 const userEvents = ['input', 'delete', 'move', 'select'];59 const updateListener = EditorView.updateListener.of((viewUpdate) => {60 // One refused change invalidates the whole update, not just its own61 // transaction: the editor now holds text the document does not, so every62 // later index in this update - including the selection used for presence63 // below - is measured against a document that never moved. Nothing may be64 // translated through `root.content` again until `syncText` has run.65 let rejected = false;66 if (viewUpdate.docChanged) {67 for (const tr of viewUpdate.transactions) {68 if (rejected) {69 break;70 }71 if (!userEvents.some((event) => tr.isUserEvent(event))) {72 continue;73 }74 if (tr.annotation(Transaction.remote)) {75 continue;76 }77 let adj = 0;78 tr.changes.iterChanges((fromA, toA, _, __, inserted) => {79 // `iterChanges` cannot be stopped early, so skip the rest of the80 // transaction once one of its changes was refused.81 if (rejected) return;8283 const insertText = inserted.toJSON().join('\n');84 try {85 doc.update((root) => {86 root.content.edit(fromA + adj, toA + adj, insertText);87 }, `update content by ${client.getID()}`);88 } catch (err) {89 // `Text.edit` refuses an index that splits a UTF-16 surrogate90 // pair, and content carrying a lone half of one, so a local91 // CodeMirror change is not guaranteed to reach the document.92 // Rebuild the editor from the document so the refused change is93 // visibly undone instead of leaving the two silently diverged.94 // The rebuild is deferred: dispatching from inside an update95 // listener re-enters CodeMirror's update cycle.96 rejected = true;97 console.error('local edit rejected, re-syncing editor:', err);98 queueMicrotask(() => syncText());99 return;100 }101 adj += insertText.length - (toA - fromA);102 });103 }104 }105106 if (rejected) {107 // The deferred `syncText` dispatches its own update, and the presence108 // selection is recomputed there against a document the editor matches.109 return;110 }111112 const hasFocus =113 viewUpdate.view.hasFocus && viewUpdate.view.dom.ownerDocument.hasFocus();114 const sel = hasFocus ? viewUpdate.state.selection.main : null;115116 doc.update((root, presence) => {117 if (sel && root.content) {118 const selection = root.content.indexRangeToPosRange([119 sel.anchor,120 sel.head,121 ]);122123 if (124 JSON.stringify(selection) !==125 JSON.stringify(presence.get('selection'))126 ) {127 presence.set({128 selection,129 });130 }131 } else if (presence.get('selection')) {132 presence.set({133 selection: undefined,134 });135 }136 });137 });138139 // 03-2. create codemirror instance140 const cmUndoRedoKeymap = keymap.of([141 {142 key: 'Mod-z',143 preventDefault: true,144 run: () => {145 if (doc.history.canUndo()) {146 doc.history.undo();147 }148 return true;149 },150 },151 {152 key: 'Mod-Shift-z',153 preventDefault: true,154 run: () => {155 if (doc.history.canRedo()) {156 doc.history.redo();157 }158 return true;159 },160 },161 ]);162 const view = new EditorView({163 doc: '',164 extensions: [cmUndoRedoKeymap, basicSetup, remoteCursors, updateListener],165 parent: editorParentElem,166 });167168 // 02-2. subscribe document event.169 const syncText = () => {170 const text = doc.getRoot().content;171 const selection = doc.getMyPresence().selection;172 const transactionSpec: TransactionSpec = {173 changes: { from: 0, to: view.state.doc.length, insert: text.toString() },174 annotations: [Transaction.remote.of(true)],175 };176177 if (selection) {178 // Restore the cursor position when the text is replaced.179 const cursor = text.posRangeToIndexRange(selection);180 transactionSpec['selection'] = {181 anchor: cursor[0],182 head: cursor[1],183 };184 }185 view.dispatch(transactionSpec);186 displayRemoteCursors();187 };188 doc.subscribe('$.content', (event) => {189 if (event.type === 'remote-change') {190 handleOperations(event.value.operations, false);191 } else if (event.source === 'undoredo') {192 handleOperations(event.value.operations, true);193 }194 });195 // Redraw other peers' cursors whenever their presence changes.196 doc.subscribe('others', () => displayRemoteCursors());197 doc.subscribe((event) => {198 if (event.type === 'snapshot') {199 // The text is replaced to snapshot and must be re-synced.200 syncText();201 }202 });203204 // 03-3. define event handler that apply remote changes to local205 function handleOperations(operations: Array<OpInfo>, moveCursor: boolean) {206 for (const op of operations) {207 if (op.type === 'edit') {208 handleEditOp(op, moveCursor);209 }210 }211 displayRemoteCursors();212 }213 function handleEditOp(op: EditOpInfo, moveCursor: boolean) {214 const changes = [215 {216 from: Math.max(0, op.from),217 to: Math.max(0, op.to),218 insert: op.value!.content,219 },220 ];221222 const transactionSpec: TransactionSpec = {223 changes,224 annotations: [Transaction.remote.of(true)],225 };226227 // Move cursor to the changed position for undo/redo228 if (moveCursor) {229 const newPosition = op.from + (op.value?.content?.length || 0);230 transactionSpec.selection = {231 anchor: newPosition,232 head: newPosition,233 };234 }235236 view.dispatch(transactionSpec);237 }238239 // 03-4. draw other peers' selections, converting each peer's position in240 // the Yorkie text back to an index in the editor.241 function displayRemoteCursors() {242 const content = doc.getRoot().content;243 const cursors = [];244 for (const { presence } of doc.getOthersPresences()) {245 if (!presence.selection) continue;246 // A peer's selection can point at text this client hasn't received247 // yet; skip that peer until it arrives instead of failing every peer.248 let from: number, to: number;249 try {250 [from, to] = content.posRangeToIndexRange(presence.selection);251 } catch {252 continue;253 }254 cursors.push({255 name: presence.username,256 color: presence.color,257 from,258 to,259 });260 }261 view.dispatch({ effects: setRemoteCursors.of(cursors) });262 }263264 syncText();265}266267main().catch(() => {268 displayError(statusElem, errorElem, rpcAddr);269});
Two clients on the same document. Edit in one and watch the other.This is one client. Open the example in another tab or on another device to watch edits sync.
- User 1