troubleshooting clojure web-app: connecting html and css for heroku deployment - html

I have two files, one html and one css. I have tried to turn them into a heroku app and even used the lein command to create a heroku friendly skeleton and plug these two files in, but cannot get it to work for the life of me. There is something very basic that I don't yet understand about how to coordinate a view with the back-end control. And the hello world tutorials aren't helping me because they do not show me how to do different things or explain what needs to change in my defroutes function, for example, for that to be accomplished. In short, my question is this: How can I coordinate these two files into a Clojure project to make the html render as the front page of a webapp and then deploy it on heroku?
html:
<html>
<head>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<img id="sun" src="http://goo.gl/dEEssP">
<div id='earth-orbit'>
<img id="earth" src="http://goo.gl/o3YWu9">
</div>
</body>
</html>
web.clj file in "lein new heroku ..." project:
(ns solar_system.web
(:require [compojure.core :refer [defroutes GET PUT POST DELETE ANY]]
[compojure.handler :refer [site]]
[compojure.route :as route]
[clojure.java.io :as io]
[ring.middleware.stacktrace :as trace]
[ring.middleware.session :as session]
[ring.middleware.session.cookie :as cookie]
[ring.adapter.jetty :as jetty]
[ring.middleware.basic-authentication :as basic]
[cemerick.drawbridge :as drawbridge]
[environ.core :refer [env]]))
(defn- authenticated? [user pass]
;; TODO: heroku config:add REPL_USER=[...] REPL_PASSWORD=[...]
(= [user pass] [(env :repl-user false) (env :repl-password false)]))
(def ^:private drawbridge
(-> (drawbridge/ring-handler)
(session/wrap-session)
(basic/wrap-basic-authentication authenticated?)))
(defroutes app
(ANY "/repl" {:as req}
(drawbridge req))
(GET "/" []
{:status 200
:headers {"Content-Type" "text/plain"}
:body (pr-str ["Hello" :from 'Heroku])}) ; <= Should I change this part here?
(ANY "*" []
(route/not-found (slurp (io/resource "404.html")))))
(defn wrap-error-page [handler]
(fn [req]
(try (handler req)
(catch Exception e
{:status 500
:headers {"Content-Type" "text/html"}
:body (slurp (io/resource "500.html"))}))))
(defn -main [& [port]]
(let [port (Integer. (or port (env :port) 5000))
;; TODO: heroku config:add SESSION_SECRET=$RANDOM_16_CHARS
store (cookie/cookie-store {:key (env :session-secret)})]
(jetty/run-jetty (-> #'app
((if (env :production)
wrap-error-page
trace/wrap-stacktrace))
(site {:session {:store store}}))
{:port port :join? false})))
;; For interactive development:
;; (.stop server)
;; (def server (-main))
project.clj file
(defproject solar_system "1.0.0-SNAPSHOT"
:description "FIXME: write description"
:url "http://solar_system.herokuapp.com"
:license {:name "FIXME: choose"
:url "http://example.com/FIXME"}
:dependencies [[org.clojure/clojure "1.4.0"]
[compojure "1.1.1"]
[ring/ring-jetty-adapter "1.1.0"]
[ring/ring-devel "1.1.0"]
[ring-basic-authentication "1.0.1"]
[environ "0.2.1"]
[com.cemerick/drawbridge "0.0.6"]]
:min-lein-version "2.0.0"
:plugins [[environ/environ.lein "0.2.1"]]
:hooks [environ.leiningen.hooks]
:profiles {:production {:env {:production true}}})
example of typical handler code that renders text:
(ns hello-world.core
(:use ring.adapter.jetty))
(defn app [req]
{:status 200
:headers {"Content-Type" "text/plain"}
:body "Hello, world"}) ; <= Could I just change this part to slurp in
; the html file and stick it in a file in my
; root directory to get a successful 'git push heroku master'?

Modifying your code:
(defroutes app
(ANY "/repl" {:as req}
(drawbridge req))
(GET "/" []
{:status 200
:headers {"Content-Type" "text/html"} ; change content type
:body (slurp "resources/public/my-file.html")}) ; wherever your file is
(ANY "*" []
(route/not-found (slurp (io/resource "404.html")))))
How I'd write it:
(defroutes app
(ANY "/repl" {:as req} (drawbridge req))
(GET "/" [] (slurp "resources/public/my-file.html")) ; wherever your file is
(route/resources "/") ; special route for serving static files like css
; default root directory is resources/public/
(route/not-found (slurp (io/resource "404.html")))) ; IDK what io/resource does
; you might not need it

Related

How do I edit Reitit routes in Reagent?

The routes created with the default reagent template look like this:
;; -------------------------
;; Routes
(def router
(reitit/router
[["/" :index]
["/items"
["" :items]
["/:item-id" :item]]
["/about" :about]]))
If I change the path of one ("/about" to "/test" below), why does it no longer work? There must be something else driving the routing, but I can't seem to figure out what.
;; -------------------------
;; Routes
(def router
(reitit/router
[["/" :index]
["/items"
["" :items]
["/:item-id" :item]]
["/test" :about]]))
This is the default reagent template (lein new reagent...) and I haven't changed anything else in the code. Any help would be greatly appreciated.
Edit - Some additional detail
I poked around in the repl a little bit in this function (from the default template):
(defn init! []
(clerk/initialize!)
(accountant/configure-navigation!
{:nav-handler
(fn [path]
(let [match (reitit/match-by-path router path)
current-page (:name (:data match))
route-params (:path-params match)]
(reagent/after-render clerk/after-render!)
(session/put! :route {:current-page (page-for current-page)
:route-params route-params})
(clerk/navigate-page! path)
))
:path-exists?
(fn [path]
(boolean (reitit/match-by-path router path)))})
(accountant/dispatch-current!)
(mount-root))
Everything looks ok to me. In fact, executing the below steps in the repl successfully navigated the browser to the correct page. I still can't enter the URL directly though.
app:problem.core=> (require '[reitit.frontend :as reitit])
nil
app:problem.core=> (reitit/match-by-path router "/test")
{:template "/test",
:data {:name :about},
:result nil,
:path-params {},
:path "/test",
:query-params {},
:parameters {:path {}, :query {}}}
app:problem.core=> (def match (reitit/match-by-path router "/test"))
#'problem.core/match
app:problem.core=> (:name (:data match))
:about
app:problem.core=> (:path-params match)
{}
app:problem.core=> (def current-page (:name (:data match)))
#'problem.core/current-page
app:problem.core=> (page-for current-page)
#'problem.core/about-page
app:problem.core=> (session/put! :route {:current-page (page-for current-page) :route-params {}})
{:route {:current-page #'problem.core/about-page, :route-params {}}}
app:problem.core=>
It looks like you changed the routes on client-side, in src/cljs/<project_name>/core.cljs, but did not change them server side in src/clj/<project_name>/handler.clj (look under the def app near the bottom of the file).
If your new to developing web applications with Clojure, I'd recommend looking at Luminus, rather than using the Reagent template. It's a much more batteries included-approach, with a lot more documentation. The book "Web Development With Clojure" is written by the same author (who is also a contributor to Reagent), and is also recommended reading.

How to use images in the resources folder in a re-frame, re-agent app?

I have an app created using Chestnut, and there's an image in the project in the location: resources/public/img.png.
I want to use this image in my app, but doing [:img {:src "public/img.png"}] or [:img {:src "./img.png"}] doesn't work. What's the correct src for the image in the resources folder?
The directory part resources/public is implicit. You need to access the file like:
(ns demo.core
(:require [clojure.java.io :as io]))
; something like this
(slurp (io/resource "img.png")) ; returns bytes from file
(io/stream (io/resource "img.png")) ; returns in InputStream for file
for example:
(ns tst.demo.core
(:use tupelo.core tupelo.test)
(:require [clojure.java.io :as io]))
(dotest
(let [bytes (slurp (io/resource "sample.json"))]
(spyx (count bytes))))
with result
(count bytes) => 72
Go to your project.clj file and search for figwheel settings. Make sure that :http-server-root is uncommented.
:figwheel {
:http-server-root "public" ;; serve static assets from resources/public/
...
}
Then [:img {:src "img.png" }] should work. And don't forget to restart figwheel.
I have not used Chestnut. I'm assuming there is a webserver running, whose root dir is resources/public. I'm presuming there is a index.html (or equivalent) in that folder. I further assume that the Hiccup you want is in that index.html file. Given all of the above, I'd try
[:img {:src "img.png"}]

DOM Control with ClojureScript and Enfocus - problem with lein cjsbuild auto

Hi I'm not an experienced developer and am working my way through this great book Living Clojure: An introduction and training plan for developers by Carin Meier
I'd appreciate your help with an issue I'm stuck on in Chapter 7 (Creating Web Applications with Clojure).
It's walked me through the following sections okay:
Creating a Web Server with Compojure
Using JSON with the Cheshire Library and Ring
Using Clojure in Your Browser with ClojureScript
Browser-Connected REPL
Making HTTP Calls with ClojureScript and cljs-http
But in the section...
DOM Control with ClojureScript and Enfocus...
...I've got to the middle of page 130, ("...Save your edits, and your cljsbuild will recompile your ClojureScript...") but the lein cjsbuild auto, which detects the changes, fails on the attempted compile.
These are the various files I've set up
project.clj
(defproject cheshire-cat "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url "http://example.com/FIXME"
:min-lein-version "2.0.0"
:dependencies [[org.clojure/clojure "1.10.0"]
[compojure "1.6.1"]
[ring/ring-defaults "0.3.2"]
[ring/ring-json "0.5.0"]
[org.clojure/clojurescript "1.10.597"]
[cljs-http "0.1.46"]
[org.clojure/core.async "0.5.527"]
[enfocus "2.1.1"]]
:plugins [[lein-ring "0.12.5"]
[lein-cljsbuild "1.1.7"]]
:ring {:handler cheshire-cat.handler/app}
:profiles
{:dev {:dependencies [[javax.servlet/servlet-api "2.5"]
[ring/ring-mock "0.4.0"]]}}
:cljsbuild {
:builds [{
:source-paths ["src-cljs"]
:compiler {
:output-to "resources/public/main.js"
:optimizations :whitespace
:pretty-print true}}]})
src / cheshire_cat / handler.clj
(ns cheshire-cat.handler
(:require [compojure.core :refer :all]
[compojure.route :as route]
[ring.middleware.defaults :refer [wrap-defaults site-defaults]]
[ring.middleware.json :as ring-json]
[ring.util.response :as rr]))
(defroutes app-routes
(GET "/" [] "Hello World")
(GET "/cheshire-cat" []
(rr/response {:name "Cheshire Cat" :status :grinning}))
(route/not-found "Not Found"))
(def app
(-> app-routes
(ring-json/wrap-json-response)
(wrap-defaults site-defaults)))
src-cljs / core.cljs
(ns cheshire-cat.core
(:require-macros [cljs.core.async.macros :refer [go]])
(:require [clojure.browser.repl :as repl]
[cljs-http.client :as http]
[cljs.core.async :refer [<!]]
[enfocus.core :as ef]))
(defn ^:export init []
(repl/connect "http://localhost:9000/repl")
(go
(let [response (<! (http/get "/cheshire-cat"))
body (:body response)]
(ef/at "#cat-name" (ef/content (:name body)))
(ef/at "#status" (ef/content (:status body))))))
resources / public / cat.html
<!DOCTYPE html>
<html>
<head>
<title>Cheshire Cat</title>
</head>
<body>
<div id="cat-name">Name</div>
<div id="status">Status</div>
<script type="text/javascript" src="main.js"></script>
<script type="text/javascript">cheshire_cat.core.init()</script>
</body>
</html>
Terminal
On one tab, I've started a server on port 3000 using lein ring server
Another tab is watching for changes before compiling ClojureScript using lein cljsbuild auto
It's here that I'm running into trouble. I'll paste the verbose response below. I tried adding a dependency of domina into the project.clj file, but that didn't help so I removed it again.
Many thanks in advance.
Garys-MacBook-Pro:cheshire-cat garyhudson$ lein cljsbuild auto
Watching for changes before compiling ClojureScript...
Compiling ["resources/public/main.js"] from ["src-cljs"]...
WARNING: domina is a single segment namespace at line 1 file:/Users/garyhudson/.m2/repository/domina/domina/1.0.3/domina-1.0.3.jar!/domina.cljs
WARNING: Protocol DomContent is overwriting function nodes in file file:/Users/garyhudson/.m2/repository/domina/domina/1.0.3/domina-1.0.3.jar!/domina.cljs
WARNING: Protocol DomContent is overwriting function single-node in file file:/Users/garyhudson/.m2/repository/domina/domina/1.0.3/domina-1.0.3.jar!/domina.cljs
WARNING: *debug* not declared dynamic and thus is not dynamically rebindable, but its name suggests otherwise. Please either indicate ^:dynamic *debug* or change the name at line 111 file:/Users/garyhudson/.m2/repository/domina/domina/1.0.3/domina-1.0.3.jar!/domina.cljs
WARNING: Use of undeclared Var goog.dom/query at line 15 file:/Users/garyhudson/.m2/repository/domina/domina/1.0.3/domina-1.0.3.jar!/domina/css.cljs
WARNING: Use of undeclared Var goog.dom/query at line 19 file:/Users/garyhudson/.m2/repository/domina/domina/1.0.3/domina-1.0.3.jar!/domina/css.cljs
Compiling ["resources/public/main.js"] failed.
clojure.lang.ExceptionInfo: failed compiling file:target/cljsbuild-compiler-0/enfocus/core.cljs
compiler.cljc:1717 cljs.compiler$compile_file$fn__3955.invoke
compiler.cljc:1677 cljs.compiler$compile_file.invokeStatic
compiler.cljc:1653 cljs.compiler$compile_file.invoke
closure.clj:653 cljs.closure/compile-file
closure.clj:631 cljs.closure/compile-file
closure.clj:727 cljs.closure/fn
closure.clj:721 cljs.closure/fn
closure.clj:549 cljs.closure/fn[fn]
closure.clj:700 cljs.closure/compile-from-jar
closure.clj:690 cljs.closure/compile-from-jar
closure.clj:737 cljs.closure/fn
closure.clj:721 cljs.closure/fn
closure.clj:549 cljs.closure/fn[fn]
closure.clj:1088 cljs.closure/compile-sources[fn]
LazySeq.java:42 clojure.lang.LazySeq.sval
LazySeq.java:51 clojure.lang.LazySeq.seq
Cons.java:39 clojure.lang.Cons.next
RT.java:709 clojure.lang.RT.next
core.clj:64 clojure.core/next
core.clj:3142 clojure.core/dorun
core.clj:3148 clojure.core/doall
core.clj:3148 clojure.core/doall
closure.clj:1084 cljs.closure/compile-sources
closure.clj:1073 cljs.closure/compile-sources
closure.clj:3012 cljs.closure/build
closure.clj:2920 cljs.closure/build
api.clj:208 cljs.build.api/build
api.clj:189 cljs.build.api/build
api.clj:195 cljs.build.api/build
api.clj:189 cljs.build.api/build
compiler.clj:61 cljsbuild.compiler/compile-cljs[fn]
compiler.clj:60 cljsbuild.compiler/compile-cljs
compiler.clj:48 cljsbuild.compiler/compile-cljs
compiler.clj:168 cljsbuild.compiler/run-compiler
compiler.clj:129 cljsbuild.compiler/run-compiler
form-init2776313306215562422.clj:1 user/eval838[fn]
form-init2776313306215562422.clj:1 user/eval838[fn]
LazySeq.java:42 clojure.lang.LazySeq.sval
LazySeq.java:51 clojure.lang.LazySeq.seq
RT.java:531 clojure.lang.RT.seq
core.clj:137 clojure.core/seq
core.clj:3133 clojure.core/dorun
core.clj:3148 clojure.core/doall
core.clj:3148 clojure.core/doall
form-init2776313306215562422.clj:1 user/eval838
form-init2776313306215562422.clj:1 user/eval838
Compiler.java:7176 clojure.lang.Compiler.eval
Compiler.java:7166 clojure.lang.Compiler.eval
Compiler.java:7635 clojure.lang.Compiler.load
Compiler.java:7573 clojure.lang.Compiler.loadFile
main.clj:452 clojure.main/load-script
main.clj:454 clojure.main/init-opt
main.clj:454 clojure.main/init-opt
main.clj:485 clojure.main/initialize
main.clj:519 clojure.main/null-opt
main.clj:516 clojure.main/null-opt
main.clj:598 clojure.main/main
main.clj:561 clojure.main/main
RestFn.java:137 clojure.lang.RestFn.applyTo
Var.java:705 clojure.lang.Var.applyTo
main.java:37 clojure.main.main
Caused by: clojure.lang.Compiler$CompilerException: Syntax error macroexpanding clojure.core/ns at (enfocus/macros.clj:1:1).
Compiler.java:6971 clojure.lang.Compiler.checkSpecs
Compiler.java:6987 clojure.lang.Compiler.macroexpand1
Compiler.java:7074 clojure.lang.Compiler.macroexpand
Compiler.java:7160 clojure.lang.Compiler.eval
Compiler.java:7635 clojure.lang.Compiler.load
RT.java:381 clojure.lang.RT.loadResourceScript
RT.java:372 clojure.lang.RT.loadResourceScript
RT.java:463 clojure.lang.RT.load
RT.java:428 clojure.lang.RT.load
core.clj:6126 clojure.core/load[fn]
core.clj:6125 clojure.core/load
core.clj:6109 clojure.core/load
RestFn.java:408 clojure.lang.RestFn.invoke
core.clj:5908 clojure.core/load-one
core.clj:5903 clojure.core/load-one
core.clj:5948 clojure.core/load-lib[fn]
core.clj:5947 clojure.core/load-lib
core.clj:5928 clojure.core/load-lib
RestFn.java:142 clojure.lang.RestFn.applyTo
core.clj:667 clojure.core/apply
core.clj:5985 clojure.core/load-libs
core.clj:5969 clojure.core/load-libs
RestFn.java:137 clojure.lang.RestFn.applyTo
core.clj:667 clojure.core/apply
core.clj:6007 clojure.core/require
core.clj:6007 clojure.core/require
RestFn.java:408 clojure.lang.RestFn.invoke
analyzer.cljc:4106 cljs.analyzer$ns_side_effects$fn__2653.invoke
analyzer.cljc:4105 cljs.analyzer$ns_side_effects.invokeStatic
analyzer.cljc:4077 cljs.analyzer$ns_side_effects.invoke
analyzer.cljc:4201 cljs.analyzer$analyze_STAR_$fn__2706.invoke
PersistentVector.java:343 clojure.lang.PersistentVector.reduce
core.clj:6827 clojure.core/reduce
core.clj:6810 clojure.core/reduce
analyzer.cljc:4201 cljs.analyzer$analyze_STAR_.invokeStatic
analyzer.cljc:4191 cljs.analyzer$analyze_STAR_.invoke
analyzer.cljc:4220 cljs.analyzer$analyze.invokeStatic
analyzer.cljc:4203 cljs.analyzer$analyze.invoke
compiler.cljc:1535 cljs.compiler$emit_source.invokeStatic
compiler.cljc:1508 cljs.compiler$emit_source.invoke
compiler.cljc:1620 cljs.compiler$compile_file_STAR_$fn__3924.invoke
compiler.cljc:1428 cljs.compiler$with_core_cljs.invokeStatic
compiler.cljc:1417 cljs.compiler$with_core_cljs.invoke
compiler.cljc:1604 cljs.compiler$compile_file_STAR_.invokeStatic
compiler.cljc:1597 cljs.compiler$compile_file_STAR_.invoke
compiler.cljc:1702 cljs.compiler$compile_file$fn__3955.invoke
Caused by: clojure.lang.ExceptionInfo: Call to clojure.core/ns did not conform to spec.
alpha.clj:705 clojure.spec.alpha/macroexpand-check
alpha.clj:697 clojure.spec.alpha/macroexpand-check
AFn.java:156 clojure.lang.AFn.applyToHelper
AFn.java:144 clojure.lang.AFn.applyTo
Var.java:705 clojure.lang.Var.applyTo
Compiler.java:6969 clojure.lang.Compiler.checkSpecs
Here is the clue you need:
Caused by: clojure.lang.Compiler$CompilerException: Syntax error
macroexpanding clojure.core/ns at (enfocus/macros.clj:1:1).
....
Caused by: clojure.lang.ExceptionInfo: Call to clojure.core/ns did
not conform to spec.
So it is a problem in the enfocus library, not your code.
IMHO the enfocus library is a bit old these days. I think you would be better served using the figwheel.main lib for the CLJS code: https://figwheel.org/
Note that this is basically Figwheel 2.0, but under a new name. It is much better than the original Figwheel.
Go through the tutorial at figwheel.org, and build your CLJS code in a separate project directory from your back-end code.
Also, be sure to use the Clojure CLI/Deps to build the CLJS project (i.e. not Leiningen). CLI/Deps is much easier to use for ClojureScript projects than Leiningen.
https://clojure.org/guides/deps_and_cli
https://clojure.org/reference/deps_and_cli

Animate antizer table with rc-animate in re-frame app

I am trying to recreate the example in http://react-component.github.io/table/examples/animation.html to add animation to a table in a re-frame app. The table is rendered using antizer which is a ClojureScript library for Ant Design react components. For the animation I'm trying to use rc-animate (as in the example) which is a JavaScript library.
To integrate rc-animate, I followed the official Webpack guide and created a src/js/index.js file:
import Animate from 'rc-animate';
window.Animate = Animate;
My project.clj is:
(defproject ant-table-animation "0.1.0-SNAPSHOT"
:dependencies [[org.clojure/clojure "1.8.0"]
[org.clojure/clojurescript "1.10.238"]
[reagent "0.8.1"]
[re-frame "0.10.5" :exclusions [reagent]]
[antizer "0.3.1"]]
:plugins [[lein-cljsbuild "1.1.7"]]
:min-lein-version "2.5.3"
:source-paths ["src/clj" "src/cljs"]
:clean-targets ^{:protect false} ["resources/public/js/compiled" "target"]
:figwheel {:css-dirs ["resources/public/css"]}
:profiles
{:dev
{:dependencies [[binaryage/devtools "0.9.10"]
[cider/piggieback "0.3.9"]
[figwheel-sidecar "0.5.16"]
[day8.re-frame/re-frame-10x "0.3.3"]]
:plugins [[lein-figwheel "0.5.16"]]}
:prod { }
}
:cljsbuild
{:builds
[{:id "dev"
:source-paths ["src/cljs"]
:figwheel {:on-jsload "ant-table-animation.core/mount-root"}
:compiler {:closure-defines {re-frame.trace.trace_enabled_QMARK_ true}
:main ant-table-animation.core
:output-to "resources/public/js/compiled/app.js"
:output-dir "resources/public/js/compiled/out"
:asset-path "js/compiled/out"
:source-map-timestamp true
:preloads [devtools.preload, day8.re-frame-10x.preload]
:external-config {:devtools/config {:features-to-install :all}}
:infer-externs true
:npm-deps false
:foreign-libs [{:file "dist/index_bundle.js"
:provides ["rc-animate" "rc-animate-child"]
:global-exports {rc-animate Animate
rc-animate-child AnimateChild}}]
}}
{:id "min"
:source-paths ["src/cljs"]
:compiler {:main ant-table-animation.core
:output-to "resources/public/js/compiled/app.js"
:optimizations :advanced
:closure-defines {goog.DEBUG false}
:pretty-print false}}
]}
)
and in my views.cljs I try to render the table like this:
(ns ant-table-animation.views
(:require
[re-frame.core :as re-frame]
[ant-table-animation.subs :as subs]
[ant-table-animation.events :as events]
[antizer.reagent :as ant]
[reagent.core :as reagent]
[rc-animate]
))
(.log js/console rc-animate)
(defn AnimateBody
[props]
(.createElement
js/React
rc-animate
(.assign js/Object #js {:transitionName "move", :component "tbody"} props)))
(.log js/console AnimateBody)
(defn orders
[]
(let [orders #(re-frame/subscribe [::subs/orders])
width 80]
[ant/table
{:columns
[{:title "Product Name" :dataIndex :product :width width}
{:title "Quantity" :dataIndex :quantity :width width}
{:title "Unit Price" :dataIndex :price :width width}
{:title "Actions" :dataIndex "actions" :width width
:render
#(reagent/as-element
[ant/button
{:icon "delete" :type "danger"
:on-click
(fn []
(re-frame/dispatch [::events/order-deleted (.-product %2)]))}])}]
:dataSource orders
:size "small"
:components {:body {:wrapper AnimateBody}}
:pagination {:page-size 20}
:scroll {:y 300}}]))
(defn main-panel []
(let [name (re-frame/subscribe [::subs/name])]
[:div
[:h1 "Hello from " #name]
[orders]
]))
I am not sure at all about the
(defn AnimateBody
[props]
(.createElement
js/React
rc-animate
(.assign js/Object #js {:transitionName "move", :component "tbody"} props)))
being equivalent to the line from the example
const AnimateBody = props => <Animate transitionName="move" component="tbody" {...props} />;
The table renders correctly, but when I try to delete a row it fails with the following error trace:
react-dom.development.js:55 Uncaught Error: Unable to find node on an unmounted component.
at invariant (react-dom.development.js:55)
at findCurrentFiberUsingSlowPath (react-dom.development.js:4256)
at findCurrentHostFiber (react-dom.development.js:4266)
at findHostInstance (react-dom.development.js:17676)
at Object.findDOMNode (react-dom.development.js:18145)
at AnimateChild.transition (AnimateChild.js:83)
at AnimateChild.componentWillLeave (AnimateChild.js:70)
at performLeave (Animate.js:339)
at Array.forEach (<anonymous>)
at Animate.componentDidUpdate (Animate.js:188)
at commitLifeCycles (react-dom.inc.js:15386)
at commitAllLifeCycles (react-dom.inc.js:16646)
at HTMLUnknownElement.callCallback (react-dom.inc.js:143)
at Object.invokeGuardedCallbackDev (react-dom.inc.js:193)
at invokeGuardedCallback (react-dom.inc.js:250)
at commitRoot (react-dom.inc.js:16800)
at completeRoot (react-dom.inc.js:18192)
at performWorkOnRoot (react-dom.inc.js:18120)
at performWork (react-dom.inc.js:18024)
at performSyncWork (react-dom.inc.js:17996)
at requestWork (react-dom.inc.js:17884)
at scheduleWork (react-dom.inc.js:17689)
at Object.enqueueForceUpdate (react-dom.inc.js:11855)
at Object.Component.forceUpdate (react.inc.js:479)
at reagent$impl$batching$run_queue (batching.cljs?rel=1541330682770:39)
at Object.flush_queues (batching.cljs?rel=1541330682770:86)
at Object.run_queues (batching.cljs?rel=1541330682770:76)
at batching.cljs?rel=1541330682770:63
at re_frame_10x.cljs?rel=1541164419576:125
It is also indicated that:
The above error occurred in the <Animate> component:
in Animate (created by ant_table_animation.views.animateBody)
in ant_table_animation.views.animateBody (created by BaseTable)
in table (created by BaseTable)
in BaseTable (created by Connect(BaseTable))
in Connect(BaseTable) (created by BodyTable)
in div (created by BodyTable)
in BodyTable (created by ExpandableTable)
in div (created by ExpandableTable)
in div (created by ExpandableTable)
in div (created by ExpandableTable)
in ExpandableTable (created by Connect(ExpandableTable))
in Connect(ExpandableTable) (created by Table)
in Provider (created by Table)
in Table (created by LocaleReceiver)
in LocaleReceiver (created by Table)
in div (created by Spin)
in AnimateChild (created by Animate)
in div (created by Animate)
in Animate (created by Spin)
in Spin (created by Table)
in div (created by Table)
in Table (created by ant_table_animation.views.orders)
in ant_table_animation.views.orders (created by ant_table_animation.views.main_panel)
in div (created by ant_table_animation.views.main_panel)
in ant_table_animation.views.main_panel
I am a Clojure beginner, and I know even less for React; this is where I ended up after a week of trying but now I feel stuck. I have uploaded my project in github for anyone that would like to give it a try.
The Unable to find node on an unmounted component error was occurring because of version issues with React. I was able to handle it by explicitly using the version of React used by the rc-animate library - 16.5.2 in my project.clj:
...
[reagent "0.8.1" :exclusions [cljsjs/react cljsjs/react-dom [cljsjs/react-dom-server]]]
[cljsjs/react "16.5.2-0"]
[cljsjs/react-dom "16.5.2-0"]
[cljsjs/react-dom-server "16.5.2-0"]
...
[antizer "0.3.1" :exclusions [cljsjs/react cljsjs/react-dom [cljsjs/react-dom-server]]]]
...
For the correct definition of the AnimateBody component I had to use a combination of reagent/adapt-react-class, reagent/as-element and reagent/reactify-component.
Specifically, in my views.cljs I define the component as:
(def animate (reagent/adapt-react-class rc-animate))
(def animateBody
(fn [props]
(reagent/as-element [animate (assoc props :transition-name "move" :component "tbody")])))
and then pass it to the ant/table component with:
...
:components {:body {:wrapper (reagent/reactify-component animateBody)}}
...

Clojurescript react-leaflet does not display tiles properly

I am trying to use react-leaflet from ClojureScript but I have problem with the way tiles render:
some tiles do not display
there are tile showing next to each other in different cities
Here is the code I have:
(ns carder-devcards.map
(:require [taoensso.timbre :as timbre]
[cljsjs.react-leaflet] ;; js/ReactLeaflet
)
(:require-macros [devcards.core :as dc :refer [defcard]]))
(defn build
([component props]
(build component props (array)))
([component props & children]
(.createElement js/React
component
(clj->js props)
(array children))))
(def tile-layer (partial build js/ReactLeaflet.TileLayer))
(def leaflet-map (partial build js/ReactLeaflet.Map))
(def marker (partial build js/ReactLeaflet.Marker))
(def popup (partial build js/ReactLeaflet.Popup))
(defcard simple-leaflet
(fn [state]
(let [{:keys [pos zoom] :as st} #state
tl (tile-layer {:url "http://{s}.tile.osm.org/{z}/{x}/{y}.png"
:attribution "© OpenStreetMap contributors"})
mk (marker {:position pos})]
(leaflet-map {:center pos :zoom zoom}
tl
mk
)))
{:pos [51.505, -0.09]
:zoom 13}
{:header true})
And here is the result I have locally.
Note: resizing the browser seems to have an effect, so this could be a css problem as well (?). I have tried including the following without effect:
.leaflet-container {
height: 400px;
width: 100%;
}
The answer from #Chris Murphy set me up on the right track since I had the same error with it.
It turns out I was missing the css files of leaflet.js, including them resolved my problem.
Just posting my own very simple first cut leaflet on the off chance that it helps:
(def URL-OSM "http://{s}.tile.osm.org/{z}/{x}/{y}.png")
(defn create-map []
(let [m (-> js/L
(.map "mapid2")
(.setView (array -33.8675 151.2070) 9)) ;; Sidney
tile1 (-> js/L (.tileLayer URL-OSM
#js{:maxZoom 16
:attribution "OOGIS RL, OpenStreetMap ©"}))
base (clj->js {"OpenStreetMap" tile1})
ctrl (-> js/L (.control.layers base nil))]
(.addTo tile1 m)
(.addTo ctrl m)))
I am using [cljsjs/leaflet "0.7.7-4"].
Edit
And here's a leaflet-centric version of the markup:
(hiccup/html
[:head
[:meta {:charset "UTF-8"}]
[:meta {:name "viewport" :content "width=device-width, initial-scale=1"}]
[:link {:rel "stylesheet" :href "http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css" :type "text/css"}]
[:script {:src "http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.js" :charset "utf-8"}]
[:body
[:div {:id "mapid"}]
[:div {:id "main-app-area"}]
[:script {:src "/reconnect/js/main.js" :type "text/javascript"}]])