Skip to content

Instantly share code, notes, and snippets.

@micha
Created December 5, 2016 00:58
Show Gist options
  • Save micha/1f547325190c9c85aaf180002ff944f3 to your computer and use it in GitHub Desktop.
Save micha/1f547325190c9c85aaf180002ff944f3 to your computer and use it in GitHub Desktop.
(ns ui.form.input
(:refer-hoplon :exclude (input textarea select)))
(defn- change-state
[state handler]
(let [handler (or handler (fn []))]
#(do (reset! state @%)
(handler %))))
(defn- field
[field {:keys [state change keyup] :as attr} kids]
(-> (dissoc attr :state)
(assoc :value state
:change (change-state state change)
:keyup (change-state state keyup))
(field kids)))
(defelem input [attr kids] (field hoplon.core/input attr kids))
(defelem textarea [attr kids] (field hoplon.core/textarea attr kids))
(defelem select [attr kids] (field hoplon.core/select attr kids))
(defelem checkbox
[{:keys [state] :as attr} _]
(hoplon.core/input
(-> (dissoc attr :state)
(assoc :type "checkbox"
:value state
:click #(with-let [_ 1]
(let [e (js/jQuery (.-target %))]
(reset! state (.is e ":checked"))))))))
(defelem checkset
[{:keys [state value] :as attr} _]
(hoplon.core/input
(-> (dissoc attr :state :value)
(assoc :type "checkbox"
:value (cell= (contains? state value))
:click #(with-let [_ 1]
(let [e (js/jQuery (.-target %))]
(swap! state (fnil (if (.is e ":checked") conj disj) #{}) @value)))))))
(defelem radio
[{:keys [state value] :as attr} _]
(let [value (cell= value)]
(hoplon.core/input
(-> (dissoc attr :state)
(assoc :type "radio"
:prop (cell= {:checked (= (str state) (str value))})
:click #(do
(reset! state @value)
true))))))
(defelem toggle
[{:keys [state] :as attr} _]
(let [label-attr (-> (dissoc attr :state)
(assoc :class "toggle")
(update :click (fn [click] (fn [e] (.preventDefault e) (click)))))]
(label label-attr
(checkbox {:state state})
(i))))
(defelem load-icon
[{:keys [loading] :as attr} _]
(div :class (cell= {:loadable true
:loading-placeholder true
:loading loading})))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment