Auto-save edits to bubble title

This commit is contained in:
Kevin McConnell
2025-02-10 13:53:37 +00:00
parent fd1556b298
commit 4121f68f7d
3 changed files with 59 additions and 2 deletions
@@ -0,0 +1,48 @@
import { Controller } from "@hotwired/stimulus"
import { submitForm } from "helpers/form_helpers"
const AUTOSAVE_INTERVAL = 3000
export default class extends Controller {
#timer
// Lifecycle
disconnect() {
this.submit()
}
// Actions
async submit() {
if (this.#dirty) {
await this.#save()
}
}
change(event) {
if (event.target.form === this.element && !this.#dirty) {
this.#scheduleSave()
}
}
// Private
#scheduleSave() {
this.#timer = setTimeout(() => this.#save(), AUTOSAVE_INTERVAL)
}
async #save() {
this.#resetTimer()
await submitForm(this.element)
}
#resetTimer() {
clearTimeout(this.#timer)
this.#timer = null
}
get #dirty() {
return !!this.#timer
}
}
+9
View File
@@ -0,0 +1,9 @@
import { FetchRequest } from "@rails/request.js"
export async function submitForm(form) {
const request = new FetchRequest(form.method, form.action, {
body: new FormData(form)
})
return await request.perform()
}
+2 -2
View File
@@ -9,8 +9,8 @@
<div>
<h1 class="bubble__title">
<% if bubble.creating? %>
<%= form_with model: bubble, url: bucket_bubble_path(bubble.bucket, bubble) do |form| %>
<%= form.text_field :title, placeholder: "Name it…", class: "input txt-align-center full-width borderless", autofocus: bubble.title.blank? %>
<%= form_with model: bubble, url: bucket_bubble_path(bubble.bucket, bubble), data: { controller: "auto-save" } do |form| %>
<%= form.text_field :title, placeholder: "Name it…", class: "input txt-align-center full-width borderless", autofocus: bubble.title.blank?, data: { action: "auto-save#change blur->auto-save#submit" } %>
<% end %>
<% else %>
<%= turbo_frame_tag bubble, :edit do %>