KonnorRogers / rhino-editor

A tiptap integration for Rails compatible with ActionText
https://rhino-editor.vercel.app
MIT License
227 stars 11 forks source link

Auto-focus in the editor on page load #169

Closed lylo closed 6 months ago

lylo commented 6 months ago

What is the correct way to have the editor receive focus on page load, if this is indeed possible? I have a Stimulus controller which calls focus() on my <rhino-editor> element but this doesn't seem to work (no error, just returns undefined). I've also tried adding autofocus in the HTML.

KonnorRogers commented 6 months ago

@lylo there's a editorOptions hook on the element itself, but I don't particularly love the API which supports "autofocus". https://github.com/KonnorRogers/rhino-editor/blob/a3db210c2b1300d15017bc6c4fd69600deb043ed/src/exports/elements/tip-tap-editor-base.ts#L305-L321

However, it requires extending the class since its a function and not a property. I think I may do something similar to the Extensions API where its just this.editorOptions = {} and then you can extend it.

For right now, I think this would be the best way:

document.addEventListener("rhino-initialize", async (e) => {
  const rhinoEditor = e.target

  await rhinoEditor.updateComplete
  rhinoEditor.querySelector(".ProseMirror").focus()
})

With a stimulus controller, I'd probably do something like this:

<rhino-editor data-controller="rhino" data-action="rhino-initialize#rhino->focus"></rhino-editor>
class extends Controller {
  connect () {
    const rhinoEditor = this.element

    // We don't know when the stimulus controlller will connect (before / after initialize of Rhino) so lets first check
    //     if the editorElement exists.
    if (rhinoEditor.editorElement) {
       rhinoEditor.editorElement.focus()
    }
  }
  focus () { 
     const rhinoEditor = this.element
     await rhinoEditor.updateComplete
     rhinoEditor.editorElement.focus()
  }
}
lylo commented 6 months ago

That's really neat, thanks for explaining @KonnorRogers, works a treat 👌