Scittlecastr: Stylish and eventful

Laughing Arab woman with curly hairstyle listening to defn in front of on orange wall

This post was entirely written by a human, with no assistance from LLMs or other "AI" technology such as pervert glasses or autonomous weapon systems. The photo is Laughing Arab woman with curly hairstyle using phone and headphones in front of on orange wall by Javier Sanchez Mingorance.

When last we left our REPL in Scittlecastr: All You Need is Persistence, built a nice podcast player interactively, then created a persistence mechanism so we can safely reload the page, and felt good about ourselves for roughly 2.5 seconds before our fingers got itchy to implement some new features.

But first, enjoy the

Table of contents

  1. I've got a need for speed - replacing the playback speed button with a nice speed control
  2. Go Speed Racer Go! - making the speed control work, but then realising that event listeners are a pain
  3. The state and evolution - keeping track of event listeners in the state atom
  4. There's no activity like interactivity - selectively updating event listeners
  5. This is the makeover - styling the new speed control
  6. Hey kid, I like your style - handling CSS pseudo-elements with style elements
  7. The return of Art Vandelay - combining style elements and inline styles when exporting CSS
  8. Never trust Mary Poppins - dealing with promises
  9. Awaiting for Godot - using async / await

Alright, let's get going!

I've got a need for speed

First among those features shall be the ability to actually set the playback speed by clicking the playback speed button, which at the moment simply taunts us in the browser console when we click it:

Handling click on                                                  nrepl.cljs:10
  β€£ <button aria-label="Playback speed" id="button-speed" class="cljcastr playback-button">…</button>
  β€£ PointerEvent {isTrusted: true, pointerId: 1, width: 1, height: 1, pressure: 0, …}
No event handler function defined
> 

Bummer!

Let's start by stealing taking some inspiration from the Overcast web player:

Overcast podcast player

If we inspect the speed control in the browser dev tools, we see some HTML that looks like this:

<div id="speedcontrols">
  <label class="speedmenu" title="Playback speed">
    <img src="/img/symbols/gauge.with.dots.needle.33percent.svg" alt="" draggable="false">
    <select id="speedselect" aria-label="Playback speed">
      <option value="750">0.75Γ—</option>
      <option value="0" selected="">1Γ—</option>
      <option value="1250">1.25Γ—</option>
      <option value="1500">1.5Γ—</option>
      <option value="1750">1.75Γ—</option>
      <option value="2000">2Γ—</option>
      <option value="2500">2.5Γ—</option>
      <option value="3000">3Γ—</option>
    </select>
  </label>
</div>

Let's see what the HTML for our own speed control looks like at this point:

(comment

  ;; ...

  (el->html "#button-speed")
  ;; => "<button aria-label=\"Playback speed\" id=\"button-speed\" class=\"cljcastr playback-button\">\n
  ;;       <img src=\"https://www.svgrepo.com/show/151785/speed-meter.svg\" draggable=\"false\" id=\"button-speed-icon\" class=\"cljcastr playback-icon\"></img>\n
  ;;     </button>\n"

  )

Hrm, that's a little different, innit?

Let's transform our speed button into something more akin to this awesomeness. To do this, we can create a new div, pop a label in there, use the same image as we already are for our button, and add a select with some speed options:

(comment

  ;; ...

  (def speed-control
    (-> (create-el
         {:tag "div", :id "speed-control", :classes ["cljcastr"]
          :children
          [(create-el
            {:tag "label", :id "speed-menu", :classes ["cljcastr"]
             :attrs {:title "Playback speed"}
             :children
             [(get-el "#button-speed-icon")
              (create-el
               {:tag "select", :id "speed-select", :classes ["cljcastr"]
                :attrs {:aria-label "Playback speed"}
                :children
                (->> [0.75 1 1.25 1.5 2]
                     (map (fn [speed]
                            (create-el {:tag "option"
                                        :classes ["cljcastr"]
                                        :text (str speed "x")
                                        :attrs (merge {:value (js/parseFloat speed)}
                                                      (when (= 1 speed)
                                                        {:selected true}))}))))})]})]})
        log))
  ;; => #'cljcastr.player/speed-control

  )

This looks pretty awesome in the console:

<div id=​"speed-control" class=​"cljcastr">​
  <label title=​"Playback speed" id=​"speed-menu" class=​"cljcastr">​
    <img src=​"https:​/​/​www.svgrepo.com/​show/​151785/​speed-meter.svg" 
      draggable=​"false" id=​"button-speed-icon" class=​"cljcastr playback-icon">​
    <select aria-label=​"Playback speed" id=​"speed-select" class=​"cljcastr">​
      <option value=​"0.75">​0.75x​</option>​
      <option value=​"1">​1x​</option>​
      <option value=​"1.25">​1.25x​</option>​
      <option value=​"1.5">​1.5x​</option>​
      <option value=​"2">​2x​</option>​
    </select>​
  </label>
​</div>​

However, our speed button seems to have disappeared from the page! Worse yet, if we inspect the DOM, we find that the enclosing button element is still there, just without its img child. 😱

This is because a node can only exist in the DOM once, and when we made img#button-speed-icon a child of the speed label, that removed it as a child of button#button-speed. 😭

Let's reload the page to return to a pristine copy of our player, then create a nice little helper function to make a copy of a node:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn create-el ...)

(defn clone-el
  "Returns a copy of the specified element. A map of overrides may also be
   specified, with the same keys as `create-el`."
  ([el]
   (clone-el el {}))
  ([el overrides]
   (-> (el->clj el)
       (merge overrides)
       create-el)))

;; (defn add-event-listener! ...)
;; ...

(comment

  ;; ...

  (-> (clone-el "#button-speed-icon")
      log)
  ;; => #object[HTMLImageElement [object HTMLImageElement]]

  (= (get-el "#button-speed-icon")
     (clone-el "#button-speed-icon"))
  ;; => false

  )

Cool! Let's try constructing the speed control again:

(comment

  ;; ...

  (def speed-control
    (-> (create-el
         {:tag "div", :id "speed-control", :classes ["cljcastr"]
          :children
          [(create-el
            {:tag "label", :id "speed-menu", :classes ["cljcastr"]
             :attrs {:title "Playback speed"}
             :children
             [(clone-el "#button-speed-icon")
              (create-el
               {:tag "select", :id "speed-select", :classes ["cljcastr"]
                :attrs {:aria-label "Playback speed"}
                :children
                (->> [0.75 1 1.25 1.5 2]
                     (map (fn [speed]
                            (create-el {:tag "option"
                                        :classes ["cljcastr"]
                                        :text (str speed "x")
                                        :attrs (merge {:value (js/parseFloat speed)}
                                                      (when (= 1 speed)
                                                        {:selected true}))}))))})]})]})
        log))
  ;; => #'cljcastr.player/speed-control

  )

This time, our speed button doesn't disappear! πŸŽ‰

Let's go ahead and add the speed control to the playback-controls div:

(comment

  ;; ...

  (add-child! "#playback-controls" speed-control)
  ;; => #object[HTMLDivElement [object HTMLDivElement]]

  )

Our player, with a very ugly speed select

Still, ugly as this is, it's like there or whatever, so let's remove the old speed button:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn add-child! ...)

(defn remove-child!
  "Removes the specified element from the DOM, returning it. A parent node may
   also be specified, for example to disambiguate the selector for a child
   element."
  ([el]
   (let [child (get-el el)]
     (remove-child! (.-parentNode child) child)))
  ([parent child]
   (-> (get-el parent)
       (.removeChild (get-el child)))))

;; (defn clear-children! ...)
;; ...

(comment

  ;; ...

  (remove-child! "#button-speed")
  ;; => #object[HTMLButtonElement [object HTMLButtonElement]]

  )

Before we get serious about beautifying that control, we have one order of business we need to attend to.

Go Speed Racer Go!

Right now, if we select a new speed from our control (such as 1.25x), nothing happens. Which makes sense, because we haven't attached any event listeners to it. πŸ˜…

Let's take a look at init-ui!, which is where we add event listeners to all the other controls:

(defn init-ui! []
  (doseq [[el-id {:keys [click-handler]}] playback-controls]
    (add-event-listener! (str "#button-" (name el-id)) "click"
                         click-handler))
  ;; ...
  (log "UI initialised"))

Ah yes, we're iterating over the playback-controls, which currently look like this:

