2019-10-13 16:37:56 +00:00
|
|
|
import { Operation, Selection } from 'slate'
|
|
|
|
import { List } from 'immutable'
|
|
|
|
import merge from 'lodash/merge'
|
|
|
|
|
2019-10-12 17:58:23 +00:00
|
|
|
import { toJS } from '../utils'
|
2019-10-13 16:37:56 +00:00
|
|
|
import { SyncDoc, CursorKey } from '../model'
|
2019-10-12 17:58:23 +00:00
|
|
|
|
2019-10-13 16:37:56 +00:00
|
|
|
export const setCursor = (
|
|
|
|
doc: SyncDoc,
|
|
|
|
key: CursorKey,
|
|
|
|
selection: Selection,
|
|
|
|
type,
|
|
|
|
data
|
|
|
|
) => {
|
|
|
|
if (!doc) return
|
2019-10-12 17:58:23 +00:00
|
|
|
|
|
|
|
if (!doc.annotations) {
|
|
|
|
doc.annotations = {}
|
|
|
|
}
|
|
|
|
|
2019-10-13 16:37:56 +00:00
|
|
|
if (!doc.annotations[key]) {
|
|
|
|
doc.annotations[key] = {
|
|
|
|
key,
|
|
|
|
type,
|
2019-10-12 17:58:23 +00:00
|
|
|
data: {}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-10-13 16:37:56 +00:00
|
|
|
const annotation = toJS(doc.annotations[key])
|
2019-10-12 17:58:23 +00:00
|
|
|
|
2019-10-13 16:37:56 +00:00
|
|
|
annotation.focus = selection.end.toJSON()
|
|
|
|
annotation.anchor = selection.start.toJSON()
|
2019-10-12 17:58:23 +00:00
|
|
|
|
2019-10-13 16:37:56 +00:00
|
|
|
annotation.data = merge(annotation.data, data, {
|
|
|
|
isBackward: selection.isBackward,
|
|
|
|
targetPath: selection.isBackward
|
|
|
|
? annotation.anchor.path
|
|
|
|
: annotation.focus.path
|
|
|
|
})
|
2019-10-12 17:58:23 +00:00
|
|
|
|
2019-10-13 16:37:56 +00:00
|
|
|
doc.annotations[key] = annotation
|
2019-10-12 17:58:23 +00:00
|
|
|
|
|
|
|
return doc
|
|
|
|
}
|
|
|
|
|
2019-10-13 16:37:56 +00:00
|
|
|
export const removeCursor = (doc: SyncDoc, key: CursorKey) => {
|
|
|
|
if (doc.annotations && doc.annotations[key]) {
|
|
|
|
delete doc.annotations[key]
|
2019-10-12 17:58:23 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return doc
|
|
|
|
}
|
|
|
|
|
2019-10-13 16:37:56 +00:00
|
|
|
export const cursorOpFilter = (ops: List<Operation>, type: string) =>
|
2019-10-12 17:58:23 +00:00
|
|
|
ops.filter(op => {
|
|
|
|
if (op.type === 'set_annotation') {
|
|
|
|
return !(
|
2019-10-13 16:37:56 +00:00
|
|
|
(op.properties && op.properties.type === type) ||
|
|
|
|
(op.newProperties && op.newProperties.type === type)
|
2019-10-12 17:58:23 +00:00
|
|
|
)
|
|
|
|
} else if (
|
|
|
|
op.type === 'add_annotation' ||
|
|
|
|
op.type === 'remove_annotation'
|
|
|
|
) {
|
2019-10-13 16:37:56 +00:00
|
|
|
return op.annotation.type !== type
|
2019-10-12 17:58:23 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return true
|
|
|
|
})
|