仅仅28行代码,就能实现一个【协同文档】!
协同文档
在平时的开发中,协同文档真的帮助到了我们很多,他可以应用到很多场景,比如:
- 需求文档同步
- 信息收集
- 公司内部文档编写
所以现阶段协同文档也是市面上很火的一种趋势,比较火的产品有:
- 企微文档
- 飞书文档
- 语雀
- 等等。。。。
协同
想要实现协同文档,其实有一个最大的痛点,那就是 协同。
通俗点说就是:两个人同时编辑同一个文档,就会有冲突,那么这个冲突应该怎么解决?
为了解决这个问题,市面上出现了两种算法(不是本文重点)
- OT (Operational transformation)
- CRDT(Conflict-free Replicated Data Type)
OT

CRDT

实现协同文档
接下来开始实现一个简单的协同文档!!!
装库
我们需要先安装几个库
npm i yjs y-quill
quill quill-cursors
y-websocket
- yjs: 一个集成 CRDT 算法的同步库,是此次协同文档的核心
- quill: 一个富文本编辑器
- quill-cursors: 一个quill的插件,用于显示多个光标,因为多个用户共同编辑就会有多个光标
- y-quill: 可以理解为他能将yjs和quill融合起来,实现协同
- y-websocket: 一个yjs的库,作用是将数据同步到多个客户端
客户端
<div id="app"></div>
import * as Y from 'yjs';
import { QuillBinding } from 'y-quill';
import Quill from 'quill';
import QuillCursors from 'quill-cursors';
import { WebsocketProvider } from 'y-websocket';
import 'quill/dist/quill.snow.css'; // 使用了 snow 主题色
// 使用 cursors 插件
Quill.register('modules/cursors', QuillCursors);
const quill = new Quill(document.querySelector('#app'), {
modules: {
cursors: true,
toolbar: [
[{ header: [1, 2, false] }],
['bold', 'italic', 'underline'],
['image', 'code-block'],
],
history: {
userOnly: true,
},
},
placeholder: '林三心不学挖掘机...',
theme: 'snow',
});
const ydoc = new Y.Doc(); // y 文档对象,保存需要共享的数据
const ytext = ydoc.getText('quill'); // 创建名为 quill 的 Text 对象
// 连接到 websocket 服务端
const provider = new WebsocketProvider('ws://localhost:1234', 'quill-demo-room', ydoc);
// 数据模型绑定,再绑上光标对象
const binding = new QuillBinding(ytext, quill, provider.awareness);
服务端
只需要在终端里运行
HOST=localhost PORT=1234 npx y-websocket

效果
现在就可以实现协同文档的效果啦!!!
