Skip to content

Commit

Permalink
fix: findNode when path is provided
Browse files Browse the repository at this point in the history
  • Loading branch information
ghingis committed Sep 17, 2021
1 parent 7bcfc78 commit cac657e
Show file tree
Hide file tree
Showing 2 changed files with 91 additions and 2 deletions.
89 changes: 89 additions & 0 deletions packages/common/src/queries/findNode.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/** @jsx jsx */

import { SPEditor } from '@udecode/plate-core';
import { jsx } from '@udecode/plate-test-utils';
import { findNode } from './findNode';

jsx;

describe('when the cursor is in a list item paragraph', () => {
const input = ((
<editor>
<hul>
<hli>
<hp>
1
<cursor />
</hp>
</hli>
</hul>
</editor>
) as any) as SPEditor;

const listNode = (
<hul>
<hli>
<hp>
1
<cursor />
</hp>
</hli>
</hul>
) as any;

const listItemNode = (
<hli>
<hp>
1
<cursor />
</hp>
</hli>
) as any;

it('should be', () => {
const res = findNode(input, { match: { type: 'p' } });

expect(res).toEqual([{ children: [{ text: '1' }], type: 'p' }, [0, 0, 0]]);
});
});

describe('when the cursor is not in a list item and a path is provided instead', () => {
const input = ((
<editor>
<hul>
<hli>
<hp>1</hp>
</hli>
</hul>
<hp>
2<cursor />
</hp>
</editor>
) as any) as SPEditor;

const listNode = (
<hul>
<hli>
<hp>
1
<cursor />
</hp>
</hli>
</hul>
) as any;

const listItemNode = (
<hli>
<hp>
1
<cursor />
</hp>
</hli>
) as any;

it('should be', () => {
const res = findNode(input, { at: [0, 0, 0, 0], match: { type: 'p' } });

expect(res).toEqual([{ children: [{ text: '1' }], type: 'p' }, [0, 0, 0]]);
});
});
4 changes: 2 additions & 2 deletions packages/common/src/queries/findNode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,13 @@ export type FindNodeOptions<T extends TNode = TNode> = EditorNodesOptions<T>;
*/
export const findNode = <T extends TNode = TNode>(
editor: TEditor,
options: FindNodeOptions<T>
options: FindNodeOptions<T> = {}
): NodeEntry<T> | undefined => {
// Slate throws when things aren't found so we wrap in a try catch and return undefined on throw.
try {
const nodeEntries = Editor.nodes<T>(editor, {
...options,
at: editor.selection || [],
...options,
match: (node) => match<Node>(node, options.match),
});

Expand Down

0 comments on commit cac657e

Please sign in to comment.