协同文档
在平时的开发中,协同文档真的帮助到了我们很多,他可以应用到很多场景,比如:
所以现阶段协同文档也是市面上很火的一种趋势,比较火的产品有:
协同
想要实现协同文档,其实有一个最大的痛点,那就是 协同。
通俗点说就是:两个人同时编辑同一个文档,就会有冲突,那么这个冲突应该怎么解决?
为了解决这个问题,市面上出现了两种算法(不是本文重点)
- OT (Operational transformation)
- CRDT(Conflict-free Replicated Data Type)
这不是本文重点,如果不想看可以直接跳到下面的代码实战~
OT

实现协同文档
接下来开始实现一个简单的协同文档!!!
装库
我们需要先安装几个库
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';
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();
const ytext = ydoc.getText('quill');
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

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

转自https://juejin.cn/post/7297522590683168783
该文章在 2025/4/14 10:19:01 编辑过