/
dom_server.clj
499 lines (436 loc) · 18.3 KB
/
dom_server.clj
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
(ns com.fulcrologic.fulcro.dom-server
"Support for rendering DOM from CLJ. Must be separate to enable same-named macros in CLJS for performance.
Usage: Create your UI in CLJC files, and require with conditional reader tags:
(ns app.ui
(:require
#?(:clj [com.fulcrologic.fulcro.dom-server :as dom] :cljs [com.fulcrologic.fulcro.dom :as dom])))"
(:refer-clojure :exclude [filter map mask meta select set symbol time use])
(:require
[clojure.core.reducers :as r]
[clojure.spec.alpha :as s]
[clojure.string :as str]
[com.fulcrologic.fulcro.algorithms.do-not-use :as util]
[com.fulcrologic.fulcro.dom-common :as cdom]
[com.fulcrologic.fulcro.raw.components :as rc :refer [component-instance?]]
[taoensso.encore :as encore]
[taoensso.timbre :as log]))
(definterface IReactDOMElement
(^StringBuilder renderToString [react-id ^StringBuilder sb]))
(declare render-element!)
(defrecord Element [tag attrs react-key children]
IReactDOMElement
(renderToString [this react-id sb]
(render-element! this react-id sb)))
(defn element?
"Returns true if the given arg is a server-side react element."
[x]
(instance? IReactDOMElement x))
(s/def ::dom-element-args
(s/cat
:css (s/? keyword?)
:attrs (s/? (s/or
:nil nil?
:map #(and (map? %)
(not (component-instance? %))
(not (element? %)))))
:children (s/* (s/or
:nil nil?
:string string?
:number number?
:collection #(or (vector? %) (seq? %))
:component component-instance?
:element element?))))
(declare a abbr address altGlyph altGlyphDef altGlyphItem animate animateColor animateMotion animateTransform area
article aside audio b base bdi bdo big blockquote body br button canvas caption circle cite clipPath code
col colgroup color-profile cursor data datalist dd defs del desc details dfn dialog discard div dl dt
ellipse em embed feBlend feColorMatrix feComponentTransfer feComposite feConvolveMatrix feDiffuseLighting
feDisplacementMap feDistantLight feDropShadow feFlood feFuncA feFuncB feFuncG feFuncR feGaussianBlur
feImage feMerge feMergeNode feMorphology feOffset fePointLight feSpecularLighting feSpotLight feTile feTurbulence
fieldset figcaption figure filter font font-face font-face-format font-face-name font-face-src font-face-uri
footer foreignObject form g glyph glyphRef h1 h2 h3 h4 h5 h6 hatch hatchpath head header hkern hr html
i iframe image img input ins kbd keygen label legend li line linearGradient link main map mark marker mask
menu menuitem mesh meshgradient meshpatch meshrow meta metadata meter missing-glyph
mpath nav noscript object ol optgroup option output p param path pattern picture polygon polyline pre progress q radialGradient
rect rp rt ruby s samp script section select set small solidcolor source span stop strong style sub summary
sup svg switch symbol table tbody td text textPath textarea tfoot th thead time title tr track tref tspan
u ul unknown use var video view vkern wbr)
;; https://github.com/facebook/react/blob/57ae3b/src/renderers/dom/shared/SVGDOMPropertyConfig.js
;; https://github.com/facebook/react/blob/57ae3b/src/renderers/dom/shared/HTMLDOMPropertyConfig.js
(def no-suffix
#{"animationIterationCount" "boxFlex" "boxFlexGroup" "boxOrdinalGroup"
"columnCount" "fillOpacity" "flex" "flexGrow" "flexPositive" "flexShrink"
"flexNegative" "flexOrder" "fontWeight" "lineClamp" "lineHeight" "opacity"
"order" "orphans" "stopOpacity" "strokeDashoffset" "strokeOpacity"
"strokeWidth" "tabSize" "widows" "zIndex" "zoom"})
(def lower-case-attrs
#{"accessKey" "allowFullScreen" "allowTransparency" "as" "autoComplete"
"autoFocus" "autoPlay" "contentEditable" "contextMenu" "crossOrigin"
"cellPadding" "cellSpacing" "charSet" "classID" "colSpan" "dateTime"
"encType" "formAction" "formEncType" "formMethod" "formNoValidate"
"formTarget" "frameBorder" "hrefLang" "inputMode" "keyParams"
"keyType" "marginHeight" "marginWidth" "maxLength" "mediaGroup"
"minLength" "noValidate" "playsInline" "radioGroup" "readOnly" "rowSpan"
"spellCheck" "srcDoc" "srcLang" "srcSet" "tabIndex" "useMap"
"autoCapitalize" "autoCorrect" "autoSave" "itemProp" "itemScope"
"itemType" "itemID" "itemRef"})
(def kebab-case-attrs
#{"acceptCharset" "httpEquiv" "accentHeight" "alignmentBaseline" "arabicForm"
"baselineShift" "capHeight" "clipPath" "clipRule" "colorInterpolation"
"colorInterpolationFilters" "colorProfile" "colorRendering" "dominantBaseline"
"enableBackground" "fillOpacity" "fillRule" "floodColor" "floodOpacity"
"fontFamily" "fontSize" "fontSizeAdjust" "fontStretch" "fontStyle"
"fontVariant" "fontWeight" "glyphName" "glyphOrientationHorizontal"
"glyphOrientationVertical" "horizAdvX" "horizOriginX" "imageRendering"
"letterSpacing" "lightingColor" "markerEnd" "markerMid" "markerStart"
"overlinePosition" "overlineThickness" "paintOrder" "panose1" "pointerEvents"
"renderingIntent" "shapeRendering" "stopColor" "stopOpacity" "strikethroughPosition"
"strikethroughThickness" "strokeDasharray" "strokeDashoffset" "strokeLinecap"
"strokeLinejoin" "strokeMiterlimit" "strokeOpacity" "strokeWidth" "textAnchor"
"textDecoration" "textRendering" "underlinePosition" "underlineThickness"
"unicodeBidi" "unicodeRange" "unitsPerEm" "vAlphabetic" "vHanging" "vIdeographic"
"vMathematical" "vectorEffect" "vertAdvY" "vertOriginX" "vertOriginY" "wordSpacing"
"writingMode" "xHeight"})
(def colon-between-attrs
#{"xlinkActuate" "xlinkArcrole" "xlinkHref" "xlinkRole" "xlinkShow" "xlinkTitle"
"xlinkType" "xmlBase" "xmlnsXlink" "xmlLang" "xmlSpace"})
(declare render-element!)
(defn append!
([^StringBuilder sb s0] (.append sb s0))
([^StringBuilder sb s0 s1]
(.append sb s0)
(.append sb s1))
([^StringBuilder sb s0 s1 s2]
(.append sb s0)
(.append sb s1)
(.append sb s2))
([^StringBuilder sb s0 s1 s2 s3]
(.append sb s0)
(.append sb s1)
(.append sb s2)
(.append sb s3))
([^StringBuilder sb s0 s1 s2 s3 s4]
(.append sb s0)
(.append sb s1)
(.append sb s2)
(.append sb s3)
(.append sb s4))
([^StringBuilder sb s0 s1 s2 s3 s4 & rest]
(.append sb s0)
(.append sb s1)
(.append sb s2)
(.append sb s3)
(.append sb s4)
(doseq [s rest]
(.append sb s))))
(def ^:dynamic *css-mode* false)
(defn escape-html ^String [^String s]
(if *css-mode*
s
(let [len (count s)]
(loop [^StringBuilder sb nil
i (int 0)]
(if (< i len)
(let [char (.charAt s i)
repl (case char
\& "&"
\< "<"
\> ">"
\" """
\' "'"
nil)]
(if (nil? repl)
(if (nil? sb)
(recur nil (inc i))
(recur (doto sb
(.append char))
(inc i)))
(if (nil? sb)
(recur (doto (StringBuilder.)
(.append s 0 i)
(.append repl))
(inc i))
(recur (doto sb
(.append repl))
(inc i)))))
(if (nil? sb) s (str sb)))))))
(defrecord Text [s]
IReactDOMElement
(renderToString [this react-id sb]
(append! sb (escape-html s))))
(defrecord ReactText [text]
IReactDOMElement
(renderToString [this react-id sb]
(append! sb "<!-- react-text: " @react-id " -->" (escape-html text) "<!-- /react-text -->")
(vswap! react-id inc)
sb))
(defrecord ReactEmpty []
IReactDOMElement
(renderToString [this react-id sb]
(append! sb "<!-- react-empty: " @react-id " -->")
(vswap! react-id inc)
sb))
(defrecord ReactFragment [elements]
IReactDOMElement
(renderToString [this react-id sb]
(doseq [e (:elements this)]
(.renderToString e react-id sb))
sb))
(defn text-node
"HTML text node"
[s]
(map->Text {:s s}))
(defn react-text-node
"HTML text node"
[s]
(map->ReactText {:text s}))
(defn- react-empty-node []
(map->ReactEmpty {}))
(defn react-fragment-node [elements]
(map->ReactFragment {:elements elements}))
(defn- render-component [c]
(if (or (nil? c) (element? c))
c
(encore/when-let [render (rc/component-options c :render)
output (render c)]
(if (vector? output)
(mapv render-component output)
(recur output)))))
(defn element
"Creates a dom node."
[{:keys [tag attrs react-key children] :as elem}]
(assert (name tag))
(assert (or (nil? attrs) (map? attrs)) (format "elem %s attrs invalid" elem))
(let [children (flatten children)
child-node-count (count children)
reduce-fn (if (> child-node-count 1)
r/reduce
reduce)
children (reduce-fn
(fn [res c]
(let [c' (cond
(element? c) c
(component-instance? c) (let [rendered (if-let [element (render-component c)]
element
(react-empty-node))
add-react-key (fn [c]
(assoc c :react-key (some-> (:props c) :fulcro$reactKey)))]
(if (vector? rendered)
(react-fragment-node (mapv add-react-key rendered))
(add-react-key rendered)))
(or (string? c) (number? c))
(let [c (cond-> c (number? c) str)]
(if (> child-node-count 1)
(react-text-node c)
(text-node c)))
(nil? c) nil
:else
(throw (IllegalArgumentException. (str "Invalid child element: ") c)))]
(cond-> res
(some? c') (conj c'))))
[] children)]
(map->Element {:tag (name tag)
:attrs attrs
:react-key react-key
:children children})))
(defn camel->other-case [^String sep]
(fn ^String [^String s]
(-> s
(str/replace #"([A-Z0-9])" (str sep "$1"))
str/lower-case)))
(def camel->kebab-case
(camel->other-case "-"))
(def camel->colon-between
(camel->other-case ":"))
(defn coerce-attr-key ^String [^String k]
(cond
(contains? lower-case-attrs k) (str/lower-case k)
(contains? kebab-case-attrs k) (camel->kebab-case k)
;; special cases
(= k "className") "class"
(= k "htmlFor") "for"
(contains? colon-between-attrs k) (camel->colon-between k)
:else k))
(defn render-xml-attribute! [sb name value]
(let [name (coerce-attr-key (clojure.core/name name))]
(append! sb " " name "=\""
(cond-> value
(string? value) escape-html) "\"")))
(defn normalize-styles! [sb styles]
(letfn [(coerce-value [k v]
(cond-> v
(string? v)
escape-html
(and (number? v)
(not (contains? no-suffix k))
(pos? v))
(str "px")))]
(run! (fn [[k v]]
(let [k (name k)]
(append! sb (camel->kebab-case k) ":" (coerce-value k v) ";")))
styles)))
(defn render-styles! [sb styles]
(when-not (empty? styles)
(append! sb " style=\"")
(normalize-styles! sb styles)
(append! sb "\"")))
(defn render-attribute! [sb [key value]]
(cond
(or (fn? value)
(not value))
nil
(identical? key :style)
(render-styles! sb value)
(or (true? value) (string? value) (number? value))
(if (true? value)
(append! sb " " (coerce-attr-key (name key)))
(render-xml-attribute! sb key value))
:else nil))
;; some props assigned first in input and option. see:
;; https://github.com/facebook/react/blob/680685/src/renderers/dom/client/wrappers/ReactDOMOption.js#L108
;; https://github.com/facebook/react/blob/680685/src/renderers/dom/client/wrappers/ReactDOMInput.js#L63
(defn render-attr-map! [sb tag attrs]
(letfn [(sorter [order]
(fn [[k _]]
(get order k (->> (vals order)
(apply max)
inc))))]
(let [attrs (cond->> attrs
(= tag "input") (sort-by (sorter {:type 0 :step 1
:min 2 :max 3}))
(= tag "option") (sort-by (sorter {:selected 0})))]
(run! (partial render-attribute! sb) attrs))))
(def ^{:doc "A list of elements that must be rendered without a closing tag."
:private true}
void-tags
#{"area" "base" "br" "col" "command" "embed" "hr" "img" "input" "keygen" "link"
"meta" "param" "source" "track" "wbr"})
(defn render-unescaped-html! [sb m]
(if-not (contains? m :__html)
(throw (IllegalArgumentException. "`props.dangerouslySetInnerHTML` must be in the form `{:__html ...}`")))
(when-let [html (:__html m)]
(append! sb html)))
(defn container-tag?
"Returns true if the tag has content or is not a void tag. In non-HTML modes,
all contentless tags are assumed to be void tags."
[tag content]
(or content (and (not (void-tags tag)))))
(defn render-element!
"Render a tag vector as a HTML element string."
[{:keys [tag attrs children]} react-id ^StringBuilder sb]
(binding [*css-mode* (= "style" tag)]
(append! sb "<" tag)
(render-attr-map! sb tag attrs)
(let [react-id-val @react-id]
(when (= react-id-val 1)
(append! sb " data-reactroot=\"\""))
(append! sb " data-reactid=\"" react-id-val "\"")
(vswap! react-id inc)
sb)
(if (container-tag? tag (seq children))
(do
(append! sb ">")
(if-let [html-map (:dangerouslySetInnerHTML attrs)]
(render-unescaped-html! sb html-map)
(run! #(.renderToString % react-id sb) children))
(append! sb "</" tag ">"))
(append! sb "/>"))))
(def key-escape-lookup
{"=" "=0"
":" "=2"})
(defn- is-element? [e]
(or
(rc/component-instance? e)
(instance? com.fulcrologic.fulcro.dom_server.IReactDOMElement e)))
(defn- render-to-str* ^StringBuilder [x]
{:pre [(or
(vector? x)
(is-element? x))]}
(if (vector? x)
(StringBuilder. (str/join " " (map render-to-str* x)))
(let [element ^com.fulcrologic.fulcro.dom_server.IReactDOMElement (if-let [element (cond-> x
(component-instance? x) render-component)]
element
(react-empty-node))
sb (StringBuilder.)]
(if (vector? element)
(doseq [e element]
(.renderToString e (volatile! 1) sb))
(.renderToString element (volatile! 1) sb))
sb)))
;; ===================================================================
;; Checksums (data-react-checksum)
(def MOD 65521)
;; Adapted from https://github.com/tonsky/rum
(defn adler32 [^StringBuilder sb]
(let [l (.length sb)
m (bit-and l -4)]
(loop [a (int 1)
b (int 0)
i 0
n (min (+ i 4096) m)]
(cond
(< i n)
(let [c0 (int (.charAt sb i))
c1 (int (.charAt sb (+ i 1)))
c2 (int (.charAt sb (+ i 2)))
c3 (int (.charAt sb (+ i 3)))
b (+ b a c0
a c0 c1
a c0 c1 c2
a c0 c1 c2 c3)
a (+ a c0 c1 c2 c3)]
(recur (rem a MOD) (rem b MOD) (+ i 4) n))
(< i m)
(recur a b i (min (+ i 4096) m))
(< i l)
(let [c0 (int (.charAt sb i))]
(recur (+ a c0) (+ b a c0) (+ i 1) n))
:else
(let [a (rem a MOD)
b (rem b MOD)]
(bit-or (int a) (unchecked-int (bit-shift-left b 16))))))))
(defn assign-react-checksum [^StringBuilder sb]
(.insert sb (.indexOf sb ">") (str " data-react-checksum=\"" (adler32 sb) "\"")))
(defn render-to-str ^String [x]
(let [sb (render-to-str* x)]
(assign-react-checksum sb)
(.toString sb)))
(defn node
"Returns the dom node associated with a component's React ref.
This is a NO-OP function for completion, and is not supported for SSR"
([component])
([component name]))
(defn create-element
"Create a DOM element for which there exists no corresponding function.
Useful to create DOM elements not included in React.DOM. Equivalent
to calling `js/React.createElement`"
([tag]
(create-element tag nil))
([tag opts & children]
(element {:tag tag
:attrs (dissoc opts :ref :key)
:react-key (:key opts)
:children children})))
(defn gen-tag-fn [tag]
`(defn ~tag ~(cdom/gen-docstring tag false)
[& ~'args]
(try
(let [conformed-args# (util/conform! ::dom-element-args ~'args)
{attrs# :attrs
children# :children
css# :css} conformed-args#
children# (mapv second children#)
attrs-value# (or (second attrs#) {})]
(element {:tag '~tag
:attrs (-> (cdom/interpret-classes attrs-value#)
(dissoc :ref :key)
(cdom/add-kwprops-to-props css#))
:react-key (:key attrs-value#)
:children children#}))
(catch Exception e#
(log/error e# ~'args)))))
(defmacro gen-all-tags []
(when-not (boolean (:ns &env))
`(do
~@(clojure.core/map gen-tag-fn cdom/tags))))
(gen-all-tags)