KonnorRogers/rhino-editor

Auto-focus in the editor on page load

Closed this issue · 2 comments

lylo commented

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.

@lylo there's a editorOptions hook on the element itself, but I don't particularly love the API which supports "autofocus".

/**
* Extend this to provide your own options, or override existing options.
* The "element" is where the editor will be initialized.
* This will be merged
* @example
* class ExtendedRhinoEditor extends TipTapEditor {
* editorOptions (_element: Element) {
* return {
* autofocus: true
* }
* }
* }
*
*/
editorOptions(_element?: Element): Partial<EditorOptions> {
return {};
}

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

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