Keith Schacht’s Weblog

Subscribe

📄 Using Hotwire it was simple to build inline title editing

17th May 2024

After generating the Rails scaffolding for my “Conversation” model, it was just a few steps to do inline editing:

  1. Modify conversations/_conversation.html.erb to wrap it in a turbo-frame
  2. Modify conversations/_form.html.erb partial to wrap it in the same turbo-frame so that the form will replace the displayed title
  3. Add a tiny bit of stimulus to enable submit on enter/blur and to enable discard with Escape

Check out this short demo and walk-through!

This part of my rails open-source ChatGPT app called HostedGPT. You can find the project on GitHub if you want to use it or help contribute to making it better!

Questions? Comment on this Reddit thread.

And this is my full inline_edit_controller.js for reference:

import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static targets = [ "input" ]

  connect() {
    this.originalText = this.inputTarget.value
    this.focusInput()
    this.cursorToEnd()
  }

  focusInput() {
    this.inputTarget.focus()
  }

  cursorToEnd() {
    this.inputTarget.selectionStart =
      this.inputTarget.selectionEnd =
        this.inputTarget.value.length
  }

  submitForm() {
    if (this.inputTarget.disabled) return

    this.element.requestSubmit()
    this.inputTarget.disabled = true
  }

  abort() {
    this.inputTarget.value = this.originalText
    this.submitForm()
  }
}

This is Using Hotwire it was simple to build inline title editing by Keith Schacht, posted on 17th May 2024.

Next: I'm loving Rails Stimulus; check out this example.