Blog>
Snippets

Collaborative Document Editor

Develop a collaborative text editor similar to Google Docs, where WebSocket is used for syncing document changes among multiple users in real-time.
// Establish a connection with the WebSocket server
const socket = new WebSocket('wss://your-server-path');

// Listen for messages from the server
socket.onmessage = function(event) {
    const changes = JSON.parse(event.data);
    applyChangesToDocument(changes);
};

// Send local changes to the server
function sendChanges(changes) {
    const message = JSON.stringify(changes);
    socket.send(message);
}
This code snippet establishes a WebSocket connection to a server and sets up an event listener to receive and apply changes from other users. It also defines a function to send local changes to the server.
// Function to apply received changes
function applyChangesToDocument(changes) {
    // Implement logic to apply changes to the document
    // This may involve complex Operational Transformation or CRDTs
    // For illustration:
    if(changes.type === 'insert') {
        documentEditor.insert(changes.position, changes.text);
    } else if(changes.type === 'delete') {
        documentEditor.delete(changes.position, changes.length);
    }
}
This code provides a function to apply received changes to the document. The actual implementation details are not included as they would depend on the specifics of the document model and synchronization algorithm, such as Operational Transformation or Conflict-free Replicated Data Types (CRDTs).
// Detect local document changes (e.g., by user input)
documentEditor.on('change', function(change) {
    // Prepare the change data to be sent
    const changes = extractChanges(change);
    // Send changes to server
    sendChanges(changes);
});

function extractChanges(change) {
    // Implement extraction logic here, depending on the editor
    return {
        type: change.type, // e.g., 'insert' or 'delete'
        position: change.position, // index of change
        text: change.text, // inserted text
        length: change.length // length of deleted text
    };
}
This code detects local changes within the document editor and sends them to the server. It is assumed that the document editor has an API to listen to change events. The `extractChanges` function should be tailored to the specifics of the editor in use.