前言
? ? ? ? 對(duì)于word的協(xié)同編輯,已經(jīng)構(gòu)思很久了,但是沒有找到合適的插件。今天推薦基于canvas/svg 的富文本編輯器 ?canvas-editor,能實(shí)現(xiàn)類似word的基礎(chǔ)功能,如果后續(xù)有更好的,也會(huì)及時(shí)更新。
Canvas-Editor
效果圖
官方文檔
canvas-editor | rich text editor by canvas/svgrich text editor by canvas/svghttps://hufe.club/canvas-editor-docs/
?官方DEMO?
canvas-editorhttps://hufe.club/canvas-editor/
Gitee
canvas-editor: 同步自https://github.com/Hufe921/canvas-editorhttps://gitee.com/mr-jinhui/canvas-editor
?前置條件與實(shí)現(xiàn)思路
? ? ? ? 雖然canvas-editor做的還不錯(cuò),API都比較完善,但是對(duì)協(xié)同部分還是空缺,因此我們此次的重點(diǎn)是實(shí)現(xiàn)協(xié)同部分的代碼,難免會(huì)修改源碼部分。因此,我們需要閱讀源碼,實(shí)現(xiàn) ts 代碼的編寫,修改其源碼,實(shí)現(xiàn)協(xié)同。
下載源碼并運(yùn)行
? ? ? ? 大家可以直接從 github下載 ,也可以從剛才給的 gitee 下。
npm i? // 下載相關(guān)依賴
npm run dev // 啟動(dòng)服務(wù)
npm run build // 打包項(xiàng)目
? ? ? ? 啟動(dòng)后,能出來與demo一致的頁面,即完成了這一步。
實(shí)現(xiàn)用戶選區(qū)
? ? ? ? 用戶閃爍的光標(biāo)目前還沒有思路實(shí)現(xiàn),后面會(huì)攻克技術(shù)難點(diǎn),但是用戶選取可以通過API實(shí)現(xiàn):
? ? ? ? ?但是這個(gè)API會(huì)導(dǎo)致我的選取也會(huì)發(fā)生改變,因此,不能直接使用,需要添加新的API
? ? ? ? 簡單解釋一下文件,command文件向外暴露了API, command 指向 commandAdapt 文件,Adapt 文件中,有需要的全部對(duì)象,包括 畫布、選取對(duì)象等,可以直接進(jìn)行底層繪制。
public setUserRange(startIndex: number, endIndex: number, payload?: string) {
if (startIndex < 0 || endIndex < 0 || endIndex < startIndex) return
const isReadonly = this.draw.isReadonly()
if (isReadonly) return
// 根據(jù) index 獲取 domList 設(shè)置顏色
const elementList = this.draw.getElementList()
for (let i = startIndex; i <= endIndex; i++) {
elementList[i].highlight = payload||'#F5EEA0'
}
this.draw.render({
isSetCursor: false,
isCompute: false
})
}
???????? 這樣用戶選取,才不會(huì)影響我的選取,而取消選取就是設(shè)置透明色即可。
// 用戶取消選取
public setUserUnRange(startIndex: number, endIndex: number) {
if (startIndex < 0 || endIndex < 0 || endIndex < startIndex) return
const isReadonly = this.draw.isReadonly()
if (isReadonly) return
// 根據(jù) index 獲取 domList 設(shè)置顏色
const elementList = this.draw.getElementList()
for (let i = startIndex; i <= endIndex; i++) {
elementList[i].highlight = 'transparent'
}
this.draw.render({
isSetCursor: false,
isCompute: false
})
}
? ? ? ? ?用戶的光標(biāo)是無狀態(tài)的,因此需要記錄光標(biāo)信息,不然我重新設(shè)置了選取,上次的選取是需要取消哦,這個(gè)后面再說。
搭建CRDT
? ? ? ? 協(xié)同的核心就是數(shù)據(jù)一致性,因此,我們需要根據(jù)現(xiàn)有的數(shù)據(jù)結(jié)構(gòu)實(shí)現(xiàn)CRDT。
新建yjs文件
// editor/core/websocket
import * as Y from 'yjs'
import { WebsocketProvider } from 'y-websocket'
import { IWebsocketProviderStatus } from '../../interface/Websocket'
export class Ydoc {
private ydoc: Y.Doc
private ymap: Y.Map<unknown>
private ytext: Y.Text
private provider: any | undefined
private connect: boolean | undefined
private url: string
private roomname: string
constructor(url: string, roomname: string) {
console.log('new Ydoc')
this.url = url
this.roomname = roomname
this.connect = false
// 創(chuàng)建 YDoc 文檔
this.ydoc = new Y.Doc()
this.ymap = this.ydoc.getMap('map')
this.ytext = this.ydoc.getText('text')
this.ymap.observe(() => {})
this.ytext.observe(() => {})
// 【方案二】 websocket 方式實(shí)現(xiàn)協(xié)同(已自己搭建 websocket 服務(wù))
this.provider = new WebsocketProvider(this.url, this.roomname, this.ydoc)
// 監(jiān)聽鏈接狀態(tài)F·
this.provider.on('status', (event: IWebsocketProviderStatus) => {
let { status } = event
if (status === 'connected') this.connect = true
else this.connect = false
})
}
public disConnection() {
if (!this.connect) return
this.provider.disconnect()
}
}
初始化 yjs?
????????入口文件 index.ts 實(shí)現(xiàn)創(chuàng)建并傳參
// 創(chuàng)建 websocket
if (ydocInfo) {
let { url, roomname, userid, username, color } = ydocInfo
if (!url || !roomname || !userid || !username)
throw Error('參數(shù)錯(cuò)誤,url、roomname、userid、username必傳!')
// 1. 如果存在,則創(chuàng)建協(xié)同
ydoc = new Ydoc(url, roomname, userid, this.command, color)
Reflect.set(window, 'ydoc', ydoc)
console.log(`用戶${username}初始化`)
ydoc.userInitEditor(`用戶${username}`)
}
? ? ? ? ?這樣,整個(gè)編輯器需要實(shí)現(xiàn)協(xié)同的地方,都能調(diào)用 ydoc 實(shí)現(xiàn)。
實(shí)現(xiàn)用戶登錄
? ? ? ? Yjs 的基本使用中,通過Map設(shè)置數(shù)據(jù),observe觀察器實(shí)現(xiàn)數(shù)據(jù)獲取,協(xié)同部分不懂得可以看上一篇文章:
深度解析 Yjs 協(xié)同編輯原理【看這篇就夠了】_深度 解析yjs原理-CSDN博客文章瀏覽閱讀1k次,點(diǎn)贊21次,收藏16次。本文帶大家分析了Yjs的API、y-websocket 的實(shí)現(xiàn)原理、Yjs的應(yīng)用及底層協(xié)同模型,并使用Logic Flow 簡單實(shí)現(xiàn)了其協(xié)同。大致的協(xié)同實(shí)現(xiàn)都有類似的思想,大家以后需要協(xié)同的場景,希望也能自行開發(fā)。_深度 解析yjs原理https://blog.csdn.net/weixin_47746452/article/details/135079472?spm=1001.2014.3001.5501
? ? ? ? 這樣,用戶每次初始化 Editor的時(shí)候,都會(huì)廣播其他用戶:
實(shí)現(xiàn)用戶選區(qū)
? ? ? ? 用戶每次操作鼠標(biāo)抬起,都會(huì)觸發(fā)setRangeStyle事件:
? ? ? ? ?因此,在這個(gè)事件中捕獲用戶的選區(qū)操作;
?????????yjs中則是正常轉(zhuǎn)發(fā),然后調(diào)用上面實(shí)現(xiàn)的選區(qū)API:
public userRange({ data }: IYMapObserve) {
let { startIndex, endIndex, userid, color } = data
this.command.setUserRange(startIndex, endIndex, userid, color)
}
? ? ? ? 效果如下:
?實(shí)現(xiàn)用戶取消選區(qū)
? ? ? ? 現(xiàn)在的選區(qū)還是有bug的,用戶退出后,無法識(shí)別,還有就是單擊時(shí),無法優(yōu)化選區(qū)。
? ? ? ? 如上圖,我點(diǎn)擊時(shí),理論上只占用一個(gè)格子,不應(yīng)該有選區(qū)【用戶光標(biāo)目前還沒能實(shí)現(xiàn)】? if (startIndex === endIndex) return 如果點(diǎn)擊的開始與結(jié)束相同,則不進(jìn)行渲染。還有用戶退出時(shí),清空用戶選區(qū):
? ? ? ? ?實(shí)現(xiàn)刪除歷史選區(qū),并刪除lastRange 記錄即可。
實(shí)現(xiàn)文本輸入與刪除
? ? ? ?CanvasEvent監(jiān)聽了input 事件,實(shí)現(xiàn)監(jiān)聽用戶的輸入,修改參數(shù)實(shí)現(xiàn)在draw 中獲取用戶數(shù)據(jù),文檔變化時(shí),會(huì)調(diào)用 draw 中的方法:
????????因此,在這里通過yjs廣播事件,修改參數(shù)后,就能拿到用戶新增的數(shù)據(jù)了:
// 內(nèi)容區(qū)變化
public contentChangeHandle(payload: IEditorData) {
/**
* 因此在這里需要重新解析用戶的選區(qū)設(shè)置,不然會(huì)導(dǎo)致選區(qū)異常 BUG
*/
// 這里要解析 userRange
let { header, footer, main } = payload
main.forEach(item => {
if (item.userRange) {
delete item.highlight
delete item.userRange
}
})
this.setValue({ header, footer, main })
}
? ? ? ? 實(shí)現(xiàn)效果:
? ? ? ? 刪除實(shí)現(xiàn):
? ? ? ? keydown.ts 中對(duì)每個(gè)事件做了監(jiān)聽,在該文件實(shí)現(xiàn)廣播,還是拿到本地的數(shù)據(jù),進(jìn)行數(shù)據(jù)解析,重新渲染。
? ? ? ? 效果如下:
實(shí)現(xiàn)樣式協(xié)同
? ? ? ? 樣式的協(xié)同,就是基于API實(shí)現(xiàn)的,因?yàn)樵趍ain.ts中,所有的菜單欄操作,都是基于API實(shí)現(xiàn),因此,我們需要在API調(diào)用處,進(jìn)行統(tǒng)一處理即可
// 選區(qū)樣式改變
public rangeStyleChange(payload: IRangeStyle) {
// 樣式只能針對(duì) 用戶的當(dāng)前選區(qū)
// 直接使用 element 的事件機(jī)制
let { startIndex = 0, endIndex = 0, attr, value } = payload
const isReadonly = this.draw.isReadonly()
if (isReadonly) return
if (startIndex === endIndex) return
// 根據(jù) index 獲取 domList 設(shè)置顏色
const elementList = this.draw.getElementList()
for (let i = startIndex; i <= endIndex; i++) {
let el = elementList[i]
if (el) {
switch (attr) {
case 'color':
value ? (el.color = <string | undefined>value) : delete el.color
break
case 'bold':
value ? (el.bold = true) : delete el.bold
break
case 'italic':
value ? (el.italic = true) : delete el.italic
break
case 'fontSize':
break
case 'underline':
value ? (el.underline = true) : delete el.underline
break
case 'highlight':
// 這里還有BUG,因?yàn)橛脩暨x區(qū)結(jié)束又被設(shè)置透明
value
? (el.highlight = <string | undefined>value)
: delete el.highlight
break
default:
break
}
}
}
this.draw.render({
isSetCursor: false,
isCompute: false
})
}
? ? ? ? 效果如下:
? ? ? ? 用戶協(xié)同選區(qū)與高亮沖突了,這個(gè)還得在想辦法處理。
打包在項(xiàng)目中使用
? ? ? ? 想要打包,需要注釋 main.ts 中的window.onload 事件,將Editor 暴露到window身上
? ? ? ? 打包后,將dist 放置到項(xiàng)目 public/libs.canvas-editor下【如果你打包報(bào)錯(cuò),基本上是TS語法檢查的問題 let const 引入沒用的模塊等】
? ? ? ? 這樣已經(jīng)實(shí)現(xiàn)了基本的協(xié)同編輯了,至于說 菜單欄、目錄,其實(shí)也是它自己加上的,然后調(diào)用API實(shí)現(xiàn):
? ? ? ? ?剩下的就是自行實(shí)現(xiàn)菜單欄,調(diào)用API即可。文章來源:http://www.zghlxwxcb.cn/news/detail-821822.html
?總結(jié)
? ? ? ? 對(duì)這個(gè)文章簡單說一下:文章來源地址http://www.zghlxwxcb.cn/news/detail-821822.html
- 這個(gè)版本的代碼肯定是粗糙的哈,大家稍微諒解一下,自己的TS還有點(diǎn)差;
- 功能實(shí)現(xiàn)上還有些缺陷,有些功能底層限制了,修改起來難度非常大,比如協(xié)同選區(qū)問題,后續(xù)會(huì)再優(yōu)化;
- 協(xié)同的底層一定是數(shù)據(jù)一致性、廣播監(jiān)聽、調(diào)用相應(yīng)API實(shí)現(xiàn)相同功能;
- 后續(xù)可能會(huì)完善這部分代碼,爭取能實(shí)現(xiàn)基本的、穩(wěn)定的協(xié)同環(huán)境,包括也會(huì)更新在 mpoe 項(xiàng)目中,有一個(gè)穩(wěn)定版本支撐協(xié)同編輯;
- 文章在書寫過程中,會(huì)發(fā)現(xiàn)BUG,然后調(diào)整代碼,可能會(huì)出現(xiàn)頁面與實(shí)際代碼不匹配,大家以實(shí)際代碼為主哈;
- 也會(huì)持續(xù)關(guān)注大家的問題與需求,大家可以提一些好的建議。
到了這里,關(guān)于Canvas-Editor 實(shí)現(xiàn)類似 Word 協(xié)同編輯的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!