1
0
mirror of https://github.com/ianstormtaylor/slate.git synced 2025-08-27 17:09:53 +02:00

feat: add Node.getIf method (#5723)

* feat: add Node.getIf support

* chore: restructure get to use getIf
This commit is contained in:
Ravi Lamkoti
2024-09-26 12:53:48 +05:30
committed by GitHub
parent f31167cf5f
commit ee2c45408c
5 changed files with 74 additions and 5 deletions

View File

@@ -0,0 +1,5 @@
---
'slate': patch
---
feat: add Node.getIf method

View File

@@ -131,6 +131,11 @@ export interface NodeInterface {
*/
get: (root: Node, path: Path) => Node
/**
* Similar to get, but returns undefined if the node does not exist.
*/
getIf: (root: Node, path: Path) => Node | undefined
/**
* Check if a descendant node exists at a specific path.
*/
@@ -389,17 +394,25 @@ export const Node: NodeInterface = {
},
get(root: Node, path: Path): Node {
const node = Node.getIf(root, path)
if (node === undefined) {
throw new Error(
`Cannot find a descendant at path [${path}] in node: ${Scrubber.stringify(
root
)}`
)
}
return node
},
getIf(root: Node, path: Path): Node | undefined {
let node = root
for (let i = 0; i < path.length; i++) {
const p = path[i]
if (Text.isText(node) || !node.children[p]) {
throw new Error(
`Cannot find a descendant at path [${path}] in node: ${Scrubber.stringify(
root
)}`
)
return
}
node = node.children[p]

View File

@@ -0,0 +1,17 @@
/** @jsx jsx */
import { Node } from 'slate'
import { jsx } from 'slate-hyperscript'
import { cloneDeep } from 'lodash'
export const input = (
<editor>
<element>
<text />
</element>
</editor>
)
export const test = value => {
return Node.getIf(value, [])
}
export const skip = true // TODO: see https://github.com/ianstormtaylor/slate/pull/4188
export const output = cloneDeep(input)

View File

@@ -0,0 +1,19 @@
/** @jsx jsx */
import { Node } from 'slate'
import { jsx } from 'slate-hyperscript'
export const input = (
<editor>
<element>
<text />
</element>
</editor>
)
export const test = value => {
return Node.getIf(value, [0])
}
export const output = (
<element>
<text />
</element>
)

View File

@@ -0,0 +1,15 @@
/** @jsx jsx */
import { Node } from 'slate'
import { jsx } from 'slate-hyperscript'
export const input = (
<editor>
<element>
<text />
</element>
</editor>
)
export const test = value => {
return Node.getIf(value, [0, 0, 0])
}
export const output = undefined