Contents

ClojureScript [Autumn 2022 Remix]

Contents

This has been re-published on dzone

Realtime React Coding in ClojureScript

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.

/cljs/B2C18A35-A4FE-47B6-BF5B-B185A2D79942.png

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 _js_main.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.

<!doctype html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>bunny frontend</title>
  </head>
  <body>
    <div id="app"></div>
    <script src="/js/main.js"></script>
  </body>
</html>

We need some ClojureScript code to get going, so in the file, src_main_acme_frontend_app.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:

/cljs/14915A91-53ED-4A9E-BCEF-38F727A82BF4.png

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 _^:dev_before-load/ and _^:dev_after-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:

/cljs/04B0D421-C8B9-4E2C-8A03-E71D1258F9C5.png

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.

/cljs/4BC9C3AD-5D7F-411F-A9AA-C90423B4F42A.png

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.

/cljs/E5D5E194-19F7-4432-ACD0-7631A65ED56A.png

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.

/cljs/05A028FD-965B-416A-911F-754242D4BE11.png

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:

/cljs/2898206B-430A-423F-A1B6-E3C4ED0820FD.png

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:

/cljs/0F659F2D-9A92-4CC6-88A2-7A160D0E90CE.png

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:

/cljs/F68AE59C-1A80-420F-BA2A-BE781F39F810.png

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.

/cljs/3B730FB1-7F06-4240-8180-5864F2179D26.png

Or you can do this access the command “Start a project REPL”: /cljs/37F7F6E4-BA2F-48C8-BCC8-23455F096928.png

/cljs/B86C4FAD-91AD-4421-9087-6A8A05A28C2E.png

/cljs/D5899793-93E9-4216-8969-435E97005AC3.png

/cljs/898A6DC9-CDAB-488A-A0AD-3F096D130B90.png

/cljs/1A91A009-62D6-4840-BE29-AF61244579FD.png

At this stage, you have a ClojureScript REPL for the browser:

/cljs/5857D753-BBC0-4DFD-98BA-2BB3DFC2CE4F.png

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:

/cljs/201B605E-9AF9-4754-9534-FB974D3DC32A.png

And see that this actually translates immediately in the browser:

/cljs/0532B19B-16C9-4F3C-895E-ECECDF166EEE.png

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:

/cljs/68EF9E92-D83B-407A-9ABD-673B24406EDF.png

And now we notice our browser started the reagent timer directly from 100.

/cljs/2A128220-60B7-47EC-B741-7750CFBB39F6.png

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 React coding from within ClojureScript.

We then moved to perform interacting coding on Reagent components using Clava Jack-in facilities.

Resources

Further Readings

#articles #articles/shadowcljs