| 1 | import { Controller } from "@hotwired/stimulus"; |
| 2 | |
| 3 | export default class extends Controller { |
| 4 | static values = { key: String }; |
| 5 | static targets = ["textarea"]; |
| 6 | |
| 7 | connect() { |
| 8 | this.storageKey = |
| 9 | this.keyValue || |
| 10 | `persist_input_${ |
| 11 | this.textareaTarget.name || this.textareaTarget.id || "default" |
| 12 | }`; |
| 13 | this.restoreValue(); |
| 14 | this.textareaTarget.addEventListener("input", this.saveValue.bind(this)); |
| 15 | this.textareaTarget.addEventListener("change", this.saveValue.bind(this)); |
| 16 | this.element.addEventListener("submit", this.clearOnSubmit.bind(this)); |
| 17 | } |
| 18 | |
| 19 | disconnect() { |
| 20 | this.textareaTarget.removeEventListener("input", this.saveValue.bind(this)); |
| 21 | this.textareaTarget.removeEventListener( |
| 22 | "change", |
| 23 | this.saveValue.bind(this), |
| 24 | ); |
| 25 | this.element.removeEventListener("submit", this.clearOnSubmit.bind(this)); |
| 26 | } |
| 27 | |
| 28 | restoreValue() { |
| 29 | const savedValue = localStorage.getItem(this.storageKey); |
| 30 | if (savedValue && !this.textareaTarget.value) { |
| 31 | this.textareaTarget.value = savedValue; |
| 32 | this.textareaTarget.dispatchEvent(new Event("input", { bubbles: true })); |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | saveValue() { |
| 37 | if (this.textareaTarget.value.trim()) { |
| 38 | localStorage.setItem(this.storageKey, this.textareaTarget.value); |
| 39 | } else { |
| 40 | localStorage.removeItem(this.storageKey); |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | clear() { |
| 45 | localStorage.removeItem(this.storageKey); |
| 46 | this.textareaTarget.value = ""; |
| 47 | this.textareaTarget.dispatchEvent(new Event("input", { bubbles: true })); |
| 48 | } |
| 49 | |
| 50 | clearOnSubmit() { |
| 51 | localStorage.removeItem(this.storageKey); |
| 52 | } |
| 53 | } |
| 54 | |