feat: cursors should works with annotations

This commit is contained in:
cudr
2019-10-13 19:37:56 +03:00
parent 242a836ce8
commit 0ceb38bbfd
19 changed files with 214 additions and 186 deletions

View File

@@ -2,6 +2,7 @@ import io from 'socket.io'
import { ValueJSON } from 'slate'
import * as Automerge from 'automerge'
import throttle from 'lodash/throttle'
import merge from 'lodash/merge'
import { toSync, toJS } from '@slate-collaborative/bridge'
@@ -18,7 +19,7 @@ class Connection {
this.io = io(options.port, options.connectOpts)
this.docSet = new Automerge.DocSet()
this.connections = {}
this.options = options
this.options = merge(defaultOptions, options)
this.configure()
}
@@ -32,7 +33,7 @@ class Connection {
private appendDoc = (path: string, value: ValueJSON) => {
const sync = toSync(value)
sync.cursors = {}
sync.annotations = {}
const doc = Automerge.from(sync)
@@ -44,11 +45,13 @@ class Connection {
if (this.options.onDocumentSave) {
const doc = this.docSet.getDoc(pathname)
const data = toJS(doc)
if (doc) {
const data = toJS(doc)
delete data.cursors
delete data.annotations
this.options.onDocumentSave(pathname, data)
this.options.onDocumentSave(pathname, data)
}
}
} catch (e) {
console.log(e)
@@ -106,6 +109,8 @@ class Connection {
socket.on('operation', this.onOperation(id, name))
socket.on('disconnect', this.onDisconnect(id, socket))
this.garbageCursors(name)
}
private onOperation = (id, name) => data => {
@@ -125,6 +130,8 @@ class Connection {
socket.leave(id)
this.garbageCursor(socket.nsp.name, id)
this.garbageCursors(socket.nsp.name)
this.garbageNsp()
}
@@ -141,17 +148,32 @@ class Connection {
garbageCursor = (nsp, id) => {
const doc = this.docSet.getDoc(nsp)
if (!doc.cursors) return
if (!doc.annotations) return
const change = Automerge.change(
doc,
`remove cursor ${id}`,
(d: any) => delete d.cursors[id]
)
const change = Automerge.change(doc, `remove cursor ${id}`, (d: any) => {
delete d.annotations[id]
})
this.docSet.setDoc(nsp, change)
}
garbageCursors = nsp => {
const doc = this.docSet.getDoc(nsp)
if (!doc.annotations) return
const namespace = this.io.of(nsp)
Object.keys(doc.annotations).forEach(key => {
if (
!namespace.sockets[key] &&
doc.annotations[key].type === this.options.cursorAnnotationType
) {
this.garbageCursor(nsp, key)
}
})
}
removeDoc = async nsp => {
const doc = this.docSet.getDoc(nsp)

View File

@@ -5,6 +5,7 @@ export interface ConnectionOptions {
connectOpts?: SocketIO.ServerOptions
defaultValue?: ValueJSON
saveTreshold?: number
cursorAnnotationType?: string
onAuthRequest?: (
query: Object,
socket?: SocketIO.Socket

View File

@@ -7,7 +7,8 @@ export const getClients = (io, nsp) =>
export const defaultOptions = {
port: 9000,
saveTreshold: 2000
saveTreshold: 2000,
cursorAnnotationType: 'collaborative_selection'
}
export { defaultValue }