From 09f30e19cf48d386590182e83a6d14a871361455 Mon Sep 17 00:00:00 2001 From: Bryce Covert Date: Fri, 25 Jan 2019 09:29:54 -0800 Subject: [PATCH] typeahead improvements --- .../auto_ap/views/components/typeahead.cljs | 41 ++++++++++++------- 1 file changed, 26 insertions(+), 15 deletions(-) diff --git a/src/cljs/auto_ap/views/components/typeahead.cljs b/src/cljs/auto_ap/views/components/typeahead.cljs index 4818902d..cb296a18 100644 --- a/src/cljs/auto_ap/views/components/typeahead.cljs +++ b/src/cljs/auto_ap/views/components/typeahead.cljs @@ -15,7 +15,7 @@ (defn typeahead [{:keys [matches on-change field text-field value class not-found-description not-found-value auto-focus]}] (let [text (r/atom (or (second (first (filter #(= (first %) value) matches))) "")) - highlighted (r/atom 0) + highlighted (r/atom nil) selected (r/atom (first (first (filter #(= (first %) value) matches)))) select (fn [[id text-description text-value]] (reset! selected id) @@ -23,8 +23,7 @@ (when on-change (if (= :not-found id) (on-change nil text-description text-value) - (on-change id text-description (or text-value text-description))))) - ] + (on-change id text-description (or text-value text-description)))))] (r/create-class {:reagent-render (fn [{:keys [matches on-change field text-field value class not-found-description]}] (let [text @text @@ -63,24 +62,36 @@ (do (select [nil ""]) true))) :on-key-up (fn [e] - (if (and (= 13 (.-keyCode e)) - (seq valid-matches)) - (do - (select (first valid-matches)) - false) - true)) + (condp = (.-keyCode e) + ; up + 38 (do + (when-let [new-match (->> valid-matches + (take-while #(not= (first %) @highlighted)) + (last))] + (reset! highlighted new-match)) + true) + ;; dwon + 40 (do + (when-let [new-match (->> valid-matches + (drop-while #(not= (first %) @highlighted)) + (drop 1) + (first))] + (reset! highlighted new-match)) + true) + 13 (when @highlighted + (select @highlighted) + false) + true) + ) :on-change (fn [e] (let [new-matches (get-valid-matches matches not-found-description not-found-value (.. e -target -value))] - (reset! highlighted (ffirst new-matches))) - - (select [nil (.. e -target -value)]))} - ]) + (reset! highlighted (first new-matches))) + (select [nil (.. e -target -value)]))}]) (cond (and (seq text) (not @selected) (seq valid-matches)) - (let [h @highlighted] - + (let [[h] @highlighted] [:div.typeahead-menu [:ul (for [[id t :as match] valid-matches]