先安装相关的组件
npm i yjs y-websocket y-quill quill quill-cursors我们通过y-websocket来搭建一个用户协同的数据交换服务器,启动命令
PORT=1234 node ./node_modules/y-websocket/bin/server.cjs
前端html代码
<link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet"> <div id="editor" />前端js代码
import Quill from 'quill' import QuillCursors from 'quill-cursors' import * as Y from 'yjs' import { QuillBinding } from 'y-quill' import { WebsocketProvider } from 'y-websocket' Quill.register('modules/cursors', QuillCursors); const quill = new Quill(document.querySelector('#editor'), { modules: { cursors: true, toolbar: [ // adding some basic Quill content features [{ header: [1, 2, false] }], ['bold', 'italic', 'underline'], ['image', 'code-block'] ], history: { // Local undo shouldn't undo changes // from remote users userOnly: true } }, placeholder: 'Start collaborating...', theme: 'snow' // 'bubble' is also great }) // A Yjs document holds the shared data const ydoc = new Y.Doc() // Define a shared text type on the document const ytext = ydoc.getText('quill') // Create an editor-binding which // "binds" the quill editor to a Y.Text type. const binding = new QuillBinding(ytext, quill) // connect to the public demo server (not in production!) const provider = new WebsocketProvider( 'wss://demos.yjs.dev:1234', 'quill-demo-room', ydoc )
最终效果
详细官方教程:https://docs.yjs.dev/getting-started/a-collaborative-editor
网友回复