cudr_slate-collaborative/packages/bridge/src/convert/remove.ts

84 lines
1.7 KiB
TypeScript
Raw Normal View History

2019-10-06 20:56:27 +00:00
import * as Automerge from 'automerge'
2019-10-05 08:44:49 +00:00
import { toSlatePath, toJS } from '../utils/index'
2019-10-05 21:24:52 +00:00
import { getTarget } from '../path'
2019-10-05 08:44:49 +00:00
2019-10-06 20:56:27 +00:00
const removeTextOp = ({ index, path }: Automerge.Diff) => () => ({
2019-10-05 08:44:49 +00:00
type: 'remove_text',
path: toSlatePath(path).slice(0, path.length),
offset: index,
text: '*',
marks: []
})
2019-10-06 20:56:27 +00:00
const removeMarkOp = ({ path, index }: Automerge.Diff) => (map, doc) => {
2019-10-05 21:24:52 +00:00
const slatePath = toSlatePath(path)
const target = getTarget(doc, slatePath)
return {
type: 'remove_mark',
path: slatePath,
mark: {
type: target.marks[index].type
}
}
}
2019-10-06 20:56:27 +00:00
const removeNodesOp = ({ index, obj, path }: Automerge.Diff) => (map, doc) => {
2019-10-06 10:30:35 +00:00
const slatePath = toSlatePath(path)
if (!map.hasOwnProperty(obj)) {
const target = getTarget(doc, [...slatePath, index] as any)
map[obj] = target
}
2019-10-05 08:44:49 +00:00
return {
type: 'remove_node',
2019-10-06 10:30:35 +00:00
path: slatePath.length ? slatePath.concat(index) : [index],
2019-10-05 08:44:49 +00:00
node: {
object: 'text'
}
}
}
const removeAnnotationOp = ({ key }: Automerge.Diff) => (map, doc) => {
const annotation = toJS(doc.annotations[key])
if (annotation) {
return {
type: 'remove_annotation',
annotation
}
}
}
2019-10-05 08:44:49 +00:00
const removeByType = {
text: removeTextOp,
2019-10-05 21:24:52 +00:00
nodes: removeNodesOp,
marks: removeMarkOp,
annotations: removeAnnotationOp
2019-10-05 08:44:49 +00:00
}
2019-10-06 20:56:27 +00:00
const opRemove = (op: Automerge.Diff, [map, ops]) => {
2019-10-05 08:44:49 +00:00
try {
const { index, path, obj } = op
if (map.hasOwnProperty(obj) && op.type !== 'text') {
map[obj].splice(index, 1)
return [map, ops]
}
if (!path) return [map, ops]
const fn = removeByType[path[path.length - 1]]
return [map, [...ops, fn(op)]]
} catch (e) {
console.error(e, op, toJS(map))
return [map, ops]
}
}
export default opRemove