diff --git a/app/javascript/controllers/bar_controller.js b/app/javascript/controllers/bar_controller.js index e83bce9a9..d3a861023 100644 --- a/app/javascript/controllers/bar_controller.js +++ b/app/javascript/controllers/bar_controller.js @@ -22,11 +22,8 @@ export default class extends Controller { this.#hideItem(this.searchTarget) } - clearInput() { - if (this.searchInputTarget.value) { - this.searchInputTarget.value = "" - this.searchInputTarget.focus() - } else { + clearInput(event) { + if (event.detail.isAlreadyEmpty) { this.reset() } } diff --git a/app/javascript/controllers/search_form_controller.js b/app/javascript/controllers/search_form_controller.js new file mode 100644 index 000000000..c4efceedc --- /dev/null +++ b/app/javascript/controllers/search_form_controller.js @@ -0,0 +1,17 @@ +import { Controller } from "@hotwired/stimulus" + +export default class extends Controller { + static targets = ["searchInput"] + + clearInput() { + this.dispatch("clear", { detail: { isAlreadyEmpty: this.isEmpty } }) + if (!this.isEmpty) { + this.searchInputTarget.value = "" + this.searchInputTarget.focus() + } + } + + get isEmpty() { + return !this.searchInputTarget.value + } +} diff --git a/app/views/searches/_form.html.erb b/app/views/searches/_form.html.erb index 0ea00678f..e3e4e3ba5 100644 --- a/app/views/searches/_form.html.erb +++ b/app/views/searches/_form.html.erb @@ -1,4 +1,10 @@ -<%= form_with url: search_path, method: :get, class: "search__form flex align-center justify-center gap-half", data: { bar_target: "form", turbo_frame: defined?(target_turbo_frame) ? target_turbo_frame : nil } do |form| %> +<%= form_with url: search_path, method: :get, + class: "search__form flex align-center justify-center gap-half", + data: { + controller: "search-form", + action: "search-form:clear->bar#clearInput", + bar_target: "form", + turbo_frame: defined?(target_turbo_frame) ? target_turbo_frame : nil } do |form| %> <%= form.label :q, "Search Fizzy", class: "font-weight-black txt-nowrap" %> <%= text_field_tag :q, query_terms, class: "search__input input", @@ -7,9 +13,11 @@ autocomplete: "off", autofocus: true, data: { + search_form_target: "searchInput", bar_target: "searchInput", action: "keydown.enter->bar#showModalAndSubmit:prevent keydown.esc->bar#reset" } %> - +