Building a Real-Time Collaborative Text Editor with Svelte and WebSockets
Introduction
Real-time collaborative text editors are essential tools in today's connected world. This article demonstrates how to build a basic version using Svelte for the frontend and WebSockets for real-time communication. We'll focus on the core logic, providing a foundation you can expand upon.
Setting Up the Svelte Project
First, create a new Svelte project using degit
:
npx degit sveltejs/template my-text-editor
cd my-text-editor
npm install
npm run dev
Creating the Editor Component
Create a component called Editor.svelte
in the src
directory. This component will contain the text area and manage the WebSocket connection.
<script>
import { onMount } from 'svelte';
let text = '';
let socket;
onMount(() => {
socket = new WebSocket('ws://localhost:8080'); // Replace with your WebSocket server URL
socket.onopen = () => {
console.log('WebSocket connection established.');
};
socket.onmessage = (event) => {
text = event.data;
};
socket.onclose = () => {
console.log('WebSocket connection closed.');
};
});
function handleInput() {
if (socket && socket.readyState === WebSocket.OPEN) {
socket.send(text);
}
}
</script>
<textarea bind:value={text} on:input={handleInput} style="width: 100%; height: 400px;"></textarea>
Creating a Simple WebSocket Server (Node.js)
To handle the real-time communication, you'll need a WebSocket server. Here's a simple example using Node.js and the ws
library:
npm install ws
Create a file called server.js
:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', ws => {
console.log('Client connected');
ws.on('message', message => {
wss.clients.forEach(client => {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});
ws.on('close', () => {
console.log('Client disconnected');
});
});
console.log('WebSocket server started on port 8080');
Run the server with node server.js
.
Integrating the Editor Component
Replace the content of src/App.svelte
with the following:
<script>
import Editor from './Editor.svelte';
</script>
<main>
<h1>Collaborative Text Editor</h1>
<Editor />
</main>
<style>
main {
font-family: sans-serif;
padding: 20px;
}
</style>
Running the Application
Make sure your WebSocket server is running, and then start the Svelte development server:
npm run dev
Open two browser windows pointing to http://localhost:5000
. Any text you type in one window should appear in the other in real-time.
Conclusion
This example provides a basic foundation for building a real-time collaborative text editor. Further development could include features such as user authentication, rich text formatting, and more robust error handling. This project demonstrates the power and ease of combining Svelte and WebSockets for real-time applications.