From fb6464b7bb2511b677c75a5f46a0877f295526a2 Mon Sep 17 00:00:00 2001
From: Felix Eckhofer <felix@eckhofer.com>
Date: Sat, 16 Nov 2024 13:56:45 +0100
Subject: [PATCH] Debounce filter so it feels snappier

---
 .../controllers/filteredlist_controller.js     | 18 +++++++++++++-----
 1 file changed, 13 insertions(+), 5 deletions(-)

diff --git a/app/javascript/controllers/filteredlist_controller.js b/app/javascript/controllers/filteredlist_controller.js
index ef334ef..00f8492 100644
--- a/app/javascript/controllers/filteredlist_controller.js
+++ b/app/javascript/controllers/filteredlist_controller.js
@@ -1,20 +1,28 @@
 import { Controller } from "@hotwired/stimulus";
 
+function debounce(func, wait) {
+  let timeout;
+  return function (...args) {
+    clearTimeout(timeout);
+    timeout = setTimeout(() => func.apply(this, args), wait);
+  };
+}
+
 export default class extends Controller {
   static targets = ["input", "list"];
 
   connect() {
-    //this.options = Array.from(this.listTarget.children)
+    this.filter = debounce(this.filter_nodebounce.bind(this), 300);
   }
 
-  filter() {
-    const query = this.inputTarget.value.toLowerCase()
+  filter_nodebounce() {
+    const query = this.inputTarget.value.toLowerCase();
     // Filter options by the `data-filteredlist-match` attribute
     for (const option of this.listTarget.children) {
       if (option.dataset.filteredlistMatch.includes(query)) {
-        option.classList.remove("hidden")
+        option.classList.remove("hidden");
       } else {
-        option.classList.add("hidden")
+        option.classList.add("hidden");
       }
     }
   }
-- 
GitLab