Skip to content

Instantly share code, notes, and snippets.

@cdbkr
Last active April 16, 2019 21:43
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 cdbkr/2bfe679df32e7226ab1909d2a1bebf46 to your computer and use it in GitHub Desktop.
Save cdbkr/2bfe679df32e7226ab1909d2a1bebf46 to your computer and use it in GitHub Desktop.
(ns frontend.core
(:require [reagent.core :as r]
[reitit.frontend :as rf]
[reitit.frontend.easy :as rfe]
[reitit.coercion :as rc]
[reitit.coercion.spec :as rss]
[spec-tools.data-spec :as ds]
[fipp.edn :as fedn]))
(defn router-component [match]
(let [[view-component & nested-view-components] (:views (:data match))]
(if view-component
[view-component (assoc-in match [:data :views] nested-view-components)])))
(defn home-page []
[:div
[:h2 "Welcome to frontend"]
[:button
{:type "button"
:on-click #(rfe/push-state ::item {:id 3})}
"Item 3"]
[:button
{:type "button"
:on-click #(rfe/replace-state ::item {:id 4})}
"Replace State Item 4"]])
(defn about-page []
[:div
[:h2 "About frontend"]
[:ul
[:li [:a {:href "http://google.com"} "external link"]]
[:li [:a {:href (rfe/href ::foobar)} "Missing route"]]
[:li [:a {:href (rfe/href ::item)} "Missing route params"]]]
[:div
{:content-editable true
:suppressContentEditableWarning true}
[:p "Link inside contentEditable element is ignored."]
[:a {:href (rfe/href ::frontpage)} "Link"]]])
(defn item-page [match]
(let [{:keys [path query]} (:parameters match)
{:keys [id]} path]
[:div
[:h2 "Selected item " id]
[router-component match]
(if (:foo query)
[:p "Optional foo query param: " (:foo query)])]))
(defonce match (r/atom nil))
(defn current-page []
[:div
[:ul
[:li [:a {:href (rfe/href ::frontpage)} "Frontpage"]]
[:li [:a {:href (rfe/href ::about)} "About"]]
[:li [:a {:href (rfe/href ::item {:id 1})} "Item 1"]]
[:li [:a {:href (rfe/href ::item-details {:id 1} )} "Item 1 with details"]]
[:li [:a {:href (rfe/href ::item {:id 2} {:foo "bar"})} "Item 2"]]]
(if @match
[router-component @match])
[:pre (with-out-str (fedn/pprint @match))]])
(defn item-details []
[:div
[:ul (map #(vector :li {:key %} %) ["alpha" "beta" "gamma" "delta" "epsilon"])]])
(def routes
[["/"
{:name ::frontpage
:views [home-page]}]
["/about"
{:name ::about
:views [about-page]}]
["/item/:id"
{:views [item-page]
:parameters {:path {:id int?}
:query {(ds/opt :foo) keyword?}}}
[""
{:name ::item}]
["/details"
{:name ::item-details
:views [item-details]}]
]])
(defn init! []
(rfe/start!
(rf/router routes {:data {:coercion rss/coercion}})
(fn [m] (reset! match m))
;; set to false to enable HistoryAPI
{:use-fragment true})
(r/render [current-page] (.getElementById js/document "app")))
(init!)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment