/
units.cljc
327 lines (276 loc) · 7.45 KB
/
units.cljc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
(ns mranderson048.garden.v1v3v3.garden.units
"Functions and macros for working with CSS units."
(:refer-clojure :exclude [rem])
#?@(:clj
[(:require
[mranderson048.garden.v1v3v3.garden.types :as types]
[mranderson048.garden.v1v3v3.garden.util :as util])
(:import
[mranderson048.garden.v1v3v3.garden.types CSSUnit])])
#?@(:cljs
[(:require
[cljs.reader :refer [read-string]]
[mranderson048.garden.v1v3v3.garden.types :as types :refer [CSSUnit]]
[mranderson048.garden.v1v3v3.garden.util :as util])
(:require-macros
[mranderson048.garden.v1v3v3.garden.units :refer [defunit]])]))
;;;; ## Unit families
(def length-units
#{:in :cm :pc :mm :pt :px (keyword "%")})
(def angular-units
#{:deg :grad :rad :turn})
(def time-units
#{:s :ms})
(def frequency-units
#{:Hz :kHz})
(def resolution-units
#{:dpi :dpcm :dppx})
;;;; ## Unit predicates
(defn unit?
"True if x is of type CSSUnit."
[x]
(instance? CSSUnit x))
(defn length?
[x]
(and (unit? x)
(contains? length-units (:unit x))))
(defn angle?
[x]
(and (unit? x)
(contains? angular-units (:unit x))))
(defn time?
[x]
(and (unit? x)
(contains? time-units (:unit x))))
(defn frequency?
[x]
(and (unit? x)
(contains? frequency-units (:unit x))))
(defn resolution?
[x]
(and (unit? x)
(contains? resolution-units (:unit x))))
;;;; ## Unit conversion
(def ^{:private true
:doc "Map associating CSS unit types to their conversion values."}
conversions
{;; Absolute units
:cm {:cm 1
:mm 10
:pc 2.36220473
:pt 28.3464567
:px 37.795275591}
:in {:cm 2.54
:in 1
:mm 25.4
:pc 6
:pt 72
:px 96}
:mm {:mm 1
:pt 2.83464567
:px 3.7795275591}
:pc {:mm 4.23333333
:pc 1
:pt 12
:px 16}
:pt {:pt 1
:px 1.3333333333}
:px {:px 1}
(keyword "%") {(keyword "%") 1}
;; Relative untis
:em {:em 1}
:rem {:rem 1}
;; Angular units
:deg {:deg 1
:grad 1.111111111
:rad 0.0174532925
:turn 0.002777778}
:grad {:grad 1
:rad 63.661977237
:turn 0.0025}
:rad {:rad 1
:turn 0.159154943}
:turn {:turn 1}
;; Time units
:s {:ms 1000
:s 1}
:ms {:ms 1}
;; Frequency units
:Hz {:Hz 1
:kHz 0.001}
:kHz {:kHz 1}})
(defn- convertable?
"True if unit is a key of convertable-units, false otherwise."
[unit]
(contains? conversions unit))
(defn- convert
"Convert a Unit with :unit left to a Unit with :unit right if possible."
[{m :magnitude left :unit} right]
(if (every? convertable? [left right])
(let [v1 (get-in conversions [left right])
v2 (get-in conversions [right left])]
(cond
v1
(CSSUnit. right (* v1 m))
v2
(CSSUnit. right (/ m v2))
;; Both units are convertible but no conversion between them exists.
:else
(throw
(ex-info
(util/format "Can't convert %s to %s" (name left) (name right)) {}))))
;; Display the inconvertible unit.
(let [x (first (drop-while convertable? [left right]))]
(throw (ex-info (str "Inconvertible unit " (name x)) {})))))
;;;; ## Unit helpers
(def ^{:doc "Regular expression for matching a CSS unit. The magnitude
and unit are captured."
:private true}
unit-re
#"([+-]?\d+(?:\.?\d+)?)(p[xtc]|in|[cm]m|%|r?em|ex|ch|v(?:[wh]|m(?:in|ax))|deg|g?rad|turn|m?s|k?Hz|dp(?:i|cm|px))")
(defn read-unit
"Read a `CSSUnit` object from the string `s`."
[s]
(when-let [[_ magnitude unit] (re-matches unit-re s)]
(let [unit (keyword unit)
magnitude (if magnitude (read-string magnitude) 0)]
(CSSUnit. unit magnitude))))
(defn make-unit-predicate
"Creates a function for verifying the given unit type."
[unit]
(fn [x] (and (unit? x) (= (:unit x) unit))))
(defn make-unit-fn
"Creates a function for creating and converting `CSSUnit`s for the
given unit. If a number n is passed the function it will produce a
new `CSSUnit` record with a the magnitude set to n. If a `CSSUnit`
is passed the function will attempt to convert it."
[unit]
(fn [x]
(cond
(number? x)
(CSSUnit. unit x)
(unit? x)
(if (and (= (unit x) unit))
x
(convert x unit))
:else
(let [;; Does `.getName` even work in CLJS? -- @noprompt
ex-message (util/format "Unable to convert from %s to %s"
(.getName type)
(name unit))
;; TODO: This needs to be populated with more helpful
;; data.
ex-data {:given {:type type
:unit unit}}]
(throw
(ex-info ex-message ex-data))))))
(defn make-unit-adder
"Create a addition function for adding Units."
[unit]
(let [u (make-unit-fn unit)]
(fn u+
([] (u 0))
([x] (u x))
([x y]
(let [{m1 :magnitude} (u x)
{m2 :magnitude} (u y)]
(u (+ m1 m2))))
([x y & more]
(reduce u+ (u+ x y) more)))))
(defn make-unit-subtractor
"Create a subtraction function for subtracting Units."
[unit]
(let [u (make-unit-fn unit)]
(fn u-
([x] (u (- x)))
([x y]
(let [{m1 :magnitude} (u x)
{m2 :magnitude} (u y)]
(u (- m1 m2))))
([x y & more]
(reduce u- (u- x y) more)))))
(defn make-unit-multiplier
"Create a multiplication function for multiplying Units."
[unit]
(let [u (make-unit-fn unit)]
(fn u*
([] (u 1))
([x] (u x))
([x y]
(let [{m1 :magnitude} (u x)
{m2 :magnitude} (u y)]
(u (* m1 m2))))
([x y & more]
(reduce u* (u* x y) more)))))
(defn make-unit-divider
"Create a division function for dividing Units."
[unit]
(let [u (make-unit-fn unit)]
(fn ud
([x] (u (/ 1 x)))
([x y]
(let [{m1 :magnitude} (u x)
{m2 :magnitude} (u y)]
(u (/ m1 m2))))
([x y & more]
(reduce ud (ud x y) more)))))
#?(:clj
(defmacro defunit
"Create a suite of functions for unit creation, conversion,
validation, and arithmetic."
([name]
`(defunit ~name ~name))
([name unit]
(let [k (keyword unit)
append #(symbol (str name %))]
`(do
(def ~name (make-unit-fn ~k))
(def ~(append \?) (make-unit-predicate ~k))
(def ~(append \+) (make-unit-adder ~k))
(def ~(append \-) (make-unit-subtractor ~k))
(def ~(append \*) (make-unit-multiplier ~k))
(def ~(append "-div") (make-unit-divider ~k)))))))
(comment
;; This:
(defunit px)
;; Is equivalent to:
(def px (make-unit-fn :px))
(def px? (make-unit-predicate :px))
(def px+ (make-unit-adder :px))
(def px- (make-unit-subtractor :px))
(def px* (make-unit-multiplier :px))
(def px-div (make-unit-divider :px)))
;; # Predefined units
;; Absolute units
(defunit cm)
(defunit mm)
(defunit in)
(defunit px)
(defunit pt)
(defunit pc)
(defunit percent "%")
;; Font-relative units
(defunit em)
(defunit ex)
(defunit ch)
(defunit rem)
;; Viewport-percentage lengths
(defunit vw)
(defunit vh)
(defunit vmin)
(defunit vmax)
;; Angles
(defunit deg)
(defunit grad)
(defunit rad)
(defunit turn)
;; Times
(defunit s)
(defunit ms)
;; Frequencies
(defunit Hz)
(defunit kHz)
;; Resolutions
(defunit dpi)
(defunit dpcm)
(defunit dppx)