-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Open
Labels
Description
Description
When using DOMEditor.findPath
within the onChange
event handler, it either throws an error, or returns a wrong path, after manipulating the document. The reason is, NODE_TO_INDEX
and NODE_TO_PARENT
only updates on render, but onChange
is fired before the changes have been rendered.
Sandbox
https://codesandbox.io/p/sandbox/fyslvy
Steps
To reproduce the behavior:
- Visit the codesandbox link
- Click within text on the first line
- Press enter
- See error / wrong paths in console
Expectation
DOMEditor.findPath
should return the correct path at any point in time.
Environment
- Slate Version: 0.118.0
- Operating System: macOS
- Browser: Chrome
Context
This became a problem while using useEditorSelector
from plate.js. useEditorSelector
is fired directly after onChange
, if we want to retrieve a path of a node in there, it fails. Example:
import { type EditorSelection, type Path, PathApi } from 'platejs';
import { useEditorSelector } from 'platejs/react';
const isPathFocused = (selection: EditorSelection, path?: Path) =>
Boolean(path && selection?.focus.path && PathApi.isCommon(path, selection.focus.path));
export const useEditorNodeFocused = (node: TNode, options?: Options) => {
const focused = useEditorSelector((editor) => {
const { selection } = editor;
const path = DOMEditor.findPath(editor, node);
return isPathFocused(selection, path);
}, []);
return focused;
};