Skip to content

Instantly share code, notes, and snippets.

@ianchow
Last active December 13, 2016 04:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ianchow/43143a8134670eb8dc5a8133f7c75aa8 to your computer and use it in GitHub Desktop.
Save ianchow/43143a8134670eb8dc5a8133f7c75aa8 to your computer and use it in GitHub Desktop.
untangled autocomplete attempt
(defui ^:once Autocomplete
static om/IQuery
(query [this]
[:id :query :show-menu? :menu-items :selected :highlighted])
static om/Ident
(ident [this props]
[:autocomplete/by-id (:id props)])
Object
(initLocalState [this]
(let [in (async/chan (async/sliding-buffer 1))]
(go
(loop [timeout (async/timeout 0)]
(<! timeout)
(let [query (<! in)]
(df/load-field this :menu-items :params {:menu-items {:query query}})
(recur (async/timeout 1000)))))
{:in in}))
(render [this]
(let [{:keys [in]} (om/get-state this)
{:keys [id query show-menu? menu-items selected highlighted]} (om/props this)
{:keys [selected-callback]} (om/get-computed this)]
(dom/div nil
(dom/input #js {:value query
:style #js {:display "block"}
:onChange (fn [e]
(let [v (.. e -target -value)]
(ucm/set-string! this :query :value v)
(if (string/blank? v)
(om/transact! this `[(autocomplete/menu-show? {:id ~id :show? false})])
(do
(put! in v)
(om/transact! this `[(autocomplete/menu-show? {:id ~id :show? true})])))))
:onBlur #(om/transact! this `[(autocomplete/menu-show? {:id ~id :show? false})])
:onKeyDown (fn [e]
(let [kc (.. e -keyCode)]
(condp = kc
KEY_DOWN (om/transact! this `[(autocomplete/menu-down {:id ~id})])
KEY_UP (do (. e preventDefault)
(om/transact! this `[(autocomplete/menu-up {:id ~id})]))
KEY_ENTER (om/transact! this `[(autocomplete/select {:id ~id :idx ~highlighted})
(autocomplete/menu-show? {:id ~id :show? false})])
KEY_ESC (om/transact! this `[(autocomplete/menu-show? {:id ~id :show? false})])
(println kc))))})
(when show-menu?
(dom/ul nil
(map-indexed (fn [idx item]
(dom/li #js {:key idx
:style #js {:backgroundColor (if (= highlighted idx) "red" "white")}
:onMouseOver #(om/transact! this `[(autocomplete/highlight {:id ~id :idx ~idx})])
:onClick #(om/transact! this `[(autocomplete/select {:id ~id :idx ~idx})
(autocomplete/menu-show? {:id ~id :show? false})])}
(str item)))
menu-items)))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment