diff --git a/app/javascript/controllers/local_save_controller.js b/app/javascript/controllers/local_save_controller.js new file mode 100644 index 000000000..aaea8fa87 --- /dev/null +++ b/app/javascript/controllers/local_save_controller.js @@ -0,0 +1,56 @@ +import { Controller } from "@hotwired/stimulus" +import { debounce } from "helpers/timing_helpers" + +export default class extends Controller { + static targets = ["input"] + static values = { key: String } + + initialize() { + this.save = debounce(this.save.bind(this), 300) + } + + connect() { + this.#restoreContent() + } + + submit({ detail: { success } }) { + if (success) { + this.#clear() + } + } + + save() { + const content = this.inputTarget.value + if (content) { + localStorage.setItem(this.keyValue, content) + } else { + this.#clear() + } + } + + // Private + + #clear() { + localStorage.removeItem(this.keyValue) + } + + #restoreContent() { + const savedContent = localStorage.getItem(this.keyValue) + if (savedContent) { + this.inputTarget.value = savedContent + this.#triggerChangeEvent(savedContent) + } + } + + #triggerChangeEvent(newValue) { + if (this.inputTarget.tagName === "HOUSE-MD") { + this.inputTarget.dispatchEvent(new CustomEvent('house-md:change', { + bubbles: true, + detail: { + previousContent: '', + newContent: newValue + } + })) + } + } +} diff --git a/app/javascript/controllers/remote_auto_save_controller.js b/app/javascript/controllers/outlet_auto_save_controller.js similarity index 100% rename from app/javascript/controllers/remote_auto_save_controller.js rename to app/javascript/controllers/outlet_auto_save_controller.js diff --git a/app/views/bubbles/show.html.erb b/app/views/bubbles/show.html.erb index 0b61270da..9c618e4d5 100644 --- a/app/views/bubbles/show.html.erb +++ b/app/views/bubbles/show.html.erb @@ -103,9 +103,9 @@ <% else %>