Skip to content

Instantly share code, notes, and snippets.

@rsslldnphy
Created June 12, 2015 15:46
Show Gist options
  • Save rsslldnphy/190d23d9394fd16f4e5f to your computer and use it in GitHub Desktop.
Save rsslldnphy/190d23d9394fd16f4e5f to your computer and use it in GitHub Desktop.
responsive fixed-data-table
(defn pixel-size
[size]
(u/str->int (second (re-matches #"(.*)px$" size))))
(defn percent-size
[size]
(u/str->int (second (re-matches #"(.*)%$" size))))
(defn absolute-column-widths
[columns]
(apply + (keep (comp pixel-size :width) columns)))
(defn calculate-widths
[space-for-percentage-widths column]
(if-let [pixels (pixel-size (:width column))]
(assoc column
:width pixels)
(if-let [percent (percent-size (:width column))]
(assoc column
:width (int (* space-for-percentage-widths percent 0.01)))
(.log js/error "Widths must be pixels or percent"))))
(defn column
[opts]
[Column opts]
(defn table
[opts & columns]
(let [table-id (gensym)
width (reagent/atom "100%")
height (reagent/atom "100%")
visible (reagent/atom false)
resize #(let [node (.getElementById js/document table-id)]
(reset! width (.-offsetWidth node))
(reset! height (.-offsetHeight node))
(reset! visible true))]
(reagent/create-class
{:component-did-mount #(do (e/listen js/window "resize" resize)
(resize)
)
:component-will-unmount #(e/unlisten js/window "resize" resize)
:render
(fn [_]
(let [total-width @width
total-height @height
absolute-column-widths (absolute-column-widths columns)
remaining-column-space (- total-width absolute-column-widths)
width-calculated-cols (map (partial calculate-widths remaining-column-space) columns)
]
[:div {:id table-id
:style {:width "100%" :height "100%" }}
(when @visible
(apply Table
(clj->js (merge {:width total-width
:height total-height} opts))
(map column width-calculated-cols)))]))})))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment