You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
cudr_slate-collaborative/packages/bridge/src/convert/remove.ts

84 lines
1.7 KiB

import * as Automerge from 'automerge'
5 years ago
import { toSlatePath, toJS } from '../utils/index'
import { getTarget } from '../path'
5 years ago
const removeTextOp = ({ index, path }: Automerge.Diff) => () => ({
5 years ago
type: 'remove_text',
path: toSlatePath(path).slice(0, path.length),
offset: index,
text: '*',
marks: []
})
const removeMarkOp = ({ path, index }: Automerge.Diff) => (map, doc) => {
const slatePath = toSlatePath(path)
const target = getTarget(doc, slatePath)
return {
type: 'remove_mark',
path: slatePath,
mark: {
type: target.marks[index].type
}
}
}
const removeNodesOp = ({ index, obj, path }: Automerge.Diff) => (map, doc) => {
const slatePath = toSlatePath(path)
if (!map.hasOwnProperty(obj)) {
const target = getTarget(doc, [...slatePath, index] as any)
map[obj] = target
}
5 years ago
return {
type: 'remove_node',
path: slatePath.length ? slatePath.concat(index) : [index],
5 years ago
node: {
object: 'text'
}
}
}
const removeAnnotationOp = ({ key }: Automerge.Diff) => (map, doc) => {
const annotation = toJS(doc.annotations[key])
if (annotation) {
return {
type: 'remove_annotation',
annotation
}
}
}
5 years ago
const removeByType = {
text: removeTextOp,
nodes: removeNodesOp,
marks: removeMarkOp,
annotations: removeAnnotationOp
5 years ago
}
const opRemove = (op: Automerge.Diff, [map, ops]) => {
5 years ago
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