-
Notifications
You must be signed in to change notification settings - Fork 1
/
dom.cljs
616 lines (577 loc) · 16.4 KB
/
dom.cljs
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
(ns ^{:doc "Convenience API for constructing virtual DOM.
This has ClojureScript wrappers for the various HTML elements.
These all expect attributes as a ClojureScript map.
Moreover, sub-element sequences need to be ClojureScript sequences of
objects constructed using `keyed-dom'.
Moreover, the `letdom' form constructing virtual DOM elements for
easy reference in an event handler."}
reacl2.dom
(:require-macros [reacl2.dom :refer [defdom]])
(:require [cljsjs.react]
[clojure.string :as string])
(:refer-clojure :exclude (meta map time)))
(defn camelize
"Camelcases a hyphenated string, for example:
> (camelize \"background-color\")
< \"backgroundColor\""
[s]
(string/replace s #"-(.)" (fn [[_ c]] (string/upper-case c))))
(defn camelize-style-name
"Camelcases a hyphenated CSS property name, for example:
> (camelize-style-name \"background-color\")
< \"backgroundColor\"
> (camelize-style-name \"-moz-transition\")
< \"MozTransition\"
> (camelize-style-name \"-ms-transition\")
< \"msTransition\"
As Andi Smith suggests
(http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix
is converted to lowercase `ms`."
[s]
(camelize (string/replace s #"^-ms" "ms-")))
(def reacl->react-attribute-names
#js {:accept "accept"
:accept-charset "acceptCharset"
:access-key "accessKey"
:action "action"
:allow-full-screen "allowFullScreen"
:allow-transparency "allowTransparency"
:alt "alt"
:async "async"
:auto-complete "autoComplete"
:auto-focus "autoFocus"
:auto-play "autoPlay"
:auto-save "autoSave"
:capture "capture"
:cell-padding "cellPadding"
:cell-spacing "cellSpacing"
:challenge "challenge"
:char-set "charSet"
:checked "checked"
:class-id "classID"
:class "className"
:color "color"
:col-span "colSpan"
:cols "cols"
:content "content"
:content-editable "contentEditable"
:context-menu "contextMenu"
:controls "controls"
:coords "coords"
:cross-origin "crossOrigin"
:data "data"
:date-time "dateTime"
:default "default"
:defer "defer"
:dir "dir"
:disabled "disabled"
:download "download"
:draggable "draggable"
:enc-type "encType"
:form "form"
:form-action "formAction"
:form-enc-type "formEncType"
:form-method "formMethod"
:form-no-validate "formNoValidate"
:form-target "formTarget"
:frame-border "frameBorder"
:headers "headers"
:height "height"
:hidden "hidden"
:high "high"
:href "href"
:href-lang "hrefLang"
:input-mode "inputMode"
:or "htmlFor"
:http-equiv "httpEquiv"
:icon "icon"
:id "id"
:key-params "keyParams"
:key-type "keyType"
:kind "kind"
:label "label"
:lang "lang"
:list "list"
:loop "loop"
:low "low"
:manifest "manifest"
:margin-height "marginHeight"
:margin-width "marginWidth"
:min-length "minLength"
:max "max"
:max-length "maxLength"
:media "media"
:media-group "mediaGroup"
:method "method"
:min "min"
:multiple "multiple"
:muted "muted"
:name "name"
:no-validate "noValidate"
:nonce "nonce"
:open "open"
:optimum "optimum"
:pattern "pattern"
:placeholder "placeholder"
:poster "poster"
:preload "preload"
:radioGroup "radioGroup"
:rel "rel"
:referrer-policy "referrerPolicy"
:readOnly "rel"
:required "required"
:results "results"
:reversed "reversed"
:role "role"
:rowSpan "rowSpan"
:rows "rows"
:sandbox "sandbox"
:scope "scope"
:scoped "scoped"
:scrolling "scrolling"
:seamless "seamless"
:security "security"
:selected "selected"
:shape "shape"
:size "size"
:sizes "sizes"
:span "span"
:spell-check "spellCheck"
:src "src"
:src-doc "srcDoc"
:src-set "srcSet"
:src-lang "srcLang"
:start "start"
:step "step"
:style "style"
:summary "summary"
:tab-index "tabIndex"
:target "target"
:title "title"
:type "type"
:use-map "useMap"
:value "value"
:width "width"
:wmode "wmode"
:wrap "wrap"
:auto-capitalize "autoCapitalize"
:auto-correct "autoCorrect"
:property "property"
:item-prop "itemProp"
:item-scope "itemScope"
:item-type "itemType"
:item-ref "itemRef"
:item-id "itemID"
:uselectable "uselectable"
:dangerously-set-inner-html "dangerouslySetInnerHTML"
;; SVG
:clip-path "clipPath"
:cx "cx"
:cy "cy"
:d "d"
:dx "dx"
:dy "dy"
:fill "fill"
:fill-opacity "fillOpacity"
:font-family "fontFamily"
:font-size "fontSize"
:fx "fx"
:fy "fy"
:gradient-transform "gradientTransform"
:gradient-units "gradientUnits"
:marker-end "markerEnd"
:marker-mid "markerMid"
:marker-start "markerStart"
:offset "offset"
:opacity "opacity"
:pattern-content-units "patternContentUnits"
:pattern-units "patternUnits"
:points "points"
:preserve-aspect-ratio "preserveAspectRatio"
:r "r"
:rx "rx"
:ry "ry"
:spread-method "spreadMethod"
:stop-color "stopColor"
:stop-opacity "stopOpacity"
:stroke "stroke"
:stroke-dasharray "strokeDasharray"
:stroke-linecap "strokeLinecap"
:stroke-opacity "strokeOpacity"
:stroke-width "strokeWidth"
:text-anchor "textAnchor"
:transform "transform"
:version "version"
:view-box "viewBox"
:x1 "x1"
:x2 "x2"
:x "x"
:y1 "y1"
:y2 "y2"
:y "y"
:xlink-actuate "xlinkActuate"
:xlink-arcrole "xlinkArcrole"
:xlink-href "xlinkHref"
:xlink-role "xlinkRole"
:xlink-show "xlinkShow"
:xlink-title "xlinkTitle"
:xlink-type "xlinkType"
:xml-base "xmlBase"
:xml-lang "xmlLang"
:xml-space "xmlSpace"
:xmlns "xmlns"
:xmlns-xlink "xmlnsXlink"
;; Event handlers
:oncopy "onCopy"
:oncopycapture "onCopyCapture"
:oncut "onCut"
:oncutcapture "onCutCapture"
:onpaste "onPaste"
:onpastecapture "onPasteCapture"
:onkeydown "onKeyDown"
:onkeydowncapture "onKeyDownCapture"
:onkeypress "onKeyPress"
:onkeypresscapture "onKeyPressCapture"
:onkeyup "onKeyUp"
:onkeyupcapture "onKeyUpCapture"
:onfocus "onFocus"
:onfocuscapture "onFocusCapture"
:onblur "onBlur"
:onblurcapture "onBlurCapture"
:onchange "onChange"
:onchangecapture "onChangeCapture"
:oninput "onInput"
:oninputcapture "onInputCapture"
:onsubmit "onSubmit"
:onsubmitcapture "onSubmitCapture"
:onclick "onClick"
:onclickcapture "onClickCapture"
:oncontextmenu "onContextMenu"
:oncontextmenucapture "onContextMenuCapture"
:ondoubleclick "onDoubleClick"
:ondoubleclickcapture "onDoubleClickCapture"
:ondrag "onDrag"
:ondragcapture "onDragCapture"
:ondragend "onDragEnd"
:ondragendcapture "onDragEndCapture"
:ondragenter "onDragEnter"
:ondragentercapture "onDragEnterCapture"
:ondragexit "onDragExit"
:ondragexitcapture "onDragExitCapture"
:ondragleave "onDragLeave"
:ondragleavecapture "onDragLeaveCapture"
:ondragover "onDragOver"
:ondragovercapture "onDragOverCapture"
:ondragstart "onDragStart"
:ondragstartcapture "onDragStartCapture"
:ondrop "onDrop"
:ondropcapture "onDropCapture"
:onmousedown "onMouseDown"
:onmousedowncapture "onMouseDownCapture"
:onmouseenter "onMouseEnter"
:onmouseleave "onMouseLeave"
:onmousemove "onMouseMove"
:onmousemovecapture "onMouseMoveCapture"
:onmouseout "onMouseOut"
:onmouseoutcapture "onMouseOutCapture"
:onmouseover "onMouseOver"
:onmouseovercapture "onMouseOverCapture"
:onmouseup "onMouseUp"
:onmouseupcapture "onMouseUpCapture"
:ontouchcancel "onTouchCancel"
:ontouchcancelcapture "onTouchCancelCapture"
:ontouchend "onTouchEnd"
:ontouchendcapture "onTouchEndCapture"
:ontouchmove "onTouchMove"
:ontouchmovecapture "onTouchMoveCapture"
:ontouchstart "onTouchStart"
:ontouchstartcapture "onTouchStartCapture"
:onscroll "onScroll"
:onscrollcapture "onScrollCapture"
:onwheel "onWheel"
:onwheelcapture "onWheelCapture"
:onabort "onAbort"
:oncanplay "onCanPlay"
:oncanplaythrough "onCanPlayThrough"
:ondurationchange "onDurationChange"
:onemptied "onEmptied"
:onencrypted "onEncrypted"
:onended "onEnded"
:onerror "onError"
:onloadeddata "onLoadedData"
:onloadedmetadata "onLoadedMetadata"
:onloadstart "onLoadStart"
:onpause "onPause"
:onplay "onPlay"
:onplaying "onPlaying"
:onprogress "onProgress"
:onratechange "onRateChange"
:onseeked "onSeeked"
:onseeking "onSeeking"
:onstalled "onStalled"
:onsuspend "onSuspend"
:ontimeupdate "onTimeUpdate"
:onvolumechange "onVolumeChange"
:onwaiting "onWaiting"
})
(def reacl->style-names
"Cache for style names encountered."
#js {})
(defn reacl->react-style-name
"Convert Reacl style name (keyword) to React name (string)."
[reacl-name]
(let [reacl-name (name reacl-name)]
(or (aget reacl->style-names reacl-name)
(let [react-name (camelize-style-name reacl-name)]
(aset reacl->style-names reacl-name react-name)
react-name))))
(defn- ^:no-doc aset-style->react
[obj style value]
(aset obj (reacl->react-style-name style) value)
obj)
(defn- ^:no-doc styles->react
"Convert a Clojure map with keyword keys to a JavaScript hashmap with string keys."
[mp]
(reduce-kv aset-style->react
#js {}
mp))
(defn- ^:no-doc aset-attribute [obj k0 v0]
(let [k (if-let [react-name (aget reacl->react-attribute-names (name k0))]
react-name
(name k0))
v (case k0
:style (styles->react v0)
v0)]
(aset obj k v)
obj))
(defn- ^:no-doc attributes
"Convert attributes represented as a Clojure map to a React map.
This knows about `:style`, and expects a Clojure map for the value."
[mp]
(reduce-kv aset-attribute
#js {}
mp))
(defprotocol HasDom
"General protocol for objects that contain or map to a virtual DOM object.
This is needed for [[letdom]], which wraps the DOM nodes on its
right-hand sides."
(-get-dom [thing]))
(defprotocol ^:no-doc IDomBinding
(binding-get-dom [this])
(binding-set-dom! [this v])
(binding-get-ref [this])
(binding-set-ref! [this v])
(binding-get-literally? [this]))
(deftype ^{:doc "Composite object
containing an atom containing DOM object and a name for referencing.
This is needed for [[letdom]]."
:no-doc true}
DomBinding
[^{:unsynchronized-mutable true} dom ^{:unsynchronized-mutable true} ref literally?]
IDomBinding
(binding-get-dom [_] dom)
(binding-set-dom! [this v] (set! dom v))
(binding-get-ref [_] ref)
(binding-set-ref! [this v] (set! ref v))
(binding-get-literally? [_] literally?)
HasDom
(-get-dom [_] dom))
(defn make-dom-binding
"Make an empty DOM binding from a ref name.
If `literally?` is not true, gensym the name."
[n literally?]
(DomBinding. nil
(if literally?
n
(gensym n))
literally?))
(defn dom-node
"Get the real DOM node associated with a binding.
Needs the component object."
[this binding]
(aget (.-refs this) (binding-get-ref binding)))
(defn keyed
"Associate a key with a virtual DOM node."
[key dom]
(if-let [ref (aget (.-props dom) "ref")]
(DomBinding. dom key false)
(DomBinding. (js/React.cloneElement dom #js {:key key})
key false)))
(defn- ^:no-doc set-dom-key
"Attach a key property to a DOM object."
[dom key]
(js/React.cloneElement dom #js {:key key}))
(defn- ^:no-doc normalize-arg
"Normalize the argument to a DOM-constructing function.
In particular, each [[HasDom]] object is mapped to its DOM object.
Also, sequences of [[KeyeDom]] sub-elements are mapped to their
respective DOM elements."
[arg]
(cond
(satisfies? HasDom arg) (-get-dom arg)
(seq? arg) (to-array (cljs.core/map normalize-arg arg))
;; deprecated
(array? arg) (to-array (cljs.core/map normalize-arg arg))
:else arg))
(defn- ^:no-doc attributes? [v]
(and (map? v)
(not (satisfies? HasDom v))))
(defn ^:no-doc dom-function
"Internal function for constructing wrappers for DOM-construction function."
[f]
(fn
([]
(f nil))
([maybe]
(if (attributes? maybe)
(f (attributes maybe))
(f nil (normalize-arg maybe))))
([maybe a1]
(if (attributes? maybe)
(f (attributes maybe) (normalize-arg a1))
(f nil (normalize-arg maybe) (normalize-arg a1))))
([maybe a1 a2]
(if (attributes? maybe)
(f (attributes maybe) (normalize-arg a1) (normalize-arg a2))
(f nil (normalize-arg maybe) (normalize-arg a1) (normalize-arg a2))))
([maybe a1 a2 a3]
(if (attributes? maybe)
(f (attributes maybe) (normalize-arg a1) (normalize-arg a2) (normalize-arg a3))
(f nil (normalize-arg maybe) (normalize-arg a1) (normalize-arg a2) (normalize-arg a3))))
([maybe a1 a2 a3 a4 & rest]
(let [args (cljs.core/map normalize-arg rest)]
(if (attributes? maybe)
(apply f (attributes maybe) (normalize-arg a1) (normalize-arg a2) (normalize-arg a3) (normalize-arg a4) args)
(apply f nil (normalize-arg maybe) (normalize-arg a1) (normalize-arg a2) (normalize-arg a3) (normalize-arg a4) args))))))
(defn ^:no-doc set-dom-binding!
"Internal function for use by `letdom'.
This sets the dom field of a DomBinding object, providing a :ref attribute."
[dn dom]
(if-let [ref (aget (.-props dom) "ref")]
;; it already has a ref, hopefully unique
(do
(assert (not (binding-get-literally? dn)))
(binding-set-ref! dn ref)
(binding-set-dom! dn dom))
(binding-set-dom! dn
(js/React.cloneElement dom #js {:ref (binding-get-ref dn)}))))
;; The following HTML elements are supported by react (http://facebook.github.io/react/docs/tags-and-attributes.html)
(defdom a)
(defdom abbr)
(defdom address)
(defdom area)
(defdom article)
(defdom aside)
(defdom audio)
(defdom b)
(defdom base)
(defdom bdi)
(defdom bdo)
(defdom big)
(defdom blockquote)
(defdom body)
(defdom br)
(defdom button)
(defdom canvas)
(defdom caption)
(defdom cite)
(defdom code)
(defdom col)
(defdom colgroup)
(defdom data)
(defdom datalist)
(defdom dd)
(defdom del)
(defdom details)
(defdom dfn)
(defdom div)
(defdom dl)
(defdom dt)
(defdom em)
(defdom embed)
(defdom fieldset)
(defdom figcaption)
(defdom figure)
(defdom footer)
(defdom form)
(defdom h1)
(defdom h2)
(defdom h3)
(defdom h4)
(defdom h5)
(defdom h6)
(defdom head)
(defdom header)
(defdom hr)
(defdom html)
(defdom i)
(defdom iframe)
(defdom img)
(defdom input)
(defdom ins)
(defdom kbd)
(defdom keygen)
(defdom label)
(defdom legend)
(defdom li)
(defdom link)
(defdom main)
(defdom map)
(defdom mark)
(defdom menu)
(defdom menuitem)
(defdom meta)
(defdom meter)
(defdom nav)
(defdom noscript)
(defdom object)
(defdom ol)
(defdom optgroup)
(defdom option)
(defdom output)
(defdom p)
(defdom param)
(defdom pre)
(defdom progress)
(defdom q)
(defdom rp)
(defdom rt)
(defdom ruby)
(defdom s)
(defdom samp)
(defdom script)
(defdom section)
(defdom select)
(defdom small)
(defdom source)
(defdom span)
(defdom strong)
(defdom style)
(defdom sub)
(defdom summary)
(defdom sup)
(defdom table)
(defdom tbody)
(defdom td)
(defdom textarea)
(defdom tfoot)
(defdom th)
(defdom thead)
(defdom time)
(defdom title)
(defdom tr)
(defdom track)
(defdom u)
(defdom ul)
(defdom var)
(defdom video)
(defdom wbr)
(defdom svg)
(defdom polygon)
(defdom line)
(defdom rect)
(defdom circle)
(defdom ellipse)
(defdom polyline)
(defdom text)
(defdom path)