suren-atoyan / monaco-react

Monaco Editor for React - use the monaco-editor in any React application without needing to use webpack (or rollup/parcel/etc) configuration files / plugins
https://monaco-react.surenatoyan.com/
MIT License
3.68k stars 264 forks source link

The cursor moves to the document header when setValue #624

Open susan88323 opened 3 months ago

susan88323 commented 3 months ago

Describe the bug I am listening the onDidChangeModelContent event. When the content has been changed, I did some updates on the editor value and set the value e.g. editor.getModel().setValue(trimmedValue);. However, when the setValue is called, the cursor moves to the document header.

To Reproduce

editor.onDidChangeModelContent(() => {
      const curValue = editor.getModel().getValue() || "";
      if (curValue.length > maxLength) {
        const trimmedValue = curValue.substring(0, maxLength);
        editor.getModel().setValue(trimmedValue);
      }
    });

Expected behavior When setValue is called, the cursor should stay at the original position

Screenshots If applicable, add screenshots to help to explain your problem.

Desktop (please complete the following information):

Additional context Add any other context about the problem here.

feri-irawan commented 3 months ago

Try use editor.getPosition()

const position = editor.getPosition()
editor.setValue(text)
editor.setPosition(position)