tiptap/docs/src/docPages/guide/collaborative-editing.md

364 lines
15 KiB
Markdown
Raw Normal View History

2020-10-05 20:56:45 +08:00
# Collaborative editing
## toc
2020-10-05 20:56:45 +08:00
## Introduction
2020-11-28 05:17:03 +08:00
Real-time collaboration, syncing between different devices and working offline used to be hard. We provide everything you need to keep everything in sync, conflict-free with the power of [Y.js](https://github.com/yjs/yjs). The following guide explains all things to take into account when you consider to make tiptap collaborative. Dont worry, a production-grade setup doesnt require much code.
2020-10-05 20:56:45 +08:00
2021-02-03 17:41:37 +08:00
## Configure the editor
2020-11-28 00:23:04 +08:00
The underyling schema tiptap uses is an excellent foundation to sync documents. With the [`Collaboration`](/api/extensions/collaboration) you can tell tiptap to track changes to the document with [Y.js](https://github.com/yjs/yjs).
2020-10-05 20:56:45 +08:00
Y.js is a conflict-free replicated data types implementation, or in other words: Its reaaally good in merging changes. And to achieve that, changes dont have to come in order. Its totally fine to change a document while being offline and merge it with other changes when the device is online again.
2020-10-05 20:56:45 +08:00
But somehow, all clients need to interchange document modifications at some point. The most popular technologies to do that are [WebRTC](https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API) and [WebSockets](https://developer.mozilla.org/de/docs/Web/API/WebSocket), so lets have a closer look at those:
2020-11-28 00:23:04 +08:00
### WebRTC
WebRTC uses a server only to connect clients with each other. The actual data is then flowing between the clients, without the server knowing anything about it and thats great to take the first steps with collaborative editing.
First, install the dependencies:
2020-11-28 00:23:04 +08:00
```bash
# with npm
npm install @tiptap/extension-collaboration yjs y-webrtc
# with Yarn
yarn add @tiptap/extension-collaboration yjs y-webrtc
```
2020-11-30 21:27:36 +08:00
Now, create a new Y document, and register it with tiptap:
2020-11-28 00:23:04 +08:00
```js
import { Editor } from '@tiptap/core'
import Collaboration from '@tiptap/extension-collaboration'
import * as Y from 'yjs'
import { WebrtcProvider } from 'y-webrtc'
// A new Y document
const ydoc = new Y.Doc()
// Registered with a WebRTC provider
const provider = new WebrtcProvider('example-document', ydoc)
const editor = new Editor({
extensions: [
// …
// Register the document with tiptap
Collaboration.configure({
document: ydoc,
2020-11-28 00:23:04 +08:00
}),
],
})
```
2020-11-28 05:17:03 +08:00
This should be enough to create a collaborative instance of tiptap. Crazy, isnt it? Try it out, and open the editor in two different browsers. Changes should be synced between different windows.
2020-11-28 00:23:04 +08:00
So how does this magic work? All clients need to connect with eachother, thats the job of a *provider*. The [WebRTC provider](https://github.com/yjs/y-webrtc) is the easiest way to get started with, as it requires a public server to connect clients directly with each other, but not to sync the actual changes. This has two downsides, though.
2020-11-28 00:23:04 +08:00
1. Browsers refuse to connect with too many clients. With Y.js its enough if all clients are connected indirectly, but even that isnt possible at some point. Or in other words, it doesnt scale well for more than 100+ clients in the same document.
2. Its likely you want to involve a server to persist changes anyway. But the WebRTC signaling server (which connects all clients with eachother) doesnt receive the changes and therefore doesnt know whats in the document.
2020-11-28 00:23:04 +08:00
2020-11-28 05:17:03 +08:00
Anyway, if you want to dive deeper, head over to [the Y WebRTC repository](https://github.com/yjs/y-webrtc) on GitHub.
2020-11-28 00:23:04 +08:00
### WebSocket (Recommended)
For most uses cases, the WebSocket provider is the recommended choice. Its very flexible and can scale very well. For the client, the example is nearly the same, only the provider is different. First, lets install the dependencies:
2020-11-28 00:23:04 +08:00
```bash
# with npm
npm install @tiptap/extension-collaboration yjs y-websocket
# with Yarn
yarn add @tiptap/extension-collaboration yjs y-websocket
```
And then register the WebSocket provider with tiptap:
```js
import { Editor } from '@tiptap/core'
import Collaboration from '@tiptap/extension-collaboration'
import * as Y from 'yjs'
import { WebsocketProvider } from 'y-websocket'
// A new Y document
const ydoc = new Y.Doc()
// Registered with a WebSocket provider
const provider = new WebsocketProvider('ws://127.0.0.1:1234', 'example-document', ydoc)
const editor = new Editor({
extensions: [
// …
// Register the document with tiptap
Collaboration.configure({
document: ydoc,
2020-11-28 00:23:04 +08:00
}),
],
})
```
That example doesnt work out of the box. As you can see, its configured to talk to a WebSocket server which is available under `ws://127.0.0.1:1234` (WebSocket protocol `ws://`, your local IP `127.0.0.1` and the port `1234`). You need to set this up, too.
#### The WebSocket backend
To make the server part as easy as possible, we provide [an opinionated server package, called hocuspocus](http://hocuspocus.dev/) (not published yet). Lets go through, how this will work once its released.
2020-11-28 00:23:04 +08:00
Create a new project, and install the hocuspocus server as a dependency:
2020-11-28 00:23:04 +08:00
```bash
# with npm
npm install @hocuspocus/server
# with Yarn
yarn add @hocuspocus/server
```
2020-11-28 05:17:03 +08:00
Create an `index.js` and throw in the following content, to create, configure and start your very own WebSocket server:
2020-11-28 00:23:04 +08:00
```js
import { Server } from '@hocuspocus/server'
2021-04-20 19:18:11 +08:00
import { RocksDB } from '@hocuspocus/extension-rocksdb'
2020-11-28 00:23:04 +08:00
const server = Server.configure({
port: 1234,
2021-04-20 19:18:11 +08:00
extensions: [
new RocksDB({ path: './database' })
],
2020-11-28 00:23:04 +08:00
})
server.listen()
```
2020-11-28 05:17:03 +08:00
Thats all. Start the script with:
2020-11-28 00:23:04 +08:00
```bash
node ./index.js
```
<!-- TODO: This should output something like “Listening on ws://127.0.0.1:1234”. -->
Try opening http://127.0.0.1:1234 in your browser. You should see a plain text `OK` if everything works fine.
Go back to your tiptap editor and hit reload, it should now connect to the WebSocket server and changes should sync with all other clients. Amazing, isnt it?
2020-10-05 20:56:45 +08:00
### Multiple network providers
You can even combine multiple providers. Thats not needed, but could keep clients connected, even if one connection - for example the WebSocket server - goes down for a while. Here is an example:
```js
new WebrtcProvider('example-document', ydoc)
new WebsocketProvider('ws://127.0.0.1:1234', 'example-document', ydoc)
```
Yes, thats all.
Keep in mind that WebRTC needs a signaling server to connect clients. This signaling server doesnt receive the synced data, but helps to let clients find each other. You can [run your own signaling server](https://github.com/yjs/y-webrtc#signaling), if you like. Otherwise its using a default URL baked into the package.
### Show other cursors
To enable users to see the cursor and text selections of each other, add the [`CollaborationCursor`](/api/extensions/collaboration-cursor) extension.
2020-11-28 00:23:04 +08:00
```js
import { Editor } from '@tiptap/core'
import Collaboration from '@tiptap/extension-collaboration'
import CollaborationCursor from '@tiptap/extension-collaboration-cursor'
import * as Y from 'yjs'
import { WebsocketProvider } from 'y-websocket'
const ydoc = new Y.Doc()
const provider = new WebsocketProvider('ws://127.0.0.1:1234', 'example-document', ydoc)
const editor = new Editor({
extensions: [
Collaboration.configure({
document: ydoc,
}),
2020-11-28 00:23:04 +08:00
// Register the collaboration cursor extension
CollaborationCursor.configure({
provider: provider,
2020-11-28 00:23:04 +08:00
name: 'Cyndi Lauper',
color: '#f783ac',
}),
// …
2020-11-28 00:23:04 +08:00
],
})
```
2020-11-30 21:44:18 +08:00
As you can see, you can pass a name and color for every user. Look at the [collaborative editing example](/examples/collaborative-editing), to see a more advanced example.
2020-10-05 20:56:45 +08:00
### Offline support
2020-11-28 05:17:03 +08:00
Adding offline support to your collaborative editor is basically a one-liner, thanks to the fantastic [Y IndexedDB adapter](https://github.com/yjs/y-indexeddb). Install it:
2020-11-28 00:23:04 +08:00
```bash
# with npm
npm install y-indexeddb
# with Yarn
yarn add y-indexeddb
```
And connect it with a Y document:
```js
import { Editor } from '@tiptap/core'
import Collaboration from '@tiptap/extension-collaboration'
import * as Y from 'yjs'
import { IndexeddbPersistence } from 'y-indexeddb'
const ydoc = new Y.Doc()
2020-11-28 00:23:04 +08:00
// Store the Y document in the browser
new IndexeddbPersistence('example-document', ydoc)
2020-11-28 00:23:04 +08:00
const editor = new Editor({
extensions: [
// …
Collaboration.configure({
document: ydoc,
2020-11-28 00:23:04 +08:00
}),
],
})
```
2020-11-28 05:17:03 +08:00
All changes will be stored in the browser then, even if you close the tab, go offline, or make changes while working offline. Next time you are online, the WebSocket provider will try to find a connection and eventually sync the changes.
2020-11-28 00:23:04 +08:00
2020-11-28 05:17:03 +08:00
Yes, its magic. As already mentioned, that is all based on the fantastic Y.js framework. And if youre using it, or our integration, you should definitely [sponsor Kevin Jahns on GitHub](https://github.com/dmonad), he is the brain behind Y.js.
2020-10-05 20:56:45 +08:00
## Our plug & play collaboration backend
Our collaborative editing backend handles the syncing, authorization, persistence and scaling. Lets go through a few common use cases here!
2020-11-28 00:23:04 +08:00
:::warning Request early access
2021-04-16 03:48:19 +08:00
Our plug & play collaboration backend hocuspocus is still work in progress. If you want to give it a try, [request early access](https://www.hocuspocus.dev).
2020-12-04 00:23:54 +08:00
:::
2020-12-04 20:41:05 +08:00
### The document name
The document name is `'example-document'` in all examples here, but it could be any string. In a real-world app youd probably add the name of your entity and the ID of the entity. Here is how that could look like:
2020-12-04 20:41:05 +08:00
```js
const documentName = 'page.140'
2020-12-04 20:41:05 +08:00
```
In the backend, you can split the string to know the user is typing on a page with the ID 140 to manage authorization and such accordingly. New documents are created on the fly, no need to tell the backend about them, besides passing a string to the provider.
And if youd like to sync multiple fields with one Y.js document, just pass different fragment names to the collaboration extension:
```js
// a tiptap instance for the field
Collaboration.configure({
document: ydoc,
field: 'title',
})
// and another instance for the summary, both in the same Y.js document
Collaboration.configure({
document: ydoc,
field: 'summary',
})
```
If your setup is somehow more complex, for example with nested fragments, you can pass a raw Y.js fragment too. `document` and `field` will be ignored then.
```js
// a raw Y.js fragment
Collaboration.configure({
fragment: ydoc.getXmlFragment('custom'),
})
```
2020-12-04 20:41:05 +08:00
2021-04-20 19:18:11 +08:00
### Authentication & Authorization
2020-12-02 22:35:41 +08:00
2021-04-20 19:18:11 +08:00
With the `onConnect` hook you can check if a client is authenticated and authorized to view the current document. In a real world application this would probably be a request to an API, a database query or something else.
2020-12-02 22:35:41 +08:00
2021-04-20 19:18:11 +08:00
When throwing an error (or rejecting the returned Promise), the connection to the client will be terminated. If the client is authorized and authenticated you can also return contextual data which will be accessible in other hooks. But you don't need to.
2020-11-28 00:23:04 +08:00
```js
import { Server } from '@hocuspocus/server'
const server = Server.configure({
2021-04-20 19:18:11 +08:00
async onConnect(data) {
const { requestParameters } = data
2020-11-28 00:23:04 +08:00
2021-04-20 19:18:11 +08:00
// Example test if a user is authenticated using a
// request parameter
if (requestParameters.access_token !== 'super-secret-token') {
2021-04-20 19:18:11 +08:00
throw new Error('Not authorized!')
}
2021-04-20 19:18:11 +08:00
// You can set contextual data to use it in other hooks
return {
user: {
id: 1234,
name: 'John',
},
}
2020-11-28 00:23:04 +08:00
},
})
server.listen()
```
2021-04-20 19:18:11 +08:00
### Handling Document changes
2020-11-28 00:23:04 +08:00
2021-04-20 19:18:11 +08:00
With the `onChange` hook you can listen to changes of the document and handle them. It should return
a Promise. It's payload contains the resulting document as well as the actual update in the Y-Doc
binary format.
2020-11-28 00:23:04 +08:00
2021-04-20 19:18:11 +08:00
In a real-world application you would probably save the current document to a database, send it via
webhook to an API or something else. If you want to send a webhook to an external API we already
have built a simple to use webhook extension you should check out.
2021-04-20 19:18:11 +08:00
It's **highly recommended** to debounce extensive operations (like API calls) as this hook can be
fired up to multiple times a second:
2021-04-20 19:18:11 +08:00
You need to serialize the Y-Doc that hocuspocus gives you to something you can actually display in
your views.
2020-11-28 00:23:04 +08:00
2021-04-20 19:18:11 +08:00
This example is **not intended** to be a primary storage as serializing to and deserializing from JSON not store the collaboration history steps but only the resulting document. Make sure to always use the RocksDB extension as primary storage.
2020-11-28 00:23:04 +08:00
2021-04-20 19:18:11 +08:00
```typescript
import {debounce} from 'debounce'
import {Server} from '@hocuspocus/server'
import {TiptapTransformer} from '@hocuspocus/transformer'
import {writeFile} from 'fs'
2020-11-28 00:23:04 +08:00
2021-04-20 19:18:11 +08:00
let debounced
2020-11-28 00:23:04 +08:00
const hocuspocus = Server.configure({
2021-04-20 19:18:11 +08:00
async onChange(data) {
const save = () => {
2021-04-20 19:18:11 +08:00
// Convert the y-doc to something you can actually use in your views.
// In this example we use the TiptapTransformer to get JSON from the given
// ydoc.
const prosemirrorJSON = TiptapTransformer.fromYdoc(data.document)
// Save your document. In a real-world app this could be a database query
// a webhook or something else
writeFile(
`/path/to/your/documents/${data.documentName}.json`,
2021-04-20 19:18:11 +08:00
prosemirrorJSON
)
2021-04-20 19:18:11 +08:00
// Maybe you want to store the user who changed the document?
// Guess what, you have access to your custom context from the
// onConnect hook here.
console.log(`Document ${data.documentName} changed by ${data.context.user.name}`)
}
2021-04-20 19:18:11 +08:00
debounced?.clear()
debounced = debounce(() => save, 4000)
debounced()
2020-11-28 00:23:04 +08:00
},
})
hocuspocus.listen()
2020-11-28 00:23:04 +08:00
```
2020-12-04 22:12:38 +08:00
## Pitfalls
### Schema updates
tiptap is very strict with the [schema](/api/schema), that means, if you add something thats not allowed according to the configured schema itll be thrown away. That can lead to a strange behaviour when multiple clients with different schemas share changes to a document.
Lets say you added an editor to your app and the first people use it already. They have all a loaded instance of tiptap with all default extensions, and therefor a schema that only allows those. But you want to add task lists in the next update, so you add the extension and deploy again.
A new user opens your app and has the updated schema (with task lists), while all others still have the old schema (without task lists). The new user checks out the newly added tasks lists and adds it to a document to show that feature to other users in that document. But then, it magically disappears right after she added it. What happened?
When one user adds a new node (or mark), that change will be synced to all other connected clients. The other connected clients apply those changes to the editor, and tiptap, strict as it is, removes the newly added node, because its not allowed according to their (old) schema. Those changes will be synced to other connected clients and oops, its removed everywhere. To avoid this you have a few options:
1. Never change the schema (not cool).
2. Force clients to update when you deploy a new schema (tough).
3. Keep track of the schema version and disable the editor for clients with an outdated schema (depends on your setup).
Its on our list to provide features to make that easier. If youve got an idea how to improve that, share it with us!