uiwjs / react-codemirror

CodeMirror 6 component for React. @codemirror https://uiwjs.github.io/react-codemirror/
https://uiwjs.github.io/react-codemirror/
MIT License
1.65k stars 132 forks source link

How to automatically track the scroll bar to the last line #345

Closed pixiake closed 2 years ago

pixiake commented 2 years ago

I tried to use react-codemirror to write a page that automatically displays real-time logs. But I found that scroll can't automatically track the latest line. I can't find the relevant example, how should I set it ? Thanks

jaywcjlove commented 2 years ago

https://codesandbox.io/embed/react-codemirror-example-codemirror-6-uiwjs-react-codemirror-issues-345-9r1zof?fontsize=14&hidenavigation=1&theme=dark

import React, { useState } from "react";
import CodeMirror from "@uiw/react-codemirror";
import { javascript } from "@codemirror/lang-javascript";
import { ViewPlugin } from "@codemirror/view";

const code = `Hello World!
Hello World!\nHello World!\nHello World!
`;

export default function App() {
  const [text, setText] = useState(code);
  const scrollBottom = ViewPlugin.fromClass(
    class {
      update(update) {
        if (update.docChanged) {
          update.view.scrollDOM.scrollTop = update.view.scrollDOM.scrollHeight;
        }
      }
    }
  );

  return (
    <div>
      <button
        onClick={() => {
          setText(text + "\nhello world");
        }}
      >
        add text
      </button>
      <CodeMirror
        value={text}
        readOnly
        height="200px"
        theme="dark"
        extensions={[scrollBottom, javascript({ jsx: true })]}
      />
    </div>
  );
}

@pixiake

https://codesandbox.io/embed/react-codemirror-example-codemirror-6-uiwjs-react-codemirror-issues-345-forked-h8gog5?fontsize=14&hidenavigation=1&theme=dark

pixiake commented 2 years ago

Thanks very much

pixiake commented 2 years ago

@jaywcjlove Hi,I tried to find any way to set auto wrap, but it didn't work. Would you please provide an example ? Thanks

jaywcjlove commented 2 years ago

@pixiake This is a new question(Issue). https://github.com/uiwjs/react-codemirror/issues/317#issuecomment-1168471146 may help you.

jaywcjlove commented 2 years ago

@pixiake https://github.com/uiwjs/react-codemirror/issues/274#issuecomment-1047488376

jaywcjlove commented 2 years ago

@pixiake

import React from "react";
import CodeMirror from "@uiw/react-codemirror";
import { javascript } from "@codemirror/lang-javascript";
+ import { EditorView } from "@codemirror/view";

export default function App() {
  return (
    <CodeMirror
      value="console.log('hello world!');"
      height="200px"
      extensions={[
         javascript({ jsx: true }), 
+         EditorView.lineWrapping
      ]}
      onChange={(value, viewUpdate) => {
        console.log("value:", value);
      }}
    />
  );
}