(def playback-controls
  {:play {:src "https://www.svgrepo.com/show/436852/play-circle-fill.svg"
          :label "Play"
          :click-handler #(.play (get-el "audio.cljcastr"))}
   :pause {:src "https://www.svgrepo.com/show/436829/pause-circle-fill.svg"
           :label "Pause"
           :click-handler #(.pause (get-el "audio.cljcastr"))}
   :forward {:src "https://www.svgrepo.com/show/495321/forward-15-seconds.svg"
             :label "Forward {{seek-dur-sec}} seconds"
             :click-handler #(skip-forward! (get-el "audio.cljcastr") seek-dur-sec)}
   :backward {:src "https://www.svgrepo.com/show/495036/backward-15-seconds.svg"
              :label "Back {{seek-dur-sec}} seconds"
              :click-handler #(skip-backward! (get-el "audio.cljcastr") seek-dur-sec)}
   :speed {:src "https://www.svgrepo.com/show/151785/speed-meter.svg"
           :label "Playback speed"}})

That :speed one is going to be a problem, since there is no #button-speed element anymore:

(comment

  ;; ...

  (get-el "#button-speed")
  ;; => nil

  (init-ui!)
  ;; => "#error {:message \"Cannot read properties of null (reading 'addEventListener')\", ...}"

  )

OK, no problem; we just need to remove the :speed entry from playback-controls. And maybe whilst we're at it, rename it playback-buttons, since that's a more accurate name:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (def seek-dur-sec ...)

(def playback-buttons
  {:play {:src "https://www.svgrepo.com/show/436852/play-circle-fill.svg"
          :label "Play"
          :click-handler #(.play (get-el "audio.cljcastr"))}
   :pause {:src "https://www.svgrepo.com/show/436829/pause-circle-fill.svg"
           :label "Pause"
           :click-handler #(.pause (get-el "audio.cljcastr"))}
   :forward {:src "https://www.svgrepo.com/show/495321/forward-15-seconds.svg"
             :label "Forward {{seek-dur-sec}} seconds"
             :click-handler #(skip-forward! (get-el "audio.cljcastr") seek-dur-sec)}
   :backward {:src "https://www.svgrepo.com/show/495036/backward-15-seconds.svg"
              :label "Back {{seek-dur-sec}} seconds"
              :click-handler #(skip-backward! (get-el "audio.cljcastr") seek-dur-sec)}})

(defn init-ui! []
  (doseq [[el-id {:keys [click-handler]}] playback-buttons]
    (add-event-listener! (str "#button-" (name el-id)) "click"
                         click-handler))
  (let [audio (get-el "audio.cljcastr")]
    (add-event-listener! "#progress-slider" "input"
                         #(->> % .-target .-value (set! (.-currentTime audio))))
    (add-event-listener! audio "timeupdate"
                         #(update-playback-position-indicators!
                           (.-currentTime audio) (.-duration audio)
                           (->> [:elapsed-time
                                 :remaining-time
                                 :progress-slider
                                 :progress-bar]
                                (map (fn [el-id]
                                       [el-id (str "#" (name el-id))]))
                                (into {}))))
    audio)
  (log "UI initialised"))

;; (defn init-ui! ...)
;; ...

(comment

  ;; ...

  (init-ui!)
  ;; => "UI initialised"

  )

Cool, init-ui! is working again. But we still haven't added any event listeners to the speed control. Let's start by figuring out what the event listener should do.

The heart and soul of our speed control is a select element, the value of which will correspond to whichever option is selected:

(comment

  ;; ...

  (get-value "#speed-select")
  ;; => "1.25"

  )

If we look at the documentation for the select element, at the very bottom of the page, we see that select fires "change" and "input" events. "change" seems like the one we're after. Let's check by adding a listener, then selecting "1.5x":

(comment

  ;; ...

  (add-event-listener! "#speed-select" "change"
                       (fn [ev]
                         (let [select-el (.-target ev)]
                           (log "New speed selected:" (get-value select-el)))))
  ;; => #object[HTMLSelectElement [object HTMLSelectElement]]

  )

And when we select "1.5x" and look at the console, we see some familiar logging:

Added listener for change events to                                nrepl.cljs:10
 β€£ <select aria-label="Playback speed" id="speed-select" class="cljcastr">…</select>

Handling change on β€£ <select aria-label="Playback speed" ...>      nrepl.cljs:10
 β€£ Event {isTrusted: true, type: 'change', target: select#speed-select.cljcastr,
   currentTarget: select#speed-select.cljcastr, eventPhase: 2, …}

New speed selected: 1.5                                            nrepl.cljs:10

OK, now that we know we've got the right event, what our event listener needs to do is to take that value and use it to actually set the playback rate of our audio control. Let's add just such an event listener to init-ui!:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (def playback-buttons ...)

(defn init-ui! []
  (doseq [[el-id {:keys [click-handler]}] playback-buttons]
    (add-event-listener! (str "#button-" (name el-id)) "click"
                         click-handler))
  (let [audio (get-el "audio.cljcastr")]
    (add-event-listener! "#progress-slider" "input"
                         #(->> % .-target .-value (set! (.-currentTime audio))))
    (add-event-listener! "#speed-select" "change"
                         #(->> % .-target .-value (set! (.-playbackRate audio))))
    (add-event-listener! audio "timeupdate"
                         #(update-playback-position-indicators!
                           (.-currentTime audio) (.-duration audio)
                           (->> [:elapsed-time
                                 :remaining-time
                                 :progress-slider
                                 :progress-bar]
                                (map (fn [el-id]
                                       [el-id (str "#" (name el-id))]))
                                (into {}))))
    audio)
  (log "UI initialised"))

;; (when-not (:initialised? @state))
;; ...

(comment

  ;; ...

  (init-ui!)
  ;; => "UI initialised"

  )

If we now start playing the audio, then select "2x" from the speed select, we should hear the defn theme song on turbo. Before our eyes pop all the way out of our head, we quickly select "0.75x" to slow things down, then click pause.

Just as we start feeling that all is right and good with the world, something in the console catches our eye:

Handling click on                                                  nrepl.cljs:10
 β€£ <button aria-label="Pause" id="button-pause" ...>…</button>
 β€£ PointerEvent {isTrusted: true, pointerId: 1, width: 1, height: 1, …}

Handling click on                                                  nrepl.cljs:10
 β€£ <button aria-label="Pause" id="button-pause" ...>…</button>
 β€£ PointerEvent {isTrusted: true, pointerId: 1, width: 1, height: 1, …}

We clicked the pause button once, but our handler fired twice. 😬

Let's see if we can figure out why by reading the documentation for the addEventListener() method:

Note: If a particular anonymous function is in the list of event listeners registered for a certain target, and then later in the code, an identical anonymous function is given in an addEventListener call, the second function will also be added to the list of event listeners for that target.

Indeed, anonymous functions are not identical even if defined using the same unchanging source-code called repeatedly, even if in a loop.

Repeatedly defining the same unnamed function in such cases can be problematic. (See Memory issues, below.)

Ah-ha! This is exactly what we're doing. It looks like we can fix this by using named functions instead of anonymous ones, but this would mean a lot of code duplication in our handlers. Let's do a little experimentation to see if we can have our anonymous functions and eat them too.

First, let's create an element to do some clicking on, and a named function to serve as an event listener, then add it to the element's "click" listeners, and finally call the element's .click() method:

(comment

  ;; ...

  (def event-testing-el (create-el {:tag "div", :id "event-testing"}))
  ;; => #'cljcastr.player/event-testing-el

  (defn named-f [ev]
    (log "I am Jack's named function"))
  ;; => #'cljcastr.player/named-f

  (.addEventListener event-testing-el "click" named-f)
  ;; => nil

  (.click event-testing-el)
  ;; => nil

  )

If we look at the console, we'll see exactly what we expect:

I am Jack's named function                                         nrepl.cljs:10

And if we add the named function again?

(comment

  ;; ...

  ;; Add named function again
  (.addEventListener event-testing-el "click" named-f)

  ;; Named function only called once
  (.click event-testing-el)
  ;; => nil

  )

Again, the console only shows named-f being called once, despite the fact that we added it as an event listener twice:

I am Jack's named function                                         nrepl.cljs:10

If we create an anonymous function, then add it as an event listener twice, it will still only be called once when the event fires:

(comment

  ;; ...

  (let [anon-f (fn [ev]
                 (log "I am anonymous"))]
    (.addEventListener event-testing-el "click" anon-f)

    ;; Add the same anonymous function again
    (.addEventListener event-testing-el "click" anon-f)

    ;; Each function only called once
    (.click event-testing-el))
  ;; => nil

  )

Quoth the console:

I am Jack's named function                                         nrepl.cljs:10
I am anonymous                                                     nrepl.cljs:10

Finally, let's do exactly what init-el! does:

(comment

  ;; ...

  ;; Add another anonymous function
  (.addEventListener event-testing-el "click"
                     (fn [ev]
                       (log "I am super anonymous")))
  ;; => nil

  ;; Add the "same" anonymous function again
  (.addEventListener event-testing-el "click"
                     (fn [ev]
                       (log "I am super anonymous")))
  ;; => nil

  ;; Super anonymous function called twice
  (.click event-testing-el)
  ;; => nil

  )

With a great sense of trepidation, we look at the console:

I am Jack's named function                                         nrepl.cljs:10
I am anonymous                                                     nrepl.cljs:10
I am super anonymous                                               nrepl.cljs:10
I am super anonymous                                               nrepl.cljs:10

The difference between the anonymous and super anonymous functions is that for the anonymous function, we added the exact same function twice, whereas for the super anonymous one, we added functions that do the exact same thing twice. In other words:

(comment

  ;; ...

  (let [anon-f (fn [ev]
                 (log "I am anonymous"))]
    {:is-anon-f-the-same-as-itself?
     (= anon-f anon-f)
     :is-one-super-anon-f-the-same-as-another?
     (= (fn [ev] (log "I am super anonymous"))
        (fn [ev] (log "I am super anonymous")))})
  ;; => {:is-anon-f-the-same-as-itself? true,
  ;;     :is-one-super-anon-f-the-same-as-another? false}

  )

This is a real head-scratcher, but before we pop into the hammock to wrestle with the problem, let's look at how we can remove event listeners from an element:

(comment

  ;; ...

  (.removeEventListener event-testing-el "click" named-f)
  ;; => nil

  (.removeEventListener event-testing-el "click"
                        (fn [ev]
                          (log "I am super anonymous")))
  ;; => nil

  (.click event-testing-el)
  ;; => nil

  )

The console sez:

I am anonymous                                                     nrepl.cljs:10
I am super anonymous                                               nrepl.cljs:10
I am super anonymous                                               nrepl.cljs:10

As expected, trying to remove the super anonymous function doesn't work, whilst removing named-f does. We can't remove the anonymous function because we don't have a reference to it. 🀷🏼

OK, into the hammock we get!

The state and evolution

What we really want with event listeners is the following:

  1. Adding a listener multiple times results in it only being called once when an event fires.
  2. We should be able to remove any listener we added.
  3. We should be able to remove all listeners at any time of our choosing.

If we squint, #1 looks similar to something else we only wanted to do once: initialise the UI. And how did we handle that?

With our state atom! So let's try that here. First, let's add a new arity to add-event-listener! that accepts an atom along with the rest of the args:

(defn add-event-listener!
  ([el event-type f]
   (add-event-listener! nil el event-type f))
  ([state-atom el event-type f]
   ...))

Now let's think about what we want to happen here. Before adding an event listener, we should first check to see if it has already been added for this event type, and if so, not add it again. This requires us to keep track of all the listeners that have been added for each event type.

Let's give it a go!

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn clone-el ...)

(defn add-event-listener!
  "Adds an event listener for the specified event type to an element. If a state
   atom is specified, the listener will be recorded in the state atom. Returns
   the element."
  ([el event-type f]
   (add-event-listener! nil el event-type f))
  ([state-atom el event-type f]
   (let [el (get-el el)
         event-type (keyword event-type)
         listeners (when state-atom
                     (get-in @state-atom [:listeners el event-type]))]
     (if (some #(= f (:f %)) listeners)
       (log "Not adding duplicate" (name event-type) "listener to" el)
       (let [wrapped-f
             (fn [ev]
               (log (str "Handling " (name event-type) " on")
                    el ev)
               (if f
                 (f ev)
                 (log "No event handler function defined")))]
         (.addEventListener el (name event-type) wrapped-f)
         (when state-atom
           (swap! state-atom update-in
                  [:listeners el event-type]
                  conj {:wrapped-f wrapped-f
                        :f f
                        :el-id (get-id el)}))
         (log "Added listener for" (name event-type) "events to" el)))
     el)))

;; (defn save-file! ...)
;; ...

(comment

  ;; ...

  (def event-testing-el (create-el {:tag "div", :id "event-testing"}))
  ;; => #'cljcastr.player/event-testing-el

  (add-event-listener! state event-testing-el :click named-f)
  ;; => #object[HTMLDivElement [object HTMLDivElement]]

  (add-event-listener! state event-testing-el :click named-f)
  ;; => #object[HTMLDivElement [object HTMLDivElement]]

  (.click event-testing-el)
  ;; => nil

  (:listeners @state)
  ;; => {#object[HTMLDivElement [object HTMLDivElement]]
  ;;     {:click [{:wrapped-f #object[Function],
  ;;               :f #object[Function],
  ;;               :el-id "event-testing"}]}}

  )

The console seems to indicate that we're on the right track:

Added listener for click listener to <div id="event-testing">      nrepl.cljs:10

Not adding duplicate listener for click listener to <div ...>      nrepl.cljs:10

Handling click on <div id="event-testing"></div>                   nrepl.cljs:10
 β€£ PointerEvent {isTrusted: true, pointerId: 1, width: 1, height: 1, …}

I am Jack's named function                                         nrepl.cljs:10

add-event-listener! is a bit hard to wrap our heads around (haha, see what I did there?), so let's break down what it does when called with a state atom:

  1. Resolves the element using get-el (as with all of our DOM functions, the el argument can be either a DOM element or a CSS selector)
  2. Turns event-type into a keyword to normalise it so that the event-type argument can be either a string like "click" or a keyword like :click
  3. Assuming the state atom contains a :listener key with a value that is a map of element to map of event type to vector of listener records (which are maps containing keys :f, :wrapped-f, and :el-id, which will be explained shortly), and grabs the sequence of listener records for this element and event type
  4. Checks to see if the specified listener function (the f argument to add-event-listener!) matches the :f key of any of the listener records
  5. If so, logs that it's not adding a duplicate listener and returns the element
  6. Otherwise, wraps the listener in a new anonymous function that logs stuff before calling the listener, then uses the JavaScript .addEventListener() method to add the anonymous function as a listener for the specified event type
  7. Creates a new listener record with the :f key set to the original listener, the :wrapped-f key set to the anonymous function we just created, and the :el-id key set to the ID of the element (this last is just to make the state atom nicer for human eyes)
  8. Adds the listener record to the vector of listener records for the specified element and event type

Now let's try it with our anonymous function:

(comment

  ;; ...

  (let [anon-f (fn [ev]
                 (log "I am anonymous"))]
    (add-event-listener! state event-testing-el "click" anon-f)

    ;; Add the same anonymous function again
    (add-event-listener! state event-testing-el "click" anon-f)

    ;; Each function only called once
    (.click event-testing-el))
  ;; => nil

  )

Looking good so far:

Added listener for click listener to <div id="event-testing">      nrepl.cljs:10

Not adding duplicate listener for click listener to <div ...>      nrepl.cljs:10

Handling click on <div id="event-testing"></div>                   nrepl.cljs:10
 β€£ PointerEvent {isTrusted: true, pointerId: 1, width: 1, height: 1, …}

I am Jack's named function                                         nrepl.cljs:10

Handling click on <div id="event-testing"></div>                   nrepl.cljs:10
 β€£ PointerEvent {isTrusted: true, pointerId: 1, width: 1, height: 1, …}

I am anonymous                                                     nrepl.cljs:10

And now for the final test, the super anonymous function:

(comment

  ;; ...

  (add-event-listener! state event-testing-el "click"
                       (fn [ev]
                         (log "I am super anonymous")))
  ;; => #object[HTMLDivElement [object HTMLDivElement]]

  (add-event-listener! state event-testing-el "click"
                       (fn [ev]
                         (log "I am super anonymous")))
  ;; => #object[HTMLDivElement [object HTMLDivElement]]

  (.click event-testing-el)
  ;; => nil

  )

This time, the console lets us down:

Added listener for click listener to <div id="event-testing">      nrepl.cljs:10

Added listener for click listener to <div id="event-testing">      nrepl.cljs:10

Handling click on <div id="event-testing"></div>                   nrepl.cljs:10
 β€£ PointerEvent {isTrusted: true, pointerId: 1, width: 1, height: 1, …}

I am Jack's named function                                         nrepl.cljs:10

Handling click on <div id="event-testing"></div>                   nrepl.cljs:10
 β€£ PointerEvent {isTrusted: true, pointerId: 1, width: 1, height: 1, …}

I am anonymous                                                     nrepl.cljs:10

Handling click on <div id="event-testing"></div>                   nrepl.cljs:10
 β€£ PointerEvent {isTrusted: true, pointerId: 1, width: 1, height: 1, …}

I am super anonymous                                               nrepl.cljs:10

Handling click on <div id="event-testing"></div>                   nrepl.cljs:10
 β€£ PointerEvent {isTrusted: true, pointerId: 1, width: 1, height: 1, …}

I am super anonymous                                               nrepl.cljs:10

So have we actually accomplished anything? Well, it turns out we have, because now we can write a function to remove all event listeners from an element:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn add-event-listener! ...)

(defn clear-event-listeners!
  "Removes all event listeners from the specified element, or if an event type
   is specified, all listeners for events of that type. Returns the element."
  ([state-atom el]
   (let [el (get-el el)]
     (clear-event-listeners! state-atom el
                             (-> (get-in @state-atom [:listeners el])
                                 keys))))
  ([state-atom el event-types]
   (let [el (get-el el)]
     (doseq [event-type (if (sequential? event-types) event-types [event-types])
             f (get-in @state-atom [:listeners el (keyword event-type)])
             :let [event-type (keyword event-type)]]
       (log "Removing listener for" (name event-type) "events from" el)
       (.removeEventListener el (name event-type) (:wrapped-f f))
       (swap! state-atom update-in [:listeners el event-type]
              (fn [fns] (->> fns
                             (remove #(= f %))
                             (into [])))))
     el)))

;; (defn save-file! ...)
;; ...

(comment

  ;; ...

  (clear-event-listeners! state event-testing-el)
  ;; => #object[HTMLDivElement [object HTMLDivElement]]

  (.click event-testing-el)
  ;; => nil

  )

And if we look at the console, we see four event listeners being removed:

Removing listener for click events from <div id="event-testing">    nrepl.cljs:10

Removing listener for click events from <div id="event-testing">    nrepl.cljs:10

Removing listener for click events from <div id="event-testing">    nrepl.cljs:10

Removing listener for click events from <div id="event-testing">    nrepl.cljs:10

Before moving on, let's address that final annoyance: the inability to add the "same" anonymous function multiple times and only have it fired once.

Step 1 is to ask ourselves why we would want to do that in the first place. πŸ˜…

There's no activity like interactivity

Well, the most likely reason is that we want to develop an event listener interactively, for example:

(comment

  ;; ...

  (defn some-listener [ev]
    (log "Just logging the event"))
  ;; => #'cljcastr.player/some-listener

  (add-event-listener! state event-testing-el :click some-listener)
  ;; => #object[HTMLDivElement [object HTMLDivElement]]

  (.click event-testing-el)
  ;; => nil

  (defn some-listener [ev]
    (let [el (.-target ev)
          event-type (.-type ev)]
      (log "Handling event of type" event-type "on element" el)))
  ;; => #'cljcastr.player/some-listener

  (add-event-listener! state event-testing-el :click some-listener)
  ;; => #object[HTMLDivElement [object HTMLDivElement]]

  (.click event-testing-el)
  ;; => nil

  )

As we've seen, every time we call add-event-listener!, we end up with a new listener attached to the poor element, when what we actually wanted was to replace the listener with a new version of itself. The only problem is that we don't have an identity for the listener, just a value. And by "identity" and "value", we mean in the Hickean sense:

By identity I mean a stable logical entity associated with a series of different values over time. Models need identity for the same reasons humans need identity - to represent the world. How could it work if identities like 'today' or 'America' had to represent a single constant value for all time? Note that by identities I don’t mean names (I call my mother Mom, but you wouldn’t).

So, for this discussion, an identity is an entity that has a state, which is its value at a point in time. And a value is something that doesn’t change. 42 doesn’t change. June 29th 2008 doesn’t change. Points don’t move, dates don’t change, no matter what some bad class libraries may cause you to believe. Even aggregates are values. The set of my favorite foods doesn’t change, i.e. if I prefer different foods in the future, that will be a different set.

Identities are mental tools we use to superimpose continuity on a world which is constantly, functionally, creating new values of itself.

Let's give good 'ol add-event-listener! one more arity, that which accepteth not only a value (of the #object[Function] variety), but also an identity:

(defn add-event-listener!
  "Adds an event listener for the specified event type to an element. If a state
   atom is specified, the listener will be recorded in the state atom. Returns
   the element."
  ([el event-type f]
   (add-event-listener! nil el event-type f))
  ([state-atom el event-type f]
   (add-event-listener! nil el event-type f nil))
  ([state-atom el event-type f id]
   ...))

Before we write the code, let's make sure we know what we want to do when we get a new function value for the same identity:

  1. Remove the existing listener with that identity
  2. Add the new listener

Let's write ourselves a function that removes a single listener:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn clone-el ...)

(defn remove-event-listener!
  "Removes the event listener with the specified id and event type."
  ([state-atom el event-type f]
   (remove-event-listener! state-atom el event-type f nil))
  ([state-atom el event-type f id]
   (let [el (get-el el)
         event-type (keyword event-type)
         path [:listeners el event-type]]
     (when-let [record (some #(and (if id
                                    (= id (:id %))
                                    (= f (:f %)))
                                   %)
                             (get-in @state-atom path))]
       (.removeEventListener el (name event-type) (:wrapped-f record))
       (swap! state-atom update-in path
              (fn [fns] (->> fns
                             (remove #(= record %))
                             (into []))))))))

;; (defn add-event-listener! ...)
;; ...

(comment

  ;; ...

  @state
  ;; => {:initialised? true,
  ;;     :listeners
  ;;     {#object[HTMLDivElement [object HTMLDivElement]]
  ;;      {:click
  ;;       ({:wrapped-f #object[Function], :f #object[Function], :el-id "event-testing"}
  ;;        {:wrapped-f #object[Function], :f #object[Function], :el-id "event-testing"})}}}

  (remove-event-listener! state event-testing-el :click some-listener)
  ;; => {:initialised? true,
  ;;     :listeners
  ;;     {#object[HTMLDivElement [object HTMLDivElement]]
  ;;      {:click
  ;;       [{:wrapped-f #object[Function], :f #object[Function], :el-id "event-testing"}]}}}

  (.click event-testing-el)
  ;; => nil

  )

Let's refactor this a bit to improve readability:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn clone-el ...)

(defn get-listener-record
  ([state-atom el event-type f]
   (get-listener-record state-atom el event-type f nil))
  ([state-atom el event-type f id]
   (let [el (get-el el)
         event-type (keyword event-type)]
     (some #(and (if id
                   (= id (:id %))
                   (= f (:f %)))
                 %)
           (get-in @state-atom [:listeners el event-type])))))

(defn remove-event-listener!
  "Removes the event listener with the specified id and event type."
  ([state-atom el event-type f]
   (remove-event-listener! state-atom el event-type f nil))
  ([state-atom el event-type f id]
   (let [el (get-el el)
         event-type (keyword event-type)]
     (when-let [record
                (get-listener-record state el :click f id)]
       (.removeEventListener el (name event-type) (:wrapped-f record))
       (swap! state-atom update-in [:listeners el event-type]
              (fn [fns] (->> fns
                             (remove #(or (= record %)
                                          (and id (= id (:id %)))))
                             (into []))))))))

;; (defn add-event-listener! ...)
;; ...

(comment

  ;; ...

  (add-event-listener! state event-testing-el :click some-listener)
  ;; => #object[HTMLDivElement [object HTMLDivElement]]

  (get-listener-record state event-testing-el :click some-listener)
  ;; => {:wrapped-f #object[Function], :f #object[Function], :el-id "event-testing"}

  (remove-event-listener! state event-testing-el :click some-listener)
  ;; => {:initialised? true,
  ;;     :listeners
  ;;     {#object[HTMLDivElement [object HTMLDivElement]]
  ;;      {:click
  ;;       [{:wrapped-f #object[Function], :f #object[Function], :el-id "event-testing"}]}}}

  )

With these lovely functions, we can now update add-event-listener! to handle an id:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn remove-event-listener! ...)

(defn add-event-listener!
  "Adds an event listener for the specified event type to an element. If a state
   atom is specified, the listener will be recorded in the state atom. Returns
   the element."
  ([el event-type f]
   (add-event-listener! nil el event-type f))
  ([state-atom el event-type f]
   (add-event-listener! state-atom el event-type f nil))
  ([state-atom el event-type f id]
   (let [el (get-el el)
         event-type (keyword event-type)
         path [:listeners el event-type]
         listeners (when state-atom
                     (get-in @state-atom path))]
     (if (some #(= f (:f %)) listeners)
       (log "Not adding duplicate" (name event-type) "listener to" el)
       (let [wrapped-f
             (fn [ev]
               (log (str "Handling " (name event-type) " on")
                    el ev)
               (if f
                 (f ev)
                 (log "No event handler function defined")))]
         (remove-event-listener! state-atom el event-type f id)
         (.addEventListener el (name event-type) wrapped-f)
         (when state-atom
           (swap! state-atom update-in path
                  conj {:id id
                        :wrapped-f wrapped-f
                        :f f
                        :el-id (get-id el)}))
         (log "Added listener for" (name event-type) "events to" el)))
     el)))

;; (defn clear-event-listeners! ...)
;; ...

(comment

  ;; ...

  (clear-event-listeners! state event-testing-el)
  ;; => #object[HTMLDivElement [object HTMLDivElement]]

  (add-event-listener! state event-testing-el :click
                       some-listener :some-listener)
  ;; => #object[HTMLDivElement [object HTMLDivElement]]

  (defn some-listener [ev]
    (let [el (.-target ev)
          event-type (.-type ev)]
      (log "Handling event" ev "on element" el)))
  ;; => #'cljcastr.player/some-listener

  (add-event-listener! state event-testing-el :click
                       some-listener :some-listener)
  ;; => #object[HTMLDivElement [object HTMLDivElement]]

  (.click event-testing-el)
  ;; => nil

  )

Now we can update init-ui! to add an ids to our listeners so we can iterate on them as we go:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (def playback-buttons ...)

(defn init-ui! []
  (doseq [[el-id {:keys [click-handler]}] playback-buttons]
    (add-event-listener! state (str "#button-" (name el-id)) :click
                         click-handler el-id))
  (let [audio (get-el "audio.cljcastr")]
    (add-event-listener! state "#progress-slider" "input"
                         #(->> % .-target .-value (set! (.-currentTime audio)))
                         :seek)
    (add-event-listener! state "#speed-select" "change"
                         #(->> % .-target .-value (set! (.-playbackRate audio)))
                         :speed)
    (add-event-listener! state audio "timeupdate"
                         #(update-playback-position-indicators!
                           (.-currentTime audio) (.-duration audio)
                           (->> [:elapsed-time
                                 :remaining-time
                                 :progress-slider
                                 :progress-bar]
                                (map (fn [el-id]
                                       [el-id (str "#" (name el-id))]))
                                (into {})))
                         :time-update)
    audio)
  (log "UI initialised"))

;; (when-not ...)
;; ...

Next time we reload the page, we'll get nice handlers. But let's not do that quite yet; instead, let's make our speed control look nicer.

This is the makeover

If we cast our gaze back to the dev tools panel in our Overcast web player browser tab, we see the following styles being applied to the speed menu label:

.speedmenu {
  position: relative;
  display: inline-flex;
  align-items: center;
  gap: 0.4em;
  color: #fc7e0f;
  border: 1px solid #fc7e0f;
  border-radius: 999px;
  padding: 5px 12px 5px 11px;
  cursor: pointer;
  -webkit-tap-highlight-color: transparent;
  transition: background-color 0.1s ease-out;
}

.speedmenu::after {
  content: "";
  position: absolute;
  right: 13px;
  top: 50%;
  width: 0.4em;
  height: 0.4em;
  border-right: 2px solid currentColor;
  border-bottom: 2px solid currentColor;
  transform: translateY(-65%) rotate(45deg);
  pointer-events: none;
}

Let's ignore that weird .speedmenu::after ruleset for now, because we only pseudo-understand pseudo-elements like ::after and just focus on the .speedmenu ruleset. Wouldn't it be lovely if we could turn this CSS text into a styles map of the sort we feed to functions like set-styles! and so on?

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn clone-el ...)

(defn css->styles
  "Returns a map of styles corresponding to the specified CSS style
   declaration."
  [css]
  (let [styles-str (-> css
                       (str/replace "\n" " ")
                       (str/replace #"^.+[{]([^}]+)[}].*$" "$1"))]
    (-> (create-el {:tag "div", :attrs {:style styles-str}})
        get-styles)))

;; (defn add-event-listener! ...)
;; ...

(comment

  ;; ...

  (let [css "
.speedmenu {
  position: relative;
  display: inline-flex;
  align-items: center;
  gap: 0.4em;
  color: #fc7e0f;
  border: 1px solid #fc7e0f;
  border-radius: 999px;
  padding: 5px 12px 5px 11px;
  cursor: pointer;
  -webkit-tap-highlight-color: transparent;
  transition: background-color 0.1s ease-out;
}"]
    (css->styles css))
  ;; => {:align-items "center",
  ;;     :color "#fc7e0f",
  ;;     :transition "background-color 0.1s ease-out",
  ;;     :cursor "pointer",
  ;;     :position "relative",
  ;;     :padding "5px 12px 5px 11px",
  ;;     :gap "0.4em",
  ;;     :-webkit-tap-highlight-color "transparent",
  ;;     :display "inline-flex",
  ;;     :border "1px solid #fc7e0f",
  ;;     :border-radius "999px"}

  )

Let's just set the styles of our #speed-menu label to these and see what that looks like:

(comment

  ;; ...

  (let [css "
.speedmenu {
  position: relative;
  display: inline-flex;
  align-items: center;
  gap: 0.4em;
  color: #fc7e0f;
  border: 1px solid #fc7e0f;
  border-radius: 999px;
  padding: 5px 12px 5px 11px;
  cursor: pointer;
  -webkit-tap-highlight-color: transparent;
  transition: background-color 0.1s ease-out;
}"]
    (->> css
         css->styles
         (set-styles! "#speed-menu")))
  ;; => #object[HTMLLabelElement [object HTMLLabelElement]]

  )

And what to our wondering eyes should appear but some rounded corners and a border so dear!

The select is still looking a bit plain though, so let's take a look at how it's styled in Overcast and rinse and repeat our style-snagging:

(comment

  ;; ...

  (let [css "
.speedmenu select {
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  font: inherit;
  font-size: 0.9em;
  font-variant-numeric: tabular-nums;
  color: inherit;
  background: transparent;
  border: 0;
  margin: 0;
  padding: 0 1.4em 0 0;
  cursor: pointer;
  outline: none;
}"]
    (->> css
         css->styles
         (set-styles! "#speed-select")))
  ;; => #object[HTMLSelectElement [object HTMLSelectElement]]

  )

Now we're getting somewhere!

Our player, with an almost nice looking speed select

The only thing that the Overcast player has that we don't is that cool looking β–Ό thingy that makes it all clicky-looking. And how pray tell did it get there? Could it be related to that .speedmenu::after ruleset that we handwaved away previously? This of course is a rhetorical question to which we already know the answer, so let's go ahead and apply them to our #speed-menu label.

(comment

  ;; ...

  (let [css "
.speedmenu::after {
  content: \"\";
  position: absolute;
  right: 13px;
  top: 50%;
  width: 0.4em;
  height: 0.4em;
  border-right: 2px solid currentColor;
  border-bottom: 2px solid currentColor;
  transform: translateY(-65%) rotate(45deg);
  pointer-events: none;
}"]
    (->> css
         css->styles
         (set-styles! "#speed-select::after")))
  ;; => "#error {:message \"Cannot set properties of null (setting 'style')\", ...}"

  )

Oops! Maybe that's why they call it a pseudo-element, eh? πŸ˜…

However, there are three ways to get CSS styles into our document:

  1. Using a link element
  2. Using a style element
  3. Inline using the style attribute

So far, we've only used numbers 1 and 3. Let's see if the second can help us out of this pseudo-jam we're in.

Hey kid, I like your style

First, let's prove to ourselves that we can put a style tag in the right place and play around with the page:

(comment

  ;; ...

  (->> (create-el {:tag "style", :id "css-rulesets", :text "div { color: red; }"})
       (add-child! "head"))
  ;; => #object[HTMLHeadElement [object HTMLHeadElement]]

  )

That worked! Of course, it looks pretty terrible, so let's put things back the way we found them:

(comment

  ;; ...

  (set-text! "#css-rulesets" "div { color: black; }")
  ;; => #object[HTMLStyleElement [object HTMLStyleElement]]

  )

OK, now let's get more Clojurey. First, let's write a function that turns a chunk of CSS into a sequence of rulesets, and then add an arity that turns the chunk of CSS in the style#css-rulesets tag into a sequence of rulesets:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn css->styles ...)

(defn get-rulesets
  "Returns a sequence of CSS rulesets from either the specified CSS string if
   present or the contents of the `style#css-rulesets` element otherwise. Each
   ruleset is a pair of condition (i.e. the list of selectors associated with a
   given CSS declaration block) and map corresponding to the CSS styles in the
   declaration block.

   See https://developer.mozilla.org/en-US/docs/Web/CSS/Guides/Syntax/Introduction#css_rulesets
   for explanations of CSS terminology like ruleset, condition, and declaration
   block.

   Example:

     (get-rulesets \"div { color: red; } a { color: blue; }\")
     ;; => [[\"div\" {:color \"red\"}] [\"a\" {:color \"blue\"}]]"
  ([]
   (when-let [el (get-el "style#css-rulesets")]
     (-> (get-text el) get-rulesets)))
  ([css]
   (when-not (empty? css)
     (->> css
          (re-seq #"(?s)^\s*([^{]+)\s*[{]([^}]+)[}]")
          (map (fn [[_match sel declarations]]
                 [(str/trim sel) (css->styles declarations)]))))))

;; (defn add-event-listener! ...)
;; ...

(comment

  ;; ...

  (get-rulesets)
  ;; => (["div" {:color "black"}])

  (let [css "
.speedmenu {
  position: relative;
  display: inline-flex;
  align-items: center;
  gap: 0.4em;
  color: #fc7e0f;
  border: 1px solid #fc7e0f;
  border-radius: 999px;
  padding: 5px 12px 5px 11px;
  cursor: pointer;
  -webkit-tap-highlight-color: transparent;
  transition: background-color 0.1s ease-out;
}

.speedmenu::after {
  content: \"\";
  position: absolute;
  right: 13px;
  top: 50%;
  width: 0.4em;
  height: 0.4em;
  border-right: 2px solid currentColor;
  border-bottom: 2px solid currentColor;
  transform: translateY(-65%) rotate(45deg);
  pointer-events: none;
}
"]
    (get-rulesets css))
  ;; => ([".speedmenu"
  ;;      {:align-items "center", :color "#fc7e0f", ...}]
  ;;     [".speedmenu::after"
  ;;      {:border-right "2px solid currentColor", :transform "translateY(-65%) rotate(45deg)", ...}])

  )

Now that we have this, we can write a few more functions for manipulating rulesets:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn get-rulesets ...)

(defn rulesets->css
  "Given a sequence of rulesets, returns the corresponding CSS."
  [rulesets]
  (->> rulesets
       (map (partial apply format-css))
       (str/join "\n\n")))

(defn set-stylesheet!
  "Sets the document's stylesheet to the specified CSS and returns it."
  [css]
  (when-not (get-el "style#css-rulesets")
    (->> (create-el {:tag "style", :id "css-rulesets"})
         (add-child! "head")))
  (set-text! "style#css-rulesets" css)
  css)

(defn set-rulesets!
  "Given a sequence of rulesets, transforms them into a stylesheet which becomes
   the text of the `style#css-rulesets` element. Returns the stylesheet."
  [rulesets]
  (-> (rulesets->css rulesets)
      set-stylesheet!))

;; (defn add-event-listener! ...)
;; ...

(comment

  ;; ...

  (let [rulesets [["#speed-menu::after"
                   {:border-right "2px solid currentColor"
                    :transform "translateY(-65%) rotate(45deg)"
                    :top "50%"
                    :content "\"\""
                    :width "0.4em"
                    :right "13px"
                    :position "absolute"
                    :pointer-events "none"
                    :height "0.4em"
                    :border-bottom "2px solid currentColor"}]]]
    (set-rulesets! rulesets))
  ;; => "#speed-menu::after {\n  border-right: 2px solid currentColor;\n  ...}"

  )

With this, we have finally achieved aesthetic perfection!

Our player, with a very pretty speed select

Before moving on, let's imagine that we'd like to turn our episode info red again. We could of course do something like this:

(comment

  ;; ...

  (-> (get-rulesets)
      (concat [["#episode-info *" {:color "red"}]])
      set-rulesets!)
  ;; => "#speed-menu::after {\n  border-right: 2px solid currentColor;\n ...}\n\n
  ;;     #episode-info * {\n  color: red\n}"

  )

But why not have a function that does this and has the benefit of a meaningful name?

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn set-rulesets! ...)

(defn add-rulesets!
  "Adds the specified rulesets to the document's stylesheet, returning the new
   stylesheet."
  [rulesets]
  (-> (get-rulesets)
      (concat rulesets)
      set-rulesets!))

(defn add-ruleset!
  "Adds the specified ruleset to the document's stylesheet, returning the new
   stylesheet."
  [ruleset]
  (add-rulesets! [ruleset]))

;; (defn add-event-listener! ...)
;; ...

(comment

  ;; ...

  (add-ruleset! ["#episode-info *" {:color "red"}])
  ;; => "#speed-menu::after {\n  border-right: 2px solid currentColor; ... }\n\n
  ;;     #episode-info * {\n  color: red\n}\n\n
  ;;     #episode-info * {\n  color: red\n}"

  )

Oops, we probably don't want to repeat the "episode-info *" ruleset. Let's update add-rulesets! to deduplicate rulesets:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn set-rulesets! ...)

(defn dedup-rulesets
  "Deduplicates rulesets by taking the last ruleset for each selector."
  [rulesets]
  (->> rulesets
       (group-by first)
       (map (fn [[_sel rulesets']]
              (last rulesets')))))

(defn add-rulesets!
  "Adds the specified rulesets to the document's stylesheet, returning the new
   stylesheet."
  [rulesets]
  (-> (get-rulesets)
      (concat rulesets)
      dedup-rulesets
      set-rulesets!))

;; (defn add-ruleset! ...)
;; ...

(comment

  ;; ...

  (add-ruleset! ["#episode-info *" {:color "red"}])
  ;; => "#speed-menu::after {\n  border-right: 2px solid currentColor; ... }\n\n
  ;;     #episode-info * {\n  color: red\n}"

  )

That's better!

Now let's consider a world in which we'd like to make that down arrow thingy a bit more impressive. We could of course copy and paste the "#speed-menu::after" ruleset from above in our Rich comment, change the border-right and border-bottom declarations, and then use add-ruleset! to overwrite the existing ruleset, but again, this doesn't communicate our intent all that well to a future reader of the code (which is highly likely to be ourselves). Surely we can do better than that!

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn get-rulesets ...)

(defn get-ruleset
  "Returns the CSS ruleset from the active stylesheet (i.e. the contents of the
   `style#css-rulesets` element) corresponding to the specified selector."
  [sel]
  (->> (get-rulesets)
       (some (fn [[rs-sel _declarations :as ruleset]]
               (and (= sel rs-sel) ruleset)))))

;; (defn rulesets->css ...)
;; ...
;; (defn add-ruleset! ...)

(defn update-ruleset!
  "Updates the declarations in the ruleset with the same selector by merging the
   existing declarations with the declarations of the specified ruleset. Returns
   the new stylesheet."
  [[sel declarations :as ruleset]]
  (let [[_sel cur-declarations] (get-ruleset sel)]
    (add-ruleset! [sel (merge cur-declarations declarations)])))

;; (defn add-event-listener! ...)
;; ...

(comment

  ;; ...

  (get-ruleset "#episode-info *")
  ;; => ["#episode-info *" {:color "red"}]

  (update-ruleset! ["#speed-menu::after"
                    {:border-right "5px solid currentColor"
                     :border-bottom "5px solid currentColor"}])
  ;; => "#speed-menu::after {\n  border-right: 5px solid currentColor; ...}\n\n
  ;;     #episode-info * {\n  color: red\n}"

  )

Now that we have all these functions, let's put things back into a good state:

(comment

  ;; ...

  (let [rulesets [["#speed-menu::after"
                   {:border-right "2px solid currentColor"
                    :transform "translateY(-65%) rotate(45deg)"
                    :top "50%"
                    :content "\"\""
                    :width "0.4em"
                    :right "13px"
                    :position "absolute"
                    :pointer-events "none"
                    :height "0.4em"
                    :border-bottom "2px solid currentColor"}]]]
    (set-rulesets! rulesets))
  ;; => "#speed-menu::after {\n  border-right: 2px solid currentColor;\n  ...}"

  )

Hurrah! Our episode info text is back to black and the down arrow is svelte once more. Now that all is right with the world, let's export a new stylesheet from the current state of our DOM.

The return of Art Vandelay

Since we've built up quite the visually impressive player, let's proceed carefully. We'll call save-css! with a different filename and take a look at the resulting styles instead of just blithely overwriting our main.css file:

(comment

  ;; ...

  (save-css! "test.css")
  ;; => nil

  )

Now we can take a look at the contents of the test.css file:

#speed-menu {
  align-items: center;
  color: rgb(252, 126, 15);
  transition: background-color 0.1s ease-out;
  cursor: pointer;
  padding: 5px 12px 5px 11px;
  gap: 0.4em;
  -webkit-tap-highlight-color: transparent;
  display: inline-flex;
  position: relative;
  border: 1px solid rgb(252, 126, 15);
  border-radius: 999px;
}

#speed-select {
  color: inherit;
  background: transparent;
  cursor: pointer;
  font: inherit;
  padding: 0px 1.4em 0px 0px;
  outline: none;
  appearance: none;
  border: 0px;
  margin: 0px;
}

Good thing we were cautious! πŸ˜…

If we think back to what save-css! actually does, the reason for this becomes clear:

(defn dom->css []
  (->> (get-els ".cljcastr")
       group-styles
       (map (fn [[_styles [el & rest-els]]]
              (if (seq rest-els)
                (let [sel (str "." (->> (:classes el)
                                        (remove (partial = "cljcastr"))
                                        first))]
                  (el->css el sel))
                (el->css el))))
       (str/join "\n\n")
       log))

(defn save-css!
  ([]
   (save-css! "main.css"))
  ([filename]
   (save-css! filename (dom->css)))
  ([filename css]
   (save-file! filename css "text/css")))

Right, we're only handling inline styles, and as noted earlier, there are actually three ways to get styles into the DOM:

  1. Using a link element
  2. Using a style element
  3. Inline using the style attribute

Let's update dom->css to handle all three.

The first thing to note is that order matters with CSS rulesets, and when the page is loaded, the browser will first apply any stylesheets named by link elements where the value of their rel attribute is "stylesheet" (in the order in which they appear in the DOM), then stylesheets included in style elements (in the order in which they appear in the DOM), then inline styles.

With that knowledge in hand, let's make dom->css handle style elements. This one is a little tricky, so let's experiment in the REPL a bit before we actually make any changes to the function:

(comment

  ;; ...

  ;; Turn the contents of all style elements into CSS rulesets
  (->> (get-els "style")
       (mapcat (comp get-rulesets get-text)))
  ;; => (["#speed-menu::after" {:border-right "2px solid currentColor", ...}])

  ;; Turn inline styles into CSS rulesets: grab the body of the current dom->css
  ;; function and slap a call to get-rulesets on the end
  (->> (get-els ".cljcastr")
       group-styles
       (map (fn [[_styles [el & rest-els]]]
              (if (seq rest-els)
                (let [sel (str "." (->> (:classes el)
                                        (remove (partial = "cljcastr"))
                                        first))]
                  (el->css el sel))
                (el->css el))))
       (str/join "\n\n")
       get-rulesets)

  ;; Combine the rulesets and turn them into CSS
  (->> (concat (->> (get-els "style")
                    (mapcat (comp get-rulesets get-text)))
               (->> (dom->css)
                    get-rulesets))
       dedup-rulesets
       rulesets->css)
  ;; => "#speed-menu::after {\n  border-right: 2px solid currentColor;\n  ... }\n\n
  ;;     #speed-menu {\n  align-items: center;\n  color: rgb(252, 126, 15);\n  ... }\n\n
  ;;     #speed-select {\n  color: inherit;\n  background: transparent;\n  ... }"

  )

With these building blocks, we're ready to tackle dom->css:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn save-html! ...)

(defn dom->css []
  (let [style-rulesets (->> (get-els "style")
                            (mapcat (comp get-rulesets get-text)))
        inline-rulesets (->> (get-els ".cljcastr")
                             group-styles
                             (map (fn [[_styles [el & rest-els]]]
                                    (if (seq rest-els)
                                      (let [sel (str "." (->> (:classes el)
                                                              (remove (partial = "cljcastr"))
                                                              first))]
                                        (el->css el sel))
                                      (el->css el))))
                             (str/join "\n\n")
                             get-rulesets)]
    (->> (concat style-rulesets inline-rulesets)
         dedup-rulesets
         rulesets->css)))

;; (defn save-css! ...)
;; ...

(comment

  ;; ...

  (dom->css)
  ;; => "#speed-menu::after {\n  border-right: 2px solid currentColor;\n  ... }\n\n
  ;;     #speed-menu {\n  align-items: center;\n  color: rgb(252, 126, 15);\n  ... }\n\n
  ;;     #speed-select {\n  color: inherit;\n  background: transparent;\n  ... }"

  )

We're making progress here, as evidenced by the new contents of test.css:

#speed-menu::after {
  border-right: 2px solid currentColor;
  transform: translateY(-65%) rotate(45deg);
  top: 50%;
  content: "";
  width: 0.4em;
  right: 13px;
  position: absolute;
  pointer-events: none;
  height: 0.4em;
  border-bottom: 2px solid currentColor
}

#speed-menu {
  align-items: center;
  color: rgb(252, 126, 15);
  transition: background-color 0.1s ease-out;
  cursor: pointer;
  padding: 5px 12px 5px 11px;
  gap: 0.4em;
  -webkit-tap-highlight-color: transparent;
  display: inline-flex;
  position: relative;
  border: 1px solid rgb(252, 126, 15);
  border-radius: 999px
}

#speed-select {
  color: inherit;
  background: transparent;
  cursor: pointer;
  font: inherit;
  padding: 0px 1.4em 0px 0px;
  outline: none;
  appearance: none;
  border: 0px;
  margin: 0px
}

Now all that's left to do is handle the link elements.

Never trust Mary Poppins

First, let's just grab all of the stylesheet links in the DOM:

(comment

  ;; ...

  (->> (get-els "link[rel=\"stylesheet\"]")
       (map #(get-attr % :href)))
  ;; => ("main.css")

  )

Now if there was just a way to fetch those files and grab their contents... like the Window.fetch() function, perhaps?

(comment

  ;; ...

  (let [url "main.css"]
    (js/fetch (js/Request. url)))
  ;; => #<Promise #object[Response [object Response]]>

  )

Oh my! What can we do with a promise?

Mary Poppins saying "That's a piecrust promise. Easily made, easily broken."

Well, it seems that the standard sort of thing is using Promise.then() to register a callback that fires when the promise is complete. Let's try that:

(comment

  ;; ...

  (let [url "main.css"]
    (-> (js/fetch (js/Request. url))
        (.then #(log "fetch returned:" %))))
  ;; => #<Promise #object[Response [object Response]]>

  )

If we peer over at the JS console, things look promising (pun not initially intended but now celebrated):

fetch returned:                                                    nrepl.cljs:10
β–Ό   Response {type: 'basic', status: 200, ok: true, ...}
    body: (...)
    bodyUsed: false
  β€£ headers: Headers {}
    ok: true
    redirected: false
    status: 200
    statusText: "OK"
    type: "basic"
    url: "http://localhost:1341/main.css"
  β€£ [[Prototype]]: Response

Cool! Now let's see what we can do with a Response:

(comment

  ;; ...

  (let [url "main.css"]
    (-> (js/fetch (js/Request. url))
        (.then (fn [resp]
                 (log "fetch returned:" resp)
                 (.text resp)))))
  ;; => #<Promise "#progress-container {\n  position: relative;\n  ...">

  )

Now if we just turn that CSS into rulesets:

(comment

  ;; ...

  (let [url "main.css"]
    (-> (js/fetch (js/Request. url))
        (.then (fn [resp]
                 (log "fetch returned:" resp)
                 (-> (.text resp)
                     get-rulesets)))))
  ;; => #error {:message "[object Promise] is not ISeqable", ... }

  )

Oops, looks like Response.text() also returns a promise. No problem, we'll just call then() on that one as well:

(comment

  ;; ...

  (let [url "main.css"]
    (-> (js/fetch (js/Request. url))
        (.then (fn [resp]
                 (log "fetch returned:" resp)
                 (.text resp)))
        (.then (fn [text]
                 (log "got text:" text)
                 (->> (get-rulesets text)
                      (log "rulesets:"))))))
  ;; => #<Promise (["#progress-container" {:position "relative", ...}] ...)>

  )

The console verifies that this has worked:

fetch returned:                                                    nrepl.cljs:10
 β€£ Response {type: 'basic', status: 200, ok: true, ...}

got text: #progress-container {                                    nrepl.cljs:10
  position: relative;
  height: 28px;
  clear: both;
}

...

rulesets:                                                          nrepl.cljs:10
   (13) [Array(2), Array(2), Array(2), Array(2), Array(2), Array(2), Array(2),
 β€£ Array(2), Array(2), Array(2), Array(2), Array(2), Array(2)] 

We could take this code and add it to dom->css, but all of those .then() calls are frankly pretty annoying. Let's see if there's something we can do about this.

Awaiting for Godot

Luckily, ClojureScript recently (as of this writing, dunno when you're reading) added support for JavaScript async functions, and Scittle followed suit shortly after that. Let's create a function to fetch some text from a URL and see how this works:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn log ...)

(defn ^:async fetch-text
  "Fetches the specified URL and returns a promise to deliver the response body
   as text."
  [url]
  (let [resp (await (js/fetch (js/Request. url)))]
    (->> (await (.text resp))
         (log "Fetched text from url:" url))))

;; (defn render ...)
;; ...

(comment

  ;; ...

  (let [url "main.css"
        fetch-rulesets (^:async fn []
                        (let [text (await (fetch-text url))]
                          (log "rulesets:" (get-rulesets text))))]
    (fetch-rulesets url))
  ;; => #<Promise (["#progress-container" {:position "relative", ...}] ...)>

  )

We're still returning a promise and logging the same thing, but at least we've gotten rid of the .then() chaining. That goofy ^:async thing before the fn is metadata that instructs the ClojureScript compiler (or in this case, Scittle) to emit a JavaScript async function, which is required in order for us to use await. That's why we need to create a little function, because if we don't await the return value of fetch-text, we'll be back in the situation we were trying to escape:

(comment

  ;; ...

  (let [url "main.css"]
    (-> (fetch-text url)
        get-rulesets))
  ;; => "#error {:message \"[object Promise] is not ISeqable\", }"

  )

But no matter! We can turn this into a function as well:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn get-rulesets ...)

(defn ^:async fetch-rulesets
  "Returns a promise to deliver rulesets from the CSS file at the specified
   URL."
  [url]
  (let [text (await (fetch-text url))
        rulesets (get-rulesets text)]
    (log "Fetched rulesets:" rulesets)
    rulesets))

;; (defn get-ruleset ...)
;; ...

(comment

  ;; ...

  (fetch-rulesets "main.css")
  ;; => #<Promise (["#progress-container" {:position "relative", ...}] ...)>

  )

Now we're getting somewhere! But of course, we've been using "main.css" explicitly, rather than operating on all of the stylesheet links. Let's add a second stylesheet to keep ourselves honest.

First, we'll create a new moar.css file and drop a silly style in it:

#episode-info * {
  color: red;
}

Now we'll create a new link element and shove it in the head of our DOM:

(comment

  ;; ...

  (->> (create-el {:tag "link"
                   :attrs {:rel "stylesheet"
                           :href "moar.css"}})
       (add-child! "head"))
  ;; => #object[HTMLHeadElement [object HTMLHeadElement]]

  )

We'll know this has worked by our episode info turning red again. πŸ˜…

Now we can grab all the stylesheet links from the DOM and map over them to turn them into a sequence of rulesets, right?

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn get-rulesets ...)

(defn ^:async fetch-rulesets
  "Returns a promise to deliver rulesets from all stylesheet links in the DOM or
   the CSS files at the specified sequence of URLs. `urls` may also be a single
   URL as a string."
  ([]
   (->> (get-els "link[rel=\"stylesheet\"]")
        (map #(get-attr % :href))
        fetch-rulesets))
  ([urls]
   (let [urls (if (sequential? urls) urls [urls])]
     (->> urls
          (mapcat (^:async fn [url]
                   (let [text (await (fetch-text url))]
                     (get-rulesets text))))
          (log "Fetched rulesets:")))))

;; (defn get-ruleset ...)
;; ...

(comment

  ;; ...

  (fetch-rulesets)
  ;; => "#error {:message \"[object Promise] is not ISeqable\", }"

  )

Argh! What's doing on here? Well, it turns out that the ClojureScript documentation on async functions explains exactly this situation in the Caveats section:

(defn ^:async fetch-statuses [urls]
  (map (^:async fn [url] (.-status (await (fetch url)))) urls))

The return value of this function will be a Promise resolving to a seq of Promise values. A possible solution is to use Promise/all to await all fetches in parallel:

(defn ^:async fetch-statuses [urls]
  (let [resps (await (Promise/all (mapv fetch urls)))]
    (map #(.-status %) resps)))

Excellent! Let's modify our function to use this pattern:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn get-rulesets ...)

(defn ^:async fetch-rulesets
  "Returns a promise to deliver rulesets from all stylesheet links in the DOM or
   the CSS files at the specified sequence of URLs. `urls` may also be a single
   URL as a string."
  ([]
   (->> (get-els "link[rel=\"stylesheet\"]")
        (map #(get-attr % :href))
        fetch-rulesets))
  ([urls]
   (let [urls (if (sequential? urls) urls [urls])]
     (->> (await (js/Promise.all (mapv fetch-text urls)))
          (mapcat get-rulesets)
          (log "Fetched rulesets:")))))

;; (defn get-ruleset ...)
;; ...

(comment

  ;; ...

  (fetch-rulesets)
  ;; => #<Promise (["#progress-container" {:position "relative", ...}] ...)>

  )

Now we don't get an error, but did this actually accomplish anything? Looking at the browser console, we see something quite promising (I'm going to ride this punny into the ground):

Fetched text from url: main.css #progress-container {              nrepl.cljs:10
  position: relative;
  height: 28px;
  clear: both;
}
...
Fetched text from url: moar.css #episode-info * {                  nrepl.cljs:10
  color: red;
}
Fetched rulesets:                                                  nrepl.cljs:10
   (14) [Array(2), Array(2), Array(2), Array(2), Array(2), Array(2), Array(2),
 β€£ Array(2), Array(2), Array(2), Array(2), Array(2), Array(2), Array(2)] 

We can see both "main.css" and "moar.css" being fetches, and now we have 14 rulesets instead of 13! πŸŽ‰

Now we can finally update dom->css and save-css!, remembering to make them async as well:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn save-html! ...)

(defn ^:async dom->css []
  (let [external-rulesets (await (fetch-rulesets))
        style-rulesets (->> (get-els "style")
                            (mapcat (comp get-rulesets get-text)))
        inline-rulesets (->> (get-els ".cljcastr")
                             group-styles
                             (map (fn [[_styles [el & rest-els]]]
                                    (if (seq rest-els)
                                      (let [sel (str "." (->> (:classes el)
                                                              (remove (partial = "cljcastr"))
                                                              first))]
                                        (el->css el sel))
                                      (el->css el))))
                             (str/join "\n\n")
                             get-rulesets)]
    (->> (concat external-rulesets style-rulesets inline-rulesets)
         dedup-rulesets
         rulesets->css)))

(defn ^:async save-css!
  ([]
   (save-css! "main.css"))
  ([filename]
   (save-css! filename (await (dom->css))))
  ([filename css]
   (save-file! filename css "text/css")))

;; (def seek-dur-sec ...)
;; ...

Taking a deep breath, we call save-css! and allow it to overwrite our main.css:

(comment

  ;; ...

  (save-css!)
  ;; => #<Promise nil>

  )

Taking a look at the new main.css, we see our CSS rulesets from:

  1. Our link elements:
    • main.css:
      • #episode-art
      • #elapsed-time
      • etc
    • moar.css:
      • #episode-info *
  2. Using a style element:
    • #speed-menu::after
  3. Inline using the style attribute:
    • #speed-select
#episode-art {
  width: 400px;
  border-radius: 5%;
  padding: 10px
}

/* ... */

#episode-info * {
  color: red
}

#speed-select {
  color: inherit;
  background: transparent;
  cursor: pointer;
  font: inherit;
  padding: 0px 1.4em 0px 0px;
  outline: none;
  appearance: none;
  border: 0px;
  margin: 0px
}

/* ... */

#speed-menu::after {
  border-right: 2px solid currentColor;
  transform: translateY(-65%) rotate(45deg);
  top: 50%;
  content: "";
  width: 0.4em;
  right: 13px;
  position: absolute;
  pointer-events: none;
  height: 0.4em;
  border-bottom: 2px solid currentColor
}

/* ... */

#elapsed-time {
  margin: 0px 5px;
  font-size: 0.7rem;
  color: grey;
  float: left
}

By George, we've done it!

Jonathan Groff as King George from "Hamilton"

Now all we need to do is export our updated HTML to add the cool new speed control. We also need to remove the style#css-rulesets tag we added, since those styles are now in main.css. We can do this by updating our dom->html function and adding a :remove-children option when we call el->html:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn keep-child? ...)

(defn dom->html
  ([]
   (dom->html {}))
  ([opts]
   (el->html "html"
             (merge opts
                    {:filter-children keep-child?
                     :remove-children (fn [el]
                                        (and (instance? js/Element el)
                                             (= "css-rulesets" (get-id el))))}))))

;; (defn save-html! ...)
;; ...

(comment

  ;; ...
 
  (save-html! {:exclude-styles? true})
  ;; => nil

  )

We overwrite our index.html, take the customary deep breath, and finally reload the page.

The completed podcast player

Not only does it look gorgeous, but it actually also works!

Of course, we still haven't gotten around to being able to play more than one hardcoded episode, but that sounds like a job for the next thrilling instalment of Scittlecastr!

You can find all the files for the player we built in this post here:

The preview image for this post was based on the Laughing Arab woman with curly hairstyle using phone and headphones in front of on orange wall photo by Javier Sanchez Mingorance from his Woman In Overall Dress photoshoot. The photo is used under The Noun Project's Royalty-Free Commercial License, and was remixed by hand in the GIMP, which does not allow genAI contributions.

Scittlecastr: All You Need is Persistence

Teenager writing HTML on chalk board

This post was entirely written by a human, with no assistance from LLMs or other "AI" technology such as pervert glasses or autonomous weapon systems. The photo is Teenager looking at equation on chalk board by Rafa Fernandez.

Last time on Scittlecastr: The Scittling, we scittled up a podcast player, using the awesome power of the ClojureScript REPL.

What we found great about this approach was the ability to create HTML elements on the fly and update the page without having to reload, but at the end of our session, we were struck by the fear that if we do reload, we will lose all the state of our running program.

Before we grit our teeth and test our hypothesis, I present to you a

Table of contents

  1. Shoot outside of the screen to reload - writing functions to get the tag name and attributes of DOM elements
  2. Data is elemental - turning DOM nodes into Clojure maps
  3. The resurrection - rebuilding the podcast player in the REPL
  4. It's an unstable era - starting to turn the DOM into HTML
  5. Textual healing - handling text nodes
  6. HTML at last - finally transforming the entire DOM into HTML
  7. Plausible deniability - filtering out DOM elements added by extensions
  8. Indenting for fun and profit - indenting generated HTML nicely
  9. Shaving that final yak - saving the HTML to a file
  10. Button mashing - making the buttons work on page reload
  11. Atomic elbow - introducing state
  12. What has CSS ever done for us anyway? - generating CSS from inline styles
  13. It’s your birthday. Someone gives you a calfskin wallet. - grouping styles by class
  14. Inline skating away on the thin ice of a new day - switching from inline styles to an external stylesheet

Shoot outside of the screen to reload

OK, with that housekeeping out of the way, let's screw our courage to the sticking point and reload the page:

Blank webpage

😭😭😭

The Buddha spake wisely when he claimed that life is a vale of tears. However, we have achieved satori through Scittle, so we discard our fragile ego and expand our consciousness to encompass all things, and discover wisdom in the infinite.

This wisdom was that of having done our interactive development in a Rich comment, thus allowing us build our interface back up by evaluating our player.cljs buffer, then stepping through the Rich comment, evaluating each form one by one (you can use cider-eval-last-sexp (C-c C-e) for this, since you don't need the comment inserted again). Let's rebuild our initial ugly player, using our slick new functions.

Make sure to evaluate the entire buffer after a page reload (C-c C-k), or you'll get an error similar to this the first time you try to evaluate a form in the REPL:

(comment

  ;; ...

  (get-el "body")
  ;; => "#error {:message \"Unable to resolve symbol: get-el\",
  ;;             :data {:type :sci/error, :line 1, :column 1, ...}}

  )

Having evaluated the buffer, let's get ugly!

(comment

  ;; ...

  (set-children! "body"
                 [(create-el {:tag "h1"
                              :classes ["cljcastr"]
                              :text "cljcastr player"})
                  (create-el {:tag "audio"
                              :classes ["cljcastr"]
                              :attrs {:controls true
                                      :src "https://media.zencastr.com/audio-files/5d9048546bacd9001de88f1c/2abc6f33-6a0a-4658-a8e0-c811984c13a0.mp3"}})])
  ;; => #object[HTMLBodyElement [object HTMLBodyElement]]

  )

That is quite a pain, though. Is there a way to effectively export the running program as HTML so we could save it to our index.html? Well, let's give it a go.

What we'd like is to turn the body DOM node into an HTML fragment. We can actually already do this in a clunky way. We log the element:

(comment

  ;; ...

  (-> (get-el "body")
      log)
  ;; => #object[HTMLBodyElement [object HTMLBodyElement]]

  )

and then look at the console:

JavaScript console with body element and children

Unfortunately, we can't directly use the console output in the REPL. We could of course just copy and paste it from the console window, but that feels too efficient, and we'd rather spend some time shaving those yaks, so let's think about how we might generate our own HTML from the DOM tree anchored at the body element.

First, we need to do a depth-first traversal of the children of body. This is quite easy for the time being, since body only has children and no grandchildren or great-grandchildren or whatever. Let's try to count those children:

(comment

  ;; ...

  (def children (-> (get-children "body")
                    log))
  ;; => #'cljcastr.player/children

  (count children)
  ;; => 3

  )

Wait, what's going on here? The JS console actually holds the key. If we look in the console at the previously logged line and expand it, we see:

  β–Ό (2) [h1.cljcastr, audio.cljcastr, protonpass-root-64f9] β„Ή        nrepl.cljs:10
    β€£ 0: h1.cljcastr
    β€£ 1: audio.cljcastr
    β€£ 2: protonpass-root-64f9
      length: 2
    β€£ [[Prototype]]: Array(0)

Looks like my Proton Pass extension is adding an element to the body. 😬

But luckily, we added the cljcastr class to all our elements, so we can use a CSS selector to limit the children to the ones we actually put there ourselves:

(comment

  ;; ...

  (def children (-> (js/document.querySelectorAll "body > .cljcastr")
                    seq
                    log))
  ;; => #'cljcastr.player/children

  (count children)
  ;; => 2

  )

Excellent! Now let's see what the element names of the children are:

(comment

  ;; ...

  (->> children
       (map get-name)
       log)
  ;; => ("h1" "audio")

  )

And their attributes?

(comment

  ;; ...
  
  (->> children
       (map #(.-attributes %))
       log)
  ;; => (#object[NamedNodeMap [object NamedNodeMap]]
  ;;     #object[NamedNodeMap [object NamedNodeMap]])

  )

Ah yes, thank you for not using a POJSO (Plain 'Ol JavaScript Object, ofc) there. I guess we'll need some sort of function to turn a NamedNodeMap into a Clojure map. No matter, we can write some simple Clojure to fix this:

(comment

  ;; ...
  
  (->> children
       (map (fn [el]
              (let [attrs (.-attributes el)]
                (->> (range (.-length attrs))
                     (map #(let [attr (.item attrs %)]
                             [(-> (.-name attr) keyword) (.-value attr)]))
                     (into {})))))
       log)
  ;; => ({:class "cljcastr"}
  ;;     {:controls "true",
  ;;      :src "https://media.zencastr.com/audio-files/...",
  ;;      :class "cljcastr"})

  )

Um. This is... yeah. I think it's time to write a few functions to decomplect this mess. Let's head back up to the top of the file and add a few little functions:

(ns cljcastr.player)

;; ...
;; (defn get-attr ...)

(defn attr->clj
  "Given an entry in an attribute map (i.e. `Attr` in a `NamedNodeMap` that is
   the value of the `.-attributes` property of an element), returns a vector of
   the name (as a keyword) and value of the attribute."
  [attr]
  [(-> (.-name attr) keyword) (.-value attr)])

(defn get-attrs
  "Returns the attributes of an element as a map of attribute names (as keywords)
   to attribute values."
  [el]
  (let [el (get-el el)
        attrs (.-attributes el)]
    (->> (range (.-length attrs))
         (map #(->> % (.item attrs) attr->clj))
         (into {}))))

;; (defn set-attr! ...)
;; ...

(comment

  ;; ...

  (->> children
       (map get-attrs)
       log)
  ;; => ({:class "cljcastr"}
  ;;     {:controls "true",
  ;;      :src "https://media.zencastr.com/audio-files/...",
  ;;      :class "cljcastr"})

  )

Now that we know how to get both the name of the tag and its attributes, let's combine them into a function that we can use to map over a list of elements and transform them into a nice Clojurey data structure.

Data is elemental

Climbing into our hammock ever so briefly, we sketch out the following:

{:tag "{{tag-name}}"
 :attrs {:k1 "{{v1}}"
         :k2 "{{v2}}"}}

Given this data structure and the functions we've already written, it's not too difficult to write the code:

(comment

  ;; ...
  
  (->> children
       (map (fn [el]
              {:tag (get-name el)
               :attrs (get-attrs el)}))
       log)
  ;; => ({:tag "h1", :attrs {:class "cljcastr"}}
  ;;     {:tag "audio",
  ;;      :attrs {:controls "true",
  ;;              :src "https://media.zencastr.com/audio-files/...",
  ;;              :class "cljcastr"}})

  )

The only thing missing from this is the inner text for the h1 element. Let's add a :text key to our map for elements that have text:

(comment

  ;; ...
  
  (->> children
       (map (fn [el]
              (let [text (get-text el)]
                (merge {:tag (get-name el)
                        :attrs (get-attrs el)}
                       (when-not (empty? text)
                         {:text text})))))
       log)
  ;; => ({:tag "h1", :attrs {:class "cljcastr"}, :text "cljcastr player"}
  ;;     {:tag "audio",
  ;;      :attrs {:controls "true",
  ;;              :src "https://media.zencastr.com/audio-files/...",
  ;;              :class "cljcastr"}})

  )

Let's turn this into a nice function, and whilst we're at it, add all of the keys that create-el takes. We also want to handle the case where the function is called with a Clojure representation of an element (i.e. a map), in which case it should just return the map:

(ns cljcastr.player)

;; ...
;; (defn add-style! ...)

(defn el->clj
  "Given an HTML element, returns a map containing :tag, :id, :classes, :styles,
   :text, and :attrs."
  [el]
  (if (map? el)
    el
    (let [el (get-el el)]
      (->> {:tag (get-name el)
            :id (get-id el)
            :classes (get-classes el)
            :styles (get-styles el)
            :text (get-text el)
            :attrs (get-attrs el)}
           (remove (fn [[_ v]] (empty? v)))
           (into {})))))

;; (defn create-el ...)
;; ...

(comment

  ;; ...
  
  (->> children
       (map el->clj)
       log)
  ;; => ({:tag "h1",
  ;;      :classes ("cljcastr"),
  ;;      :text "cljcastr player",
  ;;      :attrs {:class "cljcastr"}}
  ;;     {:tag "audio",
  ;;      :classes ("cljcastr"),
  ;;      :attrs {:controls "true",
  ;;              :src "https://media.zencastr.com/audio-files/...",
  ;;              :class "cljcastr"}})

  )

I wonder if we can roundtrip an element to a map back to an element?

(comment

  ;; ...

  (->> (create-el {:tag "button"
                   :id "button-play"
                   :classes ["cljcastr" "playback-button"]
                   :styles {:padding "0px"
                            :margin "0px"
                            :border "0px"
                            :background "transparent"
                            :cursor "pointer"}
                   :attrs {:aria-label "Play"}})
       el->clj
       create-el
       log)
  ;; => #object[HTMLButtonElement [object HTMLButtonElement]]

  )

Looking good! From this, it's pretty straightforward to turn this into an HTML string:

(comment

  ;; ...
  
  (->> children
       (map el->clj)
       (map (fn [{:keys [tag attrs text]}]
              (let [attrs-str (if (empty? attrs)
                                ""
                                (str " "
                                     (->> attrs
                                          (map (fn [[k v]] (str (name k) "=\"" v "\"")))
                                          (str/join " "))))]
                (str "<" tag attrs-str ">" text "</" tag ">"))))
       (str/join "\n")
       log)
  ;; => "<h1 class=\"cljcastr\">cljcastr player</h1>\n
  ;;     <audio controls=\"true\"
  ;;       src=\"https://media.zencastr.com/audio-files/...\"
  ;;       class=\"cljcastr\"></audio>"

  )

That looks pretty reasonable, so let's extract a few functions:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn el->clj ...)

(defn attrs->str
  "Given a map of attributes, returns a string of k=\"v\"..."
  [attrs]
  (->> attrs
       (map (fn [[k v]] (str (name k) "=\"" v "\"")))
       (str/join " ")))

(defn el->html
  "Given an element (or the Clojure representation of an element), returns an
   HTML string."
  [el]
  (let [{:keys [tag attrs text]} (if (map? el) el (el->clj el))
        attrs-str (attrs->str attrs)]
    (str "<" tag (if (empty? attrs-str) "" (str " " attrs-str)) ">"
         text
         "</" tag ">")))

;; (defn create-el ...)
;; ...

(comment

  ;; ...
  
  (->> children
       (map el->html)
       (str/join "\n")
       log)
  ;; => "<h1 class=\"cljcastr\">cljcastr player</h1>\n
  ;;     <audio controls=\"true\"
  ;;       src=\"https://media.zencastr.com/audio-files/...\"
  ;;       class=\"cljcastr\"></audio>"

  )

Just as we're about to paste our HTML into index.html, a thought occurs to us. We wrote some mucky DOM-tacular JS-interop code to create elements, but now we have an elegant Clojure data structure to describe our elements, and we can turn that into HTML, so why not into DOM nodes as well?

Well, given the way we've built up our functions for dealing with the DOM, it turns out we can do this easily!

(comment

  ;; ...

  (-> (create-el {:tag "h1", :attrs {:class "cljcastr"}, :text "cljcastr player"})
      log)
  ;; => #object[HTMLHeadingElement [object HTMLHeadingElement]]
  
  )

Looking at the browser console, we're convinced we're onto something:

  <h1 class="cljcastr">cljcastr player</h1>                          nrepl.cljs:10

Looks great! Now that we have a nicer way to build up elements interactively, as well as a way to dehydrate elements into HTML, let's think about what it would take to dehydrate the entire DOM tree rooted at our body tag.

We pretty much have everything we need:

(comment

  ;; ...

  (->> (get-els "body > .cljcastr")
       (map el->html)
       (str/join "\n")
       log)
  ;; => "<h1 class=\"cljcastr\">cljcastr player</h1>\n
  ;;     <audio controls=\"true\"
  ;;       src=\"https://media.zencastr.com/audio-files/...\"
  ;;       class=\"cljcastr\"></audio>"

  )

This looks great, so let's build the full podcast player we had before back up in our REPL and try dehydrating that into HTML. Might as well reload the page to make sure we're starting out with a pristine REPL. Remember to eval the buffer (C-c C-k) after reloading!

The resurrection

To rebuild our player, we could just step through the entire Rich comment from the beginning, evaluating each form one by one, but this sounds like a lot of work! Let's add a new add-attrs! function and another adornment to our create-el function to make life easier on ourselves:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn set-attrs! ...)
;; ...

(defn add-attrs! [el attrs]
  (let [el (get-el el)]
    (set-attrs! el (merge (get-attrs el) attrs))))

;; (defn get-id ...)
;; ...
;; (defn el->html ...)

(defn create-el [{:keys [tag id classes styles text attrs children] :as args}]
  (-> (js/document.createElement tag)
      (set-attrs! attrs)
      (set-id! id)
      (set-classes! classes)
      (set-styles! styles)
      (set-children! children)
      (set-text! text)))

;; (defn add-event-listener! ...)
;; ...

(comment

  ;; ...

  (def seek-dur-sec 15)
  ;; => #'cljcastr.player/seek-dur-sec

  (def playback-controls
    {:play {:src "https://www.svgrepo.com/show/436852/play-circle-fill.svg"
            :label "Play"
            :click-handler #(.play (get-el "audio.cljcastr"))}
     :pause {:src "https://www.svgrepo.com/show/436829/pause-circle-fill.svg"
             :label "Pause"
             :click-handler #(.pause (get-el "audio.cljcastr"))}
     :forward {:src "https://www.svgrepo.com/show/495321/forward-15-seconds.svg"
               :label "Forward {{seek-dur-sec}} seconds"
               :click-handler #(skip-forward! (get-el "audio.cljcastr") seek-dur-sec)}
     :backward {:src "https://www.svgrepo.com/show/495036/backward-15-seconds.svg"
                :label "Back {{seek-dur-sec}} seconds"
                :click-handler #(skip-backward! (get-el "audio.cljcastr") seek-dur-sec)}
     :speed {:src "https://www.svgrepo.com/show/151785/speed-meter.svg"
             :label "Playback speed"}})
  ;; => #'cljcastr.player/playback-controls

  (->> (create-el {:tag "div"
                   :id "episode-container"
                   :classes ["cljcastr"]
                   :styles {:width "100%"
                            :display "flex"
                            :flex-direction "column"
                            :align-items "center"}
                   :children
                   [
                    ;; episode-info
                    (create-el {:tag "div"
                                :id "episode-info"
                                :classes ["cljcastr"]
                                :styles {:max-width "420px"
                                         :text-align "center"}
                                :children
                                [(create-el {:tag "h3"
                                             :id "podcast-title"
                                             :classes ["cljcastr"]
                                             :text "defn"})
                                 (create-el {:tag "h2"
                                             :id "episode-title"
                                             :classes ["cljcastr"]
                                             :text "876b4c306172 Cora Sutton"})
                                 (create-el {:tag "span"
                                             :id "episode-date"
                                             :classes ["cljcastr"]
                                             :styles {:color "grey"}
                                             :text "July 9, 2025"})]})

                    ;;episode-art
                    (create-el {:tag "div"
                                :id "episode-art-container"
                                :classes ["cljcastr"]
                                :children
                                [(create-el {:tag "img"
                                             :id "episode-art"
                                             :classes ["cljcastr"]
                                             :styles {:width "400px"
                                                      :border-radius "5%"
                                                      :padding "10px"}
                                             :attrs {:src "https://media.zencastr.com/image-files/5d9048546bacd9001de88f1c/a5b922ac-7294-4d58-9a33-4308f5d4f50b.png"}})]})

                    ;;audio
                    (-> (create-el {:tag "audio"
                                    :classes ["cljcastr"]
                                    :attrs {:controls true
                                            :src "https://media.zencastr.com/audio-files/5d9048546bacd9001de88f1c/2abc6f33-6a0a-4658-a8e0-c811984c13a0.mp3"}
                                    :styles {:display "none"}})
                        (add-event-listener! "timeupdate"
                                             (fn [ev]
                                               (let [audio (.-target ev)]
                                                 (update-playback-position-indicators!
                                                  (.-currentTime audio) (.-duration audio)
                                                  {:elapsed-time "#elapsed-time"
                                                   :remaining-time "#remaining-time"
                                                   :progress-slider "#progress-slider"
                                                   :progress-bar "#progress-bar"})))))

                    ;;progress
                    (create-el {:tag "div"
                                :id "progress"
                                :classes ["cljcastr"]
                                :styles {:width "390px"
                                         :margin "1.5em auto 0 auto"}
                                :children
                                [(create-el {:tag "span"
                                             :text (secs->ts 0)
                                             :classes ["cljcastr"]
                                             :id "elapsed-time"
                                             :styles {:margin "0 5px 0 5px"
                                                      :font-size "0.7rem"
                                                      :color "grey"
                                                      :float "left"}})
                                 (create-el {:tag "span"
                                             :text (secs->ts 0)
                                             :classes ["cljcastr"]
                                             :id "remaining-time"
                                             :styles {:margin "0 5px 0 5px"
                                                      :font-size "0.7rem"
                                                      :color "grey"
                                                      :float "right"}})
                                 (create-el {:tag "div"
                                             :id "progress-container"
                                             :classes ["cljcastr"]
                                             :styles {:position "relative"
                                                      :height "28px"
                                                      :clear "both"}
                                             :children
                                             [(create-el {:tag "progress"
                                                          :id "progress-bar"
                                                          :classes ["cljcastr"]
                                                          :attrs {:min 0
                                                                  :max 0
                                                                  :value 0}
                                                          :styles {:appearance "none"
                                                                   :height "8px"
                                                                   :width "100%"
                                                                   :border "0"
                                                                   :border-radius "4px"
                                                                   :margin "0"
                                                                   :overflow "hidden"
                                                                   :background-color "lightgray"
                                                                   :color "#f7931e"
                                                                   :position "absolute"
                                                                   :top "10px"
                                                                   :left "0px"
                                                                   :z-index 0}})
                                              (create-el {:tag "input"
                                                          :id "progress-slider"
                                                          :classes ["cljcastr"]
                                                          :attrs {:type "range"
                                                                  :min 0
                                                                  :max 0
                                                                  :value 0
                                                                  :step "any"
                                                                  :aria-label "Seek"
                                                                  :aria-valuetext (str (secs->ts 0)
                                                                                       " of "
                                                                                       (secs->ts 0))
                                                                  :aria-valuemax 0}
                                                          :styles {:appearance "none"
                                                                   :cursor "pointer"
                                                                   :height "28px"
                                                                   :width "100%"
                                                                   :border "0"
                                                                   :margin "0"
                                                                   :touch-action "manipulation"
                                                                   :position "absolute"
                                                                   :top "0px"
                                                                   :left "0px"
                                                                   :z-index 1
                                                                   :background-color "transparent"}})]})]})

                    ;;playback-controls
                    (create-el {:tag "div"
                                :id "playback-controls"
                                :classes ["cljcastr"]
                                :children
                                (->> [:backward :play :pause :forward :speed]
                                     (map (fn [button-name]
                                            [button-name (get playback-controls button-name)]))
                                     (map (fn [[button-name button]]
                                            (let [button-el (create-button button-name button
                                                                           {:seek-dur-sec seek-dur-sec
                                                                            :button-class "playback-button"
                                                                            :img-class "playback-icon"})]
                                              (-> (get-children button-el)
                                                  first
                                                  (set-styles! {:width "35px"
                                                                :filter (str "invert(59%) sepia(92%) saturate(611%) "
                                                                             "hue-rotate(343deg) brightness(97%) contrast(99%)")}))
                                              button-el))) log)})]})
       log
       list
       (set-children! "body"))
  ;; => #object[HTMLBodyElement [object HTMLBodyElement]]

  (let [audio (get-el "audio.cljcastr")]
    (set-text! "#elapsed-time" (secs->ts (.-currentTime audio)))
    (set-text! "#remaining-time" (secs->ts (- (.-duration audio)
                                              (.-currentTime audio))))
    (add-attrs! "#progress-bar" {:max (.-duration audio)
                                 :value (.-currentTime audio)})
    (add-attrs! "#progress-slider" {:max (.-duration audio)
                                    :value (.-currentTime audio)
                                    :aria-valuetext (str (secs->ts (.-currentTime audio))
                                                         " of "
                                                         (secs->ts (.-duration audio)))
                                    :aria-valuemax (.-duration audio)}))
  ;; => #object[HTMLInputElement [object HTMLInputElement]]
  
  )

Much like Lazarus, our podcast player hath now been resurrected! And also like Lazarus, the method of resurrection required divine powers. But fear not! for this shall be the last time we rely on the divine to rebuild our player.

It's an unstable era

Let's get back to dehydration, shall we? We can use the same method as before, when we had a really simple player:

(comment

  ;; ...

  (->> (get-els "body > .cljcastr")
       (map el->html)
       (str/join "\n")
       log)
  ;; => "<div id=\"episode-container\" class=\"cljcastr\"
  ;;       style=\"width: 100%; display: flex; flex-direction: column;
  ;;       align-items: center;\">
  ;;       defn876b4c306172 Cora SuttonJuly 9, 202500:001:29:30</div>"

  )

Hrm, that's not very helpful. First of all, we're only getting the direct children of our body element, which in this case is a single child: the episode-container div. What we'd actually like is the entire tree of elements rooted at body.

Let's see if we can figure out how to do that.

(comment

  ;; ...

  (->> (get-els "body > .cljcastr")
       (map (fn [el]
              (let [{:keys [tag attrs text]} (if (map? el) el (el->clj el))
                    attrs-str (attrs->str attrs)
                    tag-open (str "  <" tag (if (empty? attrs-str) "" (str " " attrs-str)) ">")
                    tag-close (str "</" tag ">")
                    children (get-children el)]
                (if (seq children)
                  (str/join "\n"
                            (concat [tag-open]
                                    (map el->html children)
                                    [tag-close]))
                  (str tag-open text tag-close)))))
       (str/join "\n")
       log)
  ;; => "<div id=\"episode-container\" class=\"cljcastr\" style=\"...\">\n
  ;;       <div id=\"episode-info\" class=\"cljcastr\" style=\"...\">defn876b4c306172 Cora SuttonJuly 9, 2025</div>\n
  ;;       <div id=\"episode-art-container\" class=\"cljcastr\"></div>\n
  ;;       <audio controls=\"true\" src=\"https://media.zencastr.com/audio-files/...\" class=\"cljcastr\" style=\"display: none;\"></audio>\n
  ;;       <div id=\"progress\" class=\"cljcastr\" style=\"...\">00:37-1:28:53</div>\n
  ;;       <div id=\"playback-controls\" class=\"cljcastr\"></div>\n
  ;;       </div>"

  )

OK, this is progress, but we're only grabbing the first level of children. In order to include grandchildren and great-grandchildren and great-great-grandchildren (and so on to the last syllable of recorded time), we'll need to include our new code in el->html itself:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn attrs->str ...)

(defn el->html
  "Given an element (or the Clojure representation of an element), returns an
   HTML string."
  [el]
  (let [{:keys [tag attrs text]} (if (map? el) el (el->clj el))
        attrs-str (attrs->str attrs)
        tag-open (str "  <" tag (if (empty? attrs-str) "" (str " " attrs-str)) ">")
        tag-close (str "</" tag ">")
        children (get-children el)]
    (if (seq children)
      (str/join "\n"
                (concat [tag-open]
                        (map el->html children)
                        [tag-close]))
      (str tag-open text tag-close))))

;; (defn create-el ...)
;; ...

(comment

  ;; ...

  (->> (get-els "body > .cljcastr")
       (map el->html)
       (str/join "\n")
       log)
  ;; => "#error {:message \"Failed to execute 'querySelector' on 'Document':
  ;;                        '[object Text]' is not a valid selector.\",
  ;;             ...}"

  )

Well, that doesn't look promising. Let's see if we can figure this out.

Textual healing

Looking back out at the HTML we generated in previously, we get a hint about which element might be the culprit:

  ;; => "<div id=\"episode-container\" class=\"cljcastr\" style=\"...\">\n
  ;;       <div id=\"episode-info\" class=\"cljcastr\" style=\"...\">defn876b4c306172 Cora SuttonJuly 9, 2025</div>\n

Our #episode-info div looks a bit odd, doesn't it. Let's take a closer look:

(comment

  ;; ...

  (get-children "#episode-info")
  ;; => (#object[HTMLHeadingElement [object HTMLHeadingElement]]
  ;;     #object[HTMLHeadingElement [object HTMLHeadingElement]]
  ;;     #object[HTMLSpanElement [object HTMLSpanElement]])

  )

OK, so #episode-info has three children: two headings and a span. Let's feed the first child to el->html and see what happens:

(comment

  ;; ...

  (-> (get-children "#episode-info")
      first
      el->html)
  ;; => "#error {:message \"Failed to execute 'querySelector' on 'Document':
  ;;                        '[object Text]' is not a valid selector.\",
  ;;             ...}"

  (-> (get-children "#episode-info")
      first
      get-children
      log)
  ;; => (#object[Text [object Text]])

  )

Ah yes, there it is. So there seems to be something special about a Text node that causes el->html to blow up. Let's see what we can actually do with this type of object. Reading the documentation, we see that it inherits from the CharacterData class, which has a handy data attribute that is "string representing the textual data contained in this object". Let's try that out:

(comment

  ;; ...

  (-> (get-children "#episode-info")
      first
      get-children
      first
      log)
  ;; => #object[Text [object Text]]

  (-> (get-children "#episode-info")
      first
      get-children
      first
      (.-data))
  ;; => "defn"

  )

Armed with this knowledge, we should be able to fix get-text to handle Text nodes:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn get-name ...)

(defn get-text
  "Returns the inner text of an element."
  [el]
  (let [el (get-el el)]
    (if (instance? js/CharacterData el)
      (.-data el)
      (or (.-textContent el)
          (.-innerText el)))))

;; (defn set-text! ...)
;; ...

(comment

  ;; ...

  (-> (get-children "#episode-info")
      first
      get-children
      first
      get-text)
  ;; => "#error {:message \"Failed to execute 'querySelector' on 'Document':
  ;;                        '[object Text]' is not a valid selector.\",
  ;;             ...}"

  )

Hrm, we're back to this. Let's trace through get-text line by line to see if we can figure out what's going on:

(let [el (get-el el)]
  ...)

So we'd be calling (get-el) with our Text node. Let's try that and see what happens:

(comment

  ;; ...

  (-> (get-children "#episode-info")
      first
      get-children
      first
      get-el)
  ;; => "#error {:message \"Failed to execute 'querySelector' on 'Document':
  ;;                        '[object Text]' is not a valid selector.\",
  ;;             ...}"

  )

Aha, so the problem is in get-el, which looks like this:

(defn get-el [selector]
  (if (instance? js/Element selector)
    selector
    (js/document.querySelector selector)))

What we're trying to do here is just return the selector arg if we're passed an element, otherwise assume selector is a string and use Document.querySelector to look up the element. But wait, why should we assume it's a string? Why not actually check? In fact, why not actually write the function in the same way we would describe it in English?

If selector is a string, returns the element matching CSS selector. Otherwise, assume it's already an element and just return it.

And whilst we're at it, why not update the docstring of the function to say exactly this?

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn secs->ts ...)

(defn get-el
  "If `selector` is a string, returns the element matching CSS selector.
   Otherwise, assume it's already an element and just return it."
  [selector]
  (if (string? selector)
    (js/document.querySelector selector)
    selector))

;; (defn get-els ...)
;; ...

(comment

  ;; ...

  (-> (get-children "#episode-info")
      first
      get-children
      first
      get-text)
  ;; => "defn"

  )

Much better!

However, we still have that annoying word "assume" in our docstring. 😬

Returns the element matching the specified CSS selector. If selector is already an element, just returns the element.

How about we stop assuming, and actually throw an exception when we get an argument we can't handle? Sounds good, but the reason we're in this mess is because we were treating anything that wasn't an Element object as a string, and we discovered that Text isn't a subclass of Element. So what we actually want is a common ancestor of both Text and Element, right? And luckily, there is just such a subclass: Node! πŸŽ‰

Let's use that:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn secs->ts ...)

(defn get-el
  "If `selector` is a string, returns the element matching CSS selector.
   If `selector` is a `Node`, returns it. Otherwise, throws an exception."
  [selector]
  (cond
    (string? selector)
    (js/document.querySelector selector)

    (instance? js/Node selector)
    selector

    :else
    (let [cls (-> selector .-constructor .-name)]
      (throw (ex-info (str "Expecting a string or a Node; got: " cls)
                      {:dom/error :dom/error.invalid-class
                       :js/class cls})))))

;; (defn get-els ...)
;; ...

(comment

  ;; ...

  (get-el "#podcast-title")
  ;; => #object[HTMLHeadingElement [object HTMLHeadingElement]]

  (get-el (js/document.querySelector "#podcast-title"))
  ;; => #object[HTMLHeadingElement [object HTMLHeadingElement]]

  (get-el 42)
  ;; => "#error {:message \"Expecting a string or a Node; got: Number\", ...}"

  (try
    (get-el 42)
    (catch js/Error e
      (ex-data e)))
  ;; => {:dom/error :dom/error.invalid-class, :js/class "Number"}

  (-> (get-children "#episode-info")
      first
      get-children
      first
      get-text)
  ;; => "defn"

  )

Let's try turning the #episode-info div into HTML:

(comment

  ;; ...

  (el->html "#episode-info")
  ;; => "#error {:message \"Could not find instance method: getAttribute\", ...}"

  )

George Clooney sings "I Am a Man of Constant Sorrow"

Let's slow down for a second and actually think this through. What we're dealing with is HTML like this:

<h3>defn</h3>

which is represented by a DOM node that we can create like this:

(create-el {:tag "h3", :text "defn"})

And if we currently try to turn this into HTML, we get the "Could not find instance method: getAttribute" error, which makes sense, because neither Text nor any of its parent classes (CharacterData and Node) have a .getAttribute() method, and el->html calls el->clj, which in turn will try to get all sorts of attributes from the poor Text object. 😭

We should be able to solve this by making sure el->html can handle a Text node:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn attrs->str ...)

(defn el->html
  "Given an element (or the Clojure representation of an element), returns an
   HTML string."
  [el]
  (if (instance? js/CharacterData el)
    (get-text el)
    (let [{:keys [tag attrs text]} (if (map? el) el (el->clj el))
          attrs-str (attrs->str attrs)
          tag-open (str "  <" tag (if (empty? attrs-str) "" (str " " attrs-str)) ">")
          tag-close (str "</" tag ">")
          children (get-children el)]
      (if (seq children)
        (str/join "\n"
                  (concat [tag-open]
                          (map el->html children)
                          [tag-close]))
        (str tag-open text tag-close)))))

;; (defn format-css ...)
;; ...

(comment

  ;; ...

  (el->html (js/Text. "foo"))
  ;; => "foo"

  (-> (create-el {:tag "h3", :text "defn"})
      el->html)
  ;; => "  <h3>\ndefn\n</h3>"

  )

That seems somewhat reasonable, so let's see what happens when we turn the entire #episode-info div into HTML now:

(comment

  ;; ...

  (el->html "#episode-info")
  ;; => "  <div id=\"episode-info\" class=\"cljcastr\" style=\"max-width: 420px; text-align: center;\">\n
  ;;       <h3 id=\"podcast-title\" class=\"cljcastr\">\ndefn\n</h3>\n
  ;;       <h2 id=\"episode-title\" class=\"cljcastr\">\n876b4c306172 Cora Sutton\n</h2>\n
  ;;       <span id=\"episode-date\" class=\"cljcastr\" style=\"color: grey;\">\nJuly 9, 2025\n</span>\n
  ;;       </div>"

  )

Hey, not bad!

HTML at last

Feeling confident, we go ahead and dump the entire DOM to HTML:

(comment

  ;; ...

  (-> (el->html "html")
      log)
  ;; => "  <html xmlns=\"http://www.w3.org/1999/xhtml\">\n
  ;;       <head>\n\n
  ;;       \n
  ;;       <title>\ncljcastr episode player\n</title>\n\n
  ;;       \n
  ;;       <link rel=\"stylesheet\" href=\"main.css\"></link>\n\n\n
  ;;       \n
  ;;       <script src=\"https://cdn.jsdelivr.net/npm/scittle@0.8.33/dist/scittle.js\" type=\"application/javascript\"></script>\n\n
  ;;       \n
  ;;       <script>\nvar SCITTLE_NREPL_WEBSOCKET_PORT = 1340;\n</script>\n\n
  ;;       \n
  ;;       <script src=\"https://cdn.jsdelivr.net/npm/scittle@0.8.33/dist/scittle.nrepl.js\" type=\"application/javascript\"></script>\n\n\n\n
  ;;       <script type=\"application/x-scittle\" src=\"player.cljs\"></script>\n\n\n</head>\n\n\n\n
  ;;       <body>\n
  ;;       <div class=\"translate-tooltip-mtz blue sm-root translate hidden_translate\">
  ;;       <div class=\"header-wrapper\">
  ;;       <div class=\"header-controls\">
  ;;       ...
  ;;       </div>
  ;;       <span class=\"translate-button-mtz hidden_translate blue\"></span>\n
  ;;       <audio class=\"audio-for-speech\" src=\"\"></audio>\n
  ;;       <div id=\"episode-container\" class=\"cljcastr\" style=\"width: 100%; display: flex; flex-direction: column; align-items: center;\">\n
  ;;       <div id=\"episode-info\" class=\"cljcastr\" style=\"max-width: 420px; text-align: center;\">\n
  ;;       <h3 id=\"podcast-title\" class=\"cljcastr\">\ndefn\n</h3>\n
  ;;       <h2 id=\"episode-title\" class=\"cljcastr\">\n876b4c306172 Cora Sutton\n</h2>\n
  ;;       <span id=\"episode-date\" class=\"cljcastr\" style=\"color: grey;\">\nJuly 9, 2025\n</span>\n
  ;;       </div>\n
  ;;       ...
  ;;       <button aria-label=\"Playback speed\" id=\"button-speed\" class=\"cljcastr playback-button\" style=\"padding: 0px; margin: 0px; border: 0px; background: transparent; cursor: pointer;\">\n
  ;;       <img src=\"https://www.svgrepo.com/show/151785/speed-meter.svg\" draggable=\"false\" id=\"button-speed-icon\" class=\"cljcastr playback-icon\" style=\"width: 35px; filter: invert(59%) sepia(92%) saturate(611%) hue-rotate(343deg) brightness(97%) contrast(99%);\"></img>\n
  ;;       </button>\n
  ;;       </div>\n
  ;;       </div>\n
  ;;       </body>\n
  ;;       </html>"
  
  )

Now that's more like it! Better yet, if we look in the browser console, we see some HTML:

HTML code

Let's copy this HTML from the console and paste it into our index.html:

  <html xmlns="http://www.w3.org/1999/xhtml">
  <head>

  
  <title>
cljcastr episode player
</title>


  
  <script src="https://cdn.jsdelivr.net/npm/scittle@0.8.33/dist/scittle.js" type="application/javascript"></script>

  
  <script>
var SCITTLE_NREPL_WEBSOCKET_PORT = 1340;
</script>

  
  <script src="https://cdn.jsdelivr.net/npm/scittle@0.8.33/dist/scittle.nrepl.js" type="application/javascript"></script>



  <script type="application/x-scittle" src="player.cljs"></script>


</head>



  <body>
  <div id="episode-container" class="cljcastr" style="width: 100%; display: flex; flex-direction: column; align-items: center;">
  <div id="episode-info" class="cljcastr" style="max-width: 420px; text-align: center;">
  <h3 id="podcast-title" class="cljcastr">
defn
</h3>
  <h2 id="episode-title" class="cljcastr">
876b4c306172 Cora Sutton
</h2>
  <span id="episode-date" class="cljcastr" style="color: grey;">
July 9, 2025
</span>
</div>
  <div id="episode-art-container" class="cljcastr">
  <img src="https://media.zencastr.com/image-files/5d9048546bacd9001de88f1c/a5b922ac-7294-4d58-9a33-4308f5d4f50b.png" id="episode-art" class="cljcastr" style="width: 400px; border-radius: 5%; padding: 10px;"></img>
</div>
  <audio controls="true" src="https://media.zencastr.com/audio-files/5d9048546bacd9001de88f1c/2abc6f33-6a0a-4658-a8e0-c811984c13a0.mp3" class="cljcastr" style="display: none;"></audio>
  <div id="progress" class="cljcastr" style="width: 390px; margin: 1.5em auto 0px;">
  <span id="elapsed-time" class="cljcastr" style="margin: 0px 5px; font-size: 0.7rem; color: grey; float: left;">
00:00
</span>
  <span id="remaining-time" class="cljcastr" style="margin: 0px 5px; font-size: 0.7rem; color: grey; float: right;">
1:29:30
</span>
  <div id="progress-container" class="cljcastr" style="position: relative; height: 28px; clear: both;">
  <progress min="0" max="5370.949958" value="0" id="progress-bar" class="cljcastr" style="color: rgb(247, 147, 30); top: 10px; overflow: hidden; background-color: lightgray; width: 100%; z-index: 0; appearance: none; position: absolute; border: 0px; border-radius: 4px; height: 8px; left: 0px; margin: 0px;"></progress>
  <input min="0" value="0" aria-valuemax="5370.949958" type="range" style="top: 0px; background-color: transparent; width: 100%; cursor: pointer; z-index: 1; appearance: none; position: absolute; border: 0px; touch-action: manipulation; height: 28px; left: 0px; margin: 0px;" aria-valuetext="00:00 of 1:29:30" max="5370.949958" id="progress-slider" class="cljcastr" aria-label="Seek" step="any"></input>
</div>
</div>
  <div id="playback-controls" class="cljcastr">
  <button aria-label="Back 15 seconds" id="button-backward" class="cljcastr playback-button" style="padding: 0px; margin: 0px; border: 0px; background: transparent; cursor: pointer;">
  <img src="https://www.svgrepo.com/show/495036/backward-15-seconds.svg" draggable="false" id="button-backward-icon" class="cljcastr playback-icon" style="width: 35px; filter: invert(59%) sepia(92%) saturate(611%) hue-rotate(343deg) brightness(97%) contrast(99%);"></img>
</button>
  <button aria-label="Play" id="button-play" class="cljcastr playback-button" style="padding: 0px; margin: 0px; border: 0px; background: transparent; cursor: pointer;">
  <img src="https://www.svgrepo.com/show/436852/play-circle-fill.svg" draggable="false" id="button-play-icon" class="cljcastr playback-icon" style="width: 35px; filter: invert(59%) sepia(92%) saturate(611%) hue-rotate(343deg) brightness(97%) contrast(99%);"></img>
</button>
  <button aria-label="Pause" id="button-pause" class="cljcastr playback-button" style="padding: 0px; margin: 0px; border: 0px; background: transparent; cursor: pointer;">
  <img src="https://www.svgrepo.com/show/436829/pause-circle-fill.svg" draggable="false" id="button-pause-icon" class="cljcastr playback-icon" style="width: 35px; filter: invert(59%) sepia(92%) saturate(611%) hue-rotate(343deg) brightness(97%) contrast(99%);"></img>
</button>
  <button aria-label="Forward 15 seconds" id="button-forward" class="cljcastr playback-button" style="padding: 0px; margin: 0px; border: 0px; background: transparent; cursor: pointer;">
  <img src="https://www.svgrepo.com/show/495321/forward-15-seconds.svg" draggable="false" id="button-forward-icon" class="cljcastr playback-icon" style="width: 35px; filter: invert(59%) sepia(92%) saturate(611%) hue-rotate(343deg) brightness(97%) contrast(99%);"></img>
</button>
  <button aria-label="Playback speed" id="button-speed" class="cljcastr playback-button" style="padding: 0px; margin: 0px; border: 0px; background: transparent; cursor: pointer;">
  <img src="https://www.svgrepo.com/show/151785/speed-meter.svg" draggable="false" id="button-speed-icon" class="cljcastr playback-icon" style="width: 35px; filter: invert(59%) sepia(92%) saturate(611%) hue-rotate(343deg) brightness(97%) contrast(99%);"></img>
</button>
</div>
</div>
<protonpass-root-c873 data-protonpass-role="root" data-protonpass-theme="os"></protonpass-root-c873>
</body>

</html>

Saving the file, we take a deep breath and refresh the page in the browser. Et voilΓ , our page reappears just as we'd left it! πŸŽ‰

This is wonderful and all, but that HTML that we produced is a bit of an eyesore:

  <html xmlns="http://www.w3.org/1999/xhtml">
  <head>

  
  <title>
cljcastr episode player
</title>

  
  <link rel="stylesheet" href="main.css"></link>

  ...

</head>



  <body>
  <audio class="audio-for-speech" src=""></audio>
  <div class=\"translate-tooltip-mtz blue sm-root translate hidden_translate\">
  <div class=\"header-wrapper\">
  <div class=\"header-controls\">
  <span class=\"sound-translate\"></span>
  <span class=\"copy blue\"></span>
  <span class=\"settings-translator\"></span>
  </div>
  <div class=\"header-title\">translator</div>
  <div class=\"translate-icons\">
  <img class=\"from\" src=\"\"></img>
  <img class=\"translate-arrow\" src=\"chrome-extension://bebmphofpgkhclocdbgomhnjcpelbenh/images/right-arrow.png\"></img>
  <div class=\"translate_to_dropdown\">
  <button class=\"dropbtn dropdown-toggle\" type=\"button\" id=\"dropdownMenuButton1\" aria-expanded=\"false\"></button>
  <ul class=\"dropdown-content-wrapper languageSelector blue\">
  <li>
  <a class=\"dropdown-item\" data-lang=\"af\">Afrikaans</a>
  </li>
  <li>
  <a class=\"dropdown-item\" data-lang=\"sq\">Albanian - shqipe</a>
  </li>
  <li>
  <a class=\"dropdown-item\" data-lang=\"ar\">Arabic - β€Žβ€«Ψ§Ω„ΨΉΨ±Ψ¨ΩŠΨ©β€¬β€Ž</a>
  </li>
  ...
  <li>
  <a class=\"dropdown-item\" data-lang=\"yi\">Yiddish - Χ™Χ™Χ“Χ™Χ©</a>
  </li>
  </ul>
  </div>
  </div>
  </div>
  <div class=\"translated-text\">
  ...
  <div id="episode-container" class="cljcastr" style="width: 100%; display: flex; flex-direction: column; align-items: center;">
  <div id="episode-info" class="cljcastr" style="max-width: 420px; text-align: center;">
  ...
</button>
</div>
</div>
<protonpass-root-c873 data-protonpass-role="root" data-protonpass-theme="os"></protonpass-root-c873>
</body>

</html>

In addition to all this whitespace, what's that weird stuff we didn't add to the DOM?

  <audio class="audio-for-speech" src=""></audio>
  <div class=\"translate-tooltip-mtz blue sm-root translate hidden_translate\">
  <div class=\"header-wrapper\">
  <div class=\"header-controls\">
  ...
<protonpass-root-c873 data-protonpass-role="root" data-protonpass-theme="os"></protonpass-root-c873>

It seems that extensions occasionally shove stuff into the DOM, so maybe we should give ourselves a way to filter out nodes we don't want. Let's start by adding a new arity to get-children that lets us filter and remove children using an options map:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn set-classes! ...)

(defn get-children
  "Returns the children of the specified element. Accepts an `opts` map with the
   following keys:

     `:filter-children` - predicate passed to `filter` on list of children
     `:remove-children` - predicate passed to `remove` on list of children

   `filter` is called before `remove`."
  ([el]
   (get-children el {}))
  ([el {:keys [filter-children remove-children]
        :or {filter-children (constantly true)
             remove-children (constantly false)} :as opts}]
   (->> (get-el el)
        .-childNodes
        seq
        (filter filter-children)
        (remove remove-children))))

;; (defn add-child! ...)
;; ...

(comment

  ;; ...

  (->> (get-children "#episode-info")
       log)
  ;; => (#object[Text [object Text]]
  ;;     #object[HTMLHeadingElement [object HTMLHeadingElement]]
  ;;     #object[Text [object Text]]
  ;;     #object[HTMLHeadingElement [object HTMLHeadingElement]]
  ;;     #object[Text [object Text]]
  ;;     #object[HTMLSpanElement [object HTMLSpanElement]]
  ;;     #object[Text [object Text]])

  (->> (get-children "#episode-info"
                     {:filter-children (partial instance? js/HTMLHeadingElement)})
       log
       (map get-text))
  ;; => ("\ndefn\n" "\n876b4c306172 Cora Sutton\n")

  (->> (get-children "#episode-info"
                     {:remove-children (partial instance? js/Text)})
       log
       (map get-text))
  ;; => ("\ndefn\n" "\n876b4c306172 Cora Sutton\n" "\nJuly 9, 2025\n")

  )

Now we need a way to pass those options in to get-children from el->html:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn attrs->str ...)

(defn el->html
  "Given an element (or the Clojure representation of an element), returns an
   HTML string."
  ([el]
   (el->html el {}))
  ([el opts]
   (if (instance? js/CharacterData el)
     (get-text el)
     (let [{:keys [tag attrs text]} (if (map? el) el (el->clj el))
           attrs-str (attrs->str attrs)
           tag-open (str "  <" tag (if (empty? attrs-str) "" (str " " attrs-str)) ">")
           tag-close (str "</" tag ">")
           children (get-children el opts)]
       (if (seq children)
         (str/join "\n"
                   (concat [tag-open]
                           (map #(el->html % opts) children)
                           [tag-close]))
         (str tag-open text tag-close))))))

;; (defn format-css ...)
;; ...

(comment

  ;; ...

  (el->html "#episode-info")
  ;; => "  <div id=\"episode-info\" class=\"cljcastr\" style=\"max-width: 420px; text-align: center;\">\n\n
  ;;       \n
  ;;       <h3 id=\"podcast-title\" class=\"cljcastr\">\n\ndefn\n\n</h3>\n\n
  ;;       \n
  ;;       <h2 id=\"episode-title\" class=\"cljcastr\">\n\n876b4c306172 Cora Sutton\n\n</h2>\n\n
  ;;       \n
  ;;       <span id=\"episode-date\" class=\"cljcastr\" style=\"color: grey;\">\n\n
  ;;       July 9, 2025\n\n</span>\n\n\n
  ;;       </div>"

  ;; Remove empty text nodes
  (el->html "#episode-info"
            {:remove-children #(empty? (str/replace (get-text %) #"[\n\s]+" ""))})
  ;; => "  <div id=\"episode-info\" class=\"cljcastr\" style=\"max-width: 420px; text-align: center;\">\n
  ;;       <h3 id=\"podcast-title\" class=\"cljcastr\">\n\ndefn\n\n</h3>\n
  ;;       <h2 id=\"episode-title\" class=\"cljcastr\">\n\n876b4c306172 Cora Sutton\n\n</h2>\n
  ;;       <span id=\"episode-date\" class=\"cljcastr\" style=\"color: grey;\">\n\nJuly 9, 2025\n\n</span>\n
  ;;       </div>"

  )

Now we have what we need to clean up our HTML a little bit:

(comment

  ;; ...

  (let [empty-text? #(and (instance? js/Text %)
                          (empty? (str/replace (get-text %) #"[\n\s]+" "")))]
    (el->html "html"
              {:remove-children (fn [el]
                                  (or (empty-text? el)
                                      ;; Bye-bye Proton Pass!
                                      (str/starts-with? (or (get-name el) "")
                                                        "protonpass-")
                                      ;; Be gone, Translator!
                                      (some #(str/starts-with? % "translate-")
                                            (get-classes el))
                                      (and (= "audio" (get-name el))
                                           (not (some #{"cljcastr"} (get-classes el))))))}))
  ;; => "  <html xmlns=\"http://www.w3.org/1999/xhtml\">\n
  ;;       <head>\n
  ;;       <title>\n\ncljcastr episode player\n\n</title>\n
  ;;       <link rel=\"stylesheet\" href=\"main.css\"></link>\n
  ;;       <script src=\"https://cdn.jsdelivr.net/npm/scittle@0.8.33/dist/scittle.js\" type=\"application/javascript\"></script>\n
  ;;       <script>\n\n
  ;;       var SCITTLE_NREPL_WEBSOCKET_PORT = 1340;\n\n
  ;;       </script>\n
  ;;       <script src=\"https://cdn.jsdelivr.net/npm/scittle@0.8.33/dist/scittle.nrepl.js\" type=\"application/javascript\"></script>\n
  ;;       <script type=\"application/x-scittle\" src=\"player.cljs\"></script>\n
  ;;       </head>\n
  ;;       <body>\n
  ;;       <div id=\"episode-container\" class=\"cljcastr\" style=\"width: 100%; display: flex; flex-direction: column; align-items: center;\">\n
  ;;       ...
  ;;       </div>\n
  ;;       </div>\n
  ;;       </body>\n
  ;;       </html>"

  )

This is cool and all, but the :remove-children function is getting a bit hairy, and we're haunted by the fact that we'll need to keep adding to it every time we install a new extension that inserts nodes into the DOM. This is the classic allowlist / denylist problem, and we can take a page out of the secure development notebook and deny all nodes by default, keeping only the ones we actually want.

Plausible deniability

We know that this means using :filter-children instead of :remove-children, but what should we allow? How about this:

  • The html, head, and body elements themselves
  • All elements that are descendants of the head element (i.e. children, grandchildren, great grandchildren, etc.)
  • All elements that are descendants of the body element that have the "cljcastr" class

Let's start by adding a function to check whether an element has a specific class:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn get-classes ...)

(defn has-class?
  "Returns true if the element's list of classes contains the specified class."
  [el cls]
  (-> (get-classes el)
      set
      (contains? cls)))

;; (defn set-classes! ...)
;; ...

(comment

  ;; ...

  (has-class? "#button-backward" "cljcastr")
  ;; => true

  )

Now, how about a function that checks whether one element is a descendant of another?

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn get-els ...)

(defn descendant?
  "Returns truthy if the specified element is an ancestor of the element named by
   the specified CSS selector. NOTE: `ancestor-sel` must be a string containing
   a CSS selector, not an element!"
  [el ancestor-sel]
  (-> (get-el el)
      (.closest ancestor-sel)))

;; (defn get-attr ...)
;; ...

(comment

  ;; ...

  (descendant? "#button-backward" "#episode-container")
  ;; => #object[HTMLDivElement [object HTMLDivElement]]

  (descendant? "#button-backward" "#episode-info")
  ;; => nil

  )

Given this, we should be able to write the :filter-children function of our dreams:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn ??? ...)

;; (defn ??? ...)
;; ...

(comment

  ;; ...

  (el->html "html"
            {:filter-children (fn [el]
                                (cond
                                  (instance? js/Text el)
                                  (-> (get-text el)
                                      (str/replace #"[\n\s]+" "")
                                      not-empty)
                                  
                                  (instance? js/Element el)
                                  (or (contains? #{"html" "head" "body"}
                                                 (get-name el))
                                      (descendant? el "head")
                                      (and (descendant? el "body")
                                           (has-class? el "cljcastr")))))})
  ;; => "  <html xmlns=\"http://www.w3.org/1999/xhtml\">\n
  ;;       <head>\n
  ;;       <title>cljcastr episode player</title>\n
  ;;       <link rel=\"stylesheet\" href=\"main.css\"></link>\n
  ;;       <script src=\"https://cdn.jsdelivr.net/npm/scittle@0.8.33/dist/scittle.js\" type=\"application/javascript\"></script>\n
  ;;       <script>var SCITTLE_NREPL_WEBSOCKET_PORT = 1340;</script>\n
  ;;       <script src=\"https://cdn.jsdelivr.net/npm/scittle@0.8.33/dist/scittle.nrepl.js\" type=\"application/javascript\"></script>\n
  ;;       <script type=\"application/x-scittle\" src=\"player.cljs\"></script>\n
  ;;       </head>\n
  ;;       <body>\n
  ;;       <div id=\"episode-container\" class=\"cljcastr\" style=\"width: 100%; display: flex; flex-direction: column; align-items: center;\">\n
  ;;       <div id=\"episode-info\" class=\"cljcastr\" style=\"max-width: 420px; text-align: center;\">\n
  ;;       ...
  ;;       </div>\n
  ;;       </div>\n
  ;;     </body>\n
  ;;     </html>\n
  ;;     "

  )

This is definite progress! We're still not loving that indentation, though.

Indenting for fun and profit

Let's think about how we'd like our HTML indented:

  1. Indent children by two spaces
  2. <head> and <body> should not be indented
  3. <head> and <body> should reset indentation
  4. The content of text nodes should go on the same line as the parent node

In other words, we'd like our HTML to look like this:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>cljcastr episode player</title>
  ...
</head>
<body>
  <div id="episode-container" class="cljcastr" style="width: 100%; display: flex; flex-direction: column; align-items: center;">
    <div id="episode-info" class="cljcastr" style="max-width: 420px; text-align: center;">
      <h3 id="podcast-title" class="cljcastr">defn</h3>
      <h2 id="episode-title" class="cljcastr">876b4c306172 Cora Sutton</h2>
      <span id="episode-date" class="cljcastr" style="color: grey;">July 9, 2025</span>
    </div>
    ...
</body>
</html>

Let's start with rule #4. First of all, what does the content of one of our text nodes look like?

(comment

  ;; ...

  (->> (get-children "#podcast-title")
       first
       get-text)
  ;; => "\ndefn\n"

  )

OK, it starts with a newline and ends with two newlines. How about we get rid of those?

(comment

  ;; ...

  (->> (get-children "#podcast-title")
       first
       get-text
       str/trim)
  ;; => "defn"

  )

Great! Now we can plug this into el->html. We also need to stop putting newlines between the children (this will mess up our formatting, but we'll address that as we work our way through the rest of the rules in our list).

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn attrs->str ...)

(defn el->html
  "Given an element (or the Clojure representation of an element), returns an
   HTML string."
  ([el]
   (el->html el {}))
  ([el opts]
   (if (instance? js/CharacterData el)
     (str/trim (get-text el))
     (let [{:keys [tag attrs text]} (if (map? el) el (el->clj el))
           attrs-str (attrs->str attrs)
           tag-open (str "  <" tag (if (empty? attrs-str) "" (str " " attrs-str)) ">")
           tag-close (str "</" tag ">")
           children (get-children el opts)]
       (if (seq children)
         (str/join ""
                   (concat [tag-open]
                           (map #(el->html % opts) children)
                           [tag-close]))
         (str tag-open text tag-close))))))

;; (defn format-css ...)
;; ...

(comment

  ;; ...

  (el->html "#podcast-title")
  ;; => "  <h3 id=\"podcast-title\" class=\"cljcastr\">defn</h3>"

  )

Great! That's rule #4 ticked off the list. Of course, this has made a bit of a mess of other things:

(comment

  ;; ...

  (el->html "#episode-info")
  ;; => "  <div id=\"episode-info\" class=\"cljcastr\" style=\"max-width: 420px; text-align: center;\">  <h3 id=\"podcast-title\" class=\"cljcastr\">defn</h3>  <h2 id=\"episode-title\" class=\"cljcastr\">876b4c306172 Cora Sutton</h2>  <span id=\"episode-date\" class=\"cljcastr\" style=\"color: grey;\">July 9, 2025</span></div>"

  )

Note the extreme lack of newlines there. We can address this by adding some indentation rules to our opts map:

  • :indent-level - number of levels to indent
  • :indent-str - string to use when indenting

Now for a little helper function:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn attrs->str ...)

(defn indent
  "Returns `indent-str` repeated `indent-level` times."
  [indent-level indent-str]
  (->> (repeat indent-level indent-str)
       (str/join "")))

;; (defn el->html ...)
;; ...

(comment

  ;; ...

  (->> (range 3)
       (map #(str (indent % "  ") "indent " %)))
  ;; => ("indent 0" "  indent 1" "    indent 2")

  )

Let's plug this into el->html:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn indent ...)

(defn el->html
  "Given an element (or the Clojure representation of an element), returns an
   HTML string."
  ([el]
   (el->html el {}))
  ([el {:keys [indent-level indent-str]
        :or {indent-level 0, indent-str "  "}
        :as opts}]
   (if (instance? js/CharacterData el)
     (str/trim (get-text el))
     (let [{:keys [tag attrs]} (if (map? el) el (el->clj el))
           attrs-str (attrs->str attrs)
           children-html (->> (get-children el opts)
                              (map #(el->html % (assoc opts :indent-level
                                                       (inc indent-level))))
                              (str/join ""))
           tag-open (str (indent indent-level indent-str)
                         "<" tag
                         (if (empty? attrs-str) "" (str " " attrs-str))
                         ">"
                         (if (str/ends-with? children-html "\n")
                           "\n"
                           ""))
           tag-close (str (if (str/ends-with? children-html "\n")
                            (indent indent-level indent-str)
                            "")
                          "</" tag ">\n")]
       (str tag-open children-html tag-close)))))

;; (defn format-css ...)
;; ...

(comment

  ;; ...

  (el->html "#episode-info")
  ;; => "<div id=\"episode-info\" class=\"cljcastr\" style=\"max-width: 420px; text-align: center;\">\n
  ;;       <h3 id=\"podcast-title\" class=\"cljcastr\">defn</h3>\n
  ;;       <h2 id=\"episode-title\" class=\"cljcastr\">876b4c306172 Cora Sutton</h2>\n
  ;;       <span id=\"episode-date\" class=\"cljcastr\" style=\"color: grey;\">July 9, 2025</span>\n
  ;;     </div>\n"

  )

Biting our bottom lip to keep the fear at bay, we unleash el->html on the entire DOM:

(comment

  ;; ...

  (el->html "html"
            {:filter-children (fn [el]
                                (cond
                                  (instance? js/Text el)
                                  (-> (get-text el)
                                      (str/replace #"[\n\s]+" "")
                                      not-empty)
                                  
                                  (instance? js/Element el)
                                  (or (contains? #{"html" "head" "body"}
                                                 (get-name el))
                                      (descendant? el "head")
                                      (and (descendant? el "body")
                                           (has-class? el "cljcastr")))))})
  ;; => "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n
  ;;       <head>\n
  ;;         <title>cljcastr episode player</title>\n
  ;;         ...
  ;;       </head>\n
  ;;       <body>\n
  ;;         <audio class=\"audio-for-speech\" src=\"\"></audio>\n
  ;;         <div id=\"episode-container\" class=\"cljcastr\" style=\"width: 100%; display: flex; flex-direction: column; align-items: center;\">\n
  ;;           <div id=\"episode-info\" class=\"cljcastr\" style=\"max-width: 420px; text-align: center;\">\n
  ;;             <h3 id=\"podcast-title\" class=\"cljcastr\">defn</h3>\n
  ;;             <h2 id=\"episode-title\" class=\"cljcastr\">876b4c306172 Cora Sutton</h2>\n
  ;;             <span id=\"episode-date\" class=\"cljcastr\" style=\"color: grey;\">July 9, 2025</span>\n
  ;;           </div>\n
  ;;           ...
  ;;         </div>\n
  ;;       </body>\n
  ;;     </html>\n
  ;;     "

  )

This looks great! Or rather, almost great, because we forgot about rules #2 and #3:

2. `<head>` and `<body>` should not be indented
3. `<head>` and `<body>` should reset indentation

Turns out we can implement both of these rules with a one-line addition to el->html! Well, maybe two lines, because a comment seems appropriate.

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn indent ...)

(defn el->html
  "Given an element (or the Clojure representation of an element), returns an
   HTML string."
  ([el]
   (el->html el {}))
  ([el {:keys [indent-level indent-str]
        :or {indent-level 0, indent-str "  "}
        :as opts}]
   (if (instance? js/CharacterData el)
     (str/trim (get-text el))
     (let [{:keys [tag attrs]} (if (map? el) el (el->clj el))
           attrs-str (attrs->str attrs)
           ;; Reset indentation for <head> and <body> tags
           indent-level (if (#{"head" "body"} (str/lower-case tag)) 0 indent-level)
           children-html (->> (get-children el opts)
                              (map #(el->html % (assoc opts :indent-level
                                                       (inc indent-level))))
                              (str/join ""))
           tag-open (str (indent indent-level indent-str)
                         "<" tag
                         (if (empty? attrs-str) "" (str " " attrs-str))
                         ">"
                         (if (str/ends-with? children-html "\n")
                           "\n"
                           ""))
           tag-close (str (if (str/ends-with? children-html "\n")
                            (indent indent-level indent-str)
                            "")
                          "</" tag ">\n")]
       (str tag-open children-html tag-close)))))

;; (defn format-css ...)
;; ...

In case the two new lines where hard to spot, here they are again:

           ;; Reset indentation for <head> and <body> tags
           indent-level (if (#{"head" "body"} (str/lower-case tag)) 0 indent-level)

Now let's try again with the HTML dumping:

(comment

  ;; ...

  (el->html "html"
            {:filter-children (fn [el]
                                (cond
                                  (instance? js/Text el)
                                  (-> (get-text el)
                                      (str/replace #"[\n\s]+" "")
                                      not-empty)
                                  
                                  (instance? js/Element el)
                                  (or (contains? #{"html" "head" "body"}
                                                 (get-name el))
                                      (descendant? el "head")
                                      (and (descendant? el "body")
                                           (has-class? el "cljcastr")))))})
  ;; => "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n
  ;;     <head>\n
  ;;       <title>cljcastr episode player</title>\n
  ;;       <link rel=\"stylesheet\" href=\"main.css\"></link>\n
  ;;       <script src=\"https://cdn.jsdelivr.net/npm/scittle@0.8.33/dist/scittle.js\" type=\"application/javascript\"></script>\n
  ;;       <script>var SCITTLE_NREPL_WEBSOCKET_PORT = 1340;</script>\n
  ;;       <script src=\"https://cdn.jsdelivr.net/npm/scittle@0.8.33/dist/scittle.nrepl.js\" type=\"application/javascript\"></script>\n
  ;;       <script type=\"application/x-scittle\" src=\"player.cljs\"></script>\n
  ;;     </head>\n
  ;;     <body>\n
  ;;       <audio class=\"audio-for-speech\" src=\"\"></audio>\n
  ;;       <div id=\"episode-container\" class=\"cljcastr\" style=\"width: 100%; display: flex; flex-direction: column; align-items: center;\">\n
  ;;         <div id=\"episode-info\" class=\"cljcastr\" style=\"max-width: 420px; text-align: center;\">\n
  ;;           <h3 id=\"podcast-title\" class=\"cljcastr\">defn</h3>\n
  ;;           <h2 id=\"episode-title\" class=\"cljcastr\">876b4c306172 Cora Sutton</h2>\n
  ;;           <span id=\"episode-date\" class=\"cljcastr\" style=\"color: grey;\">July 9, 2025</span>\n
  ;;         </div>\n
  ;;         ...
  ;;       </div>\n
  ;;     </body>\n
  ;;     </html>\n
  ;;     "

  )

Looking at the browser console confirms that our HTML looks exactly as we wanted! And we could copy that sweet sweet HTML from the console and paste it into our index.html and move on with our lives... or we could shave just one more yak.

Shaving that final yak

It's a bit annoying that we have to keep remembering the elements we want to keep when dumping our HTML, so let's create a nice little set of functions to take care of that:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn update-playback-position-indicators! ...)

(defn keep-child? [el]
  (cond
    (instance? js/Text el)
    (-> (get-text el)
        (str/replace #"[\n\s]+" "")
        not-empty)
    
    (instance? js/Element el)
    (or (contains? #{"html" "head" "body"}
                   (get-name el))
        (descendant? el "head")
        (and (descendant? el "body")
             (has-class? el "cljcastr")))))

(defn dom->html []
  (el->html "html" {:filter-children keep-child?}))

;; (js/console.log ...)
;; ...

(comment

  ;; ...

  (do
    (log (dom->html))
    nil)
  ;; => nil

  )

Checking the console verifies that this is the HTML we're looking for.

But this is really not the yak we came here to shave. That big old annoying yak staring us in the face is the one that makes us use the mouse (the horror!) to copy a bunch of HTML from the browser console, and then pop back over to Emacs and switch to the index.html buffer and yank and then kill the old contents of the file and save. I mean, who has time for this kind of nonsense? Not us, that's for damn sure!

If only there was a way to save a file from the browser...

(comment

  ;; ...

  (let [filename "boring.html"
        html "<html><body><h1>Yawn...</body></html>"
        blob-url (-> (js/Blob. [html] (clj->js {:type "text/html"}))
                     js/URL.createObjectURL)]
    (-> (create-el {:tag "a"
                    :attrs {:download filename
                            :href blob-url}})
        .click))
  ;; => nil

  )

When we evaluate this form, we get a helpful save file dialog of the sort we've seen millions of times before, with boring.html helpfully prefilled.

Browser save file dialog

If you were to save this file in your public directory alongside index.html and then browse to http://localhost:1341/boring.html, you would be quite bored.

But that's OK, for we have learned the magic incantation for saving a file:

  1. Create a Blob containing some HTML and a text/html content type.
  2. Create a blob URL (i.e. a URL with blob: as its scheme) from said blob.
  3. Create an a element with its download attribute set to a filename of our choosing and its href attribute set to the blob URL we created.
  4. Click on the a element.

This is quite straightforward to turn into a couple of functions:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn add-event-listener! ...)

(defn save-file! [filename content content-type]
  (let [blob-url (-> (js/Blob. [content] (clj->js {:type content-type}))
                     js/URL.createObjectURL)]
    (-> (create-el {:tag "a"
                    :attrs {:download filename
                            :href blob-url}})
        .click)))

;; (defn create-button ...)
;; ...
;; (defn dom->html ...)

(defn save-html!
  ([]
   (save-html! "index.html"))
  ([filename]
   (save-html! filename (dom->html)))
  ([filename html]
   (save-file! filename html "text/html")))

;; (js/console.log ...)
;; ...
(comment

  ;; ...

  (save-html!)
  ;; => nil

  )

When the save file dialog pops up, let's save it over top of our existing index.html and then reload the browser.

The page looks exactly the same as before, but our index.html is a work of art, formatted as purdy as a peach, as we say back where ah'm from (locating my point of provence shall remain an exercise for the reader, though that information is readily available in the latest episode of defnβ€”as of this writing, that is; I have no clue when you're reading this). πŸ‘

All is good in the world... except that clicking the buttons on our lovely player has no effect whatsoever. πŸ˜…

Button mashing

But fear not! 'Tis but the work of a moment to fix them. Moving back over to our player.cljs buffer, we mash C-c C-k (cider-load-buffer), then pop down to the bottom of our comment form and search backwards for "(def playback-controls". Once we find what we're looking for, we copy it and paste it into our namespace, right before our "Ready to play!" message:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn save-html! ...) 

(def playback-controls
  {:play {:src "https://www.svgrepo.com/show/436852/play-circle-fill.svg"
          :label "Play"
          :click-handler #(.play (get-el "audio.cljcastr"))}
   :pause {:src "https://www.svgrepo.com/show/436829/pause-circle-fill.svg"
           :label "Pause"
           :click-handler #(.pause (get-el "audio.cljcastr"))}
   :forward {:src "https://www.svgrepo.com/show/495321/forward-15-seconds.svg"
             :label "Forward {{seek-dur-sec}} seconds"
             :click-handler #(skip-forward! (get-el "audio.cljcastr") seek-dur-sec)}
   :backward {:src "https://www.svgrepo.com/show/495036/backward-15-seconds.svg"
              :label "Back {{seek-dur-sec}} seconds"
              :click-handler #(skip-backward! (get-el "audio.cljcastr") seek-dur-sec)}
   :speed {:src "https://www.svgrepo.com/show/151785/speed-meter.svg"
           :label "Playback speed"}})

(js/console.log "Ready to play!")

(comment

  ;; ...

  )

We hit C-c C-k again, but are deeply saddened by an error message:

#error {:message "Unable to resolve symbol: seek-dur-sec",
        :data {:type :sci/error, :line 10, :column 30,
               :message "Unable to resolve symbol: seek-dur-sec",
               ;; ...
               },
        ;; ...
        }

Oops, looks like we need to grab seek-dur-sec as well:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn save-html! ...) 

(def seek-dur-sec 15)

;; (def playback-controls ...)

C-c C-k FTW?

Victory! πŸ†

Or maybe more accurately, not defeat, since clicking the buttons still doesn't work. Which isn't that surprising, since we didn't actually attach any event listeners to anything. Let's see if we can figure out how to do that.

(comment

  ;; ...

  (doseq [[el-id {:keys [click-handler]}] playback-controls]
    (add-event-listener! (str "#button-" (name el-id)) "click"
                         click-handler))
  ;; => nil

  )

Now if we click the play button, the episode starts playing! We skip backwards and forwards in the episode, try pausing it, and finally convince ourselves that all the buttons work.

The only problem is that the elapsed time, remaining time, progress bar, and slider aren't working. πŸ€”

Oh yeah, we had a handler for that as well. And we might as well attach the listener to the slider that updates the playback position too:

(comment

  ;; ...

  (let [audio (get-el "audio.cljcastr")]
    (add-event-listener! "#progress-slider" "input"
                         #(->> % .-target .-value (set! (.-currentTime audio))))
    (add-event-listener! audio "timeupdate"
                         #(update-playback-position-indicators!
                           (.-currentTime audio) (.-duration audio)
                           (->> [:elapsed-time
                                 :remaining-time
                                 :progress-slider
                                 :progress-bar]
                                (map (fn [el-id]
                                       [el-id (str "#" (name el-id))]))
                                (into {}))))
    audio)
  ;; => #object[HTMLAudioElement [object HTMLAudioElement]]

  )

If we click play again, we see the timestamps updating and slider moving, and if we move the slider ourselves, we can successfully jump around in the episode. Life is good!

That is, until we hit C-c C-k again and realise that despite the console cheerily telling us that we're "Ready to play!", the buttons don't work. 😒

Of course, we can evaluate the two forms we just added to the Rich comment, but it's hardly a good user experience to expect our users to connect a ClojureScript REPL, paste in some code, and evaluate it before they can actually play an episode.

There is a pretty easy solution to this. If we just add the two magic forms right before our "Ready to play!" log statement, the listeners should be attached on page load. Let's try it:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (def playback-controls ...)

(doseq [[el-id {:keys [click-handler]}] playback-controls]
  (add-event-listener! (str "#button-" (name el-id)) "click"
                       click-handler))

(let [audio (get-el "audio.cljcastr")]
  (add-event-listener! "#progress-slider" "input"
                       #(->> % .-target .-value (set! (.-currentTime audio))))
  (add-event-listener! audio "timeupdate"
                       #(update-playback-position-indicators!
                         (.-currentTime audio) (.-duration audio)
                         (->> [:elapsed-time
                               :remaining-time
                               :progress-slider
                               :progress-bar]
                              (map (fn [el-id]
                                     [el-id (str "#" (name el-id))]))
                              (into {}))))
  audio)

;; (js/console.log ...)

If we save the file and reload the page, the buttons now work from the start. This is good, but there is one oddity that we'll notice in the console if we pause playback then evaluate the buffer with C-c C-k again:

  Added listener for click events to                                  nrepl.cljs:10
   β€£ <button class=​"cljcastr" id=​"button-speed"
             style=​"padding:​ 0px;​ margin:​ 0px;​ border:​ 0px;​ background:​ transparent;​ cursor:​ pointer;​"
             aria-label=​"Playback speed">​…​</button>​
  Added listener for input events to                                  nrepl.cljs:10
   β€£ <input class=​"cljcastr" id=​"progress-slider" type=​"range"
            min=​"0" max=​"3138.727422" value=​"0"step=​"any"
            style=​"top:​ 0px;​ background-color:​ transparent;​ width:​ 100%;​ cursor:​ pointer;​ z-index:​ 1;​ appearance:​ none;​ position:​ absolute;​ border:​ 0px;​ touch-action:​ manipulation;​ height:​ 28px;​ left:​ 0px;​ margin:​ 0px;​"
            aria-label=​"Seek" aria-valuetext=​"11:​58 of 52:​18" 
            aria-valuemax=​"3138.727422">​
  Added listener for timeupdate events to                             nrepl.cljs:10
   β€£ <audio class=​"cljcastr" controls style=​"display:​ none;​" 
            src=​"https://media.zencastr.com/audio-files/5d9048546bacd9001de88f1c/2abc6f33-6a0a-4658-a8e0-c811984c13a0.mp3">​</audio>​
  Ready to play!

And if we click play then pause again, we see that the click handlers are firing twice:

  Handling click on                                                   nrepl.cljs:10
   β€£ <button class=​"cljcastr" id=​"button-pause"
             style=​"padding:​ 0px;​ margin:​ 0px;​ border:​ 0px;​ background:​ transparent;​ cursor:​ pointer;​"
             aria-label=​"Pause">​…​</button>​
   β€£ PointerEvent {isTrusted: true, pointerId: 1, width: 1, height: 1, pressure: 0, …}
  Handling click on                                                   nrepl.cljs:10
   β€£ <button class=​"cljcastr" id=​"button-pause"
             style=​"padding:​ 0px;​ margin:​ 0px;​ border:​ 0px;​ background:​ transparent;​ cursor:​ pointer;​"
             aria-label=​"Pause">​…​</button>​
   β€£ PointerEvent {isTrusted: true, pointerId: 1, width: 1, height: 1, pressure: 0, …}

If we evaluate the buffer again, then click play and pause, we see the handlers firing thrice! 😱

  Handling click on                                                   nrepl.cljs:10
   β€£ <button class=​"cljcastr" id=​"button-pause"
             style=​"padding:​ 0px;​ margin:​ 0px;​ border:​ 0px;​ background:​ transparent;​ cursor:​ pointer;​"
             aria-label=​"Pause">​…​</button>​
   β€£ PointerEvent {isTrusted: true, pointerId: 1, width: 1, height: 1, pressure: 0, …}
  Handling click on                                                   nrepl.cljs:10
   β€£ <button class=​"cljcastr" id=​"button-pause"
             style=​"padding:​ 0px;​ margin:​ 0px;​ border:​ 0px;​ background:​ transparent;​ cursor:​ pointer;​"
             aria-label=​"Pause">​…​</button>​
   β€£ PointerEvent {isTrusted: true, pointerId: 1, width: 1, height: 1, pressure: 0, …}
  Handling click on                                                   nrepl.cljs:10
   β€£ <button class=​"cljcastr" id=​"button-pause"
             style=​"padding:​ 0px;​ margin:​ 0px;​ border:​ 0px;​ background:​ transparent;​ cursor:​ pointer;​"
             aria-label=​"Pause">​…​</button>​
   β€£ PointerEvent {isTrusted: true, pointerId: 1, width: 1, height: 1, pressure: 0, …}

OK, so it appears that every time we evaluate the buffer, we get a new click handler. And if we think about it for a moment, it makes sense, because these forms:

(doseq [[el-id {:keys [click-handler]}] playback-controls]
  (add-event-listener! (str "#button-" (name el-id)) "click"
                       click-handler))

(let [audio (get-el "audio.cljcastr")]
  (add-event-listener! "#progress-slider" "input"
                       #(->> % .-target .-value (set! (.-currentTime audio))))
  (add-event-listener! audio "timeupdate"
                       #(update-playback-position-indicators!
                         (.-currentTime audio) (.-duration audio)
                         (->> [:elapsed-time
                               :remaining-time
                               :progress-slider
                               :progress-bar]
                              (map (fn [el-id]
                                     [el-id (str "#" (name el-id))]))
                              (into {}))))
  audio)

;; (js/console.log ...)

are getting evaluated every time, since they are at the top level of our namespace. Luckily for us, if we whip out our microscope, we find a solution (and a precipitate, but that's beside the point): the mighty atom!

Atomic elbow

A common pattern in ClojureScript apps is to define a single atom that holds all of the state we care about. It is conventional to call this atom state, so let's follow said convention because we aren't iconoclastic hipsters, after all!

(ns cljcastr.player
  (:require [clojure.string :as str]))

(defonce state (atom {}))

;; (defn log ...)
;; ...

We use defonce instead of plain ol' def, because otherwise every time we evaluated the buffer, our state var would be rebound to a fresh new atom, thus defeating the point of keeping state in the first place.

Now that we've done this, let's move our code that attaches event listeners into a function:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (def playback-controls)

(defn init-ui! []
  (doseq [[el-id {:keys [click-handler]}] playback-controls]
    (add-event-listener! (str "#button-" (name el-id)) "click"
                         click-handler))
  (let [audio (get-el "audio.cljcastr")]
    (add-event-listener! "#progress-slider" "input"
                         #(->> % .-target .-value (set! (.-currentTime audio))))
    (add-event-listener! audio "timeupdate"
                         #(update-playback-position-indicators!
                           (.-currentTime audio) (.-duration audio)
                           (->> [:elapsed-time
                                 :remaining-time
                                 :progress-slider
                                 :progress-bar]
                                (map (fn [el-id]
                                       [el-id (str "#" (name el-id))]))
                                (into {}))))
    audio)
  (log "UI initialised"))

;; (js/console.log ...)

Now if we evaluate the buffer, we don't see "UI initialised!" get printed in the console. However, if we reload the page, we're back to our buttons not working, which makes sense, because we're never calling our new init-ui! function.

Let's fix that!

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn init-ui! ...) 

(when-not (:initialised? @state)
  (init-ui!)
  (swap! state assoc :initialised? true))

;; (js/console.log ...)

If we reload the page now, we'll see our handlers getting installed and our log statement telling us "UI initialised", as well as the usual chipper "Ready to play!". And if we evaluate the buffer a couple times, we see "Ready to play!" being logged, but nothing about handlers and initialisation.

Console with initialisation messages

Better yet, everything seems to work!

What has CSS ever done for us anyway?

Of course, we are not the sort of Clojurians to rest on our laurels, for there are still improvements to be made! It is considered a bit tacky these days to use inline styles, so let's see if we can take a page out of our el->html book and export our styles.

In fact, we already have a function to get a map of styles from an element (get-styles), and code in our set-styles! function that turns a map of styles into a CSS string, so it's but the work of a moment to squish them together:

(comment

  ;; ...
  
  (->> (get-styles "#progress-bar")
       (map (fn [[k v]]
              (str (name k) ": " v)))
       (str/join "; "))
  ;; => "color: rgb(247, 147, 30); top: 10px; overflow: hidden;
  ;;     background-color: lightgray; width: 100%; z-index: 0;
  ;;     appearance: none; position: absolute; border: 0px;
  ;;     border-radius: 4px; height: 8px; left: 0px; margin: 0px;"

  )

What would be really cool, though, would be to produce a snippet like this:

#progress-bar {
  color: rgb(247, 147, 30);
  top: 10px;
  overflow: hidden;
  background-color: lightgray;
  width: 100%;
  z-index: 0;
  appearance: none;
  position: absolute;
  border: 0px;
  border-radius: 4px;
  height: 8px;
  left: 0px;
  margin: 0px;
}

Honestly, that shouldn't be too tricky. Let's see what we can do:

(comment

  ;; ...

  (let [el (get-el "#progress-bar")
        styles (get-styles el)]
    (str "#" (get-id el) " {\n  "
         (->> styles
              (map (fn [[k v]]
                     (str (name k) ": " v)))
              (str/join ";\n  "))
         "\n}"))
  ;; => "#progress-bar {\n
  ;;       color: rgb(247, 147, 30);\n
  ;;       top: 10px;\n
  ;;       overflow: hidden;\n
  ;;       background-color: lightgray;\n
  ;;       width: 100%;\n
  ;;       z-index: 0;\n
  ;;       appearance: none;\n
  ;;       position: absolute;\n
  ;;       border: 0px;\n
  ;;       border-radius: 4px;\n
  ;;       height: 8px;\n
  ;;       left: 0px;\n
  ;;       margin: 0px;\n
  ;;     }"

  )

But what about elements without an ID?

(comment

  ;; ...

  (let [el (get-el "audio.cljcastr")
        styles (get-styles el)]
    (str "#" (get-id el) " {\n  "
         (->> styles
              (map (fn [[k v]]
                     (str (name k) ": " v)))
              (str/join ";\n  "))
         "\n}"))
  ;; => "# {\n  display: none;\n}"

  )

For that, let's fall back to the tag name, plus the class if it exists:

(comment

  ;; ...

  (let [el (get-el "audio.cljcastr")
        styles (get-styles el)
        id (get-id el)
        classes (get-classes el)
        sel (if (not-empty id)
              (str "#" (get-id el))
              (str (get-name el) (if (seq classes)
                                   (str "." (first classes)))))]
    (str sel " {\n  "
         (->> styles
              (map (fn [[k v]]
                     (str (name k) ": " v)))
              (str/join ";\n  "))
         "\n}"))
  ;; => "audio.cljcastr {\n  display: none;\n}"

  )

This is a bit clunky, though. It would be a lot cleaner if we used el->clj to turn the element into a Clojure datastructure:

(comment

  ;; ...

  (let [el (get-el "audio.cljcastr")
        styles (get-styles el)
        id (get-id el)
        classes (get-classes el)
        sel (if (not-empty id)
              (str "#" (get-id el))
              (str (get-name el) (if (seq classes)
                                   (str "." (first classes)))))]
    (str sel " {\n  "
         (->> styles
              (map (fn [[k v]]
                     (str (name k) ": " v)))
              (str/join ";\n  "))
         "\n}"))
  ;; => "audio.cljcastr {\n  display: none;\n}"

  )

This code is so special it deserves a name! And lo! that name shall be el->css, and it shall be good.

Ramses I from The Ten Commandments saying 'So let it be written, so let it be done'

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn el->html ...)

(defn format-css
  "Returns a CSS string with the specified selector and styles"
  [sel styles]
  (str sel " {\n  "
       (->> styles
            (map (fn [[k v]]
                   (str (name k) ": " v)))
            (str/join ";\n  "))
       "\n}"))

(defn el->css
  "Given an element (or the Clojure representation of an element), returns a CSS
   rule corresponding to the element's ID."
  [el]
  (let [el (log (if (map? el) el (-> (get-el el) el->clj)))
        {:keys [styles id tag classes]} el
        sel (if (not-empty id)
              (str "#" id)
              (str tag (if (seq classes)
                         (str "." (first classes)))))]
    (format-css sel styles)))

;; (defn create-el ...)
;; ...

(comment

  ;; ...

  (->> (el->css "#progress-bar")
       log)
  ;; => "#progress-bar {\n
  ;;       color: rgb(247, 147, 30);\n
  ;;       top: 10px;\n
  ;;       overflow: hidden;\n
  ;;       background-color: lightgray;\n
  ;;       width: 100%;\n
  ;;       z-index: 0;\n
  ;;       appearance: none;\n
  ;;       position: absolute;\n
  ;;       border: 0px;\n
  ;;       border-radius: 4px;\n
  ;;       height: 8px;\n
  ;;       left: 0px;\n
  ;;       margin: 0px;\n
  ;;     }"

)

This is pretty cool, so why don't we add a function to generate CSS for multiple elements at a time?

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn el->css ...)

(defn els->css
  "Given an collection of elements (or Clojure representations of elements),
   returns CSS rules corresponding to the elements' IDs."
  [els]
  (->> els
       (map el->clj)
       (remove (comp empty? :styles))
       (map el->css)
       (str/join "\n\n")))

;; (defn create-el ...)
;; ...

(comment

  ;; ...

  (->> (els->css (get-els ".cljcastr"))
       log)
  ;; => "#episode-container {\n
  ;;       width: 100%;\n
  ;;       display: flex;\n
  ;;       flex-direction: column;\n
  ;;       align-items: center;\n
  ;;     }\n
  ;;     \n
  ;;     #episode-info {\n
  ;;       max-width: 420px;\n
  ;;       text-align: center;\n
  ;;     }\n
  ;;     \n
  ;;     ...

)

Casting our gaze upon the console, joy fills our hearts:

CSS code

However, (and you knew the however was coming, eh dear reader?) our heart rankles at the repetition inherent in the system.

It’s your birthday. Someone gives you a calfskin wallet.

What people do when they write CSS is use classes to combine related sets of elements. We're not going to be able to do that completely programmatically, but we can at least spit out something that's a better starting point for a person to pick up and shape to their liking.

How might we go about this?

(comment

  ;; ...

  (def style-groups
    (->> (get-els ".cljcastr")
         (map el->clj)
         (remove (comp empty? :styles))
         (group-by :styles)))
  ;; => #'cljcastr.player/style-groups

  (count style-groups)
  ;; => 13

  (->> style-groups
       (map (fn [[_styles els]]
              (map #(select-keys % [:tag :id :classes]) els))))
  ;; => (({:tag "div", :id "progress-container", :classes ("cljcastr")})
  ;;     ({:tag "div", :id "progress", :classes ("cljcastr")})
  ;;     ({:tag "progress", :id "progress-bar", :classes ("cljcastr")})
  ;;     ({:tag "img", :id "episode-art", :classes ("cljcastr")})
  ;;     ({:tag "input", :id "progress-slider", :classes ("cljcastr")})
  ;;     ({:tag "span", :id "episode-date", :classes ("cljcastr")})
  ;;     ({:tag "div", :id "episode-info", :classes ("cljcastr")})
  ;;     ({:tag "img", :id "button-backward-icon", :classes ("cljcastr" "playback-icon")}
  ;;      {:tag "img", :id "button-play-icon", :classes ("cljcastr" "playback-icon")}
  ;;      {:tag "img", :id "button-pause-icon", :classes ("cljcastr" "playback-icon")}
  ;;      {:tag "img", :id "button-forward-icon", :classes ("cljcastr" "playback-icon")}
  ;;      {:tag "img", :id "button-speed-icon", :classes ("cljcastr" "playback-icon")})
  ;;     ({:tag "audio", :classes ("cljcastr")})
  ;;     ({:tag "span", :id "elapsed-time", :classes ("cljcastr")})
  ;;     ({:tag "button", :id "button-backward", :classes ("cljcastr" "playback-button")}
  ;;      {:tag "button", :id "button-play", :classes ("cljcastr" "playback-button")}
  ;;      {:tag "button", :id "button-pause", :classes ("cljcastr" "playback-button")}
  ;;      {:tag "button", :id "button-forward", :classes ("cljcastr" "playback-button")}
  ;;      {:tag "button", :id "button-speed", :classes ("cljcastr" "playback-button")})
  ;;     ({:tag "span", :id "remaining-time", :classes ("cljcastr")})
  ;;     ({:tag "div", :id "episode-container", :classes ("cljcastr")}))

)

What we're doing here is getting all the elements having "cljcastr" as one of their classes, turning them into Clojure data structures, removing the ones with no inline styles, then grouping them by their styles. This results in a map where the keys are styles and the values are the list of the elements with those styles (see the documentation for the group-by function if this is confusing). We then map over that to look at the tag, ID, and classes of the elements with each unique set of styles.

Grouping elements like this seems useful, so let's create a function to do it:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn el->clj ...)

(defn group-styles
  "Given a collection of DOM elements, returns a map keyed by styles. The value
   at each key will be a vector of the corresponding elements, in the order they
   appeared in the original list.

   Example:

     (let [els [(create-el {:tag \"div\", :id \"el1\", :styles {:color \"red\"}})
                (create-el {:tag \"div\", :id \"el2\", :styles {:color \"blue\"}})
                (create-el {:tag \"div\", :id \"el3\"})
                (create-el {:tag \"div\", :id \"el4\", :styles {:color \"red\"}})]]
       (->> (group-styles els)
            (map (fn [[styles els]]
                   [styles (map #(select-keys % [:id]) els)]))))
     ;; => ([{:color \"red;\"} ({:id \"el1\"} {:id \"el4\"})]
     ;;     [{:color \"blue;\"} ({:id \"el2\"})])"
  [els]
  (->> els
       (map el->clj)
       (remove (comp empty? :styles))
       (group-by :styles)))

;; (defn attrs->str ...)
;; ...

Now that we have this, let's see how many of these styles apply to multiple elements:

(comment

  ;; ...

  (->> (get-els ".cljcastr")
       group-styles
       (filter (fn [[_ els]] (> (count els) 1)))
       (map (fn [[_styles els]]
              (map #(select-keys % [:tag :id :classes]) els))))
  ;; => (({:tag "img", :id "button-backward-icon", :classes ("cljcastr" "playback-icon")}
  ;;      {:tag "img", :id "button-play-icon", :classes ("cljcastr" "playback-icon")}
  ;;      {:tag "img", :id "button-pause-icon", :classes ("cljcastr" "playback-icon")}
  ;;      {:tag "img", :id "button-forward-icon", :classes ("cljcastr" "playback-icon")}
  ;;      {:tag "img", :id "button-speed-icon", :classes ("cljcastr" "playback-icon")})
  ;;     ({:tag "button", :id "button-backward", :classes ("cljcastr" "playback-button")}
  ;;      {:tag "button", :id "button-play", :classes ("cljcastr" "playback-button")}
  ;;      {:tag "button", :id "button-pause", :classes ("cljcastr" "playback-button")}
  ;;      {:tag "button", :id "button-forward", :classes ("cljcastr" "playback-button")}
  ;;      {:tag "button", :id "button-speed", :classes ("cljcastr" "playback-button")}))

)

These look like great candidates for consolidation! But what selector should we use to write the rule?

Well, we know that all of our elements share the "cljcastr" class in common, so if we exclude that, we see that both of these groups are left with a single class!

(comment

  ;; ...

  (->> (get-els ".cljcastr")
       group-styles
       (filter (fn [[_ els]] (> (count els) 1)))
       (map (fn [[_styles els]]
              (map (fn [el]
                     (-> (select-keys el [:tag :id :classes])
                         (update :classes #(remove (fn [cls] (= "cljcastr" cls)) %))))
                   els))))
  ;; => (({:tag "img", :id "button-backward-icon", :classes ("playback-icon")}
  ;;      {:tag "img", :id "button-play-icon", :classes ("playback-icon")}
  ;;      {:tag "img", :id "button-pause-icon", :classes ("playback-icon")}
  ;;      {:tag "img", :id "button-forward-icon", :classes ("playback-icon")}
  ;;      {:tag "img", :id "button-speed-icon", :classes ("playback-icon")})
  ;;     ({:tag "button", :id "button-backward", :classes ("playback-button")}
  ;;      {:tag "button", :id "button-play", :classes ("playback-button")}
  ;;      {:tag "button", :id "button-pause", :classes ("playback-button")}
  ;;      {:tag "button", :id "button-forward", :classes ("playback-button")}
  ;;      {:tag "button", :id "button-speed", :classes ("playback-button")}))

)

Let's run those through els->css and see what we get:

(comment

  ;; ...

  (->> (get-els ".cljcastr")
       group-styles
       (filter (fn [[_ els]] (> (count els) 1)))
       (map (fn [[_styles els]]
              (->> els
                   (map (fn [el]
                          (update el :classes #(remove (fn [cls] (= "cljcastr" cls)) %))))
                   els->css)))
       (str/join "\n\n")
       log)
  ;; => "#button-backward-icon {\n  width: 35px;\n  ...}"

)

Looking at the console, we see that we're back where we started:

#button-backward-icon {
  width: 35px;
  filter: invert(59%) sepia(92%) saturate(611%) hue-rotate(343deg) brightness(97%) contrast(99%);
}

#button-play-icon {
  width: 35px;
  filter: invert(59%) sepia(92%) saturate(611%) hue-rotate(343deg) brightness(97%) contrast(99%);
}

#button-pause-icon {
  width: 35px;
  filter: invert(59%) sepia(92%) saturate(611%) hue-rotate(343deg) brightness(97%) contrast(99%);
}

#button-forward-icon {
  width: 35px;
  filter: invert(59%) sepia(92%) saturate(611%) hue-rotate(343deg) brightness(97%) contrast(99%);
}

#button-speed-icon {
  width: 35px;
  filter: invert(59%) sepia(92%) saturate(611%) hue-rotate(343deg) brightness(97%) contrast(99%);
}

#button-backward {
  padding: 0px;
  margin: 0px;
  border: 0px;
  background: transparent;
  cursor: pointer;
}

#button-play {
  padding: 0px;
  margin: 0px;
  border: 0px;
  background: transparent;
  cursor: pointer;
}

#button-pause {
  padding: 0px;
  margin: 0px;
  border: 0px;
  background: transparent;
  cursor: pointer;
}

#button-forward {
  padding: 0px;
  margin: 0px;
  border: 0px;
  background: transparent;
  cursor: pointer;
}

#button-speed {
  padding: 0px;
  margin: 0px;
  border: 0px;
  background: transparent;
  cursor: pointer;
}

What we really want to do is generate a single rule for each group, with the remaining class as the selector. If we update el->css with a second arity that accepts a selector as an argument, we can accomplish this fairly easily:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn format-css ...)

(defn el->css
  "Given an element (or the Clojure representation of an element), returns a CSS
   rule corresponding to the element's ID."
  ([el]
   (let [el (if (map? el) el (-> (get-el el) el->clj))
         {:keys [styles id tag classes]} el
         sel (if (not-empty id)
               (str "#" id)
               (str tag (if (seq classes)
                          (str "." (first classes)))))]
     (el->css el sel)))
  ([el sel]
   (format-css sel (:styles el))))

;; (defn els->css ...)
;; ...

(comment

  ;; ...

  (->> (get-els ".cljcastr")
       group-styles
       (filter (fn [[_ els]] (> (count els) 1)))
       (map (fn [[_styles [el & _]]]
              (let [sel (str "." (->> (:classes el)
                                      (remove (partial = "cljcastr"))
                                      first))]
                (el->css el sel))))
       (str/join "\n\n")
       log)
  ;; => ".playback-icon {\n  width: 35px;\n  ...}"

)

And now the console fills our hearts with delight once again!

.playback-icon {
  width: 35px;
  filter: invert(59%) sepia(92%) saturate(611%) hue-rotate(343deg) brightness(97%) contrast(99%);
}

.playback-button {
  padding: 0px;
  margin: 0px;
  border: 0px;
  background: transparent;
  cursor: pointer;
}

Let's now take a step back and think about how we want to generate the rules:

  1. Group by styles
  2. For groups with a single element, just call el->css on it
  3. For groups with multiple elements, take the first one, drop "cljcastr" from its list of classes, generate a selector from the first remaining class, and then call el->css on the element, using the custom selector

And if we say this in Clojure, it looks like this:

(comment

  ;; ...

  (->> (get-els ".cljcastr")
       group-styles
       (map (fn [[_styles [el & rest-els]]]
              (if (seq rest-els)
                (let [sel (str "." (->> (:classes el)
                                        (remove (partial = "cljcastr"))
                                        first))]
                  (el->css el sel))
                (el->css el))))
       (str/join "\n\n")
       log)
  ;; => "#progress-container {\n  position: relative;\n  height: 28px;\n  ...}"

)

If we look at the console, it appears that all of our prayers are answered! πŸŽ‰

#progress-container {
  position: relative;
  height: 28px;
  clear: both;
}

#progress {
  width: 390px;
  margin: 1.5em auto 0px;
  position: relative;
}

#progress-bar {
  color: rgb(247, 147, 30);
  top: 10px;
  overflow: hidden;
  background-color: lightgray;
  width: 100%;
  z-index: 0;
  appearance: none;
  position: absolute;
  border: 0px;
  border-radius: 4px;
  height: 8px;
  left: 0px;
  margin: 0px;
}

#episode-art {
  width: 400px;
  border-radius: 5%;
  padding: 10px;
}

#progress-slider {
  top: 0px;
  background-color: transparent;
  width: 100%;
  cursor: pointer;
  z-index: 1;
  appearance: none;
  position: absolute;
  border: 0px;
  touch-action: manipulation;
  height: 28px;
  left: 0px;
  margin: 0px;
}

#episode-date {
  color: grey;
}

#episode-info {
  max-width: 420px;
  text-align: center;
}

.playback-icon {
  width: 35px;
  filter: invert(59%) sepia(92%) saturate(611%) hue-rotate(343deg) brightness(97%) contrast(99%);
}

audio.cljcastr {
  display: none;
}

#elapsed-time {
  margin: 0px 5px;
  font-size: 0.7rem;
  color: grey;
  float: left;
}

.playback-button {
  padding: 0px;
  margin: 0px;
  border: 0px;
  background: transparent;
  cursor: pointer;
}

#remaining-time {
  margin: 0px 5px;
  font-size: 0.7rem;
  color: grey;
  float: right;
}

#episode-container {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}

Now that we have all of these lovely styles, we can write a couple of functions to export them, following the same pattern as for save-html!:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn save-html! ...)

(defn dom->css []
  (->> (get-els ".cljcastr")
       group-styles
       (map (fn [[_styles [el & rest-els]]]
              (if (seq rest-els)
                (let [sel (str "." (->> (:classes el)
                                        (remove (partial = "cljcastr"))
                                        first))]
                  (el->css el sel))
                (el->css el))))
       (str/join "\n\n")
       log))

(defn save-css!
  ([]
   (save-css! "main.css"))
  ([filename]
   (save-css! filename (dom->css)))
  ([filename css]
   (save-file! filename css "text/css")))

;; (def seek-dur-sec ...)
;; ...

(comment

  ;; ...

  (save-css!)
  ;; => nil

)

We evaluate the save-css! form and save the main.css file alongside our index.html. Now all we have to do to use the styles is two things:

  1. Import the stylesheet in index.html
  2. Regenerate our HTML without the inline styles

Inline skating away on the thin ice of a new day

The first part is simple, we just add one element to the DOM:

(comment

  ;; ...

  (->> (create-el {:tag "link",
                   :attrs {:rel "stylesheet", :href "main.css"}})
       (add-child! "head"))
  ;; => #object[HTMLHeadElement [object HTMLHeadElement]]

  )

And now for the new HTML. Let's update el->html to take a new option called :exclude-styles?, and then emit the HTML without inline styles if it's truthy:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn indent ...)

(defn el->html
  "Given an element (or the Clojure representation of an element), returns an
   HTML string."
  ([el]
   (el->html el {}))
  ([el {:keys [indent-level indent-str exclude-styles?]
        :or {indent-level 0, indent-str "  "}
        :as opts}]
   (if (instance? js/CharacterData el)
     (str/trim (get-text el))
     (let [{:keys [tag attrs]} (if (map? el) el (el->clj el))
           attrs (if exclude-styles? (dissoc attrs :style) attrs)
           attrs-str (attrs->str attrs)
           ;; Reset indentation for <head> and <body> tags
           indent-level (if (#{"head" "body"} (str/lower-case tag)) 0 indent-level)
           children-html (->> (get-children el opts)
                              (map #(el->html % (assoc opts :indent-level
                                                       (inc indent-level))))
                              (str/join ""))
           tag-open (str (indent indent-level indent-str)
                         "<" tag
                         (if (empty? attrs-str) "" (str " " attrs-str))
                         ">"
                         (if (str/ends-with? children-html "\n")
                           "\n"
                           ""))
           tag-close (str (if (str/ends-with? children-html "\n")
                            (indent indent-level indent-str)
                            "")
                          "</" tag ">\n")]
       (str tag-open children-html tag-close)))))

;; (defn format-css ...)
;; ...

(comment

  ;; ...

  (->> (get-els "body > .cljcastr")
       (map #(el->html % {:exclude-styles? true}))
       (str/join "\n")
       log)
  ;; => "<div id=\"episode-container\" class=\"cljcastr\">\n
  ;;       <div id=\"episode-info\" class=\"cljcastr\">\n
  ;;         <h3 id=\"podcast-title\" class=\"cljcastr\">defn</h3>\n
  ;;         <h2 id=\"episode-title\" class=\"cljcastr\">876b4c306172 Cora Sutton</h2>\n
  ;;         <span id=\"episode-date\" class=\"cljcastr\">July 9, 2025</span>\n
  ;;       </div>\n
  ;;       ...
  ;;     </div>\n
  ;;     "

)

Let's update dom->html and save->html! to allow us to exclude styles if we wanna. But how to do it? dom->html is simple: we just add a 1-arity version of the function that takes an options map. save-html! on the other hand requires a tiny bit of design. We could add yet another arity, but then we have the problem of distinguising between what the arguments mean. Let's simplify a bit: we'll have the 0-arity function to fill in all the defaults, and a 1-arity version taking an options map:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn keep-child? ...)

(defn dom->html
  ([]
   (dom->html {}))
  ([opts]
   (el->html "html"
             (merge opts
                    {:filter-children keep-child?}))))

(defn save-html!
  ([]
   (save-html! {}))
  ([{:keys [filename html]
     :or {filename "index.html"}
     :as opts}]
   (let [html (or html (dom->html opts))]
     (save-file! filename html "text/html"))))

;; (defn save-html! ...)
;; ...

Now we can save a new version of index.html, this time without the styles:

(comment

  ;; ...

  (save-html! {:exclude-styles? true})
  ;; => nil

  )

After saving, let's check index.html to make sure things look good:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>cljcastr episode player</title>
  <link rel="stylesheet" href="main.css"></link>
  <script src="https://cdn.jsdelivr.net/npm/scittle@0.8.33/dist/scittle.js" type="application/javascript"></script>
  <script>var SCITTLE_NREPL_WEBSOCKET_PORT = 1340;</script>
  <script src="https://cdn.jsdelivr.net/npm/scittle@0.8.33/dist/scittle.nrepl.js" type="application/javascript"></script>
  <script type="application/x-scittle" src="player.cljs"></script>
</head>
<body>
  <div id="episode-container" class="cljcastr">
    <div id="episode-info" class="cljcastr">
      <h3 id="podcast-title" class="cljcastr">defn</h3>
      <h2 id="episode-title" class="cljcastr">876b4c306172 Cora Sutton</h2>
      <span id="episode-date" class="cljcastr">July 9, 2025</span>
    </div>
    ...
  </div>
</body>
</html>

Holding our breath, we reload the page, and... see the same thing we were just looking at. πŸ˜…

But actually, that's precisely what we were trying to achieve. If we open dev tools and inspect the play button, we see two exciting things:

  1. No inline styles in the button element
  2. In the Styles panel, there is a .playback-button class being applied, defined in main.css

Player with just buttons

At this point, we've built a nice podcast player interactively, then created a persistence mechanism so we can safely reload the page. This feels really good, right? πŸ˜€

We bask in the feeling for an altogether brief moment, then start thinking of ways to improve things. Like adding that transcript we were talking about many thousands of word ago? Or maybe not limiting ourselves to a single defn episode (even if it is a πŸ”₯ episode!)?

Our minds start to fill with the possibilities, but we come to our senses and decide some hammock time (in the form of a nice long walk perhapsβ€”maybe even with one of our favourite human or canine companions?) is in order.

Next time on Scittlecastr: Stylish and eventful, we return from our hammock time and get to scittling them features!

You can find all the files for the player we built in this post here:

The preview image for this post was based on the Teenager looking at equation on chalk board photo by Rafa Fernandez from his Back To School Boy photoshoot. The photo is used under The Noun Project's Royalty-Free Commercial License, and was remixed by hand in the GIMP, which does not allow genAI contributions.

Scittlecastr: The Scittling

Arab woman listening to Scittle podcast with earphones and dancing outdoors

This post was entirely written by a human, with no assistance from LLMs or other "AI" technology such as pervert glasses or autonomous weapon systems. The photo is Arab woman listening to music with earphones and dancing outdoors by Javier Sanchez Mingorance

I've mentioned cljcastr here before, but in a very tongue in cheek fashion. Since then, cljcastr has turned into a serious project to create a set of tools for producing and self-hosting podcasts. The project has two simple principles:

  1. No surveillance. Ever. cljcastr runs on your computer and only your computer. It does not connect to any external services, store data on the cloud (AKA other people's computers), or track you in any way, shape, or form.
  2. No AI. All cljcastr code is written by hand, by humans. Nothing in this repository has been AI generated, and no AI generated pull requests will even be considered for inclusion.

cljcastr is hosted on Codeberg at jmglov/cljcastr.

In this blog post, I'm going to demonstrate the cljcastr ethos by implementing a simple podcast player in ClojureScript, using the mighty Scittle. This is gonna be a long one (even by my standards), so here's a table of contents to help us all stay oriented.

Table of contents

  1. Building the skeleton - setting up a Babashka project and a Scittle app and connecting a REPL to it
  2. Interactive development - getting used to the REPL and logging Clojure data structures in the browser console
  3. Getting down to brass HTML - adding a heading
  4. Play that funky music - adding an audio player
  5. Escaping from vanilla - adding custom controls
  6. Rainbows and unicorns - applying styles
  7. Play it again, Sam - adding event listeners
  8. A11y spells ally - making controls accessible
  9. Sweeping up the shop - adding DOM helper functions and refactoring
  10. Sweeping audio under the carpet - hiding the standard audio player
  11. Hours, minutes, and seconds, oh my! - displaying elapsed and remaining time in a human-readable form
  12. Laying out the law - adding episode info in a nice layout
  13. Slipping and sliding - adding a progress bar and draggable position slider
  14. Getting into position - combining the progress bar and position slider into a typical scrubbing control

Building the skeleton

To get started, we're going to need a Babashka project set up to serve files from a local webserver. Let's create a cljcastr directory:

mkdir cljcastr

And now pop a bb.edn into it:

{:deps {io.github.babashka/sci.nrepl
        {:git/sha "80ec956af5e6610b040089ba62eecb5d223e9e76"}
        io.github.babashka/http-server
        {:git/sha "b38c1f16ad2c618adae2c3b102a5520c261a7dd3"}}

 :tasks
 {http-server {:doc "Starts http server for serving static files"
               :requires ([babashka.http-server :as http])
               :task (do (http/serve {:port 1341 :dir "resources/public"})
                         (println "Serving static assets at http://localhost:1341"))}

  browser-nrepl {:doc "Start browser nREPL"
                 :requires ([sci.nrepl.browser-server :as bp])
                 :task (bp/start! {})}

  -dev {:depends [browser-nrepl http-server]}

  dev {:doc "Development build. Starts webserver and watches for changes."
       :task (do (run '-dev {:parallel true})
                 (deref (promise)))}}
}

Now create a resources/public directory:

mkdir -p resources/public/

Drop an index.html in that directory:

<html xmlns="http://www.w3.org/1999/xhtml">

<head>
  <title>cljcastr episode player</title>

  <script src="https://cdn.jsdelivr.net/npm/scittle@0.8.33/dist/scittle.js" type="application/javascript"></script>
  <script>var SCITTLE_NREPL_WEBSOCKET_PORT = 1340;</script>
  <script src="https://cdn.jsdelivr.net/npm/scittle@0.8.33/dist/scittle.nrepl.js" type="application/javascript"></script>

  <script type="application/x-scittle" src="player.cljs"></script>
</head>

<body>
</body>

</html>

And finally, a player.cljs in the same directory that does naught but declare a namespace:

(ns cljcastr.player)

(js/console.log "Ready to play!")

Thus equipped, invoke Babashka from the top-level cljcastr directory thusly:

bb dev

Babashka will helpfully tell you where you can find your player:

Serving static assets at http://localhost:1341
nREPL server started on port 1339...
Websocket server started on 1340...

If you browse to localhost:1341, you'll see an amazingly blank page titled "cljcastr episode player". If you open the JavaScript console in dev tools (Ctrl + Shift + i in many browsers), you should see the player reporting for duty:

  Ready to play!                                                    core.cljs:80
> 

So let's play!

Interactive development

In addition to the HTTP server serving up static files from our resources/public directory, we have an nREPL server listening on port 1339 and a websocket server on port 1340. When we loaded the index.html webpage in the browser, scittle.nrepl opened a websocket connection to port 1340 and started listening for commands. In order to send it some commands, we will need to connect an nREPL client to the nREPL server on port 1339. Let's do it!

This section assumes that you are a reasonable person and are thus using Emacs with CIDER, but if you've unreasonably chosen to use a lesser editor or one of those new-fangled "IDEs" like Cursive or Calva, you probably know how to operate nREPL in that editor, so just translate accordingly.

First, we open up player.cljs in our editor. Next, we use CIDER's cider-connect-cljs command (C-c M-C) to connect to localhost on port 1339, choosing REPL type nbb when prompted. CIDER should open a REPL buffer that says something like this:

;; Connected to nREPL server - nrepl://localhost:1339
;; CIDER 1.12.0 (Split)
;;
;; ClojureScript REPL type: nbb
;;
nil> 

Now we're all set up for interactive development, so let's interact. First, execute cider-load-buffer (C-c C-k) in the player.cljs buffer. If you're watching the JS console in your browser, you'll see something like the following pop up:

  Ready to play!                                                   nrepl.cljs:10
> 

And meanwhile in your terminal, you'll see the nREPL server log some output:

:msg "{:value \"nil\", :id \"246\", :session \"e443955d-e285-4d5b-bbde-9b7f21f1561c\", :ns \"cljcastr.player\"}"
:msg "{:status [\"done\"], :id \"246\", :session \"e443955d-e285-4d5b-bbde-9b7f21f1561c\", :ns \"cljcastr.player\"}"

We've now completed the circle of LISP, meaning we can control everything on our player page with ClojureScript! πŸ’₯

Let's try some simple arithmetic just to get a sense of the power at our fingertips. In the player.cljs buffer, we'll add a Rich comment and some code:

(comment

  (+ 1 2)

  )

Positioning our cursor right after the (+ 1 2) form, we hit C-c C-v f c e to execute cider-pprint-eval-last-sexp-to-comment, and are rewarded by a nice comment being inserted on the next line:

(comment

  (+ 1 2)
  ;; => 3

  )

We can also print this result to the browser console by adding another line inside the (comment) form:

(comment

  ;; ...
  
  (js/console.log (+ 1 2))

  )

If you're using CIDER with an autocomplete setup, you should actually see completion candidates popping up as you type. 🀯

If you position the cursor after the form and evaluate it again with C-c C-v f c e, you'll get a comment on the next line saying

  ;; => nil

This is somewhat underwhelming, but if you take a peek at your browser console, you'll be more satisfied:

  3                                                                nrepl.cljs:10
> 

Can we have our cake and eat it too? (Note that from here on, I'll assume you're whacking C-c C-v f c e after the new form you add, which will produce the ;; => comment on the next line.)

(comment

  ;; ...
  
  (doto (+ 1 2)
    js/console.log)
  ;; => 3

  )

Now we're cooking with biofuel!

Let's try something a little more complex:

(comment

  ;; ...
  
  (doto (map inc (range 5))
    js/console.log)
  ;; => (1 2 3 4 5)

  )

This is great, but what in the world is happening over in the browser console?

  β€£ $APP.ggΒ {J: null, na: null, I: null, F: 32374988, ma: Ζ’, …}    nrepl.cljs:10
> 

If we click on the β€£, things get even wilder:

  β€£ $APP.gg {J: null, na: null, I: null, F: 32374988, ma: Ζ’, …}    nrepl.cljs:10
      F: 32374988
      I: null
      J: null
      M: 1
      ma: null
    β€£ na: $APP.lg {hc: kg, Zc: $…P.gg, J: null, I: null, F: 31850732, …}
    β€£ [[Prototype]]: Object
>

What we're seeing is a JavaScript representation of a ClojureScript vector. This is of course super cool and all, but not so readable (unless you're Rich Hickey and you don't even see the persistent data structures but just the woman in the red dress). Let's see if we can do better:

(comment

  ;; ...
  
  (doto (->> (map inc (range 5))
             clj->js)
    js/console.log)
  ;; => #js [1 2 3 4 5]

  )

The browser console is looking good!

  β€£ (5) [1, 2, 3, 4, 5]                                            nrepl.cljs:10

But life inside our (comment) form is less idyllic. What's up with this nonsense?

  ;; => #js [1 2 3 4 5]

Now we're seeing ClojureScript's JavaScript data literal. πŸ˜…

Let's try one more thing:

(comment

  ;; ...
  
  (let [res (map inc (range 5))]
    (js/console.log (clj->js res))
    res)
  ;; => (1 2 3 4 5)

  )

That's much better! Now how about we extract this to a function so we can use it to log stuff?

(ns cljcastr.player)

(defn log [v]
  (js/console.log (clj->js v))
  v)

(comment

  ;; ...

  (log (map inc (range 5)))
  ;; => (1 2 3 4 5)

  )

Good stuff. Thus equipped, we can start sprucing up this empty webpage.

Getting down to brass HTML

Let's add an h1 HTML element to the page to let users know what's up. The obvious way to do this would be to open up index.html and drop in something like this:

<body>
  <h1>cljcastr player</h1>
</body>

However, this would require a page reload for us to see the changes, and that would blow away the state we've carefully built up in our REPL. 😭

Let's see if we can do this in the REPL instead. The basic idea is this:

  1. Create an h1 element.
  2. Set its inner text to "cljcastr player".
  3. Grab the body element that we helpfully put in our HTML page skeleton.
  4. Add the new h1 element as a child of the body element.

And if we were to call an imaginary eng->clj function, that would look something like this:

(comment

  ;; ...
  
  ;; 1. Create an **h1** element.
  (def h1 (js/document.createElement "h1"))
  ;; => #'cljcastr.player/h1

  ;; 2. Set its inner text to "cljcastr player".
  (set! (.-textContent h1) "cljcastr player")
  ;; => "cljcastr player"

  ;; 3. Grab the **body** element that we helpfully put in our HTML page skeleton.
  (def body (js/document.querySelector "body"))
  ;; => #'cljcastr.player/body

  ;; 4. Add the new **h1** element as a child of the **body** element.
  (.appendChild body h1)
  ;; => #object[HTMLHeadingElement [object HTMLHeadingElement]]

  )

Et voilΓ ! Our boring page has been transformed into an amazing feast for the eyes!

Before moving on, let's take a brief detour into a new JavaScript literal:

  ;; => #object[HTMLHeadingElement [object HTMLHeadingElement]]

This is a bit opaque, but we can always feed it to our log function to make it nicely inspectable in the console:

(comment

  ;; ...
  
  (log h1)
  ;; => #object[HTMLHeadingElement [object HTMLHeadingElement]]

  )

The console will render this as:

  <h1>cljcastr player</h1>                                         nrepl.cljs:10

Play that funky music

Let's find ourselves the URL of a random podcast episode and add an audio element to the page:

(comment

  ;; ...

  (def audio (js/document.createElement "audio"))
  ;; => #'cljcastr.player/audio

  (set! (.-controls audio) true)
  ;; => true

  (set! (.-src audio)
        "https://media.zencastr.com/audio-files/5d9048546bacd9001de88f1c/2abc6f33-6a0a-4658-a8e0-c811984c13a0.mp3")

  (->> audio
       (.appendChild body))
  ;; => #object[HTMLAudioElement [object HTMLAudioElement]]

  (log audio)
  ;; => #object[HTMLAudioElement [object HTMLAudioElement]]

)

Now we should see an audio player pop up on screen!

Simple podcast player with a heading and an audio player

And if we click play, we hear the defn theme music.

We could declare victory right here, but we're missing a few things that a podcast player usually has, such as:

  1. Sweet custom controls instead of the ugly HTML5 default audio player.
  2. The ability to play any podcast episode, not just one we've helpfully downloaded ahead of time.
  3. If a transcript is available, display it with clickable timestamps.

Let's see what we can do about that.

Escaping from vanilla

The standard HTML audio control is functional, but a bit boring. In our hubris, we decide we can do way better than that!

Let's look at a typical podcast player for inspiration:

Overcast podcast player

It looks like we'll want the following buttons:

  • Play
  • Pause
  • Skip backward
  • Skip forward
  • Playback speed

Let's see if we can find some nice vector graphics for our buttons. SVG Repo is a great place to start, and a search there for "play" turns up a nice looking SVG named Play Circle Fill SVG, which is provided under the MIT Licence. That looks promising!

Better yet, the SVG is part of a collection called [Framework7 Filled Icons] (https://www.svgrepo.com/collection/framework7-filled-icons/). Let's click into that and see if we can find some SVGs for other useful media player buttons. Searching within the collection, we find a nice Pause button, but nothing for the other three we need. 😭

No matter! We widen our search to all of SVG Repo and find nice graphics for the rest. Here's where we land:

Let's create a set of HTML images for each. We'll start by defining a map to describe them:

(comment

  ;; ...

  (def playback-controls
    {:play {:src "https://www.svgrepo.com/show/436852/play-circle-fill.svg"
            :label "Play"}
     :pause {:src "https://www.svgrepo.com/show/436829/pause-circle-fill.svg"
             :label "Pause"}
     :forward {:src "https://www.svgrepo.com/show/495321/forward-15-seconds.svg"
               :label "Forward {{seek-dur-sec}} seconds"}
     :backward {:src "https://www.svgrepo.com/show/495036/backward-15-seconds.svg"
             :label "Back {{seek-dur-sec}} seconds"}
     :speed {:src "https://www.svgrepo.com/show/151785/speed-meter.svg"
             :label "Playback speed"}})
  ;; => #'cljcastr.player/playback-controls

  (def seek-dur-sec 15)
  ;; => #'cljcastr.player/seek-dur-sec

  )

Now we can map over the map (yeah yeah, I know) to create our img elements:

(comment

  ;; ...

  (def playback-buttons
    (->> playback-controls
         (map (fn [[control-name {:keys [src label]}]]
                (let [el (js/document.createElement "img")]
                  (set! (.-id el) (str "button-" (name control-name)))
                  (set! (.-classList el) "cljcastr playback-icon")
                  (set! (.-src el) src)
                  (set! (.-draggable el) false)
                  el)))
         log))
  ;; => #'cljcastr.player/playback-buttons

  )

Note that we're adding a playback-icon class to the element in addition to our standard cljcastr class, and also giving the element an ID so it's easy to grab it with a CSS selector later. We also set the draggable attribute to false to prevent drag-and-drop silliness from happening.

Now, how about a container to hold them?

(comment

  ;; ...

  (def playback-controls-container
    (-> (let [el (js/document.createElement "div")]
          (set! (.-id el) "playback-controls")
          (set! (.-classList el) "cljcastr")
          el)
        log))
  ;; => #'cljcastr.player/playback-controls-container

  (doseq [el playback-buttons]
    (.appendChild playback-controls-container el))
  ;; => nil

  )

Finally, let's display the controls!

(comment

  ;; ...

  (.appendChild body playback-controls-container)
  ;; => #object[HTMLDivElement [object HTMLDivElement]]

  )

Player with a huge play button

Let's set the width of the images to a more reasonable size:

(comment

  ;; ...

  (doseq [el playback-buttons]
    (set! (.-style el) "width: 35px"))
  ;; => nil

  )

That's much better! However, this black and white page is starting to bum us out.

Rainbows and unicorns

Since our controls are SVGs, we can use the magic of CSS filters to colour them.

Let's start by picking a colour, and what better colour for the sake of this demo than a lovely amber sort of shade called #f7931e. Of course, CSS filters can't be specified in something as prosaic as hex colour codes, so we'll use a magic CodePen thingy to generate a filter from our hex code. (We could also port the JavaScript from this spectacular StackOverflow answer to ClojureScript, but we kinda don't feel like it.)

What we come up with is this:

filter: invert(59%) sepia(92%) saturate(611%) hue-rotate(343deg) brightness(97%) contrast(99%);

We can now add this as a style to our img tags:

(comment

  ;; ...

  (doseq [el playback-buttons]
    (set! (.-style el)
          (str "width: 35px; filter: invert(59%) sepia(92%) saturate(611%) "
               "hue-rotate(343deg) brightness(97%) contrast(99%);")))
  ;; => nil

  )

Better!

Player with a orange playback controls

One thing that's slightly annoying is that we had to remember to include to include the width style when we added the filters. Why don't we write some code that adds a style to an existing element whilst preserving existing styles?

First, let's help ourselves out by pulling in clojure.string:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...

(comment

  ;; ...

  ;; What do styles look like?
  (-> playback-buttons
      first
      (.getAttribute "style"))
  ;; => "width: 35px; filter: invert(59%) sepia(92%) saturate(611%)
  ;;     hue-rotate(343deg) brightness(97%) contrast(99%);"

  ;; Parse into a list of styles
  (-> playback-buttons
      first
      (.getAttribute "style")
      (str/split #";\s+"))
  ;; => ["width: 35px"
  ;;     "filter: invert(59%) sepia(92%) saturate(611%)
  ;;      hue-rotate(343deg) brightness(97%) contrast(99%);"]

  ;; Turn it into a map
  (let [styles (-> playback-buttons
                   first
                   (.getAttribute "style")
                   (str/split #";\s+"))]
    (->> styles
         (map #(let [[k v] (str/split % #":\s+")]
                 [(keyword k) v]))
         (into {})))
  ;; => {:width "35px",
  ;;     :filter "invert(59%) sepia(92%) saturate(611%)
  ;;              hue-rotate(343deg) brightness(97%) contrast(99%);"}

  )

Now we have a thing that we can easily turn into a function!

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; (defn log ...)

(defn get-styles
  "Returns the inline styles of an element as a map of style name to value."
  [el]
  (let [styles (-> el
                   (.getAttribute "style")
                   (str/split #";\s+"))]
    (->> styles
         (map #(let [[k v] (str/split % #":\s+")]
                 [(-> (str/trim k) keyword) (str/trim v)]))
         (into {}))))

;; ...

(comment

  ;; ...

  (-> playback-buttons
      first
      get-styles)
  ;; => {:width "35px",
  ;;     :filter "invert(59%) sepia(92%) saturate(611%)
  ;;              hue-rotate(343deg) brightness(97%) contrast(99%);"}

  )

How about going the other direction, i.e. turning a map of styles into a style string?

(comment

  ;; ...

  (->> {:width "35px", :height "35px"}
       (map (fn [[k v]]
              (str (name k) ": " v)))
       (str/join "; "))
  ;; => "width: 35px; height: 35px"

  )

From this, 'tis merely a hop, skip, and a jump to write a function that sets the styles of an element:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; (defn get-styles ...)

(defn set-styles!
  "Sets the styles of an element from a map of style name to value."
  [el styles]
  (let [styles-str (->> styles
                        (map (fn [[k v]]
                               (str (name k) ": " v)))
                        (str/join "; "))]
    (set! (.-style el) styles-str))
  el)

;; ...

(comment

  ;; ...

  ;; Back to black!
  (doseq [el playback-buttons]
    (set-styles! el {:width "35px"}))
  ;; => nil

  )

Finally, let's put this together and create a function that adds a style instead of replacing all the existing ones:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn set-styles! ...)

(defn add-style!
  "Adds a style to an element"
  [el style-name style-value]
  (let [styles (get-styles el)]
    (set-styles! el (assoc styles (name style-name) style-value)))
  el)

;; ...

(comment

  ;; ...

  ;; Amber is the new black
  (doseq [el playback-buttons]
    (add-style! el :filter
                (str "invert(59%) sepia(92%) saturate(611%) "
                     "hue-rotate(343deg) brightness(97%) contrast(99%)")))
  ;; => nil

  )

Play it again, Sam

Now that we have visually stunning buttons, let's actually make them do something.

Or rather, let's do something that allows us to make them do something. πŸ˜…

Remember how we added a cljcastr class to the buttons so we could easier grab them with js/document.querySelector? Well, we didn't do this to our poor audio element, which will now cause us a problem:

(comment

  ;; ...

  (-> (js/document.querySelector "audio")
      log)
  ;; => #object[HTMLAudioElement [object HTMLAudioElement]]

  )

Seems OK in the REPL, but if we look at the JS console, things (might not, depending on your browser and which extensions you have installed) look so good:

  <audio class="audio-for-speech" src></audio>                     nrepl.cljs:10

Seems like my browser is set up with a screen reader, which is very nice for accessibility, but not nice for Clojure programmers who didn't get enough hammock time. Let's add a class so we can use a more precise selector:

(comment

  ;; ...

  (set! (.-classList audio) "cljcastr")
  ;; => "cljcastr"

  (-> (js/document.querySelector "audio.cljcastr")
      log)
  ;; => #object[HTMLAudioElement [object HTMLAudioElement]]

  )

And now the console looks more like what we expected:

  <audio class="cljcastr" controls                                 nrepl.cljs:10
  src="https://media.zencastr.com/audio-files/5d9048546bacd9001de88f1c/2abc6f33-6a0a-4658-a8e0-c811984c13a0.mp3">
  </audio>

Now we can proceed with making our buttons come alive:

(comment

  ;; ...

  ;; Grab the play button
  (def play-button (js/document.querySelector "#button-play"))
  ;; => #'cljcastr.player/play-button

  ;; Add a click handler
  (.addEventListener play-button "click"
                     (fn [ev]
                       (log ev)
                       (.play (js/document.querySelector "audio.cljcastr"))))
  ;; => nil

  )

If we click the button, we hear the podcast start playing, and can see the playback position in the standard HTML audio element above.

Player playing an episode

Now we can do the same for the pause button:

(comment

  ;; ...

  ;; Grab the pause button
  (def pause-button (js/document.querySelector "#button-pause"))
  ;; => #'cljcastr.player/play-button

  ;; Add a click handler
  (.addEventListener pause-button "click"
                     (fn [ev]
                       (log ev)
                       (.pause (js/document.querySelector "audio.cljcastr"))))
  ;; => nil

  )

That was easy! Skipping forward will be a little more interesting, since there's no JS function to tell the audio object "skip forward x seconds", there's only a currentTime property that we can query and set:

(comment

  ;; ...

  (.-currentTime audio)
  ;; => 29.396358

  (set! (.-currentTime audio) 15.0)
  ;; => 15

  )

Given this, it's not too hard to figure out how to skip forward and backward an arbitrary number of seconds:

(comment

  ;; ...

  ;; Forward
  (let [cur (.-currentTime audio)]
    (set! (.-currentTime audio) (+ cur seek-dur-sec)))
  ;; => 30

  ;; Backward
  (let [cur (.-currentTime audio)]
    (set! (.-currentTime audio) (- cur seek-dur-sec)))
  ;; => 15

  )

It's probably a good idea not to skip forward past the end of the episode or backward past the beginning, so let's see if we can put a stop to that silliness:

(comment

  ;; ...

  ;; Forward with guard
  (let [cur (.-currentTime audio)]
    (set! (.-currentTime audio) (min (+ cur seek-dur-sec)
                                     (.-duration audio))))
  ;; => 30

  ;; The end is nigh!
  (set! (.-currentTime audio) (- (.-duration audio) 5))
  ;; => 5365.949958

  ;; Don't worry, all is well
  (let [cur (.-currentTime audio)]
    (set! (.-currentTime audio) (min (+ cur seek-dur-sec)
                                     (.-duration audio))))
  ;; => 5370.949958

  ;; Hitting 88 miles per hour
  (set! (.-currentTime audio) 5)
  ;; => 5

  ;; Backward
  (let [cur (.-currentTime audio)]
    (set! (.-currentTime audio) (max (- cur seek-dur-sec)
                                     0)))
  ;; => 0

  )

Armed with this code, let's make some functions:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn add-style! ...)

(defn skip-forward! [audio-el sec]
  (let [cur (.-currentTime audio-el)]
    (set! (.-currentTime audio-el) (min (+ cur sec)
                                        (.-duration audio-el)))))

(defn skip-backward! [audio-el sec]
  (let [cur (.-currentTime audio-el)]
    (set! (.-currentTime audio-el) (max (- cur sec)
                                        0))))

;; ...

(comment

  ;; ...

  (skip-forward! audio seek-dur-sec)
  ;; => 15

  (skip-backward! audio seek-dur-sec)
  ;; => 0

  )

Now we can wire up the skip buttons as well:

(comment

  ;; ...

  (def forward-button (js/document.querySelector "#button-forward"))
  ;; => #'cljcastr.player/forward-button

  (def backward-button (js/document.querySelector "#button-backward"))
  ;; => #'cljcastr.player/backward-button

  (.addEventListener forward-button "click"
                     (fn [ev]
                       (log ev)
                       (skip-forward! audio seek-dur-sec)))
  ;; => nil

  (.addEventListener backward-button "click"
                     (fn [ev]
                       (log ev)
                       (skip-backward! audio seek-dur-sec)))
  ;; => nil

  )

Look at this! All of our buttons work! (Except the playback speed one, but that's a little more complicated, so let's save it for later. πŸ˜‰)

The only thing that's obviously wrong with this amazing player is that it has two sets of controls, the standard HTML one and our amazing buttons. There's also something that's not obviously wrong to most readers, unless they happen to be using a screen reader: the accessibility of our buttons sucks! In fact, the only way we know they're buttons is by their appearance, because we're using img elements, which are semantically just images. They could be images of an elephant for all a screen reader knows.

Let's see what we can do about that!

A11y spells ally

From the excellent MDN article on Accessibility:

Accessibility (often abbreviated to A11y β€” as in, "a", then 11 characters, and then "y") in web development means enabling as many people as possible to use websites, even when those people's abilities are limited in some way.

For many people, technology makes things easier. For people with disabilities, technology makes things possible. Accessibility means developing content to be as accessible as possible, no matter an individual's physical and cognitive abilities and how they access the web.

The W3C Accessibility Initiative puts it in even more inspiring terms:

The Web is fundamentally designed to work for all people, whatever their hardware, software, language, location, or ability. When the Web meets this goal, it is accessible to people with a diverse range of hearing, movement, sight, and cognitive ability.

We certainly want all people to adopt our superior podcast player, so let's make sure it works for them, using the power of ARIA!

Arya Stark after killing the Frey soldier with a knife

No, not that one. πŸ˜‰

This one: ARIA.

If we wrap each of our img elements in a button element, we're now conveying semantic meaning to a screen reader (or any other user agent, for that matter; imagine a script that is trying to identify all the buttons on a page... such as the one we're in the process of writing). And if we set that button's aria-label attribute, we're now identifying what the button is meant to do.

Remember the :label key we included in our playback-controls map but never used way back when?

(comment

  ;; ...

  (def playback-controls
    {:play {:src "https://www.svgrepo.com/show/436852/play-circle-fill.svg"
            :label "Play"}
     :pause {:src "https://www.svgrepo.com/show/436829/pause-circle-fill.svg"
             :label "Pause"}
     :forward {:src "https://www.svgrepo.com/show/495321/forward-15-seconds.svg"
               :label "Forward {{seek-dur-sec}} seconds"}
     :backward {:src "https://www.svgrepo.com/show/495036/backward-15-seconds.svg"
             :label "Back {{seek-dur-sec}} seconds"}
     :speed {:src "https://www.svgrepo.com/show/151785/speed-meter.svg"
             :label "Playback speed"}})
  ;; => #'cljcastr.player/playback-controls

  )

Turns out we had accessibility in mind all along!

Let's try wrapping a button:

(comment

  ;; ...

  (let [button-name :play
        {:keys [src label]} {:src "https://www.svgrepo.com/show/495321/forward-15-seconds.svg"
                             :label "Forward {{seek-dur-sec}} seconds"}]
    (let [button-id (str "button-" (name button-name))
          button-el (js/document.createElement "button")
          img-el (js/document.createElement "img")]
      (set! (.-id button-el) button-id)
      (set! (.-classList button-el) "cljcastr")
      (set! (.-ariaLabel button-el) label)
      (set! (.-id img-el) (str button-id "-icon"))
      (set! (.-classList img-el) "cljcastr playback-icon")
      (set! (.-src img-el) src)
      (set! (.-draggable img-el) false)
      (.appendChild button-el img-el)
      (log button-el)))
  ;; => #object[HTMLButtonElement [object HTMLButtonElement]]

  )

All of this set! stuff is starting to get annoying. Why don't we write a nice function that we can call to give us back a fully baked DOM element?

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn add-style! ...)

(defn create-el [{:keys [tag attrs] :as args}]
  (let [el (js/document.createElement tag)]
    (doseq [[attr v] attrs]
      (.setAttribute el (name attr) v))
    el))

;; (defn skip-forward! ...)
;; ...

(comment

  ;; ...

  (let [button-name :play
        {:keys [src label]} {:src "https://www.svgrepo.com/show/495321/forward-15-seconds.svg"
                             :label "Forward {{seek-dur-sec}} seconds"}]
    (let [button-id (str "button-" (name button-name))
          button-el (create-el {:tag "button"
                                :attrs {:id button-id
                                        :class "cljcastr"
                                        :aria-label label}})
          img-el (create-el {:tag "img"
                             :attrs {:id (str button-id "-icon")
                                     :class "cljcastr playback-icon"
                                     :src src
                                     :draggable false}})]
      (.appendChild button-el img-el)
      (log button-el)))
  ;; => #object[HTMLButtonElement [object HTMLButtonElement]]

  )

This looks pretty reasonable in the JS console:

  β€£ <button class="cljcastr" id="button-play"                      nrepl.cljs:10
            aria-label="Forward {{seek-dur-sec}} seconds">
      <img class="cljcastr playback-icon" id="button-play-icon"
           src="https://www.svgrepo.com/show/495321/forward-15-seconds.svg"
           draggable="false">
    </button>

Except this bit, that is:

aria-label="Forward {{seek-dur-sec}} seconds"

Looks like we got a bit clever there with some Selmer-style templating to allow for changing the number of seconds we're skipping around. Let's quickly figure out how to interpolate such strings:

(comment

  ;; ...

  (let [s "Something {{something}} something"]
    (str/replace s "{{something}}" "SOMETHING"))
  ;; => "Something SOMETHING something"

  (let [s "Something {{something}} something"
        ctx {:something "SOMETHING"}]
    (str/replace s #"\{\{(something)\}\}" (fn [[_ k]] (get ctx (keyword k)))))
  ;; => "Something SOMETHING something"

  )

This may appear slightly inscrutable at first glance, but if we look at the documentation for clojure.string/replace, we see that the replacement argument can actually be a function, in which case it's passed the match as an argument and whatever it returns is the replacement string. When the match contains a capturing group, the argument to the function is a vector of [match group1 group2 ...]. For example:

(comment

  ;; ...

  (let [s "It's easy as 123, ABC, baby you and me"]
    (str/replace s #"(\d)+.+([A-Z]+)"
                 (fn [match-vector] (str "<<<" (pr-str match-vector) ">>>"))))
  ;; => "It's easy as <<<[\"123, ABC\" \"3\" \"C\"]>>>, baby you and me"

  )

Let's turn this into a proper function:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; (defn log ...)

(defn render
  "Given a string `s` and a context map `ctx`, replaces template variables of the
   form {{k}} with the value of the corresponding key in the context map. If
   the key `k` doesn't exist in the context map, the template variable won't be
   replaced (i.e. \"{{foo}}\" will remain \"{{foo}}\" in the interpolated
   string)."
  [s ctx]
  (str/replace s #"\{\{([^}]+)\}\}"
               (fn [[match k]] (get ctx (keyword k) match))))

;; (defn get-styles ...)
;; ...

(comment

  ;; ...

  (render "foo {{bar}} baz {{blah}} {{barf}}" {:bar 27, :blah 42})
  ;; => "foo 27 baz 42 {{barf}}"

  )

Now we can make use of our new render function in our button-wrapping code:

(comment

  ;; ...

  (let [button-name :play
        {:keys [src label]} {:src "https://www.svgrepo.com/show/495321/forward-15-seconds.svg"
                             :label "Forward {{seek-dur-sec}} seconds"}]
    (let [button-id (str "button-" (name button-name))
          button-el (create-el {:tag "button"
                                :attrs {:id button-id
                                        :class "cljcastr"
                                        :aria-label (render label {:seek-dur-sec seek-dur-sec})}})
          img-el (create-el {:tag "img"
                             :attrs {:id (str button-id "-icon")
                                     :class "cljcastr playback-icon"
                                     :src src
                                     :draggable false}})]
      (.appendChild button-el img-el)
      (log button-el)))
  ;; => #object[HTMLButtonElement [object HTMLButtonElement]]

  )

Quoth the console:

  β€£ <button class="cljcastr" id="button-forward"                      nrepl.cljs:10
            aria-label="Forward 15 seconds">
      <img class="cljcastr playback-icon" id="button-forward-icon"
           src="https://www.svgrepo.com/show/495321/forward-15-seconds.svg"
           draggable="false">
    </button>

Now we can extract a nice function to create a button:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn create-el ...)

(defn create-button
  ([button-name button]
   (create-button button-name button {}))
  ([button-name {:keys [label src click-handler]} ctx]
   (let [button-id (str "button-" (name button-name))
         button-el (create-el {:tag "button"
                               :attrs {:id button-id
                                       :class (render "cljcastr {{button-class}}" ctx)
                                       :aria-label (render label ctx)}})
         img-el (create-el {:tag "img"
                            :attrs {:id (str button-id "-icon")
                                    :class (render "cljcastr {{img-class}}" ctx)
                                    :src src
                                    :draggable false}})]
     (.addEventListener button-el "click" click-handler)
     (.appendChild button-el img-el)
     button-el)))

;; (defn skip-forward! ...)
;; ...

(comment

  ;; ...

  (->> (create-button :forward
                      {:src "https://www.svgrepo.com/show/495321/forward-15-seconds.svg"
                       :label "Forward {{seek-dur-sec}} seconds"}
                      {:seek-dur-sec seek-dur-sec
                       :button-class "playback-button"
                       :img-class "playback-icon"})
       log)
  ;; => #object[HTMLButtonElement [object HTMLButtonElement]]

  )

We've pulled another nice thing out of Clojure's bag of tricks: multi-arity functions:


(defn create-button
  ([button-name button]
   (create-button button-name button {}))
  ([button-name {:keys [label src]} ctx]
   ;; ...
  ))

This allows us to call create-button without a context:

(create-button :play {:label "Play", :src "play.svg"})

This will call the version of create-button that takes two arguments, which in turn calls the three-argument version, passing along the button-name and button arguments as is, and adding an empty map as the ctx argument.

OK, now we can use our create-button function to sew new a11y'd buttons onto our playback-controls div:

(comment

  ;; ...

  ;; Throw away the current crappy buttons
  (.replaceChildren playback-controls-container)
  ;; => nil

  ;; Let's fix the order of our buttons whilst we're at it
  (def playback-buttons
    (->> [:backward :play :pause :forward :speed]
         (map (fn [button-name]
                [button-name (get playback-controls button-name)]))
         (map (fn [[button-name button]]
                (let [button-el (create-button button-name button
                                               {:seek-dur-sec seek-dur-sec
                                                :button-class "playback-button"
                                                :img-class "playback-icon"})]
                  (-> button-el
                      .-firstChild
                      (set-styles! {:width "35px"
                                    :filter "invert(59%) sepia(92%) saturate(611%) hue-rotate(343deg) brightness(97%) contrast(99%)"}))
                  button-el)))
         log))
  ;; => #'cljcastr.player/playback-buttons

  (doseq [el playback-buttons]
    (.appendChild playback-controls-container el))
  ;; => nil

  ;; Grab the new buttons
  (def play-button (js/document.querySelector "#button-play"))
  ;; => #'cljcastr.player/play-button

  (def pause-button (js/document.querySelector "#button-pause"))
  ;; => #'cljcastr.player/play-button

  (def forward-button (js/document.querySelector "#button-forward"))
  ;; => #'cljcastr.player/forward-button

  (def backward-button (js/document.querySelector "#button-backward"))
  ;; => #'cljcastr.player/backward-button

  ;; Attach the click handlers to them
  (.addEventListener play-button "click"
                     (fn [ev]
                       (log ev)
                       (.play (js/document.querySelector "audio.cljcastr"))))
  ;; => nil

  (.addEventListener pause-button "click"
                     (fn [ev]
                       (log ev)
                       (.pause (js/document.querySelector "audio.cljcastr"))))
  ;; => nil

  (.addEventListener forward-button "click"
                     (fn [ev]
                       (log ev)
                       (skip-forward! (js/document.querySelector "audio.cljcastr")
                                      seek-dur-sec)))
  ;; => nil

  (.addEventListener backward-button "click"
                     (fn [ev]
                       (log ev)
                       (skip-backward! (js/document.querySelector "audio.cljcastr")
                                       seek-dur-sec)))
  ;; => nil

  )

Player with buttons with backgrounds and borders

The only problem with this approach is that our buttons now look like, well, buttons. πŸ˜…

Let's restyle them a bit so they look like they did before:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn create-el ...)

(defn create-button
  ([button-name button]
   (create-button button-name button {}))
  ([button-name {:keys [label src click-handler]} ctx]
   (let [button-id (str "button-" (name button-name))
         button-el (create-el {:tag "button"
                               :attrs {:id button-id
                                       :class (render "cljcastr {{button-class}}" ctx)
                                       :aria-label (render label ctx)}})
         img-el (create-el {:tag "img"
                            :attrs {:id (str button-id "-icon")
                                    :class (render "cljcastr {{img-class}}" ctx)
                                    :src src
                                    :draggable false}})]
     (set-styles! button-el {:padding 0
                             :margin 0
                             :border 0
                             :background "transparent"
                             :cursor "pointer"})
     (.addEventListener button-el "click" click-handler)
     (.appendChild button-el img-el)
     button-el)))

;; (defn skip-forward! ...)
;; ...

(comment

  ;; ...

  (.replaceChildren playback-controls-container)
  ;; => nil

  (def playback-buttons
    (->> [:backward :play :pause :forward :speed]
         (map (fn [button-name]
                [button-name (get playback-controls button-name)]))
         (map (fn [[button-name button]]
                (let [button-el (create-button button-name button
                                               {:seek-dur-sec seek-dur-sec
                                                :button-class "playback-button"
                                                :img-class "playback-icon"})]
                  (-> button-el
                      .-firstChild
                      (set-styles! {:width "35px"
                                    :filter (str "invert(59%) sepia(92%) saturate(611%) "
                                                 "hue-rotate(343deg) brightness(97%) contrast(99%)")}))
                  button-el)))
         log))
  ;; => #'cljcastr.player/playback-buttons

  (doseq [el playback-buttons]
    (.appendChild playback-controls-container el))
  ;; => nil

  (def play-button (js/document.querySelector "#button-play"))
  ;; => #'cljcastr.player/play-button

  (def pause-button (js/document.querySelector "#button-pause"))
  ;; => #'cljcastr.player/play-button

  (def forward-button (js/document.querySelector "#button-forward"))
  ;; => #'cljcastr.player/forward-button

  (def backward-button (js/document.querySelector "#button-backward"))
  ;; => #'cljcastr.player/backward-button

  (.addEventListener play-button "click"
                     (fn [ev]
                       (log ev)
                       (.play (js/document.querySelector "audio.cljcastr"))))
  ;; => nil

  (.addEventListener pause-button "click"
                     (fn [ev]
                       (log ev)
                       (.pause (js/document.querySelector "audio.cljcastr"))))
  ;; => nil

  (.addEventListener forward-button "click"
                     (fn [ev]
                       (log ev)
                       (skip-forward! audio seek-dur-sec)))
  ;; => nil

  (.addEventListener backward-button "click"
                     (fn [ev]
                       (log ev)
                       (skip-backward! audio seek-dur-sec)))
  ;; => nil

  )

Now our buttons look like they did before! πŸŽ‰

However, recreating these buttons is getting a little tedious. Let's do some cleaning up.

Sweeping up the shop

First of all, our log function is a little limited. It would be nice if we could include a log message in addition to whatever data we're logging. In other words, we'd like to do this:

(comment

  ;; ...

  (log "Something happened!" {:foo 1, :bar 2})
  ;; => "Something happened!"

  )

But if we look at the console now, we only see the message logged and not the data:

  Something happened!                                                 nrepl.cljs:10

Luckily, the fix is pretty straightforward:

(ns cljcastr.player
  (:require [clojure.string :as str]))

(defn log [& args]
  (apply js/console.log (map clj->js args))
  (last args))

;; (defn render ...)
;; ...

(comment

  ;; ...

  (log "Something happened!" {:foo 1, :bar 2})
  ;; => {:foo 1, :bar 2}

  )

The value returned is what we wanted, and the console looks good as well:

  Something happened!  β€£ {foo: 1, bar: 2}                             nrepl.cljs:10

Next annoyance: all those js/document.querySelector calls. Extraction!

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn render ...)

(defn get-el
  "Returns the element matching the specified CSS selector. If `selector` is
   already an element, just returns the element."
  [selector]
  (if (instance? js/Element selector)
    selector
    (js/document.querySelector selector)))

;; (defn get-styles ...)
;; ...

(comment

  ;; ...

  (get-el "#button-play")
  ;; => #object[HTMLButtonElement [object HTMLButtonElement]]

  )

Might as well have a function to get a list of elements too:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn get-el ...)

(defn get-els
  "Returns a sequence containing the elements matching the specified CSS
   selector."
  [selector]
  (->> (js/document.querySelectorAll selector)
       seq))

;; (defn get-styles ...)
;; ...

(comment

  ;; ...

  (get-els "#playback-controls > button")
  ;; => (#object[HTMLButtonElement [object HTMLButtonElement]] 
  ;;     #object[HTMLButtonElement [object HTMLButtonElement]] 
  ;;     #object[HTMLButtonElement [object HTMLButtonElement]] 
  ;;     #object[HTMLButtonElement [object HTMLButtonElement]] 
  ;;     #object[HTMLButtonElement [object HTMLButtonElement]])

  )

How about one to return the children of an element?

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn get-els ...)

(defn get-children [el]
  (-> (get-el el)
      .-childNodes
      seq))

;; (defn get-styles ...)
;; ...

(comment

  ;; ...

  (-> (get-children "#playback-controls")
      log)
  ;; => (#object[HTMLButtonElement [object HTMLButtonElement]] 
  ;;     #object[HTMLButtonElement [object HTMLButtonElement]] 
  ;;     #object[HTMLButtonElement [object HTMLButtonElement]] 
  ;;     #object[HTMLButtonElement [object HTMLButtonElement]] 
  ;;     #object[HTMLButtonElement [object HTMLButtonElement]])

  )

We added another nicety there: by using get-el, our function can take either an element or a CSS selector as its argument. Let's continue to use this pattern as we add a function for adding a child to an element:

But if we look at the console, we see something extremely odd:

                                                                      nrepl.cljs:10
  β€£ he {value: button#backward, Ee: ArrayIterator, Ag: null, F: 8388672, M: 0}

The answers, my friend, are blowing in the wind of get-children:

(defn get-children [el]
  (-> (get-el el)
      .-childNodes
      seq))

We're taking the childNodes attribute of our HTMLDivElement, which is a NodeList object:

(comment

  ;; ...

  (-> (get-el "#playback-controls")
      .-childNodes
      log)
  ;; => #object[NodeList [object NodeList]]

  )

This looks great in the console:

                                                                      nrepl.cljs:10
    NodeList(5) [button#button-backward.cljcastr.playback-button,
    button#button-play.cljcastr.playback-button,
  β€£ button#button-pause.cljcastr.playback-button,
    button#button-forward.cljcastr.playback-button,
    button#button-speed.cljcastr.playback-button]

But we can't use it in Clojure all that well:

(comment

  ;; ...

  (-> (get-el "#playback-controls")
      .-childNodes
      count)
  ;; => "#error {:message \"No protocol method ICounted.-count defined for type object: [object NodeList]\", ...}"

  )

That's why get-children adds the call to seq at the end. That lets normal Clojure code deal with the list of children, but as we've seen, it doesn't look good in the console when logged.

Let's see what we can do about this:

(comment

  ;; ...

  (-> (get-children "#playback-controls")
      vec
      log)
  ;; => [#object[HTMLButtonElement [object HTMLButtonElement]]
  ;;     #object[HTMLButtonElement [object HTMLButtonElement]]
  ;;     #object[HTMLButtonElement [object HTMLButtonElement]]
  ;;     #object[HTMLButtonElement [object HTMLButtonElement]]
  ;;     #object[HTMLButtonElement [object HTMLButtonElement]]]

  )

Now the console is looking quite reasonable!

                                                                      nrepl.cljs:10
    (5) [button#button-backward.cljcastr.playback-button,
    button#button-play.cljcastr.playback-button,
  β€£ button#button-pause.cljcastr.playback-button,
    button#button-forward.cljcastr.playback-button,
    button#button-speed.cljcastr.playback-button]

Let's see if we can apply what we've learned here to our log function:

(ns cljcastr.player
  (:require [clojure.string :as str]))

(defn log [& args]
  (let [seq->vec #(if (seq? %) (vec %) %)]
    (apply js/console.log (map (comp clj->js seq->vec) args)))
  (last args))

  ;; (defn render ...)
  ;; ...

(comment

  ;; ...

  (-> (get-children "#playback-controls")
      log)
  ;; => (#object[HTMLButtonElement [object HTMLButtonElement]]
  ;;     #object[HTMLButtonElement [object HTMLButtonElement]]
  ;;     #object[HTMLButtonElement [object HTMLButtonElement]]
  ;;     #object[HTMLButtonElement [object HTMLButtonElement]]
  ;;     #object[HTMLButtonElement [object HTMLButtonElement]])

  )
(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn get-children ...)

(defn add-child! [parent-el el]
  (let [parent-el (get-el parent-el)]
    (-> parent-el
        (.appendChild el))
    parent-el))

;; (defn get-styles ...)
;; ...

(comment

  ;; ...

  (->> (add-child! "#playback-controls"
                   (create-el {:tag "span"
                               :text "Some nonsense"}))
       (log "I got a new child"))
  ;; => #object[HTMLDivElement [object HTMLDivElement]]

  )

Wanna clear all the children of an element?

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn add-child! ...)

(defn clear-children! [el]
  (let [el (get-el el)]
    (.replaceChildren el)
    el))

;; (defn get-styles ...)
;; ...

(comment

  ;; ...

  (->> (clear-children! "#playback-controls")
       (log "Empty nest"))
  ;; => #object[HTMLDivElement [object HTMLDivElement]]

  )

Set the children of an element?

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn clear-children! ...)

(defn set-children! [parent-el els]
  (let [parent-el (get-el parent-el)]
    (clear-children! parent-el)
    (doseq [el els]
      (add-child! parent-el el))
    parent-el))

;; (defn get-styles ...)
;; ...

(comment

  ;; ...

  (->> (set-children! "#playback-controls" playback-buttons)
       log)
  ;; => #object[HTMLDivElement [object HTMLDivElement]]

  )

Final annoyance: all the repetition in the click handlers. Let's extract a function for that as well:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn create-el ...)

(defn add-event-listener! [el event-type f]
  (let [el (get-el el)]
    (.addEventListener el event-type
                       (fn [ev]
                         (log (str "Handling " event-type " on")
                              el ev)
                         (if f
                           (f ev)
                           (log "No event handler function defined"))))
    (log "Added listener for" event-type "events to" el)
    el))

;; (defn create-button ...)
;; ...

(comment

  ;; ...

  (add-event-listener! "#button-speed" "click"
                       #(log "Should probably do something with this event, eh?" %))
  ;; => #object[HTMLButtonElement [object HTMLButtonElement]]

  )

And if we now click the playback speed button, the console rewards us with some rich logging:

Console log of event handler

With all these awesome functions, we can finally recreate our buttons much more concisely:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn add-event-listener! ...)

(defn create-button
  ([button-name button]
   (create-button button-name button {}))
  ([button-name {:keys [label src click-handler]} ctx]
   (let [button-id (str "button-" (name button-name))]
     (-> (create-el {:tag "button"
                     :attrs {:id button-id
                             :class (render "cljcastr {{button-class}}" ctx)
                             :aria-label (render label ctx)}})
         (set-styles! {:padding 0
                       :margin 0
                       :border 0
                       :background "transparent"
                       :cursor "pointer"})
         (add-event-listener! "click" click-handler)
         (add-child! (create-el {:tag "img"
                                 :attrs {:id (str button-id "-icon")
                                         :class (render "cljcastr {{img-class}}" ctx)
                                         :src src
                                         :draggable false}}))))))

;; (defn skip-forward! ...)
;; ...

(comment

  ;; ...

  (def playback-controls
    {:play {:src "https://www.svgrepo.com/show/436852/play-circle-fill.svg"
            :label "Play"
            :click-handler #(.play (get-el "audio.cljcastr"))}
     :pause {:src "https://www.svgrepo.com/show/436829/pause-circle-fill.svg"
             :label "Pause"
             :click-handler #(.pause (get-el "audio.cljcastr"))}
     :forward {:src "https://www.svgrepo.com/show/495321/forward-15-seconds.svg"
               :label "Forward {{seek-dur-sec}} seconds"
               :click-handler #(skip-forward! (get-el "audio.cljcastr") seek-dur-sec)}
     :backward {:src "https://www.svgrepo.com/show/495036/backward-15-seconds.svg"
                :label "Back {{seek-dur-sec}} seconds"
                :click-handler #(skip-backward! (get-el "audio.cljcastr") seek-dur-sec)}
     :speed {:src "https://www.svgrepo.com/show/151785/speed-meter.svg"
             :label "Playback speed"}})
  ;; => #'cljcastr.player/playback-controls

  (def playback-buttons
    (->> [:backward :play :pause :forward :speed]
         (map (fn [button-name]
                [button-name (get playback-controls button-name)]))
         (map (fn [[button-name button]]
                (let [button-el (create-button button-name button
                                               {:seek-dur-sec seek-dur-sec
                                                :class "playback-control"})]
                  (-> (get-children button-el)
                      first
                      (set-styles! {:width "35px"
                                    :filter "invert(59%) sepia(92%) saturate(611%) hue-rotate(343deg) brightness(97%) contrast(99%)"}))
                  button-el)))
         log))
  ;; => #'cljcastr.player/playback-buttons

  (set-children! "#playback-controls" playback-buttons)
  ;; => #object[HTMLDivElement [object HTMLDivElement]]

  )

OK, so we've fixed the non-obvious (to those of us not using screen readers) problem with the player. Scratching our heads, we try to recall what the obvious problem was. πŸ€”

Oh yeah! Two sets of controls, right. Let's fix.

Sweeping audio under the carpet

Making our audio element disappear isn't that hard. Let's use this as an excuse to create a few more helper functions and spread the get-el pattern a little wider as well:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn get-els ...)

(defn get-attr
  "Returns the value of the specified attribute."
  [el attr]
  (let [el (get-el el)]
    (.getAttribute el (name attr))))

(defn set-attr!
  "Sets the value of the specified attribute."
  [el attr v]
  (let [el (get-el el)]
    (.setAttribute el (name attr) v)
    el))

(defn set-attrs! [el attrs]
  (let [el (get-el el)]
    (doseq [[k v] attrs]
      (.setAttribute el (name k) v))
    el))

(defn get-id
  "Returns the ID of an element."
  [el]
  (let [el (get-el el)]
    (.-id el)))

(defn set-id!
  "Sets the ID of an element."
  [el id]
  (let [el (get-el el)]
    (when-not (empty? id)
      (set-attr! el :id id))
    el))

(defn get-name
  "Returns the tag name of an element."
  [el]
  (let [el (get-el el)]
    (.-localName el)))

(defn get-text
  "Returns the inner text of an element."
  [el]
  (let [el (get-el el)]
    (or (.-textContent el)
        (.-innerText el))))

(defn set-text! [el text]
  (let [el (get-el el)]
    (when-not (empty? text)
      (set! (.-textContent el) text))
    el))

(defn get-classes
  "Returns the classes of the specified element as a list of class names."
  [el]
  (let [el (get-el el)]
    (->> (str/split (.-classList el) #"\s")
         (remove empty?))))

(defn set-classes!
  "Sets the classes of the specified element. Classes may either be a list or a
   string.

   Example:

     ;; These two are equivalent
     (set-classes el [\"foo\" \"bar\"])
     (set-classes el \"foo bar\")"
  [el classes]
  (let [el (get-el el)]
    (when-not (empty? classes)
      (set! (.-classList el) (if (string? classes)
                               classes
                               (str/join " " classes))))
    el))

;; (defn get-children ...)
;; ...
;; (defn set-children! ...)

(defn get-styles
  "Returns the inline styles of an element as a map of style name to value."
  [el]
  (let [styles (-> (get-el el)
                   (.getAttribute "style")
                   (str/split #";\s+"))]
    (->> styles
         (remove empty?)
         (map #(let [[k v] (str/split % #":\s+")]
                 [(-> (str/trim k) keyword) (str/trim v)]))
         (into {}))))

(defn set-styles!
  "Sets the styles of an element from a map of style name to value."
  [el styles]
  (let [el (get-el el)]
    (when-not (empty? styles)
      (set! (.-style el) (->> styles
                              (map (fn [[k v]]
                                     (str (name k) ": " v)))
                              (str/join "; "))))
    el))

(defn add-styles!
  "Given a map of style name to value, adds the styles to the element."
  [el styles]
  (-> el
      (set-styles! (merge (get-styles el) styles))))

(defn add-style!
  "Adds a style to an element"
  [el style-name style-value]
  (-> el
      (add-styles! {style-name style-value})))

;; (defn create-el)
;; ...

Now that we have all of this awesomeness, we can streamline create-el by accepting a few more keys:

  • :id "foo" instead of :attrs {:id "foo"}
  • :classes ["foo" "bar"] instead of :attrs {:class "foo bar"}
  • :text to set the text content of the element

We also have to update create-button to take advantage of this.

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn add-style! ...)

(defn create-el [{:keys [tag id classes text attrs] :as args}]
  (-> (js/document.createElement tag)
      (set-attrs! attrs)
      (set-id! id)
      (set-classes! classes)
      (set-text! text)))

;; (defn add-event-listener! ...)
;; ...

(defn create-button
  ([button-name button]
   (create-button button-name button {}))
  ([button-name {:keys [label src click-handler]} ctx]
   (let [button-id (str "button-" (name button-name))]
     (-> (create-el {:tag "button"
                     :id button-id
                     :classes ["cljcastr"
                               (render "{{button-class}}" ctx)]
                     :attrs {:aria-label (render label ctx)}})
         (set-styles! {:padding 0
                       :margin 0
                       :border 0
                       :background "transparent"
                       :cursor "pointer"})
         (add-event-listener! "click" click-handler)
         (add-child! (create-el {:tag "img"
                                 :id (str button-id "-icon")
                                 :classes ["cljcastr"
                                           (render "{{img-class}}" ctx)]
                                 :attrs {:src src
                                         :draggable false}}))))))

;; (defn skip-forward! ...)
;; ...

(comment

  ;; ...

  (add-style! audio :display "none")
  ;; => #object[HTMLAudioElement [object HTMLAudioElement]]

  (def playback-buttons
    (->> [:backward :play :pause :forward :speed]
         (map (fn [button-name]
                [button-name (get playback-controls button-name)]))
         (map (fn [[button-name button]]
                (let [button-el (create-button button-name button
                                               {:seek-dur-sec seek-dur-sec
                                                :button-class "playback-button"
                                                :img-class "playback-icon"})]
                  (-> (get-children button-el)
                      first
                      (set-styles! {:width "35px"
                                    :filter (str "invert(59%) sepia(92%) saturate(611%) "
                                                 "hue-rotate(343deg) brightness(97%) contrast(99%)")}))
                  button-el)))
         log))
  ;; => #'cljcastr.player/playback-buttons

  (set-children! "#playback-controls" playback-buttons)
  ;; => #object[HTMLDivElement [object HTMLDivElement]]

  )

Player with just buttons

Testing our controls, we verify that they still work. However, we've lost three important things:

  1. The progress bar, which gave us a visual indication of where we are and a way to move to an arbitrary point in the episode by clicking or dragging.
  2. The display of the current position in the episode.
  3. The display of the duration of the episode.

Actually, on the third point, we like Overcast's choice to display the time remaining instead of the duration, so let's do that as well.

Having made these bold design decisions, let's get to implementing! We'll start with the easy stuff, displaying the time elapsed and remaining:

(comment

  ;; ...

  (def elapsed-time (create-el {:tag "span"
                                :text (str (.-currentTime audio))
                                :classes ["cljcastr"]
                                :id "elapsed-time"}))
  ;; => #'cljcastr.player/cur-time

  (def remaining-time (create-el {:tag "span"
                                  :text (str (- (.-duration audio)
                                                (.-currentTime audio)))
                                  :classes ["cljcastr"]
                                  :id "remaining-time"}))
  ;; => #'cljcastr.player/remaining-time

  (doseq [el [elapsed-time remaining-time]]
    (add-child! "#playback-controls" el))
  ;; => nil

  )

Times displayed as fractional seconds

Well, this is something, at least. Something incredibly confusing and also ugly. 😭

Let's enumerate the problems:

  1. Times are displayed as fractional seconds, not the more familiar h:mm:ss.
  2. The spans are side by side with no padding, so it's not possible to tell where elapsed time ends and remaining time begins.
  3. The font size is too large compared to the buttons. And maybe black isn't the best choice of colour anyway.
  4. We'd like the times displayed above the buttons (and the progress bar, when we get around to adding it).

Now that we know what's wrong, let's tackle things one at a time.

Hours, minutes, and seconds, oh my!

How can we convert from seconds to h:mm:ss?

(comment

  ;; ...

  (set! (.-currentTime audio) 3645)
  ;; => 3645

  (let [secs (.-currentTime audio)
        h (-> secs (/ 3600) int)
        mm (-> secs (/ 60) (- (* h 60)) int)
        ss (-> secs (mod 60) int)]
    (str (int h) ":" (int mm) ":" (int ss)))
  ;; => "1:0:45"

  )

OK, not a bad start. Let's zero-pad the minutes and seconds, though, because "1:00:45" looks way better than "1:0:45". πŸ˜‰

(comment

  ;; ...

  (let [secs (.-currentTime audio)
        h (-> secs (/ 3600) int)
        mm (-> secs (/ 60) (- (* h 60)) int)
        ss (-> secs (mod 60) int)
        zero-pad #(-> % int str (str/replace #"^(\d)$" "0$1"))]
    (str (int h) ":" (zero-pad mm) ":" (zero-pad ss)))
  ;; => "1:00:45"

  (set! (.-currentTime audio) 46)
  ;; => 46

  (let [secs (.-currentTime audio)
        h (-> secs (/ 3600) int)
        mm (-> secs (/ 60) (- (* h 60)) int)
        ss (-> secs (mod 60) int)
        zero-pad #(-> % int str (str/replace #"^(\d)$" "0$1"))]
    (str (int h) ":" (zero-pad mm) ":" (zero-pad ss)))
  ;; => "0:00:46"

  )

Hrm, maybe one more tweak. It's conventional to omit the hour(s) portion of timestamps less than an hour:

(comment

  ;; ...

  (let [secs (.-currentTime audio)
        h (-> secs (/ 3600) int)
        mm (-> secs (/ 60) (- (* h 60)) int)
        ss (-> secs (mod 60) int)
        zero-pad #(-> % int str (str/replace #"^(\d)$" "0$1"))]
    (str (if (pos? (int h))
           (str (int h) ":")
           "")
         (zero-pad mm) ":" (zero-pad ss)))
  ;; => "00:46"

  )

Nice! Now let's turn this into a function:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn render ...)

(defn secs->ts
  "Given a number of seconds, returns a timestamp of the form h:mm:ss."
  [secs]
  (let [h (-> secs (/ 3600) int)
        mm (-> secs (/ 60) (- (* h 60)) int)
        ss (-> secs (mod 60) int)
        zero-pad #(-> % int str (str/replace #"^(\d)$" "0$1"))]
    (str (if (pos? (int h))
           (str (int h) ":")
           "")
         (zero-pad mm) ":" (zero-pad ss))))

;; (defn get-el ...)
;; ...

(comment

  ;; ...

  ;; Elapsed time
  (secs->ts (.-currentTime audio))
  ;; => "00:46"

  ;; Remaining time
  (secs->ts (- (.-duration audio) (.-currentTime audio)))
  ;; => "1:28:44"

  (-> elapsed-time
      (set-text! (secs->ts (.-currentTime audio)))
      log)
  ;; => #object[HTMLSpanElement [object HTMLSpanElement]]

  (-> remaining-time
      (set-text! (str "-" (secs->ts (- (.-duration audio) (.-currentTime audio)))))
      log)
  ;; => #object[HTMLSpanElement [object HTMLSpanElement]]
  
  )

OK, we've solved problem number 1. πŸŽ‰

Problems 2 and 3 are just styling, so the fixes are pretty straightforward:

(comment

  ;; ...

  (doseq [el [elapsed-time remaining-time]]
    (add-styles! el {:margin "0 5px 0 5px"
                     :font-size "0.7rem"
                     :color "grey"}))
  ;; => nil

  )

Timestamps displayed in smaller, grey text

Whilst we're at it, let's fix another annoyance: with our current create-el function, we either have to call add-styles! (or set-styles!) afterwards, or do the stringifying of the styles ourselves:

(create-el {:tag "div"
            :attrs {:id "whatever"
                    :style "margin: 0 5px 0 5px; font-size: 0.7rm; color: grey"}})

We also have the same issue with classes and ID. πŸ™

But instead of wallowing in misery, let's modify create-el to take a :styles key:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn add-style! ...)

(defn create-el [{:keys [tag id classes styles text attrs] :as args}]
  (-> (js/document.createElement tag)
      (set-attrs! attrs)
      (set-id! id)
      (set-classes! classes)
      (set-styles! styles)
      (set-text! text)))

;; (defn add-event-listener! ...)
;; ...

(comment

  ;; ...

  (let [el (-> (create-el {:tag "span"
                           :id "elapsed-time"
                           :classes ["cljcastr"]
                           :text (secs->ts 123)
                           :styles {:margin "0 5px 0 5px"
                                    :font-size "0.7rem"
                                    :color "grey"}})
               log)]
    (add-child! "#playback-controls" el))
  ;; => #object[HTMLDivElement [object HTMLDivElement]]

  )

Now, let's address the last problem.

Laying out the law

It is now time to employ the most awesome technology known to humankind to figure out our layout: ASCII art!

+-----------------------------------+
|            Podcast title          |
+-----------------------------------+
|            Episode title          |
+-----------------------------------+
|            Release date           |
+-----------------------------------+
|            Episode art            |
+-----------------------------------+
|     Elapsed time | Remaining time |
+-----------------------------------+
|            Progress bar           |
+-----------------------------------+
| Backward | Play | Pause | Forward |
+-----------------------------------+
|           Playback speed          |
+-----------------------------------+

We've been using the body element to hold our player, but we should probably deploy a div at this point so we can style things according to our liking. We can also group similar things together in divs, something like this:

+ episode-container ----------------------------+
|                                               |
| + episode-intro ----------------------------+ |
| |                Podcast title              | |
| +-------------------------------------------+ |
| |                Episode title              | |
| +-------------------------------------------+ |
| |                Release date               | |
| +-------------------------------------------+ |
|                                               |
+-----------------------------------------------+
|                  Episode art                  |
+-----------------------------------------------+
|                Audio (hidden)                 |
+-----------------------------------------------+
|                                               |
| + progress ---------------------------------+ |
| |       Elapsed time | Remaining time       | |
| +-------------------------------------------+ |
| |                Progress bar               | |
| +-------------------------------------------+ |
|                                               |
+-----------------------------------------------+
|                                               |
| + playback-controls ------------------------+ |
| | Backward | Play | Pause | Forward | Speed | |
| +-------------------------------------------+ |
|                                               |
+-----------------------------------------------+

Let's start by creating the new nested containers (we already have one for playback controls) and populating them with some hard-coded data:

(comment

  ;; ...

  (def episode-container (create-el {:tag "div"
                                     :id "episode-container"
                                     :classes ["cljcastr"]
                                     :styles {:width "100%"
                                              :display "flex"
                                              :flex-direction "column"
                                              :align-items "center"}}))
  ;; => #'cljcastr.player/episode-container

  (def episode-info
    (-> (create-el {:tag "div"
                    :id "episode-info"
                    :classes ["cljcastr"]
                    :styles {:max-width "420px"
                             :text-align "center"}})
        (set-children! [(create-el {:tag "h3"
                                    :id "podcast-title"
                                    :classes ["cljcastr"]
                                    :text "defn"})
                        (create-el {:tag "h2"
                                    :id "episode-title"
                                    :classes ["cljcastr"]
                                    :text "876b4c306172 Cora Sutton"})
                        (create-el {:tag "span"
                                    :id "episode-date"
                                    :classes ["cljcastr"]
                                    :styles {:color "grey"}
                                    :text "July 9, 2025"})])
        log))
  ;; => #'cljcastr.player/episode-info

  (def episode-art
    (-> (create-el {:tag "div"
                    :id "episode-art-container"
                    :classes ["cljcastr"]})
        (add-child! (create-el {:tag "img"
                                :id "episode-art"
                                :classes ["cljcastr"]
                                :styles {:width "400px"
                                         :border-radius "5%"
                                         :padding "10px"}
                                :attrs {:src "https://media.zencastr.com/image-files/5d9048546bacd9001de88f1c/a5b922ac-7294-4d58-9a33-4308f5d4f50b.png"}}))
        log))
  ;; => #'cljcastr.player/episode-art

  (def progress (create-el {:tag "div"
                            :id "progress"
                            :classes ["cljcastr"]
                            :styles {:width "390px"
                                     :margin "1.5em auto 0 auto"}}))
  ;; => #'cljcastr.player/progress

  (def playback-controls-container (-> (create-el {:tag "div"
                                                   :id "playback-controls"
                                                   :classes ["cljcastr"]})
                                       (set-children! playback-buttons)
                                       log))
  ;; => #'cljcastr.player/playback-controls-container

  (def playback-speed (create-el {:tag "div"
                                  :id "playback-speed"
                                  :classes ["cljcastr"]}))
  ;; => #'cljcastr.player/playback-speed

  (-> episode-container
      (set-children! [episode-info
                      episode-art
                      (-> audio
                          (set-styles! {:display "none"}))
                      progress
                      playback-controls-container
                      playback-speed])
      log)
  ;; => #object[HTMLDivElement [object HTMLDivElement]]

  (set-children! "body" [episode-container])
  ;; => #object[HTMLBodyElement [object HTMLBodyElement]]

  )

Player with defn episode

This is looking really good (relatively speaking), but there's one major component missing.

Slipping and sliding

We have no idea where in the episode we are! Let's see about getting that progress bar in place.

Luckily, HTML has got us covered! There just so happens to be a progress element designed exactly for what we want to do!

(comment

  ;; ...

  (def progress-bar
    (create-el {:tag "progress"
                :id "progress-bar"
                :classes ["cljcastr"]
                :attrs {:min 0
                        :max (.-duration audio)
                        :value (.-currentTime audio)}
                :styles {:appearance "none"
                         :height "8px"
                         :width "100%"
                         :border "0"
                         :border-radius "4px"
                         :margin "0"
                         :overflow "hidden"
                         :background-color "lightgray"
                         :color "#f7931e"}}))
  ;; => #'cljcastr.player/progress-bar

  )

Now that we have the progress bar, let's add it to our #progress div, along with the current and elapsed time spans we created before:

(comment

  ;; ...

  (-> progress
      (set-children! [(-> elapsed-time
                          (add-styles! {:float "left"}))
                      (-> remaining-time
                          (add-styles! {:float "right"}))
                      progress-bar])
      log)
  ;; => #object[HTMLDivElement [object HTMLDivElement]]

  )

Progress bar added

Hurrah! I mean, it's a bit ugly, but at least it's there! πŸ˜…

Let's click the play button, then skip forward a few times. Now, we can try setting the value of the progress bar to the current time of the audio element:

(comment

  ;; ...

  (set! (.-value progress-bar) (.-currentTime audio))
  ;; => 370.277385

  )

We should see the progress bar move along a bit.

This is great and all, but it would be lovely to have a way to actually move forward and backward in the episode by clicking or dragging on the progress bar. You know, the way every audio player ever works?

Sadly, the progress bar itself isn't really designed for this. We could certainly hack it up with some "click" event listeners and a lot of arithmetic, but surely there must be a better way, right?

And indeed there is! HTML has an input element of type range that is designed for exactly this case! Let's try it out:

(comment

  ;; ...

  (def progress-slider
    (create-el {:tag "input"
                :id "progress-slider"
                :classes ["cljcastr"]
                :attrs {:type "range"
                        :min 0
                        :max (.-duration audio)
                        :value (.-currentTime audio)
                        :step "any"
                        :aria-label "Seek"
                        :aria-valuetext (str (secs->ts (.-currentTime audio))
                                             " of "
                                             (secs->ts (.-duration audio)))
                        :aria-valuemax (.-duration audio)}
                :styles {:appearance "none"
                         :cursor "pointer"
                         :height "28px"
                         :width "100%"
                         :border "0"
                         :margin "0"
                         :touch-action "manipulation"}}))
  ;; => #'cljcastr.player/progress-slider

  (-> progress
      (set-children! [(-> elapsed-time
                          (add-styles! {:float "left"}))
                      (-> remaining-time
                          (add-styles! {:float "right"}))
                      progress-slider
                      progress-bar])
      log)
  ;; => #object[HTMLDivElement [object HTMLDivElement]]

  )

OK, a blue dot has appeared. Let's skip forward in the episode a bit more, then update the value of the slider to the current playback position. Oh yeah, might as well update the value of the progress bar as well, whilst we're at it:

(comment

  ;; ...

  (doseq [el [progress-slider progress-bar]]
    (set! (.-value el) (.-currentTime audio)))
  ;; => nil

  )

Now, how about setting the playback position in the episode when we click or drag the slider?

(comment

  ;; ...

  (add-event-listener! progress-slider "input"
                       #(->> % .-target .-value (set! (.-currentTime audio))))
  ;; => #object[HTMLInputElement [object HTMLInputElement]]

  )

We now have a pretty good representation of playback position:

  • A span showing the elapsed time
  • A span showing the remaining time
  • A slider letting us control the playback position
  • A progress bar giving us a visual indication of the playback position

Let's see if we can keep all of these in sync. First, some code to update them all in one go:

(comment

  ;; ...

  (let [secs (.-currentTime audio)
        duration-secs (.-duration audio)]
    (set-text! elapsed-time (secs->ts secs))
    (set-text! remaining-time (str "-" (secs->ts (- duration-secs secs))))
    (.setAttribute progress-slider "aria-valuetext"
                   (str (secs->ts secs) " of " (secs->ts duration-secs)))
    (doseq [el [progress-slider progress-bar]]
      (set! (.-value el) (.-currentTime audio))))
  ;; => nil

  )

Looks like that works, so let's extract it into a function. And whilst we're at it, maybe we can extract functions for the attribute and value setting so we don't have to expose the raw DOM interactions. And for the sake of completeness, we can add getters as well:

(ns cljcastr.player
  (:require [clojure.string :as str]))

;; ...
;; (defn set-text! ...)

(defn get-value
  "Returns the value attribute of the specified element."
  [el]
  (let [el (get-el el)]
    (.-value el)))

(defn set-value!
  "Sets the value attribute of the specified element."
  [el v]
  (let [el (get-el el)]
    (set! (.-value el) v)))

;; (defn set-classes! ...)
;; ...
;; (defn skip-backward! ...)

(defn update-playback-position-indicators!
  "Given a current playback time and duration (both in seconds) and a map of
   elements, updates the elements to reflect the current playback position. The
   element map should contain the following keys:
   `:elapsed-time` - text element (for example: label, span, etc.)
   `:remaining-time` - text element (for example: label, span, etc.)
   `:progress-slider` - input element of type range
   `:progress-bar` - progress element"
  [current-secs duration-secs
   {:keys [elapsed-time remaining-time progress-slider progress-bar]}]
  (set-text! elapsed-time (secs->ts current-secs))
  (set-text! remaining-time (str "-" (secs->ts (- duration-secs current-secs))))
  (set-attr! progress-slider :aria-valuetext
             (str (secs->ts current-secs) " of " (secs->ts duration-secs)))
  (doseq [el [progress-slider progress-bar]]
    (set-value! el current-secs)))

;; ...

(comment

  ;; ...

  (update-playback-position-indicators! (.-currentTime audio) (.-duration audio)
                                        {:elapsed-time elapsed-time
                                         :remaining-time remaining-time
                                         :progress-slider progress-slider
                                         :progress-bar progress-bar})
  ;; => nil

  )

There's one final touch we should apply here before we move on. It's getting a bit silly to have to manually update these elements, right? How about we update them automatically as the episode plays? For this, we can use the timeupdatechange event of our audio element:

(comment

  ;; ...

  (add-event-listener! audio "timeupdate"
                       #(update-playback-position-indicators!
                         (.-currentTime audio) (.-duration audio)
                         {:elapsed-time elapsed-time
                          :remaining-time remaining-time
                          :progress-slider progress-slider
                          :progress-bar progress-bar}))
  ;; => #object[HTMLAudioElement [object HTMLAudioElement]]

  )

Now things are running smoothly, but there's another thing that's bothering us. The progress slider that we use to control the playback position is above the progress bar, which just looks weird, and also goes against the expectations of our hordes of users that there should be a handle on the progress bar itself that they can drag around. You know, like this:

Overcast web player

Getting into position

What we'd really like is to set our slider down right on top of the progress bar. This will give us the seeking we seek (sorry) as well as a visual indication of the current playback position. In order to do this, we're going to have to learn a bit about CSS positioning.

Basically, we'll need to create a new container to hold the progress bar and the slider, and set its position style to "relative". Then, we can add our progress bar and slider as children of it, setting their position to "absolute" (relative to their parent container). Yes, I know, this is enough to make our heads explode, but I guess it makes sense once you achieve enlightenment or something?

We also need to set the z-indexes of the two elements. We set the progress bar to 0 to put it at the bottom of the stack, and the slider to 1 so it's on top. That means we need to make the background colour of the slider transparent so the progress bar can shine through in all its glory.

Finally, we position both elements 0 pixels from the left of the enclosing container, then the slider 0 pixels from the top and the progress bar 10 pixels from the top. Why 10 pixels? Well, because:

  • The slider is 28 pixels high.
  • The progress bar is 8 pixels high.
  • We want to vertically centre the progress bar underneath the slider.
  • 20 - 8 is 10.

With that advanced mathematics out of the way, let's make it happen!

(comment

  ;; ...

  (def progress-container
    (create-el {:tag "div"
                :id "progress-container"
                :classes ["cljcastr"]
                :styles {:position "relative"
                         :height "28px"
                         :clear "both"}}))
  ;; => #'cljcastr.player/progress-container

  (-> progress-container
      (set-children! [(-> progress-bar
                          (add-styles! {:position "absolute"
                                        :top "10px"
                                        :left "0px"
                                        :z-index 0}))
                      (-> progress-slider
                          (add-styles! {:position "absolute"
                                        :top "0px"
                                        :left "0px"
                                        :z-index 1
                                        :background-color "transparent"}))])
      log)
  ;; => #object[HTMLDivElement [object HTMLDivElement]]

  (-> progress
      (add-styles! {:position "relative"})
      (set-children! [(-> elapsed-time
                          (add-styles! {:float "left"}))
                      (-> remaining-time
                          (add-styles! {:float "right"}))
                      progress-container])
      log)
  ;; => #object[HTMLDivElement [object HTMLDivElement]]

  )

Player with a nice progress bar and slider

This is looking pretty good! There are a few more things we might want to do, but just as we're about to start doing some of those things, a bone-chilling thought occurs to us: what if we reload the page? We've been building our player up in the REPL one s-expression at a time, but our HTML file still has a body that looks like this:

<body>
</body>

Should a feline friend prance across the keyboard, stepping on the Ctrl and r keys simultaneously (or Apple-r, if you're one of those too-cool-for-school types), all will be lost!

Before giving in to despair, we realise that we have the awesome power of ClojureScript at our fingertips, and thus can make a permanent record of what we've done so far. And that, my dear readers, we shall endeavour to do in the new post in this series, which shall be called Scittlecastr: All You Need is Persistence.

You can find all the files for the player we built in this post here:

The preview image for this post is based on the Arab woman listening to music with earphones and dancing outdoors photo by Javier Sanchez Mingorance from his Woman In Overall Dress photoshoot. The photo is used under The Noun Project's Royalty-Free Commercial License, and was remixed by hand in the GIMP, which does not allow genAI contributions.