├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── doc └── intro.md ├── examples └── re-frame │ ├── expo-example │ ├── .babelrc │ ├── .gitignore │ ├── .projectile │ ├── LICENSE │ ├── app.json │ ├── assets │ │ ├── icons │ │ │ ├── app.png │ │ │ └── loading.png │ │ └── images │ │ │ ├── cljs.png │ │ │ ├── cljs@2x.png │ │ │ └── cljs@3x.png │ ├── build.boot │ ├── env │ │ ├── dev │ │ │ ├── env │ │ │ │ └── main.cljs │ │ │ ├── externs.clj │ │ │ └── user.clj │ │ └── prod │ │ │ └── env │ │ │ └── main.cljs │ ├── js │ │ └── figwheel-bridge.js │ ├── package.json │ ├── project.clj │ ├── readme.md │ ├── src │ │ ├── cljsjs │ │ │ ├── create_react_class.cljs │ │ │ ├── react.cljs │ │ │ └── react │ │ │ │ ├── dom.cljs │ │ │ │ └── dom │ │ │ │ └── server.cljs │ │ ├── expo_example │ │ │ ├── core.cljs │ │ │ ├── db.cljs │ │ │ ├── handlers.cljs │ │ │ └── subs.cljs │ │ └── reagent │ │ │ ├── dom.cljs │ │ │ └── dom │ │ │ └── server.cljs │ └── yarn.lock │ └── uiexplorer │ ├── .babelrc │ ├── .gitignore │ ├── .projectile │ ├── LICENSE │ ├── README.md │ ├── app.json │ ├── assets │ ├── icons │ │ ├── app.png │ │ └── loading.png │ └── images │ │ ├── cljs.png │ │ ├── cljs@2x.png │ │ └── cljs@3x.png │ ├── env │ ├── dev │ │ ├── env │ │ │ └── main.cljs │ │ ├── externs.clj │ │ └── user.clj │ └── prod │ │ └── env │ │ └── main.cljs │ ├── js │ └── figwheel-bridge.js │ ├── package.json │ ├── project.clj │ ├── src │ ├── cljsjs │ │ ├── create_react_class.cljs │ │ ├── react.cljs │ │ └── react │ │ │ ├── dom.cljs │ │ │ └── dom │ │ │ └── server.cljs │ ├── reagent │ │ ├── dom.cljs │ │ └── dom │ │ │ └── server.cljs │ └── uiexplorer │ │ ├── core.cljs │ │ ├── db.cljs │ │ ├── events.cljs │ │ ├── react_requires.cljs │ │ ├── routing.cljs │ │ ├── scenes │ │ └── login.cljs │ │ └── subs.cljs │ └── yarn.lock ├── project.clj ├── src └── cljs_react_navigation │ ├── base.cljs │ ├── re_frame.cljs │ └── reagent.cljs └── test └── cljs_react_navigation └── core_test.clj /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /classes 3 | /checkouts 4 | pom.xml 5 | pom.xml.asc 6 | *.jar 7 | *.class 8 | /.lein-* 9 | /.nrepl-port 10 | .hgignore 11 | .hg/ 12 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | ## [0.1.1] - 2017-05-15 3 | ### Changed 4 | - Initial check-in 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2017 Sean Tempesta 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # cljs-react-navigation 2 | 3 | This library is my attempt to unify all `cljs` `react-navigation` libraries under a shared code base. Right now it only includes `Reagent/Re-Frame` libraries, but I'm hoping other people will help me add `om-next` and `rum` libraries. 4 | 5 | ![](https://clojars.org/cljs-react-navigation/latest-version.svg) 6 | 7 | ![](https://media.giphy.com/media/3o7bu14rq4AVqTK1Nu/giphy.gif) 8 | 9 | ## Tested with 10 | 11 | Clojurescript 12 | ```clojure 13 | [org.clojure/clojurescript "1.9.854"] ;; using cljs.spec.alpha namespace 14 | [reagent "0.7.0"] ;; Import the cljs-react-navigation.reagent namespace 15 | [re-frame "0.9.3"] ;; Import the cljs-react-navigation.re-frame namespace 16 | ``` 17 | 18 | Javascript 19 | ```js 20 | "react": "16.0.0-alpha.12", 21 | "react-native": "0.44.0", 22 | "react-navigation": "^1.0.0-beta.9" 23 | ``` 24 | 25 | ## Do this first 26 | 27 | Add `react-navigation` to your project. 28 | ``` 29 | npm install react-navigation --save 30 | ``` 31 | 32 | If you're using re-natal, also add it to re-natal 33 | ```js 34 | re-natal use-component react-navigation 35 | re-natal use-figwheel 36 | ``` 37 | 38 | If you're using my [cljs expo template](https://github.com/seantempesta/expo-cljs-template), make sure to require react-navigation somewhere in your code. 39 | ```clojure 40 | ; react-navigation 41 | (defonce ReactNavigation (js/require "react-navigation")) 42 | ``` 43 | 44 | ## Documentation 45 | 46 | Anything `react-navigation` related is documented on [their site](https://reactnavigation.org/docs/getting-started.html). The idea for this library isn't to re-invent the wheel, but make it cljs friendly. 47 | 48 | Specifically: 49 | - Conforming whatever cljs wrapper components into the correct react components/elements 50 | - Converting props to cljs data structures to avoid `clj->js` & `js->clj`ing everything. 51 | 52 | 53 | ## Usage for base 54 | 55 | Yeah, you really don't use this directly. Try extending this set of specs and and functions. See the `reagent` version. 56 | 57 | That being said, I'm literally just spec'ing out the javascript API, with some minor tweaks: 58 | - `screen` function isn't overloaded (there's a `stack-screen` and a `tab-screen`) 59 | - `screen` functions accepts the `navigationOptions` as a second param (god knows why they insist on doing ES6 style initializations) 60 | 61 | ## Usage for reagent 62 | 63 | First import the reagent version of the library library: 64 | ```clojure 65 | (ns uiexplorer.routing 66 | (:require [cljs-react-navigation.reagent :refer [stack-navigator tab-navigator stack-screen tab-screen router]])) 67 | 68 | ``` 69 | 70 | Then create reagent-components that accept props like this: 71 | 72 | ```clojure 73 | (defn home 74 | "Each Screen will receive two props: 75 | - screenProps - Extra props passed down from the router (rarely used) 76 | - navigation - The main navigation functions in a map as follows: 77 | {:state - routing state for this screen 78 | :dispatch - generic dispatch fn 79 | :goBack - pop's the current screen off the stack 80 | :navigate - most common way to navigate to the next screen 81 | :setParams - used to change the params for the current screen}" 82 | [props] 83 | (fn [{:keys [screenProps navigation] :as props}] 84 | (let [{:keys [navigate goBack]} navigation] 85 | [:> View {:style {:flex 1 86 | :alignItems "center" 87 | :justifyContent "center"}} 88 | [:> Button {:style {:fontSize 17} 89 | :onPress #(navigate "Modal") 90 | :title "Modal Me!"}] 91 | [:> Button {:style {:fontSize 17} 92 | :onPress #(goBack) 93 | :title "Go Back!"}] 94 | [:> Button {:style {:fontSize 17} 95 | :onPress #(navigate "Placeholder")}]]))) 96 | ``` 97 | 98 | And then you can create stacks and screens for them like this: 99 | ```clojure 100 | (def HomeStack (stack-navigator {:Home {:screen (stack-screen home {:title "Home"})}})) 101 | 102 | ``` 103 | 104 | And then you can just render that Stack like a normal reagent component: 105 | 106 | ```clojure 107 | (defn app-root [] 108 | (fn [] 109 | [:> HomeStack {}])) 110 | 111 | (defn init [] 112 | (.registerComponent AppRegistry "UIExplorer" #(r/reactify-component app-root))) 113 | ``` 114 | 115 | 116 | TODO: Create an example 117 | 118 | 119 | ## Usage for re-frame 120 | 121 | Pretty much the same as the Reagent version, but you can store the routing state in re-frame's app-db (which is great for serializing state to AsyncStorage). Also, dispatch routing changes from anywhere. 122 | 123 | See the [examples folder](https://github.com/seantempesta/cljs-react-navigation/tree/master/examples/re-frame/uiexplorer). 124 | 125 | ## TODO 126 | 127 | - Finish spec'ing all functions and parameters (I think I've got most of them) 128 | - Reagent example 129 | - Rum example 130 | - Om-Next example 131 | 132 | 133 | ## License 134 | 135 | Copyright © 2017 Sean Tempesta 136 | 137 | Distributed under the MIT license. 138 | -------------------------------------------------------------------------------- /doc/intro.md: -------------------------------------------------------------------------------- 1 | # Introduction to cljs-react-navigation 2 | 3 | TODO: write [great documentation](http://jacobian.org/writing/what-to-write/) 4 | -------------------------------------------------------------------------------- /examples/re-frame/expo-example/.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": ["babel-preset-expo"] 3 | } 4 | -------------------------------------------------------------------------------- /examples/re-frame/expo-example/.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/**/* 2 | .expo/* 3 | npm-debug.* 4 | /target 5 | /classes 6 | /checkouts 7 | pom.xml 8 | pom.xml.asc 9 | *.jar 10 | *.class 11 | /.lein-* 12 | /.nrepl-port 13 | .hgignore 14 | .hg/ 15 | figwheel_server.log 16 | main.js 17 | .js-modules.edn 18 | /env/dev/env/dev.cljs 19 | /env/dev/env/index.cljs 20 | -------------------------------------------------------------------------------- /examples/re-frame/expo-example/.projectile: -------------------------------------------------------------------------------- 1 | -/node_modules 2 | -/target 3 | -/.git 4 | -/.exponent 5 | -/figwheel_server.log 6 | -------------------------------------------------------------------------------- /examples/re-frame/expo-example/LICENSE: -------------------------------------------------------------------------------- 1 | THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC 2 | LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM 3 | CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. 4 | 5 | 1. DEFINITIONS 6 | 7 | "Contribution" means: 8 | 9 | a) in the case of the initial Contributor, the initial code and 10 | documentation distributed under this Agreement, and 11 | 12 | b) in the case of each subsequent Contributor: 13 | 14 | i) changes to the Program, and 15 | 16 | ii) additions to the Program; 17 | 18 | where such changes and/or additions to the Program originate from and are 19 | distributed by that particular Contributor. A Contribution 'originates' from 20 | a Contributor if it was added to the Program by such Contributor itself or 21 | anyone acting on such Contributor's behalf. Contributions do not include 22 | additions to the Program which: (i) are separate modules of software 23 | distributed in conjunction with the Program under their own license 24 | agreement, and (ii) are not derivative works of the Program. 25 | 26 | "Contributor" means any person or entity that distributes the Program. 27 | 28 | "Licensed Patents" mean patent claims licensable by a Contributor which are 29 | necessarily infringed by the use or sale of its Contribution alone or when 30 | combined with the Program. 31 | 32 | "Program" means the Contributions distributed in accordance with this 33 | Agreement. 34 | 35 | "Recipient" means anyone who receives the Program under this Agreement, 36 | including all Contributors. 37 | 38 | 2. GRANT OF RIGHTS 39 | 40 | a) Subject to the terms of this Agreement, each Contributor hereby grants 41 | Recipient a non-exclusive, worldwide, royalty-free copyright license to 42 | reproduce, prepare derivative works of, publicly display, publicly perform, 43 | distribute and sublicense the Contribution of such Contributor, if any, and 44 | such derivative works, in source code and object code form. 45 | 46 | b) Subject to the terms of this Agreement, each Contributor hereby grants 47 | Recipient a non-exclusive, worldwide, royalty-free patent license under 48 | Licensed Patents to make, use, sell, offer to sell, import and otherwise 49 | transfer the Contribution of such Contributor, if any, in source code and 50 | object code form. This patent license shall apply to the combination of the 51 | Contribution and the Program if, at the time the Contribution is added by the 52 | Contributor, such addition of the Contribution causes such combination to be 53 | covered by the Licensed Patents. The patent license shall not apply to any 54 | other combinations which include the Contribution. No hardware per se is 55 | licensed hereunder. 56 | 57 | c) Recipient understands that although each Contributor grants the licenses 58 | to its Contributions set forth herein, no assurances are provided by any 59 | Contributor that the Program does not infringe the patent or other 60 | intellectual property rights of any other entity. Each Contributor disclaims 61 | any liability to Recipient for claims brought by any other entity based on 62 | infringement of intellectual property rights or otherwise. As a condition to 63 | exercising the rights and licenses granted hereunder, each Recipient hereby 64 | assumes sole responsibility to secure any other intellectual property rights 65 | needed, if any. For example, if a third party patent license is required to 66 | allow Recipient to distribute the Program, it is Recipient's responsibility 67 | to acquire that license before distributing the Program. 68 | 69 | d) Each Contributor represents that to its knowledge it has sufficient 70 | copyright rights in its Contribution, if any, to grant the copyright license 71 | set forth in this Agreement. 72 | 73 | 3. REQUIREMENTS 74 | 75 | A Contributor may choose to distribute the Program in object code form under 76 | its own license agreement, provided that: 77 | 78 | a) it complies with the terms and conditions of this Agreement; and 79 | 80 | b) its license agreement: 81 | 82 | i) effectively disclaims on behalf of all Contributors all warranties and 83 | conditions, express and implied, including warranties or conditions of title 84 | and non-infringement, and implied warranties or conditions of merchantability 85 | and fitness for a particular purpose; 86 | 87 | ii) effectively excludes on behalf of all Contributors all liability for 88 | damages, including direct, indirect, special, incidental and consequential 89 | damages, such as lost profits; 90 | 91 | iii) states that any provisions which differ from this Agreement are offered 92 | by that Contributor alone and not by any other party; and 93 | 94 | iv) states that source code for the Program is available from such 95 | Contributor, and informs licensees how to obtain it in a reasonable manner on 96 | or through a medium customarily used for software exchange. 97 | 98 | When the Program is made available in source code form: 99 | 100 | a) it must be made available under this Agreement; and 101 | 102 | b) a copy of this Agreement must be included with each copy of the Program. 103 | 104 | Contributors may not remove or alter any copyright notices contained within 105 | the Program. 106 | 107 | Each Contributor must identify itself as the originator of its Contribution, 108 | if any, in a manner that reasonably allows subsequent Recipients to identify 109 | the originator of the Contribution. 110 | 111 | 4. COMMERCIAL DISTRIBUTION 112 | 113 | Commercial distributors of software may accept certain responsibilities with 114 | respect to end users, business partners and the like. While this license is 115 | intended to facilitate the commercial use of the Program, the Contributor who 116 | includes the Program in a commercial product offering should do so in a 117 | manner which does not create potential liability for other Contributors. 118 | Therefore, if a Contributor includes the Program in a commercial product 119 | offering, such Contributor ("Commercial Contributor") hereby agrees to defend 120 | and indemnify every other Contributor ("Indemnified Contributor") against any 121 | losses, damages and costs (collectively "Losses") arising from claims, 122 | lawsuits and other legal actions brought by a third party against the 123 | Indemnified Contributor to the extent caused by the acts or omissions of such 124 | Commercial Contributor in connection with its distribution of the Program in 125 | a commercial product offering. The obligations in this section do not apply 126 | to any claims or Losses relating to any actual or alleged intellectual 127 | property infringement. In order to qualify, an Indemnified Contributor must: 128 | a) promptly notify the Commercial Contributor in writing of such claim, and 129 | b) allow the Commercial Contributor tocontrol, and cooperate with the 130 | Commercial Contributor in, the defense and any related settlement 131 | negotiations. The Indemnified Contributor may participate in any such claim 132 | at its own expense. 133 | 134 | For example, a Contributor might include the Program in a commercial product 135 | offering, Product X. That Contributor is then a Commercial Contributor. If 136 | that Commercial Contributor then makes performance claims, or offers 137 | warranties related to Product X, those performance claims and warranties are 138 | such Commercial Contributor's responsibility alone. Under this section, the 139 | Commercial Contributor would have to defend claims against the other 140 | Contributors related to those performance claims and warranties, and if a 141 | court requires any other Contributor to pay any damages as a result, the 142 | Commercial Contributor must pay those damages. 143 | 144 | 5. NO WARRANTY 145 | 146 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON 147 | AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER 148 | EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR 149 | CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A 150 | PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the 151 | appropriateness of using and distributing the Program and assumes all risks 152 | associated with its exercise of rights under this Agreement , including but 153 | not limited to the risks and costs of program errors, compliance with 154 | applicable laws, damage to or loss of data, programs or equipment, and 155 | unavailability or interruption of operations. 156 | 157 | 6. DISCLAIMER OF LIABILITY 158 | 159 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY 160 | CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, 161 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION 162 | LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 163 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 164 | ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE 165 | EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY 166 | OF SUCH DAMAGES. 167 | 168 | 7. GENERAL 169 | 170 | If any provision of this Agreement is invalid or unenforceable under 171 | applicable law, it shall not affect the validity or enforceability of the 172 | remainder of the terms of this Agreement, and without further action by the 173 | parties hereto, such provision shall be reformed to the minimum extent 174 | necessary to make such provision valid and enforceable. 175 | 176 | If Recipient institutes patent litigation against any entity (including a 177 | cross-claim or counterclaim in a lawsuit) alleging that the Program itself 178 | (excluding combinations of the Program with other software or hardware) 179 | infringes such Recipient's patent(s), then such Recipient's rights granted 180 | under Section 2(b) shall terminate as of the date such litigation is filed. 181 | 182 | All Recipient's rights under this Agreement shall terminate if it fails to 183 | comply with any of the material terms or conditions of this Agreement and 184 | does not cure such failure in a reasonable period of time after becoming 185 | aware of such noncompliance. If all Recipient's rights under this Agreement 186 | terminate, Recipient agrees to cease use and distribution of the Program as 187 | soon as reasonably practicable. However, Recipient's obligations under this 188 | Agreement and any licenses granted by Recipient relating to the Program shall 189 | continue and survive. 190 | 191 | Everyone is permitted to copy and distribute copies of this Agreement, but in 192 | order to avoid inconsistency the Agreement is copyrighted and may only be 193 | modified in the following manner. The Agreement Steward reserves the right to 194 | publish new versions (including revisions) of this Agreement from time to 195 | time. No one other than the Agreement Steward has the right to modify this 196 | Agreement. The Eclipse Foundation is the initial Agreement Steward. The 197 | Eclipse Foundation may assign the responsibility to serve as the Agreement 198 | Steward to a suitable separate entity. Each new version of the Agreement will 199 | be given a distinguishing version number. The Program (including 200 | Contributions) may always be distributed subject to the version of the 201 | Agreement under which it was received. In addition, after a new version of 202 | the Agreement is published, Contributor may elect to distribute the Program 203 | (including its Contributions) under the new version. Except as expressly 204 | stated in Sections 2(a) and 2(b) above, Recipient receives no rights or 205 | licenses to the intellectual property of any Contributor under this 206 | Agreement, whether expressly, by implication, estoppel or otherwise. All 207 | rights in the Program not expressly granted under this Agreement are 208 | reserved. 209 | 210 | This Agreement is governed by the laws of the State of New York and the 211 | intellectual property laws of the United States of America. No party to this 212 | Agreement will bring a legal action under this Agreement more than one year 213 | after the cause of action arose. Each party waives its rights to a jury trial 214 | in any resulting litigation. 215 | -------------------------------------------------------------------------------- /examples/re-frame/expo-example/app.json: -------------------------------------------------------------------------------- 1 | { 2 | "expo": { 3 | "name": "expo-example", 4 | "description": "No description", 5 | "slug": "expo-example", 6 | "sdkVersion": "22.0.0", 7 | "version": "1.0.0", 8 | "orientation": "portrait", 9 | "primaryColor": "#cccccc", 10 | "privacy": "public", 11 | "icon": "./assets/icons/app.png", 12 | "notification": { 13 | "icon": "./assets/icons/loading.png", 14 | "color": "#000000" 15 | }, 16 | "loading": { 17 | "icon": "https://s3.amazonaws.com/exp-brand-assets/ExponentEmptyManifest_192.png", 18 | "hideExponentText": false 19 | }, 20 | "packagerOpts": { 21 | "assetExts": [ 22 | "ttf", 23 | "otf" 24 | ], 25 | "nonPersistent": "" 26 | }, 27 | "ios": { 28 | "supportsTablet": true 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /examples/re-frame/expo-example/assets/icons/app.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seantempesta/cljs-react-navigation/d8f6f998543608e930de8d565e7b48221ecfbe8a/examples/re-frame/expo-example/assets/icons/app.png -------------------------------------------------------------------------------- /examples/re-frame/expo-example/assets/icons/loading.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seantempesta/cljs-react-navigation/d8f6f998543608e930de8d565e7b48221ecfbe8a/examples/re-frame/expo-example/assets/icons/loading.png -------------------------------------------------------------------------------- /examples/re-frame/expo-example/assets/images/cljs.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seantempesta/cljs-react-navigation/d8f6f998543608e930de8d565e7b48221ecfbe8a/examples/re-frame/expo-example/assets/images/cljs.png -------------------------------------------------------------------------------- /examples/re-frame/expo-example/assets/images/cljs@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seantempesta/cljs-react-navigation/d8f6f998543608e930de8d565e7b48221ecfbe8a/examples/re-frame/expo-example/assets/images/cljs@2x.png -------------------------------------------------------------------------------- /examples/re-frame/expo-example/assets/images/cljs@3x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seantempesta/cljs-react-navigation/d8f6f998543608e930de8d565e7b48221ecfbe8a/examples/re-frame/expo-example/assets/images/cljs@3x.png -------------------------------------------------------------------------------- /examples/re-frame/expo-example/build.boot: -------------------------------------------------------------------------------- 1 | (set-env! 2 | :source-paths #{"src" "env/dev"} 3 | :dependencies '[[ajchemist/boot-figwheel "0.5.4-6" :scope "test"] ;; latest release 4 | [org.clojure/tools.nrepl "0.2.12" :scope "test"] 5 | [com.cemerick/piggieback "0.2.1" :scope "test"] 6 | [figwheel-sidecar "0.5.4-7" :scope "test"] 7 | [react-native-externs "0.0.2-SNAPSHOT" :scope "test"] 8 | 9 | [org.clojure/clojure "1.9.0-alpha16"] 10 | [org.clojure/clojurescript "1.9.542"] 11 | [org.clojure/core.async "0.3.442"] 12 | [reagent "0.6.1" :exclusions [cljsjs/react cljsjs/react-dom cljsjs/react-dom-server]] 13 | [re-frame "0.9.3"]]) 14 | 15 | (require 16 | '[boot-figwheel :refer [figwheel cljs-repl]] 17 | '[cljs.build.api :as b] 18 | '[user :as user] 19 | '[externs :as externs]) 20 | 21 | (require 'boot.repl) 22 | (swap! boot.repl/*default-middleware* 23 | conj 'cemerick.piggieback/wrap-cljs-repl) 24 | 25 | (deftask dev 26 | "boot dev, then input (cljs-repl)" 27 | [] 28 | (user/prepare) 29 | 30 | (comp 31 | (figwheel 32 | :build-ids ["main"] 33 | :all-builds [{:id "main" 34 | :source-paths ["src" "env/dev"] 35 | :figwheel true 36 | :compiler {:output-to "not-used.js" 37 | :main "env.main" 38 | :optimizations :none 39 | :output-dir "."}}] 40 | :figwheel-options {:open-file-command "emacsclient" 41 | :validate-config false}) 42 | (repl))) 43 | 44 | (deftask prod 45 | [] 46 | (externs/-main) 47 | 48 | (println "Start to compile clojurescript ...") 49 | (let [start (System/nanoTime)] 50 | (b/build ["src" "env/prod"] 51 | {:output-to "main.js" 52 | :main "env.main" 53 | :output-dir "target" 54 | :static-fns true 55 | :externs ["js/externs.js"] 56 | :parallel-build true 57 | :optimize-constants true 58 | :optimizations :advanced 59 | :closure-defines {"goog.DEBUG" false}}) 60 | (println "... done. Elapsed" (/ (- (System/nanoTime) start) 1e9) "seconds"))) 61 | -------------------------------------------------------------------------------- /examples/re-frame/expo-example/env/dev/env/main.cljs: -------------------------------------------------------------------------------- 1 | (ns ^:figwheel-no-load env.main 2 | (:require [reagent.core :as r] 3 | [expo-example.core :as core] 4 | [figwheel.client :as figwheel :include-macros true] 5 | [env.dev])) 6 | 7 | (enable-console-print!) 8 | 9 | (def cnt (r/atom 0)) 10 | (defn reloader [] @cnt [core/app-root]) 11 | (def root-el (r/as-element [reloader])) 12 | 13 | (figwheel/watch-and-reload 14 | :websocket-url (str "ws://" env.dev/ip ":3449/figwheel-ws") 15 | :heads-up-display false 16 | :jsload-callback #(swap! cnt inc)) 17 | 18 | (core/init) 19 | -------------------------------------------------------------------------------- /examples/re-frame/expo-example/env/dev/externs.clj: -------------------------------------------------------------------------------- 1 | (ns externs 2 | (:require [cljs.compiler.api :as compiler] 3 | [cljs.analyzer.api :as analyzer] 4 | [cljs.analyzer :as ana] 5 | [clojure.walk :refer [prewalk]] 6 | [clojure.pprint :refer [pprint]] 7 | [clojure.java.io :as io] 8 | [clojure.string :as str] 9 | [cljs.env :as env] 10 | [clojure.tools.reader :as r] 11 | [clojure.tools.reader.reader-types :refer [string-push-back-reader]] 12 | [cljs.tagged-literals :as tags]) 13 | (:import (clojure.lang LineNumberingPushbackReader))) 14 | 15 | ;; Idea from https://gist.github.com/Chouser/5796967 16 | 17 | ;; TODO (NAMESPACE/MODULE.method ...args) or NAMESPACE/MODULE.field not work 18 | ;; For example, (ui/Facebook.logInWithReadPermissionsAsync ...args) 19 | ;; or ui/Permissions.REMOTE_NOTIFICATIONS, 20 | ;; we already know logInWithReadPermissionsAsync is `invoke' op 21 | ;; and REMOTE_NOTIFICATIONS is a property, need to dig deeper to the ast 22 | 23 | ;; TODO ana/analyze is slow 24 | 25 | (defonce cenv (analyzer/empty-state)) 26 | 27 | (defn compile-project 28 | [src target] 29 | (analyzer/with-state cenv 30 | (compiler/with-core-cljs 31 | (compiler/compile-root src target)))) 32 | 33 | (defn get-namespaces 34 | [] 35 | (:cljs.analyzer/namespaces @cenv)) 36 | 37 | (defn get-namespace 38 | ([] 39 | (get-namespace ana/*cljs-ns*)) 40 | ([k] 41 | (get (get-namespaces) k))) 42 | 43 | (defn get-alias 44 | [ns] 45 | (apply merge 46 | ((juxt :requires :require-macros) 47 | (get-namespace ns)))) 48 | 49 | (defn print-ast [ast] 50 | (pprint ;; pprint indents output nicely 51 | (prewalk ;; rewrite each node of the ast 52 | (fn [x] 53 | (if (map? x) 54 | (select-keys x [:children :name :form :op]) ;; return selected entries of each map node 55 | x)) ;; non-map nodes are left unchanged 56 | ast))) 57 | 58 | (defn get-ns 59 | [s] 60 | (some->> 61 | (re-find #"\(ns[\s]+([^\s]+)" s) 62 | (last) 63 | (symbol))) 64 | 65 | (defn read-file 66 | [filename] 67 | (try 68 | (let [form-str (slurp filename) 69 | current-ns (get-ns form-str) 70 | reader (string-push-back-reader form-str) 71 | endof (gensym)] 72 | (binding [r/*read-eval* false 73 | r/*data-readers* tags/*cljs-data-readers* 74 | r/*alias-map* (try 75 | (get-alias (ns-name current-ns)) 76 | (catch Exception e 77 | {}))] 78 | (->> #(r/read reader false endof) 79 | (repeatedly) 80 | (take-while #(not= % endof)) 81 | (doall)))) 82 | (catch Exception e 83 | (println e) 84 | '()))) 85 | 86 | (defn file-ast 87 | "Return the ClojureScript AST for the contents of filename. Tends to 88 | be large and to contain cycles -- be careful printing at the REPL." 89 | [filename] 90 | (binding [ana/*cljs-ns* 'cljs.user ;; default namespace 91 | ana/*cljs-file* filename] 92 | (mapv 93 | (fn [form] 94 | (try (ana/no-warn (ana/analyze (ana/empty-env) form {:cache-analysis true})) 95 | (catch Exception e 96 | (prn filename e)))) 97 | (read-file filename)))) 98 | 99 | (defn flatten-ast [ast] 100 | (mapcat #(tree-seq :children :children %) ast)) 101 | 102 | (defn get-interop-used 103 | "Return a set of symbols representing the method and field names 104 | used in interop forms in the given sequence of AST nodes." 105 | [flat-ast] 106 | (keep #(let [ret (and (map? %) 107 | (when-let [sym (some % [:method :field])] 108 | (when-not (str/starts-with? sym "cljs") 109 | sym)))] 110 | (if ret 111 | ret 112 | nil)) flat-ast)) 113 | 114 | (defn externs-for-interop [syms] 115 | (apply str 116 | "var DummyClass={};\n" 117 | (map #(str "DummyClass." % "=function(){};\n") 118 | syms))) 119 | 120 | (defn var-defined? 121 | "Returns true if the given fully-qualified symbol is known by the 122 | ClojureScript compiler to have been defined, based on its mutable set 123 | of namespaces." 124 | [sym] 125 | (contains? (let [ns (get (get-namespaces) (symbol (namespace sym)))] 126 | (merge (:defs ns) 127 | (:macros ns))) 128 | (symbol (name sym)))) 129 | 130 | (defn get-vars-used 131 | "Return a set of symbols representing all vars used or referenced in 132 | the given sequence of AST nodes." 133 | [requires flat-ast] 134 | (->> flat-ast 135 | (filter #(let [ns (-> % :info :ns)] 136 | (and (= (:op %) :var) 137 | ns 138 | (not= ns 'js)))) 139 | (map #(let [sym (-> % :info :name) 140 | sym-namespace (get requires (symbol (namespace sym))) 141 | sym-name (name sym)] 142 | (if sym-namespace 143 | (symbol (str sym-namespace) sym-name) 144 | sym))))) 145 | 146 | (defn extern-for-var [[str-namespace symbols]] 147 | (let [symbols-str (->> symbols 148 | (map (fn [sym] (format "%s.%s={};\n" (namespace sym) (name sym)))) 149 | (apply str))] 150 | (format "var %s={};\n%s" 151 | str-namespace symbols-str))) 152 | 153 | (defn externs-for-vars [grouped-syms] 154 | (apply str (map extern-for-var grouped-syms))) 155 | 156 | (defn get-undefined-vars [requires flat-ast] 157 | (->> (get-vars-used requires flat-ast) 158 | (remove var-defined?))) 159 | 160 | (defn get-undefined-vars-and-interop-used [file] 161 | (let [ast (file-ast file) 162 | ns-name (:name (first ast)) 163 | ns-requires (:requires (first ast)) 164 | flat-ast (flatten-ast ast)] 165 | [(get-undefined-vars ns-requires flat-ast) 166 | (get-interop-used flat-ast)])) 167 | 168 | ;; copy from https://github.com/ejlo/lein-externs/blob/master/src/leiningen/externs.clj 169 | (defn cljs-file? 170 | "Returns true if the java.io.File represents a normal Clojurescript source 171 | file." 172 | [^java.io.File file] 173 | (and (.isFile file) 174 | (.endsWith (.getName file) ".cljs"))) 175 | 176 | (defn get-source-paths [build-type builds] 177 | (or 178 | (when build-type 179 | (:source-paths 180 | (or ((keyword build-type) builds) 181 | (first (filter #(= (name (:id %)) build-type) builds))))) 182 | ["src" "cljs"])) 183 | 184 | (defn -main 185 | "Generate an externs file" 186 | [] 187 | ;; TODO configurable 188 | (println "Start to generate externs...") 189 | (compile-project (io/file "src") (io/file "target")) 190 | 191 | (let [source-paths ["src" "env/prod"] 192 | 193 | files (->> source-paths 194 | (map io/file) 195 | (mapcat file-seq) 196 | (filter cljs-file?)) 197 | col (apply concat (doall (pmap get-undefined-vars-and-interop-used files))) 198 | vars (->> (take-nth 2 col) 199 | (remove empty?) 200 | (flatten) 201 | (set) 202 | (sort) 203 | (group-by namespace) 204 | ;; remove goog dependencies, need to dig deeper(TODO) 205 | (remove (fn [[ns _]] (str/starts-with? ns "goog"))) 206 | (externs-for-vars)) 207 | interop (->> (take-nth 2 (rest col)) 208 | (remove empty?) 209 | (flatten) 210 | (set) 211 | (sort) 212 | (externs-for-interop)) 213 | result (str vars interop)] 214 | (spit "js/externs.js" result) 215 | (println "Generated externs to js/externs.js") 216 | 217 | ;; prevent jvm hang after this task, maybe Clojurescript uses pmap for parallel compilation. 218 | (shutdown-agents))) 219 | -------------------------------------------------------------------------------- /examples/re-frame/expo-example/env/dev/user.clj: -------------------------------------------------------------------------------- 1 | (ns user 2 | (:require [figwheel-sidecar.repl-api :as ra] 3 | [clojure.java.io :as io] 4 | [clojure.string :as str] 5 | [hawk.core :as hawk] 6 | [clojure.tools.reader.edn :as edn] 7 | [clojure.set :as set])) 8 | ;; This namespace is loaded automatically by nREPL 9 | 10 | (defn get-cljs-builds 11 | [] 12 | (let [project-config (->> "project.clj" 13 | slurp 14 | read-string 15 | (drop 1) 16 | (apply hash-map)) 17 | profiles (:profiles project-config)] 18 | (get-in profiles [:dev :cljsbuild :builds]))) 19 | 20 | (defn enable-source-maps 21 | [] 22 | (println "Source maps enabled.") 23 | (let [path "node_modules/metro-bundler/src/Server/index.js"] 24 | (spit path 25 | (str/replace (slurp path) "/\\.map$/" "/main.map$/")))) 26 | 27 | (defn write-main-js 28 | [] 29 | (-> "'use strict';\n\n// cljsbuild adds a preamble mentioning goog so hack around it\nwindow.goog = {\n provide() {},\n require() {},\n};\nrequire('./target/env/index.js');\n" 30 | ((partial spit "main.js")))) 31 | 32 | (defn get-lan-ip 33 | [] 34 | (cond 35 | (= "Mac OS X" (System/getProperty "os.name")) 36 | (.getHostAddress (java.net.InetAddress/getLocalHost)) 37 | 38 | :else 39 | (->> (java.net.NetworkInterface/getNetworkInterfaces) 40 | (enumeration-seq) 41 | (filter #(not (or (str/starts-with? (.getName %) "docker") 42 | (str/starts-with? (.getName %) "vboxnet") 43 | (str/starts-with? (.getName %) "br-")))) 44 | (map #(.getInterfaceAddresses %)) 45 | (map 46 | (fn [ip] 47 | (seq (filter #(instance? 48 | java.net.Inet4Address 49 | (.getAddress %)) 50 | ip)))) 51 | (remove nil?) 52 | (first) 53 | (filter #(instance? 54 | java.net.Inet4Address 55 | (.getAddress %))) 56 | (first) 57 | (.getAddress) 58 | (.getHostAddress)))) 59 | 60 | (defn write-env-dev 61 | [] 62 | (let [hostname (.getHostName (java.net.InetAddress/getLocalHost)) 63 | ip (get-lan-ip)] 64 | (-> "(ns env.dev)\n(def hostname \"%s\")\n(def ip \"%s\")" 65 | (format 66 | hostname 67 | ip) 68 | ((partial spit "env/dev/env/dev.cljs"))))) 69 | 70 | (defn rebuild-env-index 71 | [js-modules] 72 | (let [modules (->> (file-seq (io/file "assets")) 73 | (filter #(and (not (re-find #"DS_Store" (str %))) 74 | (.isFile %))) 75 | (map (fn [file] (when-let [path (str file)] 76 | (str "../../" path)))) 77 | (concat js-modules ["react" "react-native" "expo" "create-react-class"]) 78 | (distinct)) 79 | modules-map (zipmap 80 | (->> modules 81 | (map #(str "\"" 82 | (if (str/starts-with? % "../../assets") 83 | (-> % 84 | (str/replace "../../" "./") 85 | (str/replace "@2x" "") 86 | (str/replace "@3x" "")) 87 | %) 88 | "\""))) 89 | (->> modules 90 | (map #(format "(js/require \"%s\")" 91 | (-> % 92 | (str/replace "@2x" "") 93 | (str/replace "@3x" ""))))))] 94 | (try 95 | (-> "(ns env.index\n (:require [env.dev :as dev]))\n\n;; undo main.js goog preamble hack\n(set! js/window.goog js/undefined)\n\n(-> (js/require \"figwheel-bridge\")\n (.withModules %s)\n (.start \"main\"))\n" 96 | (format 97 | (str "#js " (with-out-str (println modules-map)))) 98 | ((partial spit "env/dev/env/index.cljs"))) 99 | 100 | (catch Exception e 101 | (println "Error: " e))))) 102 | 103 | ;; Each file maybe corresponds to multiple modules. 104 | (defn watch-for-external-modules 105 | [] 106 | (let [path ".js-modules.edn"] 107 | (hawk/watch! [{:paths ["src"] 108 | :filter hawk/file? 109 | :handler (fn [ctx {:keys [kind file] :as event}] 110 | (let [m (edn/read-string (slurp path)) 111 | file-name (-> (.getPath file) 112 | (str/replace (str (System/getProperty "user.dir") "/") ""))] 113 | 114 | ;; file is deleted 115 | (when (= :delete kind) 116 | (let [new-m (dissoc m file-name)] 117 | (spit path new-m) 118 | (rebuild-env-index (flatten (vals new-m))))) 119 | 120 | (when (.exists file) 121 | (let [content (slurp file) 122 | js-modules (some->> 123 | content 124 | (re-seq #"\(js/require \"([^\"]+)\"\)") 125 | (map last) 126 | (vec)) 127 | commented-modules (some->> 128 | content 129 | (re-seq #"[;]+[\s]*\(js/require \"([^\"]+)\"\)") 130 | (map last) 131 | (set)) 132 | js-modules (if commented-modules 133 | (vec (remove commented-modules js-modules)) 134 | js-modules)] 135 | (let [old-js-modules (get m file-name)] 136 | (when (not= old-js-modules js-modules) 137 | (let [new-m (if (seq js-modules) 138 | (assoc m file-name js-modules) 139 | (dissoc m file-name))] 140 | (spit path new-m) 141 | 142 | (rebuild-env-index (flatten (vals new-m))))))))) 143 | ctx)}]))) 144 | 145 | (defn rebuild-modules 146 | [] 147 | (let [path ".js-modules.edn" 148 | m (atom {})] 149 | ;; delete path 150 | (when (.exists (java.io.File. path)) 151 | (clojure.java.io/delete-file path)) 152 | 153 | (doseq [file (file-seq (java.io.File. "src"))] 154 | (when (.isFile file) 155 | (let [file-name (-> (.getPath file) 156 | (str/replace (str (System/getProperty "user.dir") "/") "")) 157 | content (slurp file) 158 | js-modules (some->> 159 | content 160 | (re-seq #"\(js/require \"([^\"]+)\"\)") 161 | (map last) 162 | (vec)) 163 | commented-modules (some->> 164 | content 165 | (re-seq #"[;]+[\s]*\(js/require \"([^\"]+)\"\)") 166 | (map last) 167 | (set)) 168 | js-modules (if commented-modules 169 | (vec (remove commented-modules js-modules)) 170 | js-modules)] 171 | (if js-modules 172 | (swap! m assoc file-name (vec js-modules)))))) 173 | (spit path @m) 174 | (rebuild-env-index (flatten (vals @m))))) 175 | 176 | (defn init-external-modules 177 | [] 178 | (rebuild-modules)) 179 | 180 | ;; Lein 181 | (defn start-figwheel 182 | "Start figwheel for one or more builds" 183 | [& build-ids] 184 | (init-external-modules) 185 | (enable-source-maps) 186 | (write-main-js) 187 | (write-env-dev) 188 | (watch-for-external-modules) 189 | (ra/start-figwheel! 190 | {:figwheel-options {} 191 | :build-ids (if (seq build-ids) 192 | build-ids 193 | ["main"]) 194 | :all-builds (get-cljs-builds)}) 195 | (ra/cljs-repl)) 196 | 197 | (defn stop-figwheel 198 | "Stops figwheel" 199 | [] 200 | (ra/stop-figwheel!)) 201 | 202 | (defn -main 203 | [args] 204 | (case args 205 | "--figwheel" 206 | (start-figwheel) 207 | 208 | "--rebuild-modules" 209 | (rebuild-modules) 210 | 211 | (prn "You can run lein figwheel or lein rebuild-modules."))) 212 | 213 | ;; Boot 214 | (defn prepare 215 | [] 216 | (init-external-modules) 217 | (enable-source-maps) 218 | (write-main-js) 219 | (write-env-dev) 220 | (watch-for-external-modules)) 221 | -------------------------------------------------------------------------------- /examples/re-frame/expo-example/env/prod/env/main.cljs: -------------------------------------------------------------------------------- 1 | (ns env.main 2 | (:require [expo-example.core :as core])) 3 | 4 | (core/init) 5 | -------------------------------------------------------------------------------- /examples/re-frame/expo-example/js/figwheel-bridge.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Originally taken from https://github.com/decker405/figwheel-react-native 3 | * 4 | * @providesModule figwheel-bridge 5 | */ 6 | 7 | var CLOSURE_UNCOMPILED_DEFINES = null; 8 | var debugEnabled = false; 9 | 10 | var config = { 11 | basePath: "target/", 12 | googBasePath: 'goog/', 13 | serverPort: 19001 14 | }; 15 | 16 | var React = require('react'); 17 | var ReactNative = require('react-native'); 18 | var WebSocket = require('WebSocket'); 19 | var createReactClass = require('create-react-class'); 20 | var self; 21 | var scriptQueue = []; 22 | var serverHost = null; // will be set dynamically 23 | var fileBasePath = null; // will be set dynamically 24 | var evaluate = eval; // This is needed, direct calls to eval does not work (RN packager???) 25 | var externalModules = {}; 26 | var evalListeners = [ // Functions to be called after each js file is loaded and evaluated 27 | function (url) { 28 | if (url.indexOf('jsloader') > -1) { 29 | shimJsLoader(); 30 | } 31 | }, 32 | function (url) { 33 | if (url.indexOf('/figwheel/client/socket') > -1) { 34 | setCorrectWebSocketImpl(); 35 | } 36 | }]; 37 | 38 | var figwheelApp = function (platform, devHost) { 39 | return createReactClass({ 40 | getInitialState: function () { 41 | return {loaded: false} 42 | }, 43 | render: function () { 44 | if (!this.state.loaded) { 45 | var plainStyle = {flex: 1, alignItems: 'center', justifyContent: 'center'}; 46 | return ( 47 | 48 | Waiting for Figwheel to load files. 49 | 50 | ); 51 | } 52 | return this.state.root; 53 | }, 54 | componentDidMount: function () { 55 | var app = this; 56 | if (typeof goog === "undefined") { 57 | var url = this.props.url || 58 | this.props.exp.manifest.bundleUrl; 59 | var hostPort = url.split('/')[2].split(':'); 60 | devHost = hostPort[0]; 61 | 62 | if (hostPort[1]) { 63 | config.serverPort = hostPort[1]; 64 | } 65 | 66 | loadApp(platform, devHost, function (appRoot) { 67 | app.setState({root: appRoot, loaded: true}) 68 | }); 69 | } 70 | } 71 | }) 72 | }; 73 | 74 | function logDebug(msg) { 75 | if (debugEnabled) { 76 | console.log(msg); 77 | } 78 | } 79 | 80 | // evaluates js code ensuring proper ordering 81 | function customEval(url, javascript, success, error) { 82 | if (scriptQueue.length > 0) { 83 | if (scriptQueue[0] === url) { 84 | try { 85 | evaluate(javascript); 86 | logDebug('Evaluated: ' + url); 87 | scriptQueue.shift(); 88 | evalListeners.forEach(function (listener) { 89 | listener(url) 90 | }); 91 | success(); 92 | } catch (e) { 93 | console.error(e); 94 | error(); 95 | } 96 | } else { 97 | setTimeout(function () { 98 | customEval(url, javascript, success, error) 99 | }, 5); 100 | } 101 | } else { 102 | console.error('Something bad happened...'); 103 | error() 104 | } 105 | } 106 | 107 | var isChrome = function () { 108 | return typeof importScripts === "function" 109 | }; 110 | 111 | function asyncImportScripts(url, success, error) { 112 | logDebug('(asyncImportScripts) Importing: ' + url); 113 | scriptQueue.push(url); 114 | fetch(url) 115 | .then(function (response) { 116 | return response.text() 117 | }) 118 | .then(function (responseText) { 119 | return customEval(url, responseText, success, error); 120 | }) 121 | .catch(function (error) { 122 | console.error(error); 123 | return error(); 124 | }); 125 | } 126 | 127 | function syncImportScripts(url, success, error) { 128 | try { 129 | importScripts(url); 130 | logDebug('Evaluated: ' + url); 131 | evalListeners.forEach(function (listener) { 132 | listener(url) 133 | }); 134 | success(); 135 | } catch (e) { 136 | console.error(e); 137 | error() 138 | } 139 | } 140 | 141 | // Loads js file sync if possible or async. 142 | function importJs(src, success, error) { 143 | if (typeof success !== 'function') { 144 | success = function () { 145 | }; 146 | } 147 | if (typeof error !== 'function') { 148 | error = function () { 149 | }; 150 | } 151 | 152 | var file = fileBasePath + '/' + src; 153 | 154 | logDebug('(importJs) Importing: ' + file); 155 | if (isChrome()) { 156 | syncImportScripts(serverBaseUrl("localhost") + '/' + file, success, error); 157 | } else { 158 | asyncImportScripts(serverBaseUrl(serverHost) + '/' + file, success, error); 159 | } 160 | } 161 | 162 | function interceptRequire() { 163 | var oldRequire = window.require; 164 | console.info("Shimming require"); 165 | window.require = function (id) { 166 | console.info("Requiring: " + id); 167 | if (externalModules[id]) { 168 | return externalModules[id]; 169 | } 170 | return oldRequire(id); 171 | }; 172 | } 173 | 174 | function compileWarningsToYellowBox() { 175 | var log = window.console.log; 176 | var compileWarningRx = /Figwheel: Compile/; 177 | var compileExceptionRx = /Figwheel: Compile Exception/; 178 | var errorInFileRx = /Error on file/; 179 | var isBuffering = false; 180 | var compileExceptionBuffer = ""; 181 | window.console.log = function (msg) { 182 | log.apply(window.console, arguments); 183 | if (compileExceptionRx.test(msg)) { // enter buffering mode to get all the messages for exception 184 | isBuffering = true; 185 | compileExceptionBuffer = msg + "\n"; 186 | } else if (errorInFileRx.test(msg) && isBuffering) { // exit buffering mode and log buffered messages to YellowBox 187 | isBuffering = false; 188 | console.warn(compileExceptionBuffer + msg); 189 | compileExceptionBuffer = ""; 190 | } else if (isBuffering) { //log messages buffering mode 191 | compileExceptionBuffer += msg + "\n"; 192 | } else if (compileWarningRx.test(msg)) { 193 | console.warn(msg); 194 | } 195 | }; 196 | } 197 | 198 | function serverBaseUrl(host) { 199 | return "http://" + host + ":" + config.serverPort 200 | } 201 | 202 | function setCorrectWebSocketImpl() { 203 | figwheel.client.socket.get_websocket_imp = function () { 204 | return WebSocket; 205 | }; 206 | } 207 | 208 | function loadApp(platform, devHost, onLoadCb) { 209 | serverHost = devHost; 210 | fileBasePath = config.basePath; 211 | 212 | // callback when app is ready to get the reloadable component 213 | var mainJs = '/env/main.js'; 214 | evalListeners.push(function (url) { 215 | if (url.indexOf(mainJs) > -1) { 216 | onLoadCb(env.main.root_el); 217 | console.info('Done loading Clojure app'); 218 | } 219 | }); 220 | 221 | if (typeof goog === "undefined") { 222 | console.info('Loading Closure base.'); 223 | interceptRequire(); 224 | compileWarningsToYellowBox(); 225 | importJs('goog/base.js', function () { 226 | shimBaseGoog(); 227 | importJs('cljs_deps.js'); 228 | importJs('goog/deps.js', function () { 229 | // This is needed because of RN packager 230 | // seriously React packager? why. 231 | var googreq = goog.require; 232 | 233 | googreq('figwheel.connect.build_main'); 234 | }); 235 | }); 236 | } 237 | } 238 | 239 | function startApp(appName, platform, devHost) { 240 | ReactNative.AppRegistry.registerComponent( 241 | appName, () => figwheelApp(platform, devHost)); 242 | } 243 | 244 | function withModules(moduleById) { 245 | externalModules = moduleById; 246 | return self; 247 | } 248 | 249 | // Goog fixes 250 | function shimBaseGoog() { 251 | console.info('Shimming goog functions.'); 252 | goog.basePath = 'goog/'; 253 | goog.writeScriptSrcNode = importJs; 254 | goog.writeScriptTag_ = function (src, optSourceText) { 255 | importJs(src); 256 | return true; 257 | }; 258 | } 259 | 260 | // Figwheel fixes 261 | // Used by figwheel - uses importScript to load JS rather than