Fork me on GitHub
#clerk
<
2023-07-02
>
Aziz Aldawood11:07:37

what is the easiest way to color cells based on value in clerk/table?

Aziz Aldawood11:07:28

for some reason I have this fear of updating viewers

mkvlr17:07:08

you can also use clerk/html on the cell values

Aziz Aldawood17:07:13

ah good idea 👍 I will try it

mkvlr17:07:44

here’s an example:

;; # Table Viewer Composition

(ns table-viewer-composition
  {:nextjournal.clerk/visibility {:code :hide :result :hide}}
  (:require [nextjournal.clerk :as clerk]))

(defn sparkline [values]
  (clerk/vl {:data {:values (map-indexed (fn [i v] {:date i :price v}) values)}
             :mark {:type "line" :strokeWidth 1.2}
             :width 140
             :height 20
             :config {:background nil :border nil :view {:stroke "transparent"}}
             :encoding {:x {:field "date" :type "temporal" :axis nil :background nil}
                        :y {:field "price" :type "quantitative" :axis nil :background nil}}}))

(sparkline (shuffle (range 50)))

(defn format-million [value]
  (clerk/html
   [:div.text-right.tabular-nums
    [:span.text-slate-400 "$M "] [:span (format "%,12d" value)]]))

(defn format-percent [value]
  (clerk/html
   [:div.text-right.tabular-nums
    (if (neg? value)
      [:span.text-red-500 "–"]
      [:span.text-green-500 "+"])
    [:span (format "%.2f" (abs value))]
    [:span.text-slate-400 "%"]]))

;; Table cells can again use other viewers.

^{::clerk/viewer clerk/table ::clerk/width :full ::clerk/visibility {:code :show :result :show}}
(def prices-table
  {"" (repeatedly 5 #(sparkline (shuffle (range 50))))
   "Assets" (map format-million [64368 62510 50329 47355 40500])
   "Fund" ["Vanguard 500" "Fidelity Magellan" "Amer A Invest" "Amer A WA" "Pimco"]
   "4 wks" (map format-percent [-2.0 -2.1 -1.2 -1.5 -2.3])
   "2003" (map format-percent [12.2 11.3 9.4 9.4 2.4])
   "3 years" (map format-percent [-11.7 -12.9 -3.9 0.8 9.4])
   "5 years" (map format-percent [-0.8 -0.2 4.0 3.0 7.6])})

🙏 2