Skip to content

Instantly share code, notes, and snippets.

@houshuang
Created February 14, 2021 06:18
Show Gist options
  • Save houshuang/2f5458e5c0ce23aaf6aea795dc890f36 to your computer and use it in GitHub Desktop.
Save houshuang/2f5458e5c0ce23aaf6aea795dc890f36 to your computer and use it in GitHub Desktop.
generate table in Clojure, based on https://roamresearch.com/#/app/Zsolt-Blog/page/02-13-2021
(ns myTablev03
(:require
[reagent.core :as r]
clojure.pprint
[datascript.core :as d]
[roam.datascript.reactive :as dr]))
(defn rand-str [len]
(apply str (take len (repeatedly #(char (+ (rand 26) 65))))))
(def divUID (rand-str 12))
(defn getBlockUID [uid]
(let [b_id (-> js/document
(.getElementById uid)
(.-parentElement)
(.-parentElement)
(.-parentElement)
(.-id))]
(subs b_id (- (count b_id) 9))
)
)
;;need reagent.core/atom instead of clojure.core/atom for hiccup update to work when atom is swap!-ed
(def block_id (r/atom divUID))
(def query_res (r/atom ""))
(def table (r/atom []))
(defn query_table [uid]
(let [res_map (dr/q '[:find (pull ?b [{:block/children [:block/string :block/order {:block/children ...}]}])
:in $ ?uid
:where [?b :block/uid ?uid]]
uid
)]
(swap! query_res (fn [n] @res_map))
)
)
(defn sort-by-order [blocks]
(sort-by :block/order blocks))
(defn create-sorted-cols [col-header]
(cons (:block/string col-header) (map :block/string (sort-by-order (:block/children col-header)))))
(defn transpose [args]
(let [
max-count (apply max (map #(count %1) args))
items (map #(take max-count (concat %1 (repeat ""))) args)
]
(apply map vector items)))
(defn format-table [table]
(let [
sorted-col-headers (sort-by-order (:block/children (first (first table))))
sorted-cols (map create-sorted-cols sorted-col-headers)
rows (transpose sorted-cols)
]
rows))
(defn genTable []
[:div {:id divUID}
[:button {:on-click (fn [e] (swap! block_id (fn [n] (getBlockUID divUID)))
(query_table @block_id))} "Update"]
[:br]
(clojure.pprint/pprint (format-table @query_res))
(if (= @query_res "") "true" [:table {:style {:border "1px solid black"}}
(map (fn [row] [:tr
(map (fn [cell] [:td {:style {:padding "10px" :border "1px solid black"}} cell])
row)]) (format-table @query_res)
)]
)])
@houshuang
Copy link
Author

You can remote the pprint of course

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment