[
  {
    "path": ".gitignore",
    "content": "/target\n/classes\n/checkouts\npom.xml\npom.xml.asc\n*.jar\n*.class\n/.lein-*\n/.nrepl-port\n"
  },
  {
    "path": ".travis.yml",
    "content": "lein: lein2\nlanguage: clojure\njdk:\n  - oraclejdk7\n"
  },
  {
    "path": "LICENSE",
    "content": "THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC\nLICENSE (\"AGREEMENT\"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM\nCONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.\n\n1. DEFINITIONS\n\n\"Contribution\" means:\n\na) in the case of the initial Contributor, the initial code and\ndocumentation distributed under this Agreement, and\n\nb) in the case of each subsequent Contributor:\n\ni) changes to the Program, and\n\nii) additions to the Program;\n\nwhere such changes and/or additions to the Program originate from and are\ndistributed by that particular Contributor. A Contribution 'originates' from\na Contributor if it was added to the Program by such Contributor itself or\nanyone acting on such Contributor's behalf. Contributions do not include\nadditions to the Program which: (i) are separate modules of software\ndistributed in conjunction with the Program under their own license\nagreement, and (ii) are not derivative works of the Program.\n\n\"Contributor\" means any person or entity that distributes the Program.\n\n\"Licensed Patents\" mean patent claims licensable by a Contributor which are\nnecessarily infringed by the use or sale of its Contribution alone or when\ncombined with the Program.\n\n\"Program\" means the Contributions distributed in accordance with this\nAgreement.\n\n\"Recipient\" means anyone who receives the Program under this Agreement,\nincluding all Contributors.\n\n2. GRANT OF RIGHTS\n\na) Subject to the terms of this Agreement, each Contributor hereby grants\nRecipient a non-exclusive, worldwide, royalty-free copyright license to\nreproduce, prepare derivative works of, publicly display, publicly perform,\ndistribute and sublicense the Contribution of such Contributor, if any, and\nsuch derivative works, in source code and object code form.\n\nb) Subject to the terms of this Agreement, each Contributor hereby grants\nRecipient a non-exclusive, worldwide, royalty-free patent license under\nLicensed Patents to make, use, sell, offer to sell, import and otherwise\ntransfer the Contribution of such Contributor, if any, in source code and\nobject code form.  This patent license shall apply to the combination of the\nContribution and the Program if, at the time the Contribution is added by the\nContributor, such addition of the Contribution causes such combination to be\ncovered by the Licensed Patents. The patent license shall not apply to any\nother combinations which include the Contribution. No hardware per se is\nlicensed hereunder.\n\nc) Recipient understands that although each Contributor grants the licenses\nto its Contributions set forth herein, no assurances are provided by any\nContributor that the Program does not infringe the patent or other\nintellectual property rights of any other entity. Each Contributor disclaims\nany liability to Recipient for claims brought by any other entity based on\ninfringement of intellectual property rights or otherwise. As a condition to\nexercising the rights and licenses granted hereunder, each Recipient hereby\nassumes sole responsibility to secure any other intellectual property rights\nneeded, if any. For example, if a third party patent license is required to\nallow Recipient to distribute the Program, it is Recipient's responsibility\nto acquire that license before distributing the Program.\n\nd) Each Contributor represents that to its knowledge it has sufficient\ncopyright rights in its Contribution, if any, to grant the copyright license\nset forth in this Agreement.\n\n3. REQUIREMENTS\n\nA Contributor may choose to distribute the Program in object code form under\nits own license agreement, provided that:\n\na) it complies with the terms and conditions of this Agreement; and\n\nb) its license agreement:\n\ni) effectively disclaims on behalf of all Contributors all warranties and\nconditions, express and implied, including warranties or conditions of title\nand non-infringement, and implied warranties or conditions of merchantability\nand fitness for a particular purpose;\n\nii) effectively excludes on behalf of all Contributors all liability for\ndamages, including direct, indirect, special, incidental and consequential\ndamages, such as lost profits;\n\niii) states that any provisions which differ from this Agreement are offered\nby that Contributor alone and not by any other party; and\n\niv) states that source code for the Program is available from such\nContributor, and informs licensees how to obtain it in a reasonable manner on\nor through a medium customarily used for software exchange.\n\nWhen the Program is made available in source code form:\n\na) it must be made available under this Agreement; and\n\nb) a copy of this Agreement must be included with each copy of the Program.\n\nContributors may not remove or alter any copyright notices contained within\nthe Program.\n\nEach Contributor must identify itself as the originator of its Contribution,\nif any, in a manner that reasonably allows subsequent Recipients to identify\nthe originator of the Contribution.\n\n4. COMMERCIAL DISTRIBUTION\n\nCommercial distributors of software may accept certain responsibilities with\nrespect to end users, business partners and the like. While this license is\nintended to facilitate the commercial use of the Program, the Contributor who\nincludes the Program in a commercial product offering should do so in a\nmanner which does not create potential liability for other Contributors.\nTherefore, if a Contributor includes the Program in a commercial product\noffering, such Contributor (\"Commercial Contributor\") hereby agrees to defend\nand indemnify every other Contributor (\"Indemnified Contributor\") against any\nlosses, damages and costs (collectively \"Losses\") arising from claims,\nlawsuits and other legal actions brought by a third party against the\nIndemnified Contributor to the extent caused by the acts or omissions of such\nCommercial Contributor in connection with its distribution of the Program in\na commercial product offering.  The obligations in this section do not apply\nto any claims or Losses relating to any actual or alleged intellectual\nproperty infringement. In order to qualify, an Indemnified Contributor must:\na) promptly notify the Commercial Contributor in writing of such claim, and\nb) allow the Commercial Contributor tocontrol, and cooperate with the\nCommercial Contributor in, the defense and any related settlement\nnegotiations. The Indemnified Contributor may participate in any such claim\nat its own expense.\n\nFor example, a Contributor might include the Program in a commercial product\noffering, Product X. That Contributor is then a Commercial Contributor. If\nthat Commercial Contributor then makes performance claims, or offers\nwarranties related to Product X, those performance claims and warranties are\nsuch Commercial Contributor's responsibility alone. Under this section, the\nCommercial Contributor would have to defend claims against the other\nContributors related to those performance claims and warranties, and if a\ncourt requires any other Contributor to pay any damages as a result, the\nCommercial Contributor must pay those damages.\n\n5. NO WARRANTY\n\nEXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON\nAN \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER\nEXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR\nCONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A\nPARTICULAR PURPOSE. Each Recipient is solely responsible for determining the\nappropriateness of using and distributing the Program and assumes all risks\nassociated with its exercise of rights under this Agreement , including but\nnot limited to the risks and costs of program errors, compliance with\napplicable laws, damage to or loss of data, programs or equipment, and\nunavailability or interruption of operations.\n\n6. DISCLAIMER OF LIABILITY\n\nEXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY\nCONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION\nLOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE\nEXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY\nOF SUCH DAMAGES.\n\n7. GENERAL\n\nIf any provision of this Agreement is invalid or unenforceable under\napplicable law, it shall not affect the validity or enforceability of the\nremainder of the terms of this Agreement, and without further action by the\nparties hereto, such provision shall be reformed to the minimum extent\nnecessary to make such provision valid and enforceable.\n\nIf Recipient institutes patent litigation against any entity (including a\ncross-claim or counterclaim in a lawsuit) alleging that the Program itself\n(excluding combinations of the Program with other software or hardware)\ninfringes such Recipient's patent(s), then such Recipient's rights granted\nunder Section 2(b) shall terminate as of the date such litigation is filed.\n\nAll Recipient's rights under this Agreement shall terminate if it fails to\ncomply with any of the material terms or conditions of this Agreement and\ndoes not cure such failure in a reasonable period of time after becoming\naware of such noncompliance. If all Recipient's rights under this Agreement\nterminate, Recipient agrees to cease use and distribution of the Program as\nsoon as reasonably practicable. However, Recipient's obligations under this\nAgreement and any licenses granted by Recipient relating to the Program shall\ncontinue and survive.\n\nEveryone is permitted to copy and distribute copies of this Agreement, but in\norder to avoid inconsistency the Agreement is copyrighted and may only be\nmodified in the following manner. The Agreement Steward reserves the right to\npublish new versions (including revisions) of this Agreement from time to\ntime. No one other than the Agreement Steward has the right to modify this\nAgreement. The Eclipse Foundation is the initial Agreement Steward. The\nEclipse Foundation may assign the responsibility to serve as the Agreement\nSteward to a suitable separate entity. Each new version of the Agreement will\nbe given a distinguishing version number. The Program (including\nContributions) may always be distributed subject to the version of the\nAgreement under which it was received. In addition, after a new version of\nthe Agreement is published, Contributor may elect to distribute the Program\n(including its Contributions) under the new version. Except as expressly\nstated in Sections 2(a) and 2(b) above, Recipient receives no rights or\nlicenses to the intellectual property of any Contributor under this\nAgreement, whether expressly, by implication, estoppel or otherwise. All\nrights in the Program not expressly granted under this Agreement are\nreserved.\n\nThis Agreement is governed by the laws of the State of Washington and the\nintellectual property laws of the United States of America. No party to this\nAgreement will bring a legal action under this Agreement more than one year\nafter the cause of action arose. Each party waives its rights to a jury trial\nin any resulting litigation.\n"
  },
  {
    "path": "README.md",
    "content": "# pushy\n[![Build Status](https://travis-ci.org/kibu-australia/pushy.svg?branch=master)](https://travis-ci.org/kibu-australia/pushy)\n\nA Clojurescript library for quick and easy HTML5 pushState.\n\n## Install\n\n[![Clojars Project](http://clojars.org/kibu/pushy/latest-version.svg)](http://clojars.org/kibu/pushy)\n\n## Usage\n\n### Setup\n\nYou can construct a new instance by calling the `pushy` function.\n\n`pushy` takes in two arguments:\n\n* `dispatch` fn: gets called when there is a match\n* `match` fn: checks if the path matches any routes defined.\n\nOptionally, you can specify an `:identity-fn` which parses and returns the route based on the result of the `match` fn.\n\n### Event listeners\n\nYou can start the event listeners with the `start!` method.\n\nThis adds an event listener to all `click` events, which dispatches on all matched routes.\nBypasses on Alt, Shift, Meta, Ctrl keys and middle clicks.\n\nThe `stop!` method will tear down all event listeners of the pushy instance.\n\n### Routing libraries\n\npushy should work with any routing library:\n\n[Secretary](https://github.com/gf3/secretary)\n\n```clojure\n(ns foo.core\n  (:require [secretary.core :as secretary :include-macros true :refer-macros [defroute]]\n            [pushy.core :as pushy]))\n\n(secretary/set-config! :prefix \"/\")\n\n(defroute index \"/foo\" []\n  (.log js/console \"Hi\"))\n\n(def history (pushy/pushy secretary/dispatch!\n                          (fn [x] (when (secretary/locate-route x) x))))\n\n;; Start event listeners\n(pushy/start! history)\n```\n\n[Bidi](https://github.com/juxt/bidi)\n\n```clojure\n(ns foo.core\n  (:require [bidi.bidi :as bidi]\n            [pushy.core :as pushy]))\n\n(def state (atom {}))\n\n(def app-routes\n  [\"/\" {\"foo\" :foo}])\n\n(defn set-page! [match]\n  (swap! state assoc :page match))\n\n(def history\n  (pushy/pushy set-page! (partial bidi/match-route app-routes)))\n\n(pushy/start! history)\n```\n\n[Silk](https://github.com/DomKM/silk)\n\n```clojure\n(ns foo.core\n  (:require [domkm.silk :as silk]\n            [pushy.core :as pushy]))\n\n(def state (atom {}))\n\n(def app-routes\n  (silk/routes [[:foo [[\"/foo\"]]]]))\n\n(defn set-page! [match]\n  (swap! state assoc :page match))\n\n(def history\n  (pushy/pushy set-page! (partial silk/arrive app-routes)))\n\n(pushy/start! history)\n```\n\n[Router](https://github.com/darkleaf/router)\n\n```clojure\n(ns foo.core\n  (:require [pushy.core :as pushy]\n            [darkleaf.router :as r]))\n\n(r/defcontroller root-controller\n  (show [_req]\n    :root))\n\n(r/defcontroller pages-controller\n  (index [_req]\n    :pages-index))\n\n(def routing\n  (r/group\n    (r/resource :root root-controller, :segment false)\n    (r/resources :pages :page pages-controller)))\n\n(def handler (r/make-handler routing))\n\n(def history (pushy/pushy (fn [response] (prn response))\n                          (fn [uri] (handler {:uri uri, :request-method :get}))))\n\n(pushy/start! history)\n\n#_(pushy/set-token! history \"/\")\n#_(pushy/set-token! history \"/pages\")\n```\n\n[Sibiro](https://github.com/aroemers/sibiro)\n\n```clojure\n(ns foo.core\n  (:require [sibiro.core :as sibiro]\n            [pushy.core :as pushy]))\n\n(def state (atom {}))\n\n(defn set-page! [match]\n  (assoc state :page match))\n\n(def routes\n  {[:get \"/home\" :home]})\n\n(defn match-uri [uri]\n  (:route-handler (sibiro/match-uri (sibiro/compile-routes routes) uri :get)))\n\n(def history (pushy/pushy set-page! match-uri))\n\n(pushy/start! history)\n```\n\n### URL handling\n\nBy default pushy will dispatch on all relative URLs and absolute URLs that match the window's origin. This means that all external links will be bypassed.\n\nIt is possible to specify which URLs are processable to pushy by specifying a custom predicate function `:processable-url?` in the constructor. This function is passed a single argument which is an instance of `goog.URI`.\n\n### goog.history.HTML5History methods\n\nYou can set the history state manually by calling the `set-token!` method. This will call the `dispatch` fn on a successfully matched path.\n\nExample:\n\n```clojure\n(set-token! history \"/foo\")\n\n(get-token history)\n;; => /foo\n```\n\nLikewise, you can call `replace-token!` which will also call the `dispatch` fn and replace the current history state without affecting the rest of the history stack.\n\n## License\n\nCopyright © 2017\n\nDistributed under the Eclipse Public License either version 1.0\n"
  },
  {
    "path": "project.clj",
    "content": "(defproject kibu/pushy \"0.3.8\"\n  :description \"HTML5 pushState for Clojurescript\"\n  :url \"https://github.com/kibu-australia/pushy\"\n  :license {:name \"Eclipse Public License\"\n            :url \"http://www.eclipse.org/legal/epl-v10.html\"}\n\n  :dependencies [[org.clojure/clojure \"1.8.0\" :scope \"provided\"]\n                 [org.clojure/clojurescript \"1.9.494\" :scope \"provided\"]]\n\n  :aliases {\"deploy\" [\"do\" \"clean,\" \"deploy\" \"clojars\"]\n            \"test\" [\"do\" \"clean,\" \"with-profile\" \"dev\" \"cljsbuild\" \"test\"]}\n\n  :lein-release {:deploy-via :shell\n                 :shell [\"lein\" \"deploy\"]}\n\n  :source-paths [\"src\"]\n\n  :profiles {:dev {:dependencies [[secretary \"1.2.1\"]]\n                   :plugins [[lein-cljsbuild \"1.1.5\"]\n                             [com.cemerick/clojurescript.test \"0.3.3\"]]\n\n                   :cljsbuild\n                   {:test-commands\n                    {\"unit\" [\"phantomjs\" :runner\n                             \"target/unit-test.js\"]}\n                    :builds\n                    {:test {:source-paths [\"src\" \"test\"]\n                            :compiler {:output-to \"target/unit-test.js\"\n                                       :optimizations :whitespace\n                                       :pretty-print true}}}}}})\n"
  },
  {
    "path": "src/pushy/core.cljs",
    "content": "(ns pushy.core\n  (:require [goog.events :as events]\n            [clojure.string])\n  (:import goog.History\n           goog.history.Html5History\n           goog.history.Html5History.TokenTransformer\n           goog.history.EventType\n           goog.Uri))\n\n(defn- on-click [funk]\n  (events/listen js/document \"click\" funk))\n\n(defn- update-history! [h]\n  (doto h\n    (.setUseFragment false)\n    (.setPathPrefix \"\")\n    (.setEnabled true)))\n\n(defn- set-retrieve-token! [t]\n  (set! (.. t -retrieveToken)\n        (fn [path-prefix location]\n          (str (.-pathname location) (.-search location))))\n  t)\n\n(defn- set-create-url! [t]\n  (set! (.. t -createUrl)\n        (fn [token path-prefix location]\n          (str path-prefix token)))\n  t)\n\n(defn new-history\n  ([]\n   (new-history (-> (TokenTransformer.) set-retrieve-token! set-create-url!)))\n  ([transformer]\n   (-> (Html5History. js/window transformer) update-history!)))\n\n(defprotocol IHistory\n  (set-token! [this token] [this token title])\n  (replace-token! [this token] [this token title])\n  (get-token [this])\n  (start! [this])\n  (stop! [this]))\n\n(defn- processable-url? [uri]\n  (and (not (clojure.string/blank? uri))                    ;; Blank URLs are not processable.\n       (or (and (not (.hasScheme uri)) (not (.hasDomain uri))) ;; By default only process relative URLs + URLs matching window's origin\n           (some? (re-matches (re-pattern (str \"^\" (.-origin js/location) \".*$\"))\n                              (str uri))))))\n\n(defn- get-token-from-uri [uri]\n  (let [path (.getPath uri)\n        query (.getQuery uri)]\n    ;; Include query string in token\n    (if (empty? query) path (str path \"?\" query))))\n\n(defn pushy\n  \"Takes in three functions:\n    * dispatch-fn: the function that dispatches when a match is found\n    * match-fn: the function used to check if a particular route exists\n    * identity-fn: (optional) extract the route from value returned by match-fn\"\n  [dispatch-fn match-fn &\n   {:keys [processable-url? identity-fn prevent-default-when-no-match?]\n    :or   {processable-url?               processable-url?\n           identity-fn                    identity\n           prevent-default-when-no-match? (constantly false)}}]\n\n  (let [history (new-history)\n        event-keys (atom nil)]\n    (reify\n      IHistory\n      (set-token! [_ token]\n        (. history (setToken token)))\n      (set-token! [_ token title]\n        (. history (setToken token title)))\n\n      (replace-token! [_ token]\n        (. history (replaceToken token)))\n      (replace-token! [_ token title]\n        (. history (replaceToken token title)))\n\n      (get-token [_]\n        (.getToken history))\n\n      (start! [this]\n        (stop! this)\n        ;; We want to call `dispatch-fn` on any change to the location\n        (swap! event-keys conj\n               (events/listen history EventType.NAVIGATE\n                              (fn [e]\n                                (when-let [match (-> (.-token e) match-fn identity-fn)]\n                                  (dispatch-fn match)))))\n\n        ;; Dispatch on initialization\n        (when-let [match (-> (get-token this) match-fn identity-fn)]\n          (dispatch-fn match))\n\n        (swap! event-keys conj\n               (on-click\n                (fn [e]\n                  (when-let [el (some-> e .-target (.closest \"a\"))]\n                    (let [uri (.parse Uri (.-href el))]\n                      ;; Proceed if `identity-fn` returns a value and\n                      ;; the user did not trigger the event via one of the\n                      ;; keys we should bypass\n                      (when (and (processable-url? uri)\n                                 ;; Bypass dispatch if any of these keys\n                                 (not (.-altKey e))\n                                 (not (.-ctrlKey e))\n                                 (not (.-metaKey e))\n                                 (not (.-shiftKey e))\n                                 ;; Bypass if target = _blank\n                                 (not (get #{\"_blank\" \"_self\"} (.getAttribute el \"target\")))\n                                 ;; Bypass if explicitly instructed to ignore this element\n                                 (or (not (.hasAttribute el \"data-pushy-ignore\"))\n                                     (= (.getAttribute el \"data-pushy-ignore\") \"false\"))\n                                 ;; Only dispatch on left button click\n                                 (= 0 (.-button e)))\n                        (let [next-token (get-token-from-uri uri)]\n                          (if (identity-fn (match-fn next-token))\n                            ;; Dispatch!\n                            (do\n                              (if-let [title (-> el .-title)]\n                                (set-token! this next-token title)\n                                (set-token! this next-token))\n                              (.preventDefault e))\n\n                            (when (prevent-default-when-no-match? next-token)\n                              (.preventDefault e))))))))))\n        nil)\n\n      (stop! [this]\n        (doseq [key @event-keys]\n          (events/unlistenByKey key))\n        (reset! event-keys nil)))))\n\n(defn supported?\n  \"Returns whether Html5History is supported\"\n  ([] (supported? js/window))\n  ([window] (.isSupported Html5History window)))\n\n;; Backwards compatibility with pushy <= 0.2.2\n(defn push-state!\n  ([dispatch-fn match-fn]\n   (push-state! dispatch-fn match-fn identity))\n  ([dispatch-fn match-fn identity-fn]\n   (let [h (pushy dispatch-fn match-fn :identity-fn identity-fn)]\n     (start! h)\n     h)))\n"
  },
  {
    "path": "test/pushy/test/core.cljs",
    "content": "(ns pushy.test.core\n  (:require-macros\n   [cemerick.cljs.test :refer (is deftest done use-fixtures)])\n  (:require\n   [pushy.core :as pushy]\n   [secretary.core :as secretary :refer-macros [defroute]]\n   [goog.events :as events]\n   [cemerick.cljs.test :as t])\n  (:import goog.history.Html5History))\n\n(secretary/set-config! :prefix \"/\")\n(def test-val (atom false))\n\n(def history\n  (pushy/pushy secretary/dispatch!\n               (fn [x] (when (secretary/locate-route x) x))\n               identity))\n\n(defroute foo-route \"/foo\" []\n  (reset! test-val true))\n\n(defroute bar-route \"/bar\" []\n  (reset! test-val true))\n\n(deftest constructing-history\n  (is (instance? Html5History (pushy/new-history))))\n\n(deftest constructing-pushy\n  (is (satisfies? pushy/IHistory (pushy/pushy (constantly nil) (constantly nil)))))\n\n(deftest supported-browser\n  (is (pushy/supported?)))\n\n;; event listeners started = dispatch\n(deftest ^:async push-state-foo-route\n  (reset! test-val false)\n  (pushy/start! history)\n  (pushy/replace-token! history \"/foo\")\n  (js/setTimeout\n   (fn []\n     (is @test-val)\n     (is (nil? (pushy/stop! history)))\n     (is (= \"/foo\" (pushy/get-token history)))\n     (done))\n   5000))\n\n;; no event listeners started = no dispatch\n(deftest ^:async push-state-bar-route\n  (reset! test-val false)\n  (pushy/replace-token! history \"/bar\")\n  (js/setTimeout\n   (fn []\n     (is (false? @test-val))\n     (is (= \"/bar\" (pushy/get-token history)))\n     (done))\n   5000))\n"
  }
]