Skip to content

Commit

Permalink
feat: add Node.getIf support
Browse files Browse the repository at this point in the history
  • Loading branch information
RavenColEvol committed Sep 18, 2024
1 parent 85a1e1d commit 57589eb
Show file tree
Hide file tree
Showing 4 changed files with 72 additions and 0 deletions.
21 changes: 21 additions & 0 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 @@ -408,6 +413,22 @@ export const Node: NodeInterface = {
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]) {
return
}

node = node.children[p]
}

return node
},

has(root: Node, path: Path): boolean {
let node = root

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

0 comments on commit 57589eb

Please sign in to comment.