How to selection text range programmatically in Lexical.js

369 views Asked by At

I'm experimenting with lexical, and I have a specific use case I can't implement.

A user enters some text, the app sends it to a backend to check for mistakes. In response, the backend returns information about errors with specified position of a word which contains an error.

Now, I need to take these offsets and select a fragment of the text based on them.

For example. User entered text: "Hello worldd!" Got from backend info that I should highlight the worldd.

I have not found how to do it in lexical.

This is an example of what I have tried.

editor.update(() => {
  const rangeSelection = $createRangeSelection();

  rangeSelection.applyDOMRange({
    startContainer: editor.getRootElement(),
    endContainer: editor.getRootElement(),
    collapsed: false,
    startOffset: 6,
    endOffset: 12,
  });

  $setSelection(rangeSelection);
});

// Here I'm trying to get the current selection.
const selection = $getSelection();

// The text contains the entire text in editor, but not the text I selected at previous step
const text = selection.getTextContent();

0

There are 0 answers