Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/clean-icons-bow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'slate': patch
---

feat: add Node.getIf method
23 changes: 18 additions & 5 deletions packages/slate/src/interfaces/node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*/
Expand Down Expand Up @@ -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]
Expand Down
17 changes: 17 additions & 0 deletions packages/slate/test/interfaces/Node/getIf/root.tsx
Original file line number Diff line number Diff line change
@@ -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)
19 changes: 19 additions & 0 deletions packages/slate/test/interfaces/Node/getIf/success.tsx
Original file line number Diff line number Diff line change
@@ -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>
)
15 changes: 15 additions & 0 deletions packages/slate/test/interfaces/Node/getIf/undefined.tsx
Original file line number Diff line number Diff line change
@@ -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