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

70 lines
1.3 KiB
TypeScript
Raw Normal View History

2019-10-06 20:56:27 +00:00
import * as Automerge from 'automerge'
2019-10-05 21:24:52 +00:00
import { toSlatePath, toJS } from '../utils/index'
2019-10-06 20:56:27 +00:00
const setDataOp = ({ path, value }: Automerge.Diff) => map => ({
2019-10-05 21:24:52 +00:00
type: 'set_node',
path: toSlatePath(path),
properties: {},
newProperties: {
data: map[value]
}
})
const AnnotationSetOp = ({ key, value }: Automerge.Diff) => (map, doc) => {
if (!doc.annotations) {
doc.annotations = {}
}
let op
/**
* Looks like set_annotation option is broken, temporary disabled
*/
// if (!doc.annotations[key]) {
op = {
type: 'add_annotation',
annotation: map[value]
}
// } else {
// op = {
// type: 'set_annotation',
// properties: toJS(doc.annotations[key]),
// newProperties: map[value]
// }
// }
return op
}
2019-10-05 21:24:52 +00:00
const setByType = {
2019-10-06 10:30:35 +00:00
data: setDataOp
2019-10-05 21:24:52 +00:00
}
2019-10-05 08:44:49 +00:00
2019-10-06 20:56:27 +00:00
const opSet = (op: Automerge.Diff, [map, ops]) => {
2019-10-06 10:30:35 +00:00
const { link, value, path, obj, key } = op
2019-10-05 08:44:49 +00:00
try {
2019-10-05 21:24:52 +00:00
const set = setByType[key]
2019-10-06 10:30:35 +00:00
if (set && path) {
2019-10-05 21:24:52 +00:00
ops.push(set(op))
2019-10-10 19:45:31 +00:00
} else if (map[obj]) {
2019-10-05 21:24:52 +00:00
map[obj][key] = link ? map[value] : value
}
2019-10-05 08:44:49 +00:00
/**
* Annotation
*/
if (path && path.length === 1 && path[0] === 'annotations') {
ops.push(AnnotationSetOp(op))
}
2019-10-05 08:44:49 +00:00
return [map, ops]
} catch (e) {
console.error(e, op, toJS(map))
return [map, ops]
}
}
export default opSet