uiwjs / react-markdown-editor

A markdown editor with preview, implemented with React.js and TypeScript.
https://uiwjs.github.io/react-markdown-editor
MIT License
327 stars 32 forks source link

Scroll editor to the last symbol position #191

Closed lofti198 closed 2 years ago

lofti198 commented 2 years ago

I set focus into the editor using this solution: https://github.com/uiwjs/react-markdown-editor/issues/189#issuecomment-1231974561 . However, as for anchor I use anchor: view.state.doc.length. And if editor contains more text, than its height, in this case I need it to be automatically scrolled to the bottom (and at the same time to the last symbol position). Any ideas how to achieve this? Thank you in advance!

jaywcjlove commented 2 years ago

@lofti198 https://codesandbox.io/embed/react-markdown-editor-uiwjs-react-markdown-editor-issues-189-4imdj6?fontsize=14&hidenavigation=1&theme=dark

view.dispatch(
  view.state.update({ selection: { anchor: view.state.doc.length } })
);
view.scrollDOM.scrollTop = view.scrollDOM.scrollHeight;
import MarkdownEditor from "@uiw/react-markdown-editor";
import { useState, useRef, useEffect } from "react";
const code = `# title\n\nHello World!\n\n# title\n\nHello World!\n\n# title\n\nHello World!\n\n# title\n\nHello World!\n\n# title\n\nHello World!\n\n# title\n\nHello World!\n\n# title\n\nHello World!\n\n# title\n\nHello World!\n\n# title\n\nHello World!\n\n# title\n\nHello World!\n\n# title\n\nHello World!\n\n# title\n\nHello World!\n\n# title\n\nHello World!\n\n# title\n\nHello World!\n\n# title\n\nHello World!\n\n`;

export function Editor() {
  const $ref = useRef(null);
  const [markdownVal, setMarkdownVal] = useState(code);

  useEffect(() => {
    setTimeout(() => {
      const view = $ref.current?.editor.current?.view;
      if (view) {
        console.log(view.state.doc.length);
        view.focus();
        view.dispatch(
          view.state.update({ selection: { anchor: view.state.doc.length } })
        );
        view.scrollDOM.scrollTop = view.scrollDOM.scrollHeight;
      }
    }, 200);
  }, [$ref]);
  return (
    <MarkdownEditor
      ref={$ref}
      value={markdownVal}
      height="300px"
      onChange={(value, vu) => {
        setMarkdownVal(value);
      }}
      onStatistics={(data) => {
        // main = data.selectionAsSingle;
        // console.log("data:", data.selectionAsSingle);
      }}
    />
  );
}
lofti198 commented 2 years ago

Thank you!