core.cljs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. (ns microtables-frontend.core
  2. (:require
  3. [reagent.core :as r]
  4. ["mathjs" :as mathjs]))
  5. ; to generate random values
  6. ;for(let i = 0, s = new Set(); i < 10; i++){ let r = Math.floor(Math.random() * 15)+1, c = a[Math.floor(Math.random() * a.length)], k = `${c}${r}`; if(s.has(k)){ i--; continue; } s.add(k); v.push(`{:row ${r} :col "${c}" :value "${Math.floor(Math.random() * 10000)}"}`); }
  7. (def sample-data [{:row 1 :col "A" :value "59" :view :display}
  8. {:row 5 :col "C" :value "269" :view :display}
  9. {:row 4 :col "B" :value "7893" :view :display}
  10. {:row 2 :col "F" :value "8650" :view :display}
  11. {:row 6 :col "D" :value "4065" :view :display}
  12. {:row 7 :col "F" :value "5316" :view :display}
  13. {:row 12 :col "A" :value "2405" :view :display}
  14. {:row 5 :col "B" :value "7863" :view :display}
  15. {:row 9 :col "E" :value "3144" :view :display}
  16. {:row 10 :col "D" :value "8272" :view :display}
  17. {:row 11 :col "D" :value "2495" :view :display}
  18. {:row 15 :col "E" :value "8968" :view :display}
  19. {:row 7 :col "B" :value "=C5 + D6" :view :display}
  20. {:row 8 :col "B" :value "=B7 * 2" :view :display}
  21. {:row 7 :col "C" :value "=D1" :view :display}
  22. {:row 12 :col "B" :value "=C12" :view :display}])
  23. (defonce data-atom (r/atom sample-data))
  24. (defn highest [dir data] (apply max (map dir data)))
  25. ; COLUMN NAMES
  26. (defn increment-letter-code [s]
  27. (let [l (last s)]
  28. (cond
  29. (empty? s) [65]
  30. (= l 90) (conj (increment-letter-code (subvec s 0 (dec (count s)))) 65)
  31. :else (conj (subvec s 0 (dec (count s))) (inc l)))))
  32. (defn next-letter [lc]
  33. (apply str (map char (increment-letter-code (mapv #(.charCodeAt % 0) lc)))))
  34. (def col-letters (iterate next-letter "A"))
  35. ; CHANGE VALUE FUNCTIONS
  36. (defn update-value [c r existing-datum value]
  37. (if (nil? existing-datum)
  38. (swap! data-atom conj {:row r :col c :value value :dirty true})
  39. (swap! data-atom (partial map #(if (and (= r (:row %)) (= c (:col %))) (assoc (assoc % :dirty true) :value value) %)))))
  40. ;TODO: consider changing this for a single "view" atom which points to zero or one cells, which will determine whether to show the formula or evaluation
  41. (defn toggle-display [data c r view-mode]
  42. (println (str " toggling " c r " to " view-mode))
  43. (map #(if (and (= r (:row %)) (= c (:col %))) (assoc % :view view-mode) %) data))
  44. ; CALCULATION / FORMULA EVALUATION FUNCTIONS
  45. (def parse-variables (memoize (fn [expression]
  46. (js->clj (.getVariables mathjs expression)))))
  47. (def evaluate-expression (memoize (fn [expression variables]
  48. (let [answer (.evaluate mathjs expression (clj->js variables))]
  49. (if (nil? (.-error answer))
  50. answer
  51. :calc-error)))))
  52. (def str->rc (memoize (fn [s]
  53. (let [c (re-find #"^[A-Z]+" s)
  54. r (.parseInt js/window (re-find #"[0-9]+$" s))]
  55. {:row r :col c}))))
  56. ;TODO: deal with lowercase cell references
  57. (defn find-cell [data c r]
  58. (some #(if (and (= (:col %) c) (= (:row %) r)) %) data))
  59. (defn find-ref [data cell-ref]
  60. (some (fn [{:keys [row col] :as datum}] (if (and (= row (:row cell-ref)) (= col (:col cell-ref))) datum)) data))
  61. (defn copy-display-values [data display-values]
  62. (let [original (map #(dissoc % :dirty) data)
  63. removed (map #(-> % (dissoc :found) (dissoc :inputs) (dissoc :dirty)) display-values)]
  64. (into original removed)))
  65. ;TODO: memoize dynamically? probably not worth memoizing directly, and could take up too much memory over time
  66. ; https://stackoverflow.com/a/13123571/8172807
  67. (defn find-cycle
  68. ([data datum] (find-cycle data datum #{}))
  69. ([data datum ances]
  70. (let [cur {:row (:row datum) :col (:col datum)}
  71. this-and-above (conj ances cur)
  72. refs (:refs datum)
  73. found (not (empty? (clojure.set/intersection this-and-above (set refs))))]
  74. (if found
  75. :cycle-error
  76. (some (fn [cell]
  77. (find-cycle data (find-ref data cell) this-and-above)) refs)))))
  78. (defn find-val [data c r]
  79. (let [l (find-cell data c r)
  80. v (get l :display (get l :value))
  81. formula? (and (string? v) (= (first v) "="))]
  82. (cond
  83. (nil? v) 0
  84. ;(contains? l :error) :ref-error
  85. formula? :not-yet
  86. :else v)))
  87. ;TODO: figure out how to re-evaluate only when the cell modified affects other cells
  88. (defn re-evaluate [data]
  89. (let [{has-formula true original-values false} (group-by #(= (first (:value %)) "=") data)
  90. found-cycles (map #(let [found (find-cycle data %)] (if found (assoc % :error found) %)) has-formula)
  91. {eligible true ineligible false} (group-by #(not (contains? % :error)) found-cycles)]
  92. (loop [values (into original-values ineligible) mapped-cell-keys eligible]
  93. (let [search-values (map (fn [datum] (assoc datum :found (map #(find-val (concat values mapped-cell-keys) (:col %) (:row %)) (:refs datum)))) mapped-cell-keys)
  94. {not-ready true ready nil} (group-by (fn [datum] (some #(= :not-yet %) (:found datum))) search-values)
  95. prepped-for-eval (map (fn [datum] (assoc datum :inputs (apply hash-map (interleave (:vars datum) (:found datum))))) ready)
  96. evaluated (map (fn [datum] (assoc datum :display (evaluate-expression (subs (:value datum) 1) (:inputs datum)))) prepped-for-eval)
  97. updated-values (copy-display-values values evaluated)]
  98. (println "EVALUATED" evaluated)
  99. (if (nil? not-ready)
  100. updated-values
  101. (recur updated-values not-ready))))))
  102. (defn add-parsed-variables [datum]
  103. (if (= (first (:value datum)) "=")
  104. (let [vars (parse-variables (subs (:value datum) 1))
  105. refs (map str->rc vars)]
  106. (-> datum (assoc :vars vars) (assoc :refs refs) (dissoc :error)))
  107. (-> datum (dissoc :vars) (dissoc :refs) (dissoc :display) (dissoc :error))))
  108. (defn add-parsed-variables-to-specific-datum
  109. "Parse variables from the value of a datum and add in :vars and :refs (for swap! data-atom).
  110. If the value does not contain a fomula, remove any :vars and :refs that may have been there."
  111. [c r data] (map #(if (and (= (:col %) c) (= (:row %) r))
  112. (add-parsed-variables %)
  113. %) data))
  114. (defn on-enter-cell [c r e]
  115. (println (str "entering cell " c r))
  116. (swap! data-atom #(toggle-display % c r :value)))
  117. (defn on-change [c r datum e]
  118. (update-value c r datum (.. e -target -value)))
  119. (defn on-leave-cell [c r e]
  120. (println (str "leaving cell " c r))
  121. (swap! data-atom #(as-> % data
  122. (toggle-display data c r :display)
  123. (add-parsed-variables-to-specific-datum c r data)
  124. (re-evaluate data))))
  125. (defn on-keyPress [c r e]
  126. (println "key press" c r (.. e -which) (.keys js/Object e))
  127. (if (= 13 (.. e -which)) (.focus (.getElementById js/document (str c (inc r)))))
  128. ;TODO TODO TODO TODO TODO TODO TODO TODO TODO
  129. )
  130. ;; -------------------------
  131. ;; Views
  132. (defn smart-border [c r]
  133. [:div {:class "smartborder"}
  134. [:div {:class "extendrange button"
  135. :title "extend range"
  136. :on-click #(println "extend range")}]
  137. [:div {:class "fillrange button"
  138. :title "fill range"
  139. :on-click #(println "fill range")}]
  140. [:div {:class "moverange button"
  141. :title "move range"
  142. :on-click #(println "move range")}]
  143. [:div {:class "emptyrange button"
  144. :title "empty range"
  145. :on-click #(println "empty range")}]
  146. [:div {:class "deleterange button"
  147. :title "delete range"
  148. :on-click #(println "delete range")}]
  149. [:div {:class "copyrange button"
  150. :title "copy range"
  151. :on-click #(println "copy range")}]
  152. ]
  153. )
  154. (defn cell [c r data]
  155. (let [datum (some #(if (and (= c (:col %)) (= r (:row %))) %) data)]
  156. ^{:key (str c r)} [:td
  157. [:input {:id (str c r)
  158. :value (if (= (get datum :view nil) :value)
  159. (get datum :value "")
  160. (get datum :error (get datum :display (get datum :value ""))))
  161. :on-change (partial on-change c r datum)
  162. :on-blur (partial on-leave-cell c r)
  163. :on-focus (partial on-enter-cell c r)
  164. :on-paste #(println "paste" %);TODO
  165. :on-drop #(println "drop" %);TODO
  166. :on-keyPress (partial on-keyPress c r)}]
  167. (smart-border c r)]))
  168. (defn row [r cols data]
  169. ^{:key (str "row-" r)} [:tr
  170. (cons
  171. ^{:key (str "row-head-" r)} [:th (str r)]
  172. (map #(cell % r data) cols))])
  173. (defn header-row [cols]
  174. ^{:key "header"} [:tr
  175. (cons
  176. ^{:key "corner"} [:th]
  177. (map (fn [c] ^{:key (str "col-head-" c)} [:th c]) cols))])
  178. (defn sheet [data]
  179. [:table [:tbody
  180. (let [maxrow (highest :row data)
  181. cols (take-while (partial not= (next-letter (highest :col data))) col-letters)]
  182. (cons
  183. (header-row cols)
  184. (map #(row % cols data) (range 1 (inc maxrow)))))]])
  185. (defn app []
  186. [:div
  187. ;[:h3 "Microtables"]
  188. [sheet @data-atom]])
  189. ;; -------------------------
  190. ;; Initialize app
  191. (swap! data-atom #(->> % (map add-parsed-variables) (re-evaluate))) ; evalutate any formulas the first time
  192. (defn mount-root []
  193. (r/render [app] (.getElementById js/document "app")))
  194. (defn init! []
  195. (mount-root))