Sha256: 7795b6f5ad1793c9ab76e51e26a6ad509a2aec089e64bf571cf0ae0a58bf2e34

Contents?: true

Size: 1.32 KB

Versions: 3

Compression:

Stored size: 1.32 KB

Contents

import { Controller } from "@hotwired/stimulus"
import { FetchRequest } from "@rails/request.js"

const AUTOSAVE_INTERVAL = 3000

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

  #timer

  disconnect() {
    this.#submit()
  }

  change() {
    !this.#dirty && this.#scheduleSave()
    !this.#dirty && this.#updateAppearance()
  }

  async #submit() {
    this.#dirty && await this.#save()
  }

  async #save() {
    this.#updateAppearance(true)
    this.#resetTimer()
    await submitForm(this.element)
    this.#updateAppearance()
  }

  #updateAppearance(saving = false) {
    if (saving) {
      this.element.setAttribute("aria-busy", true)
      this.submitterTarget.setAttribute("aria-disabled", true)
      this.submitterTarget.disabled = true
    } else {
      this.element.removeAttribute("aria-busy")
      this.submitterTarget.removeAttribute("aria-disabled")
      this.submitterTarget.disabled = false
    }
  }

  #scheduleSave() {
    this.#timer = setTimeout(() => this.#save(), AUTOSAVE_INTERVAL)
  }

  #resetTimer() {
    clearTimeout(this.#timer); this.#timer = null
  }

  get #dirty() {
    return !!this.#timer
  }
}

// Helpers

async function submitForm(form) {
  const request = new FetchRequest(form.method, form.action, {
    body: new FormData(form)
  })

  return await request.perform()
}

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
css-zero-0.0.54 lib/generators/css_zero/add/templates/app/javascript/controllers/autosave_controller.js
css-zero-0.0.53 lib/generators/css_zero/add/templates/app/javascript/controllers/autosave_controller.js
css-zero-0.0.52 lib/generators/css_zero/add/templates/app/javascript/controllers/autosave_controller.js