Skip to content

Instantly share code, notes, and snippets.

@iwillig
Created December 16, 2015 04:07
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 iwillig/dd07668352df3035ad82 to your computer and use it in GitHub Desktop.
Save iwillig/dd07668352df3035ad82 to your computer and use it in GitHub Desktop.
(ns admin-ui.core
(:require [goog.dom :as gdom]
[cljs.pprint :as pp]
[om.next :as om :refer-macros [defui]]
[cognitect.transit :as t]
[sablono.core :as html :refer-macros [html]]
[om.dom :as dom])
(:import [goog.net XhrIo]))
(enable-console-print!)
(defn- get-orgs [state key]
(let [st @state]
(into [] (map #(get-in st %)) (get st key))))
;; ----- Read -----
(defmulti read om/dispatch)
(defmethod read :admin-ui/organizations
[{:keys [state] :as env} key params]
(if (contains? @state key)
{:value (get-in @state [key])}
{:remote true}))
(defmethod read :organization/by-id
[{:keys [state]} key params]
{:value "bob"})
;; ----- Mutate -----
(defmulti mutate om/dispatch)
(defmethod mutate :default
[_ _ _] {:remote true})
(defmethod mutate 'admin-ui/toggle
[{:keys [state ref]} _ {:keys [:db/id]}]
{:action (fn []
(println (get-in @state [:organization/by-id id])) ;; nil
(swap! state update-in [:organization/by-id id :organization/disabled?] not))
:remote true})
;; ----- Components -----
(defui OrganizationItem
static om/Ident
(ident [this {:keys [:db/id]}]
[:organization/by-id id])
static om/IQuery
(query [this]
'[:db/id :organization/name :organization/disabled?])
Object
(render [this]
(let [{:keys [:db/id :organization/name :organization/disabled?] :as org} (om/props this)]
(html [:li
[:a {:href "#" :on-click (fn [_] (om/transact! this `[(admin-ui/toggle ~org)]))} name]
[:p (str org)]]))))
(def org-item (om/factory OrganizationItem {:keyfn :db/id}))
(defui ListView
Object
(render [this]
(let [list (om/props this)]
(html
[:ul (map org-item list)]))))
(def list-view (om/factory ListView))
(defui RootView
static om/IQuery
(query [this]
`[{:admin-ui/organizations ~(om/get-query OrganizationItem)}])
Object
(render [this]
(let [{:keys [:admin-ui/organizations] :as root} (om/props this)]
(html [:div (list-view organizations)]))))
;; ----- Reconciler -----
(defn transit-post [url]
(fn [{:keys [remote]} cb]
(.send XhrIo url
(fn [e]
(this-as this
(cb (t/read (t/reader :json) (.getResponseText this)))))
"POST" (t/write (t/writer :json) remote)
#js {"Content-Type" "application/transit+json"})))
(def reconciler
(om/reconciler
{:state (atom {})
:parser (om/parser {:read read :mutate mutate})
:normalize true
:send (transit-post "http://localhost:4001/hooks/v1/admin-ui")}))
(om/add-root! reconciler
RootView (gdom/getElement "app"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment