2020-07-01 21:56:48 +00:00
|
|
|
import { Element, Node, Path } from 'slate'
|
2019-10-05 08:44:49 +00:00
|
|
|
|
2020-05-11 06:21:49 +00:00
|
|
|
import { SyncValue } from '../model'
|
2020-05-10 13:50:12 +00:00
|
|
|
|
|
|
|
export const isTree = (node: Node): boolean => Boolean(node?.children)
|
2019-10-05 08:44:49 +00:00
|
|
|
|
2020-07-01 21:56:48 +00:00
|
|
|
export const getTarget = (doc: SyncValue | Element, path: Path) => {
|
2019-10-05 08:44:49 +00:00
|
|
|
const iterate = (current: any, idx: number) => {
|
2020-05-10 13:50:12 +00:00
|
|
|
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)}`
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2020-05-10 13:50:12 +00:00
|
|
|
return current[idx] || current?.children[idx]
|
2019-10-05 08:44:49 +00:00
|
|
|
}
|
|
|
|
|
2020-05-10 13:50:12 +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] => {
|
2020-05-10 13:50:12 +00:00
|
|
|
if (level > path.length) {
|
2019-10-05 08:44:49 +00:00
|
|
|
throw new TypeError('requested ancestor is higher than root')
|
|
|
|
}
|
|
|
|
|
2020-05-10 13:50:12 +00:00
|
|
|
return [path[path.length - level], path.slice(0, path.length - level)]
|
2019-10-05 08:44:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export const getParent = (
|
2020-07-01 21:56:48 +00:00
|
|
|
doc: SyncValue | Element,
|
2019-10-05 08:44:49 +00:00
|
|
|
path: Path,
|
|
|
|
level = 1
|
2020-05-10 13:50:12 +00:00
|
|
|
): [any, number] => {
|
2019-10-05 08:44:49 +00:00
|
|
|
const [idx, parentPath] = getParentPath(path, level)
|
2020-05-10 13:50:12 +00:00
|
|
|
|
2019-10-05 08:44:49 +00:00
|
|
|
return [getTarget(doc, parentPath), idx]
|
|
|
|
}
|
2020-05-10 13:50:12 +00:00
|
|
|
|
2020-05-11 06:21:49 +00:00
|
|
|
export const getChildren = (node: any) => node.children || node
|