Realtime React Coding in ClojureScript [Autumn 2022 Remix]
I love ClojureScript. The language, the look, the feeling when I type the code to make my React components with it, makes me stay up all night. It actually did yesterday when I try to pick up on a friend setup and get back a modern environment to do my coding. Let’s walk through the first few steps to get to a setup with a React counter in ClojureScript, all this with live code reloading from VSCode. Most Clojure people are veterans coders, and are mostly using emacs to get their job done. I am going to present a setup with VSCode and the minimal setup for coding at ease with it. Setup VSCode with Clava Clava requires clojure-lsp to be installed on your machine, and the installation process is described here. As a side note, to make things smooth, (and avoid this) I had to have npx installed globally: npm install -g npx --force Setup a new project with shadow-cljs Shadow CLJS User’s Guide will be at the core of this setup. I just picked it up yesterday thanks to my dear friend Tokoma, and I just love its speed, ease of use, and its full integration with the standard npm world. Supposing you have npx installed, if not let’s do it. npm install -g npx We will start by creating a new acme app, in the same fashion as the tutorial fromshadow-cljs: npx create-cljs-project acme-app I was a bit taken aback, this new generated app comes with the default setup, but: no build instruction no ClojureScript code whatsoever So you do have REPLs ready to run with: npx shadow-cljs node-repl # or npx shadow-cljs browser-repl But not much else. What we do have, is a set of files with the following structure (only keeping important files): . ├── package.json ├── package-lock.json ├── shadow-cljs.edn └── src ├── main └── test The file package.json from the standard nodejs world only contains a dev dependency to the Javascript part of ShadowCLJS: { "name": "bunny-app", "version": "0.0.1", "private": true, "devDependencies": { "shadow-cljs": "2.20.1" } } The second important file is the shadow-cljs.edn file, which is an EDN based the configuration used by shadow to do its magic, and at generation time its pretty bare: ;; shadow-cljs configuration {:source-paths ["src/dev" "src/main" "src/test"] :dependencies [] :builds {} So, first of all, we want to host an index.html file to do our javascript coding. We will: put it in public/index.html with some bare content, and we will add a reference to jsmain.js main.js is the file that will be generated from our ClojureScript code in a few seconds. Here is the source for HTML file. We need some ClojureScript code to get going, so in the file, srcmainacmefrontendapp.cljs: mkdir -p src/main/bunny/frontend touch src/main/bunny/frontend/app.cljs Let’s write some basic Clojure code: (ns bunny.frontend.app) (defn init [] (println "Hello Bunny")) We then update the :builds section of the shadow-cljs.edn file with: {:frontend {:target :browser :modules {:main {:init-fn acme.frontend.app/init} } There are multiple :target available: Supporting various targets :browser, :node-script, :npm-module, :react-native, :chrome-extension, ... We will use browser for now, and the to-be-compiled module’s function will be the init function in the ClojureScript file we just wrote above. We are ready, so let’s run the magic command: npx shadow-cljs watch frontend See that frontend is the build definition we wrote in shadow-cljs.edn, so make sure to use that in the watch command above. Ah … but we need something to host and make the files in the public folder available via a web server. Let’s go back to the shadow-cljs.edn file, and add: { ;... :dev-http {8080 "public"} ;... } Then we can head to: http://localhost:8080 And open the browser console to see our bunny showing up in the browser's console: It would be nice, if when saving the ClojureScript file, we could reload the code dynamically, and one way to do this is via annotations on functions. See how ^:devbefore-load/ and ^:devafter-load/ are being used. (defn init [] (println "Hello Bunny")) (defn ^:dev/before-load stop [] (js/console.log "stop")) (defn ^:dev/after-load start [] (js/console.log "start") (init)) Now saving the ClojureScript file, will automatically reload code triggered by the init function, and so we now have two rabbits in the console: Some raw DOM manipulation We will see later how to play with React, but for now, let’s see how we can simply add a rabbit picture in our HTML file. Basically, we would like to achieve the equivalent of the below JavaScript code: const img = document.createElement ("img"); img.src = "/bunny-512.webp"; document.body.appendChild (img); And providing, you have the bunny.webp picture in the public folder, the code below would work: (defn init [] (let [img (doto (.createElement js/document "img") (set! -src "/bunny-512.webp") (set! -height 64) (set! -width 64))] (.appendChild (.getElementById js/document "app") img))) It’s just a tad laborious to revert to using directly set! for setting properties on a dom element, so in a separate bunny.frontend.utils namespace, let’s create two convenient functions: (ns bunny.frontend.utils) (defn set-props [o property-map] (doseq [[k v] property-map] (.setAttribute o (name k) v))) (defn create-el [tag-name property-map] (let [el (.createElement js/document tag-name)] (set-props el property-map) el)) And let’s use that namespace from the main app namespace: (ns bunny.frontend.app (:require [acme.frontend.utils :as u])) (defn init [] (println “Init”) (let [img (u/create-el "img" {:src "/bunny-512.webp" :height 128 :width 128})] (.appendChild (.getElementById js/document "app") img))) And you should see a nice little rabbit. Of course, you can play with the :height and :width keys in the properties map, and see a new image bigger or smaller appearing in your browser. Going React These days, directly manipulating the DOM does feel a bit like cracking eggs with a hammer. Let’s see how we can use React, first without a ClojureScript wrapper, just the plain npm package. At the time of writing I had some glitches later on with React v18+Reagent, so let’s stick to version 17 for this article with: npm install react@17.0.2 react-dom@17.0.2 The package.json file should now have those dependencies included: { "name": "bunny-app", "version": "0.0.1", "private": true, "devDependencies": { "shadow-cljs": "2.20.1" }, "dependencies": { "react": "^17.0.2", "react-dom": "^17.0.2" } } Those are not ClojureScript dependencies, so we do not have to update the :dependencies section of the shadow-cljs.edn file. (It stays the same). Now on to our ClojureScript code, note that we can have shortcuts when including the js dependencies straight in the :require section of the namespace. (ns bunny.frontend.app3 (:require ["react" :as react] ["react-dom" :as dom])) (defn init [] (dom/render (react/createElement "h2" nil (str "Hello, Bunny ")) (.getElementById js/document "app"))) The rest is pretty standard ClojureScript interop code, so we will leave the reader to scrutinise the three lines of code. The rendering works as expected, and you can check that adding more bunnies in our h2 component does the job and bunnies are multiplying like crazy. Adding a ClojureScript library I often find my self needing a time library somehow, just to be sure on timezone, and other leap years problems. Before moving on to using ClojureScript’s Reagent, let’s see how we can add it to our shadow-cljs project setup. The dependency cljs-time itself is defined as: [com.andrewmcveigh/cljs-time "0.5.2"] And we include it in the shadow-cljs.edn file as shown below: { ;... :dependencies [[com.andrewmcveigh/cljs-time "0.5.2"]] ;... } You’ll need to restart the watch command for this dependency to be actually picked up by the compiler. npx shadow-cljs watch frontend Then on to our updated React code with the cljs-time ClojureScript library, where we get the current date, to which we add one month and three weeks. (ns bunny.frontend.app4 (:require [cljs-time.core :as t :refer [plus months weeks]]) (:require ["react" :as react] ["react-dom" :as dom])) (defn init [] (dom/render (react/createElement "h2" nil (str "Hello, Bunny" (plus (t/now) (months 1) (weeks 3)))) (.getElementById js/document "app"))) And the equivalent rendered html in the browser: Does the job ! Easy coding with Reagent Reagent provides ClojureScripts like easy to use constructs around the React framework. As with did with the cljs-time library, we will first add the reagent library to the shadow-cljs.edn file, so with the changes from before that gives: { ;... :dependencies [[com.andrewmcveigh/cljs-time "0.5.2"][reagent "1.1.1"]] ;... } We will make a simple counter, the code is directly taken from cljs-counter updated to work with the latest reagent: (ns bunny.frontend.app5 (:require [reagent.core :as r][reagent.dom :as d])) (defonce state (r/atom {:model 0})) (defn increment [] (swap! state update :model inc)) (defn decrement [] (swap! state update :model dec)) (defn main [] [:div {:style “float:left;”} [:button {:on-click decrement} “-“] [:div (:model @state)] [:button {:on-click increment} “+”]]) (defn init [] (d/render [main] (.getElementById js/document “app”))) It does not look support sexy, but with just a bit of efforts, and more Reagentism we can do the below: (ns bunny.frontend.app5 (:require [clojure.string :as str]) (:require [reagent.core :as r][reagent.dom :as d])) (defonce state (r/atom {:model 0})) (defn increment [] (swap! state update :model inc)) (defn decrement [] (swap! state update :model dec)) (defn n-to-image[idx n] [:img {:key idx :src (str "/img/nums/" n ".png")}]) (defn counter[] (let [m (:model @state) m-as-characters (rest (str/split (str m) #""))] [:span (map-indexed n-to-image m-as-characters)])) (defn button [display fn] [:button {:style {:background-color "white"} :on-click fn} [:img {:src (str "/img/nums/" display "-key.png")}]] ) (defn main [] [:div (button "minus" decrement) (counter) (button "plus" increment)]) (defn init [] (d/render [main] (.getElementById js/document "app"))) And we icons downloaded from icon8 we now get something like the counter below: Advanced coding with Reagent The last example in this article shows how to (ns bunny.frontend.app6 (:require [reagent.core :as reagent] [reagent.dom :as dom])) (defonce app-state (reagent/atom {:seconds-elapsed 0})) (defn set-timeout! [ratom] (js/setTimeout #(swap! ratom update :seconds-elapsed inc) 1000)) (defn timer-render [ratom] (let [seconds-elapsed (:seconds-elapsed @ratom)] [:div "Seconds Elapsed: " seconds-elapsed])) (defn timer-component [ratom] (reagent/create-class {:reagent-render #(timer-render ratom) :component-did-mount #(set-timeout! ratom) :component-did-update #(set-timeout! ratom)})) (defn render! [] (dom/render [timer-component app-state] (.getElementById js/document "app"))) (defn init [] (render!)) And this gives the dynamically refreshing page below: We leave that to the reader to style this using the icon set from icon8 here again. Jack-in with Clava There’s just a little bit too much to know if we go in the details, so to finish this article we will just have a look at how to jack-in and code directly in the browser using Clava. To make sure we understand what is happening, let’s comment out the render! Call in the init function of our example with Reagent. (defn init [] (println "init") ;; (render!) ) Now let’s start a coding session via a browser REPL created from within VisualCode/Calva. If you have visual code and look at the bottom, you can see a greyed-out REPL icon, let’s click on it and open a new REPL session to the browser, using shadow-cljs. Or you can do this access the command “Start a project REPL”: Our whole setup is done via shadow-cljs so we will use that, but note that you have other REPL options: And we will select the build defined in the shadow-cljs.edn file: And the build kicks in ! At this stage, you have a ClojureScript REPL for the browser: but this REPL is not yet connected to the browser, so refresh the page in your browser. Let’s play with our newly created REPL and look at the effect in the browser . First, let’s execute a simple print statement from the REPL: And see that this actually translates immediately in the browser: Now, let’s try to render our reagent component as well. Notice, that we start in the wrong namespace so we will change that first, and for more impact we will update the internal timer contained in the app-state before rendering our reagent component. So at the REPL let’s write the commands below one by one: (ns bunny.frontend.app6) (swap! app-state update :seconds-elapsed #(+ % 100)) (render!) At the REPL at a glance that gives: And now we notice our browser started the reagent timer directly from 100. Voila. Summary In this article we briefly covered the basic for ClojureScript coding with VisualStudio Code, Shadow-cljs, Reagent, and Clava. We started by settings up the project, then moving on to pure coding from within ClojureScript. We then moved to perform interacting coding on Reagent components using Clava Jack-in facilities. Resources ClojureScript Cheatsheet Shadow-cljs user guide cljs-time infer-externs React Counter Further Readings Clojurescript Reagent Image-Previewing Selector | Tech.ToryAnderson.com Cropping images in ClojureScript. Displaying images in CSS is always a… | by Bingen Galartza Iparragirre | magnet.coop | Medium Wave Function Collapse Algorithm in ClojureScript · Andrey Listopadov Learn ClojureScript | Learn ClojureScript GitHub - tolitius/mount: managing Clojure and ClojureScript app state since (reset)
September 27, 2022
by Nicolas Modrzyk
·
4,050 Views
·
1 Like