Skip to content

DOMEditor.findPath returns no or wrong path #5938

@delijah

Description

@delijah

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:

  1. Visit the codesandbox link
  2. Click within text on the first line
  3. Press enter
  4. 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;
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions