Last active
August 29, 2015 14:04
-
-
Save alandipert/ebcf88eac4a78e68a1d0 to your computer and use it in GitHub Desktop.
Hoplon contacts example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(page "index.html" | |
(:require [clojure.string :as string])) | |
(def my-contacts | |
(cell #{{:first "Ben" :last "Bitdiddle" :email "benb@mit.edu"} | |
{:first "Alyssa" :middle-initial "P" :last "Hacker" :email "aphacker@mit.edu"} | |
{:first "Eva" :middle "Lu" :last "Ator" :email "eval@mit.edu"} | |
{:first "Louis" :last "Reasoner" :email "prolog@mit.edu"} | |
{:first "Cy" :middle-initial "D" :last "Effect" :email "bugs@mit.edu"} | |
{:first "Lem" :middle-initial "E" :last "Tweakit" :email "morebugs@mit.edu"}})) | |
(defn middle-name [{:keys [middle middle-initial]}] | |
(cond | |
middle (str " " middle) | |
middle-initial (str " " middle-initial "."))) | |
(defn display-name [{:keys [first last] :as contact}] | |
(str last ", " first (middle-name contact))) | |
(defelem contacts [{:keys [from sorted-by] :or {sorted-by identity}}] | |
(loop-tpl :bindings [contact (cell= (sort-by sorted-by from))] | |
(li (span (cell= (display-name contact))) | |
(button :click #(swap! from disj @contact) "Delete")))) | |
(defn parse-contact [contact-str] | |
(let [[first middle last :as parts] (string/split contact-str #"\s+") | |
[first last middle] (if (nil? last) [first middle] [first last middle]) | |
middle (when middle (string/replace middle "." "")) | |
c (if middle (count middle) 0)] | |
(when (>= (count parts) 2) | |
(cond-> {:first first :last last} | |
(== c 1) (assoc :middle-initial middle) | |
(>= c 2) (assoc :middle middle))))) | |
(defelem contact-input [{:keys [to]} [label]] | |
(let [new-contact (cell "") | |
parsed (cell= (parse-contact new-contact))] | |
(div | |
(input | |
:value new-contact | |
:input #(reset! new-contact (.val (js/jQuery (.-target %))))) | |
(button | |
:click #(when-let [c @parsed] | |
(swap! to conj c) | |
(reset! new-contact "")) | |
:disabled (cell= (not parsed)) | |
label) | |
(pre (cell= (pr-str parsed)))))) | |
(html | |
(head | |
(link :rel "stylesheet" :type "text/css" :href "css/main.css")) | |
(body | |
(h2 "Contact list") | |
(ul (contacts :from my-contacts :sorted-by :last)) | |
(contact-input :to my-contacts "Add contact"))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment