Alan Yue
Alan Yue

Reputation: 51

ProseMirror / Tiptap: how to ScrollIntoView without focus?

I am working on a note-taking app that uses ProseMirror as the editor. I want to achieve the feature that when the user searches, the editor will automatically scroll to the most relevant position calculated by other functions. Meanwhile, the search bar should NOT lose the input focus so the user can modify the search content. Therefore, the straightforward way of

editor.chain().focus().setTextSelection().run()

would not work.

I have found a way to set the editor selection without focus. But the view is not scrolled. I need it to scroll to the new selection.

Here is an illustration of the scenario

enter image description here

I tried

editor.commands.scrollIntoView()

It does not work. But

editor.commands.setTextSelection()

does change the selection of editor.view.

Upvotes: 4

Views: 2126

Answers (1)

martinstoeckli
martinstoeckli

Reputation: 24141

You can use ProseMirror directly (instead of TipTap objects), or finding the DOM node worked for me too:

/**
 * Scrolls to the current position/selection of the document. It does the same as scrollIntoView()
 * but without requiring the focus on the editor, thus it can be called from the search box while
 * typing or in shopping mode when the editor is disabled.
 * @param {Editor}  editor - A TipTap editor instance.
*/
function scrollToSelection(editor: Editor): void {
  const { node } = editor.view.domAtPos(editor.state.selection.anchor);
  if (node) {
      (node as any).scrollIntoView?.(false);
  }
}

Copied from SilentNotes

Upvotes: 4

Related Questions