cudr_slate-collaborative/packages/bridge/src/path/index.ts

43 lines
1.0 KiB
TypeScript
Raw Normal View History

import { Element, Node, Path } from 'slate'
2019-10-05 08:44:49 +00:00
import { SyncValue } from '../model'
export const isTree = (node: Node): boolean => Boolean(node?.children)
2019-10-05 08:44:49 +00:00
export const getTarget = (doc: SyncValue | Element, path: Path) => {
2019-10-05 08:44:49 +00:00
const iterate = (current: any, idx: number) => {
if (!(isTree(current) || current[idx])) {
2019-10-05 08:44:49 +00:00
throw new TypeError(
`path ${path.toString()} does not match tree ${JSON.stringify(current)}`
)
}
return current[idx] || current?.children[idx]
2019-10-05 08:44:49 +00:00
}
return path.reduce(iterate, doc)
2019-10-05 08:44:49 +00:00
}
export const getParentPath = (
path: Path,
level: number = 1
): [number, Path] => {
if (level > path.length) {
2019-10-05 08:44:49 +00:00
throw new TypeError('requested ancestor is higher than root')
}
return [path[path.length - level], path.slice(0, path.length - level)]
2019-10-05 08:44:49 +00:00
}
export const getParent = (
doc: SyncValue | Element,
2019-10-05 08:44:49 +00:00
path: Path,
level = 1
): [any, number] => {
2019-10-05 08:44:49 +00:00
const [idx, parentPath] = getParentPath(path, level)
2019-10-05 08:44:49 +00:00
return [getTarget(doc, parentPath), idx]
}
export const getChildren = (node: any) => node.children || node