Auto-save edits to bubble title
This commit is contained in:
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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 %>
|
||||
|
||||
Reference in New Issue
Block a user