Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add recur for other attrs than href #34

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 44 additions & 3 deletions src/pushy/core.cljs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,25 @@
(defn- on-click [funk]
(events/listen js/document "click" funk))

(defn- on-submit [funk]
(events/listen js/document "submit" funk))

(defn- recur-href
"Traverses up the DOM tree and returns the first node that contains a href, action or formAction attr"
[target]
(if (goog.object/get target "href")
target
(when (.-parentNode target)
(recur-href (.-parentNode target)))))

(defn- recur-action
"Traverses up the DOM tree and returns the first node that contains a href, action or formAction attr"
[target]
(if (goog.object/get target "action")
target
(when (.-parentNode target)
(recur-action (.-parentNode target)))))

(defn- update-history! [h]
(doto h
(.setUseFragment false)
Expand Down Expand Up @@ -39,7 +58,8 @@
(replace-token! [this token] [this token title])
(get-token [this])
(start! [this])
(stop! [this]))
(stop! [this])
(get-event-keys [this]))

(defn- processable-url? [uri]
(and (not (clojure.string/blank? uri)) ;; Blank URLs are not processable.
Expand Down Expand Up @@ -78,6 +98,9 @@
(replace-token! [_ token title]
(. history (replaceToken token title)))

(get-event-keys [_]
event-keys)

(get-token [_]
(.getToken history))

Expand All @@ -97,8 +120,8 @@
(swap! event-keys conj
(on-click
(fn [e]
(when-let [el (some-> e .-target (.closest "a"))]
(let [uri (.parse Uri (.-href el))]
(when-let [el (recur-href (-> e .-target))]
(let [uri (.parse Uri (goog.object/get el "href"))]
;; Proceed if `identity-fn` returns a value and
;; the user did not trigger the event via one of the
;; keys we should bypass
Expand Down Expand Up @@ -126,6 +149,24 @@

(when (prevent-default-when-no-match? next-token)
(.preventDefault e))))))))))

(swap! event-keys conj
(on-submit
(fn [e]
(when-let [el (recur-action (-> e .-target))]
(let [uri (.parse Uri (goog.object/get el "action"))]
(when (processable-url? uri)
(let [next-token (get-token-from-uri uri)]
(if (identity-fn (match-fn next-token))
;; Dispatch!
(do
(if-let [title (-> el .-title)]
(set-token! this next-token title)
(set-token! this next-token))
(.preventDefault e))

(when (prevent-default-when-no-match? next-token)
(.preventDefault e))))))))))
nil)

(stop! [this]
Expand Down