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

77 lines
1.6 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-06 20:56:27 +00:00
const insertTextOp = ({ index, path, value }: Automerge.Diff) => () => ({
2019-10-05 08:44:49 +00:00
type: 'insert_text',
path: toSlatePath(path),
offset: index,
text: value,
marks: []
})
2019-10-06 20:56:27 +00:00
const insertNodeOp = ({ value, obj, index, path }: Automerge.Diff) => map => {
2019-10-05 21:24:52 +00:00
const ops = []
2019-10-06 20:56:27 +00:00
const inserate = ({ nodes, ...json }: any, path) => {
2019-10-06 10:30:35 +00:00
const node = nodes ? { ...json, nodes: [] } : json
if (node.object === 'mark') {
ops.push({
type: 'add_mark',
path: path.slice(0, -1),
mark: node
})
} else {
ops.push({
type: 'insert_node',
path,
node
})
}
2019-10-05 21:24:52 +00:00
2019-10-06 20:56:27 +00:00
nodes && nodes.forEach((n, i) => inserate(n, [...path, i]))
2019-10-05 21:24:52 +00:00
}
2019-10-06 10:30:35 +00:00
const source = map[value] || (map[obj] && toJS(map[obj]))
2019-10-06 20:56:27 +00:00
source && inserate(source, [...toSlatePath(path), index])
2019-10-05 21:24:52 +00:00
return ops
}
2019-10-05 08:44:49 +00:00
const insertByType = {
text: insertTextOp,
list: insertNodeOp
}
2019-10-06 20:56:27 +00:00
const opInsert = (op: Automerge.Diff, [map, ops]) => {
2019-10-05 08:44:49 +00:00
try {
const { link, obj, path, index, type, value } = op
if (link && map[obj]) {
map[obj].splice(index, 0, map[value] || value)
} else if (type === 'text' && !path) {
map[obj] = map[obj]
? map[obj]
.slice(0, index)
.concat(value)
.concat(map[obj].slice(index))
: value
} else {
const insert = insertByType[type]
const operation = insert && insert(op, map)
ops.push(operation)
}
return [map, ops]
} catch (e) {
console.error(e, op, toJS(map))
return [map, ops]
}
}
export default opInsert