協(xié)同文檔
在平時(shí)的開(kāi)發(fā)中,協(xié)同文檔真的幫助到了我們很多,他可以應(yīng)用到很多場(chǎng)景,比如:
- 需求文檔同步
- 信息收集
- 公司內(nèi)部文檔編寫(xiě)
所以現(xiàn)階段協(xié)同文檔也是市面上很火的一種趨勢(shì),比較火的產(chǎn)品有:
- 企微文檔
- 飛書(shū)文檔
- 語(yǔ)雀
- 等等。。。。
協(xié)同
想要實(shí)現(xiàn)協(xié)同文檔,其實(shí)有一個(gè)最大的痛點(diǎn),那就是 協(xié)同。
通俗點(diǎn)說(shuō)就是:兩個(gè)人同時(shí)編輯同一個(gè)文檔,就會(huì)有沖突,那么這個(gè)沖突應(yīng)該怎么解決?
為了解決這個(gè)問(wèn)題,市面上出現(xiàn)了兩種算法(不是本文重點(diǎn))
- OT (Operational transformation)
- CRDT(Conflict-free Replicated Data Type)
這不是本文重點(diǎn),如果不想看可以直接跳到下面的代碼實(shí)戰(zhàn)~
OT

實(shí)現(xiàn)協(xié)同文檔
接下來(lái)開(kāi)始實(shí)現(xiàn)一個(gè)簡(jiǎn)單的協(xié)同文檔?。。?/p>
裝庫(kù)
我們需要先安裝幾個(gè)庫(kù)
npm i yjs y-quill
quill quill-cursors
y-websocket
- yjs: 一個(gè)集成 CRDT 算法的同步庫(kù),是此次協(xié)同文檔的核心
- quill: 一個(gè)富文本編輯器
- quill-cursors: 一個(gè)quill的插件,用于顯示多個(gè)光標(biāo),因?yàn)槎鄠€(gè)用戶(hù)共同編輯就會(huì)有多個(gè)光標(biāo)
- y-quill: 可以理解為他能將yjs和quill融合起來(lái),實(shí)現(xiàn)協(xié)同
- y-websocket: 一個(gè)yjs的庫(kù),作用是將數(shù)據(jù)同步到多個(gè)客戶(hù)端
客戶(hù)端
<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: '林三心不學(xué)挖掘機(jī)...',
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);
服務(wù)端
只需要在終端里運(yùn)行
HOST=localhost PORT=1234 npx y-websocket

效果
現(xiàn)在就可以實(shí)現(xiàn)協(xié)同文檔的效果啦?。。?/p>

?轉(zhuǎn)自https://juejin.cn/post/7297522590683168783
該文章在 2025/4/14 10:19:01 編輯過(guò)