Feature request: scrollTo with alignToTop

In order to restore the user’s scroll position when they re-open a document, we’d like to be able to scroll a stored line to the top of the viewport.

Using the browser’s native scrollIntoView API, this would be either scrollIntoView(true) or scrollIntoView({block: "start", inline: "nearest"}), but in the CodeMirror 6 API there’s nowhere to set the alignToTop option.

We’re currently working around this by dispatching an EditorView.scrollTo effect (to make sure the target line is available), then setting view.scrollDOM.scrollTop manually to scroll the desired line to the top of the viewport:

const line = view.state.doc.line(firstVisibleLine)

  effects: EditorView.scrollTo.of(
    EditorSelection.range(line.from, line.from)

window.setTimeout(() => {
  view.scrollDOM.scrollTop = view.visualLineAt(line.from, 0).top
}, 0)

Maybe for CodeMirror 6 this could be a new effect, like centerOn, that takes a range and the same options as the native scrollIntoView as parameters? Anything that allows passing alignToTop as an option would be enough for this use case, though.

1 Like

Yeah, this seems reasonable. This patch adds a new, more general way to create a scroll effect.


EditorView.scrollIntoView works perfectly, thanks @marijn.