diff --git a/app/javascript/controllers/autosave_controller.js b/app/javascript/controllers/autosave_controller.js new file mode 100644 index 000000000..b863b648b --- /dev/null +++ b/app/javascript/controllers/autosave_controller.js @@ -0,0 +1,50 @@ +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.debouncedSave = debounce(() => { + const content = this.inputTarget.value + if (content) { + localStorage.setItem(this.keyValue, content) + } else { + this.clear() + } + }, 300) + } + + connect() { + this.restoreContent() + } + + submit({ detail: { success } }) { + if (success) { + this.clear() + } + } + + save() { + this.debouncedSave() + } + + clear() { + localStorage.removeItem(this.keyValue) + } + + restoreContent() { + const savedContent = localStorage.getItem(this.keyValue) + if (savedContent) { + this.inputTarget.value = savedContent + this.inputTarget.dispatchEvent(new CustomEvent('house-md:change', { + bubbles: true, + detail: { + previousContent: '', + newContent: savedContent + } + })) + } + } +} \ No newline at end of file diff --git a/app/views/comments/_new.html.erb b/app/views/comments/_new.html.erb index 136db289e..b8feca412 100644 --- a/app/views/comments/_new.html.erb +++ b/app/views/comments/_new.html.erb @@ -2,9 +2,11 @@
<%= form_with model: Comment.new, url: bucket_bubble_comments_path(bubble.bucket, bubble), class: "flex flex-column gap full-width", - data: { controller: "form paste", - action: "keydown.ctrl+enter->form#submit:prevent keydown.meta+enter->form#submit:prevent keydown.esc->form#cancel:stop paste->paste#pasteFiles" } do |form| %> - <%= form.markdown_area :body, class: "input comment__input", required: true, placeholder: new_comment_placeholder(bubble) %> + data: { controller: "form paste autosave", + autosave_key_value: "comment-#{bubble.id}", + action: "turbo:submit-end->autosave#submit keydown.ctrl+enter->form#submit:prevent keydown.meta+enter->form#submit:prevent keydown.esc->form#cancel:stop paste->paste#pasteFiles" } do |form| %> + <%= form.markdown_area :body, class: "input comment__input", required: true, placeholder: new_comment_placeholder(bubble), + data: { autosave_target: "input", action: "house-md:change->autosave#save" } %> <%= form.button class: "comment__submit btn btn--reversed flex-item-justify-end txt-small" do %> <%= image_tag "check.svg", aria: { hidden: "true" }, size: 24 %> Save