typeahead improvements

This commit is contained in:
Bryce Covert
2019-01-25 09:29:54 -08:00
parent 226a54b7ad
commit 09f30e19cf

View File

@@ -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]