Skip to content

Instantly share code, notes, and snippets.

@galdolber
Created September 12, 2017 15:29
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 galdolber/edbd4ac3bc427bbf37f9b59ee1954cfb to your computer and use it in GitHub Desktop.
Save galdolber/edbd4ac3bc427bbf37f9b59ee1954cfb to your computer and use it in GitHub Desktop.
(defn file-input [{:keys [id doc multiple on-change hide-msg
preview directory on-raw-change] :as attrs}]
[error {:errors (get (:bouncer.core/errors @doc) id) :hide-msg hide-msg}
[:div.flex.flex1.flex-column {:style {:display "inline-block"}}
(when (and preview (get @doc id))
[preview (get @doc id)])
[:div [:b (if multiple
(apply str (interpose ", " (map :name (id @doc))))
(:name (id @doc)))]]
(let [attrs (merge
{:type "file"
:multiple (if multiple "multiple" "")
:on-change
(fn [e]
(let [target (.-target e)
files (.-files target)
a (atom [])]
(doseq [n (range (alength files))]
(let [file (aget files n)
reader (js/FileReader.) ]
(when on-raw-change
(on-raw-change file))
(aset reader "onerror" #(do
(println "ON ERROR")
(swap! a conj nil)))
(aset reader "onabort" #(do
(println "ON ABORT")
(swap! a conj nil)))
(aset reader "onloadend"
#(let [b64 (.-result (.-target %))
b64 (.substring b64 (inc (.indexOf b64 ",")))]
(swap! a conj {:file/name (.-name file) :file/data b64
:file/directory directory})
(when (= (count @a) (alength files))
(set! (.-value target) nil)
(swap! doc assoc id
(if multiple
(vec (filter identity @a))
(first @a)))
(when on-change
(on-change (id @doc))))))
(.readAsDataURL reader file)))))}
(dissoc attrs :on-change :multiple :id :doc :preview
:hide-msg :on-raw-change :directory))]
[:input attrs])]])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment