Saturday, January 29, 2022

Drawing Young diagrams with HTML5 Canvas

The previous Java Swing program to visualize members of Young's lattice $\mathbb{Y}$ can fairly easily be ported to ClojureScript to make an HTML based application.
; this is a clojure common method
(defn determine-coordinates
  "Get the coordinates of a young diagram."
  [coll]

  (let [sorted-seq (sort > (seq coll))]
    (apply
     concat
     (map-indexed
      (fn [x v]
        (map
         (fn [y]
           [x y])
         (range 0 v)))
      sorted-seq))))
      
; this is specific to clojurescript
(defn display-young-diagram
  "Display a young diagram onto an html canvas"
  [ctx data start end block-width block-height]
  
  (let [coords (determine-coordinates data)] 
    (set! (.-strokeStyle ctx) "black")
    (doseq [[x y] coords] 
      (.strokeRect 
        ctx 
        (+ start (* x block-width)) 
        (+ end (* y block-height)) 
        block-width 
        block-height))))

; clojurescript is the best way to develop web applications
(defn init []
  (let [ctx (.getContext (.getElementById js/document "canvas") "2d")]
    (display-young-diagram ctx data '(1 2 3 4) 50 30 30)))
The real hero of this port is Clojure Common, which allows us to share code between the backend and the frontend, so that we can more easily port JVM based applications to the web. The determine coordinates function as you can see can be shifted over to ClojureScript without a single change to our code base.

Its not a perfect solution, as there are obviously things you can do on the JVM (like make use of Java libraries such as apache commons and the standard library) that cannot readily be ported to the browser setting but it is better then nothing which is quite often is what we were left with doing web development in the old days.

So write as much code as possible in Clojure Commons so that porting JVM based applications to the web will be easier. Generally, these will be pure functions that express business logic, and since they don't need side effects they won't have to depend so much on the platform they are running on.

No comments:

Post a Comment