Sha256: df289532eac487ad07f248760504156bd098d16585ba310d0a2207b9f6e2ab2d

Contents?: true

Size: 1.34 KB

Versions: 1

Compression:

Stored size: 1.34 KB

Contents

import { Controller } from "@hotwired/stimulus"
import { FetchRequest } from "https://cdn.skypack.dev/@rails/request.js@0.0.11"

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 this.#submitForm(this.element)
    this.#updateAppearance()
  }

  async #submitForm(form) {
    const request = new FetchRequest(form.method, form.action, { body: new FormData(form) })
    return await request.perform()
  }

  #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
  }
}

Version data entries

1 entries across 1 versions & 1 rubygems

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