reagent/demo/reagentdemo/page.cljs

95 lines
2.9 KiB
Plaintext
Raw Normal View History

(ns reagentdemo.page
(:require [reagent.core :as reagent :refer [atom partial]]
[reagent.debug :refer-macros [dbg]]
[clojure.string :as string]
2014-02-03 13:40:37 +00:00
[goog.events :as events]
[goog.history.EventType :as hevt])
(:import [goog History]
2014-02-03 13:40:37 +00:00
[goog.history Html5History]))
(def page (atom ""))
2014-01-27 21:30:42 +00:00
(def base-path (atom nil))
(def html5-history false)
(defn create-history []
(when reagent/is-client
(let [proto (-> js/window .-location .-protocol)]
(if (and (.isSupported Html5History)
(case proto "http:" true "https:" true false))
2014-01-27 21:30:42 +00:00
(do (set! html5-history true)
(doto (Html5History.)
(.setUseFragment false)))
(History.)))))
(defn setup-history []
(when-let [h (create-history)]
2014-02-03 13:40:37 +00:00
(events/listen h hevt/NAVIGATE
2014-01-29 10:53:45 +00:00
(fn [e]
(reset! page (subs (.-token e)
(count @base-path)))
(reagent/flush)))
(add-watch page ::history (fn [_ _ oldp newp]
2014-01-27 21:30:42 +00:00
(.setToken h (str @base-path newp))))
(.setEnabled h true)
h))
(def history (setup-history))
2014-01-27 21:30:42 +00:00
(defn set-start-page [p]
(when html5-history
;; Find base-path for html5 history
(let [loc (-> js/window .-location .-pathname)
split #".[^/]*"
loc-parts (re-seq split loc)
page-parts (re-seq split (case p "" "." p))
base (str (apply str
(drop-last (count page-parts) loc-parts))
"/")]
(reset! base-path (string/replace base #"^/" ""))))
(reset! page p))
2014-01-21 10:50:08 +00:00
(def title-atom (atom ""))
2014-01-21 10:50:08 +00:00
(def page-map (atom nil))
(def reverse-page-map (atom nil))
(add-watch page-map ::page-map-watch
(fn [_ _ _ new-map]
(reset! reverse-page-map
(into {} (for [[k v] new-map]
[v k])))))
(defn prefix [href]
(let [depth (-> #"/" (re-seq @page) count)]
(str (->> "../" (repeat depth) (apply str)) href)))
(defn link [props child]
2014-01-21 10:50:08 +00:00
(let [rpm @reverse-page-map
href (-> props :href rpm)]
(assert (string? href))
[:a (assoc props
:href (prefix href)
:on-click (if history
(fn [e]
(.preventDefault e)
(reset! page href)
(reagent/flush)
(set! (.-scrollTop (.-body js/document))
0))
identity))
child]))
2014-01-21 10:50:08 +00:00
2014-01-30 21:29:42 +00:00
(add-watch page ::title-watch
(fn [_ _ _ p]
;; First title on a page wins
(reset! title-atom "")))
(defn title [name]
(when (= @title-atom "")
(if reagent/is-client
(let [title (aget (.getElementsByTagName js/document "title") 0)]
(set! (.-innerHTML title) name)))
(reset! title-atom name))
[:div])