uiwjs / react-codemirror

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

Scroll to a specific line in codemirror #617

Open GevinHasmitha opened 8 months ago

GevinHasmitha commented 8 months ago

I'm adding a classname to a specific line in the codemirror using classnameExt function provided by uiw codemirror. I have access to the classname and the line number of the specific line. I want to scroll to that specific line on a button click.

<CodeMirror id="codemirrorId" value={value} height={height} theme={darkMode ? aura : xcodeLight} extensions={extensions} onChange={onChange} readOnly={readOnly} color="text.primary" />

This is my codemirror component, how can i scroll to the specific line which has my classname?

jaywcjlove commented 8 months ago

@GevinHasmitha I don't understand what you mean. Do you want to scroll to the specified line?

GevinHasmitha commented 8 months ago

@jaywcjlove Yes, I want the editor to scroll to the line where my added classname is present when i click on a button. (Im adding the classname using the classnameExt extension)

jaywcjlove commented 8 months ago
Screenshot 2024-01-17 at 13 24 39

You need to get the dom node of div.cm-scroller to control the scroll bar.

Then get the height of the row and position it.

jaywcjlove commented 8 months ago

https://github.com/uiwjs/react-codemirror/blob/bf3b862923d0cb04ccf4bb9da0791bdc7fd6d29b/extensions/events/src/index.ts#L18-L48

GevinHasmitha commented 8 months ago
 const scroller = document.getElementsByClassName("cm-scroller")[0];
    if (scroller) {
      const totalLines = 200     /* total number of lines */
      const totalHeight = scroller.scrollHeight;
      const singleLineHeight = totalHeight / totalLines;

      scroller.scrollTop = (singleLineHeight * x);   /*x is the line number to scroll to*/
    }
flatsiedatsie commented 4 months ago
 const scroller = document.getElementsByClassName("cm-scroller")[0];
    if (scroller) {
      const totalLines = 200     /* total number of lines */
      const totalHeight = scroller.scrollHeight;
      const singleLineHeight = totalHeight / totalLines;

      scroller.scrollTop = (singleLineHeight * x);   /*x is the line number to scroll to*/
    }

That only works if the lines are of equal height. When using CodeMirror as a text-editor that might not be the case.