HarryChen0506 / react-markdown-editor-lite

a light-weight Markdown editor based on React. 一款轻量的基于React的markdown编辑器
https://harrychen0506.github.io/react-markdown-editor-lite/
MIT License
1.02k stars 160 forks source link

modifying editor text value in handle change scrolls to bottom #212

Open jaddoescad opened 3 years ago

jaddoescad commented 3 years ago

Here is a simple example, below is the handle change function where everytime a text is added the word random is added at the beginning.

  const handleEditorChange = ({ html, text }) => {
    const newValue = "random" + text
    setValue(newValue);
  }

Now if the text is really long, the editor will scroll all the way to the bottom everytime the word random is manually added, how can I stop it from scrolling whenever the middle of text changes from handleupload.

https://user-images.githubusercontent.com/12466304/121588056-73b6bb00-ca03-11eb-9991-3ade0fad845f.mov

sylingd commented 3 years ago

Please make a minimal reproduction with codesandbox. If your bug involves a build setup, please create a project using create-react-app and provide the link to a GitHub repository.

jaddoescad commented 3 years ago

Hello, I have reproduced the bug in codesandbox. This is the link: https://codesandbox.io/s/admiring-flower-8gdqc?file=/src/App.js.

All you have to do is write in the editor, and the editor will end up scrolling to bottom.

sylingd commented 3 years ago

Hello, I have reproduced the bug in codesandbox. This is the link: https://codesandbox.io/s/admiring-flower-8gdqc?file=/src/App.js.

All you have to do is write in the editor, and the editor will end up scrolling to bottom.

Did you forget to save? This URL did not contain any editor

jaddoescad commented 3 years ago

@sylingd Hello sorry I did forget to save, it should work now!

sylingd commented 3 years ago

@sylingd Hello sorry I did forget to save, it should work now!

If you change the value prop, the editor can not detect where the cursor should move to, so editor move it to the end. You can control the cursor with getSelection and setSelection API (docs here), for example:

// How to get editor's instance, see: https://codesandbox.io/s/rmel-demo-ref-in-function-component-u04gb

// Get original selection
const originalSelection = editor.currrent.getSelection();
// Add "random" to the start
setValue("random" + value);
// Set new selection after editor has been update
setTimeout(() => {
  editor.currrent.setSelection({ start: originalSelection.start + 6, end: originalSelection.end+ 6});
}, 0);
jaddoescad commented 3 years ago

Hi,

Progress is being made. The editor selection goes back to the right place. Unfortunately, the editor still scrolls to the bottom after the editor updates, I'm not entirely sure how to stop that behaviour. I have recreated it in the sandbox below: https://codesandbox.io/s/admiring-flower-8gdqc?file=/src/App.js