-
Notifications
You must be signed in to change notification settings - Fork 6
/
html.scala
984 lines (890 loc) · 38.5 KB
/
html.scala
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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
package org.lrng
package binding
import com.thoughtworks.binding.Binding._
import com.thoughtworks.binding._
import com.thoughtworks.binding.bindable.{Bindable, BindableSeq}
import org.lrng.binding.dynamicanyref.{AnyRefApplyDynamic, AnyRefSelectDynamic}
import org.scalajs.dom.raw.HTMLElement
import org.scalajs.dom.{Element, Node, document}
import scala.annotation._
import scala.language.experimental.macros
import scala.language.{dynamics, implicitConversions}
import scala.reflect.macros.whitebox
import scala.scalajs.js
object html {
def mount(parent: Node, children: BindingSeq[Node]): Binding[Unit] = {
new NodeBindingSeq.NodeSeqMountPoint(parent, children)
}
def render[Children](parent: Node, children: Children)(implicit bindableSeq: BindableSeq.Lt[Children, Node]) = {
mount(parent, bindableSeq.toBindingSeq(children)).watch()
}
/** The factory class to create [[ElementBuilder]] */
trait ElementFactory[E <: Element] extends Curried {
protected def tagName: String
@inline def applyBegin = new NodeBinding.Constant.ElementBuilder(document.createElement(tagName).asInstanceOf[E])
}
object AttributeFactory {
private object Typed {
final class AttributeMountPointBuilder[E <: Element, A <: Typed](
implicit attributeSetter: NodeBinding.Constant.AttributeSetter[E, A])
extends NodeBinding.Interpolated.MountPointBuilder[E, A, String] {
def mountProperty(e: E, binding: Binding[String]): Binding[Unit] = {
Binding.BindingInstances.map(binding)(attributeSetter.setAttribute(e, _))
}
}
final class OptionAttributeMountPointBuilder[E <: Element, A <: Typed](
implicit attributeSetter: NodeBinding.Constant.AttributeSetter[E, A],
attributeRemover: NodeBinding.Constant.AttributeRemover[E, A])
extends NodeBinding.Interpolated.MountPointBuilder[E, A, Option[String]] {
def mountProperty(e: E, binding: Binding[Option[String]]): Binding[Unit] = {
Binding.BindingInstances.map(binding)(optValue =>
optValue match {
case Some(value) => attributeSetter.setAttribute(e, value)
case _ => attributeRemover.removeAttribute(e)
})
}
}
}
trait Typed extends Curried {
@inline
implicit def attributeMountPointBuilder[E <: Element](
implicit attributeSetter: NodeBinding.Constant.AttributeSetter[E, this.type])
: NodeBinding.Interpolated.MountPointBuilder[E, this.type, String] =
new Typed.AttributeMountPointBuilder[E, this.type]
@inline
implicit def optionalAttributeMountPointBuilder[E <: Element](
implicit attributeSetter: NodeBinding.Constant.AttributeSetter[E, this.type],
attributeRemover: NodeBinding.Constant.AttributeRemover[E, this.type]
): NodeBinding.Interpolated.MountPointBuilder[E, this.type, Option[String]] =
new Typed.OptionAttributeMountPointBuilder[E, this.type]
@inline
def applyBegin = new NodeBinding.Constant.MultipleAttributeBuilder.Typed[this.type](this)
@inline
def apply() = new NodeBinding.Constant.AttributeBuilder.Typed[this.type]("")
@inline
def apply(textBuilder: NodeBinding.Constant.TextBuilder) =
new NodeBinding.Constant.AttributeBuilder.Typed[this.type](textBuilder.data)
@inline def apply[A <: Binding[Any]](value: A) = new NodeBinding.Interpolated.PropertyBuilder[this.type, A](value)
}
final class Untyped(private val attributeName: String) extends AnyVal with Curried {
@inline
protected def setAttribute(element: Element, value: String) = {
element.setAttribute(attributeName, value)
}
@inline
def applyBegin = new NodeBinding.Constant.MultipleAttributeBuilder.Untyped(this)
@inline
def apply() = new NodeBinding.Constant.AttributeBuilder.Untyped(setAttribute(_, ""))
@inline
def apply(textBuilder: NodeBinding.Constant.TextBuilder) =
new NodeBinding.Constant.AttributeBuilder.Untyped(setAttribute(_, textBuilder.data))
protected type Self = Untyped
def apply(binding: Binding[String]) =
new NodeBinding.Interpolated.AttributeBuilder({ element =>
Binding.BindingInstances.map(binding)(element.setAttribute(attributeName, _))
})
def apply(optionalBinding: Binding[Option[String]])(implicit dummyImplicit: DummyImplicit =
DummyImplicit.dummyImplicit) =
new NodeBinding.Interpolated.AttributeBuilder({ element =>
Binding.BindingInstances.map(optionalBinding) {
case Some(value) => element.setAttribute(attributeName, value)
case _ => element.removeAttribute(attributeName)
}
})
// def apply(optionalBinding: Binding[Option[String]])(implicit dummyImplicit: DummyImplicit =
// DummyImplicit.dummyImplicit): Unit = new NodeBinding.Interpolated.AttributeBuilder({ element =>
// Binding.BindingInstances.map(optionalBinding)(optValue => optValue match {
// case Some(value) => attributeSetter.setAttribute(e, value)
// case _ => attributeRemover.removeAttribute(e)element.setAttribute(attributeName, _))
// })
}
}
type NodeBindingSeq[+A] = BindingSeq[A] {
def value: collection.Seq[A]
}
object NodeBindingSeq {
@inline
@tailrec
private def removeAll(parent: Node): Unit = {
val firstChild = parent.firstChild
if (firstChild != null) {
parent.removeChild(firstChild)
removeAll(parent)
}
}
private[lrng] final class NodeSeqMountPoint(parent: Node, childrenBinding: BindingSeq[Node])
extends MultiMountPoint[Node](childrenBinding) {
protected def set(children: Seq[Node]): Unit = {
set(children: Iterable[Node])
}
protected def set(children: Iterable[Node]): Unit = {
removeAll(parent)
for (child <- children) {
if (child.parentNode != null) {
throw new IllegalStateException(raw"""Cannot insert ${child.toString} twice!""")
}
parent.appendChild(child)
}
}
protected def splice(from: Int, that: Iterable[Node], replaced: Int): Unit = {
spliceGenIterable(from, that, replaced)
}
protected def splice(from: Int, that: collection.GenSeq[Node], replaced: Int): Unit = {
spliceGenIterable(from, that, replaced)
}
private def spliceGenIterable(from: Int, that: collection.GenIterable[Node], replaced: Int): Unit = {
@inline
@tailrec
def removeChildren(child: Node, n: Int): Node = {
if (n == 0) {
child
} else {
val nextSibling = child.nextSibling
parent.removeChild(child)
removeChildren(nextSibling, n - 1)
}
}
val child = removeChildren(parent.childNodes(from), replaced)
if (child == null) {
for (newChild <- that) {
if (newChild.parentNode != null) {
throw new IllegalStateException(raw"""Cannot insert a ${newChild.toString} element twice!""")
}
parent.appendChild(newChild)
}
} else {
for (newChild <- that) {
if (newChild.parentNode != null) {
throw new IllegalStateException(raw"""Cannot insert a ${newChild.toString} element twice!""")
}
parent.insertBefore(newChild, child)
}
}
}
}
final class Builder(val childNodes: js.Array[Node] = new js.Array(0),
val mountPoints: js.Array[Binding[Unit]] = new js.Array(0))
extends ChildBuilder {
def applyEnd: NodeBindingSeq[Node] = {
if (childNodes.isEmpty) {
Constants(scalajs.runtime.toScalaVarArgs(childNodes): _*)
} else {
new NodeBindingSeq.Interpolated(childNodes, mountPoints)
}
}
}
type Constants[+A] = Binding.Constants[A]
final class Interpolated private[lrng] (private[lrng] val nodes: js.Array[Node] = new js.Array(0),
private[lrng] val mountPoints: js.Array[Binding[Unit]] = new js.Array(0))
extends BindingSeq[Node] {
type All[+A] = collection.Seq[A]
def value: collection.Seq[Node] = nodes
private var referenceCount = 0
protected def addPatchedListener(listener: PatchedListener[Node]): Unit = {
if (referenceCount == 0) {
mountPoints.foreach(_.watch())
}
referenceCount += 1
}
protected def removePatchedListener(listener: PatchedListener[Node]): Unit = {
referenceCount -= 1
if (referenceCount == 0) {
mountPoints.foreach(_.unwatch())
}
}
}
}
type NodeBinding[+A] = Binding[A] {
val value: A
}
object NodeBinding {
object Constant {
@implicitNotFound("${AttributeObject} is not an attribute of ${E}")
final class AttributeSetter[-E <: Element, AttributeObject](val setAttribute: (E, String) => Unit) extends AnyVal
@implicitNotFound("${AttributeObject} is not an attribute of ${E}")
final class AttributeRemover[-E <: Element, AttributeObject](val removeAttribute: (E) => Unit) extends AnyVal
final class ElementBuilder[+E <: Element] private[lrng] (private[lrng] val element: E) extends AnyVal {
@inline
def applyNext[AttributeObject](child: AttributeBuilder.Untyped) = {
child.set(element)
this
}
@inline
def applyNext[AttributeObject](child: AttributeBuilder.Typed[AttributeObject])(
implicit attributeSetter: AttributeSetter[E, AttributeObject]) = {
attributeSetter.setAttribute(element, child.value)
this
}
def applyNext(child: Binding[String]) = {
toInterpolated.applyNext(child)
}
def applyNext[Child](child: Binding[Child])(implicit bindableSeq: BindableSeq.Lt[Child, Node]) = {
toInterpolated.applyNext(child)
}
@inline
def applyNext(child: NodeBinding.Interpolated.AttributeBuilder)(implicit dummyImplicit: DummyImplicit =
DummyImplicit.dummyImplicit) = {
toInterpolated.applyNext(child)
}
@inline
def applyNext[Property, Expected](child: NodeBinding.Interpolated.PropertyBuilder[Property, Binding[Expected]])(
implicit mountPointBuilder: Interpolated.MountPointBuilder[E, Property, Expected]
) = {
toInterpolated.applyNext(child)
}
@inline
def applyNext(child: NodeBinding.Constant.ElementBuilder[Element]) = {
toInterpolated.applyNext(child)
}
def applyNext(child: NodeBinding.Interpolated.ElementBuilder[Element]) = {
toInterpolated.applyNext(child)
}
@inline
def applyNext(child: NodeBinding.Constant.NodeBuilder[Node]) = {
toInterpolated.applyNext(child)
}
@inline
def applyNext(child: NodeBinding.Constant.TextBuilder) = {
toInterpolated.applyNext(child)
}
@inline
def applyEnd = this
private def toInterpolated = new NodeBinding.Interpolated.ElementBuilder[E](element)
}
final class NodeBuilder[+Node] private[lrng] (private[lrng] val node: Node) extends AnyVal
final class TextBuilder private[lrng] (private[lrng] val data: String) extends AnyVal
object AttributeBuilder {
final class Untyped(private[lrng] val set: Element => Unit) extends AnyVal
final class Typed[A](private[lrng] val value: String) extends AnyVal
}
object MultipleAttributeBuilder {
final class Typed[A <: AttributeFactory.Typed](private[html] val attributeFactory: A,
stringBuilder: StringBuilder = new StringBuilder) {
def applyNext(textBuilder: TextBuilder) = {
stringBuilder ++= textBuilder.data
this
}
def applyEnd = {
new AttributeBuilder.Typed[A](stringBuilder.toString())
}
}
final class Untyped(attributeFactory: AttributeFactory.Untyped,
stringBuilder: StringBuilder = new StringBuilder) {
def applyNext(textBuilder: TextBuilder) = {
stringBuilder ++= textBuilder.data
this
}
def applyEnd: AttributeBuilder.Untyped = {
attributeFactory(new TextBuilder(stringBuilder.toString()))
}
}
}
}
type Constant[+A] = Binding.Constant[A]
final class Interpolated[+A] private[lrng] (val value: A, private[lrng] val mountPoints: js.Array[Binding[Unit]])
extends Binding[A] {
private var referenceCount = 0
protected def addChangedListener(listener: ChangedListener[A]): Unit = {
if (referenceCount == 0) {
mountPoints.foreach(_.watch())
}
referenceCount += 1
}
protected def removeChangedListener(listener: ChangedListener[A]): Unit = {
referenceCount -= 1
if (referenceCount == 0) {
mountPoints.foreach(_.unwatch())
}
}
}
object Interpolated {
final class AttributeBuilder(val mountPoint: Element => Binding[Unit]) extends AnyVal
final class PropertyBuilder[PropertyType, Value](val value: Value) extends AnyVal
@implicitNotFound("${AttributeObject} of type ${V} is not a property of ${E}")
trait MountPointBuilder[-E <: Element, AttributeObject, -V] {
def mountProperty(e: E, binding: Binding[V]): Binding[Unit]
}
object MountPointBuilder {
implicit def convertedMountPointBuilder[E <: Element, A, V0, V1](
implicit mountPointBuilder: MountPointBuilder[E, A, V1],
bindable: Bindable.Lt[Binding[V0], V1]): MountPointBuilder[E, A, V0] = new MountPointBuilder[E, A, V0] {
def mountProperty(e: E, binding: Binding[V0]): Binding[Unit] = {
mountPointBuilder.mountProperty(e, bindable.toBinding(binding))
}
}
}
final class ElementBuilder[+E <: Element](val element: E,
val bindingSeqs: js.Array[Binding[BindingSeq[Node]]] = new js.Array(0),
var childNodes: js.Array[Node] = new js.Array(0),
val mountPoints: js.Array[Binding[Unit]] = new js.Array(0))
extends ChildBuilder {
private[lrng] def mergeTrailingNodes(): Unit = {
if (childNodes.nonEmpty) {
bindingSeqs += Binding.Constant(Binding.Constants(scalajs.runtime.toScalaVarArgs(childNodes): _*))
childNodes = new js.Array(0)
}
}
private[lrng] def flush(): Unit = {
mergeTrailingNodes()
if (bindingSeqs.nonEmpty) {
mountPoints += mount(element, Constants(scalajs.runtime.toScalaVarArgs(bindingSeqs): _*).flatMapBinding(identity))
}
}
@inline
def applyEnd = this
def applyNext(child: Binding[String]) = {
val textNode = document.createTextNode("")
childNodes += textNode
mountPoints += Binding.BindingInstances.map(child)(textNode.data_=)
this
}
def applyNext[Child](child: Binding[Child])(implicit bindableSeq: BindableSeq.Lt[Child, Node]) = {
mergeTrailingNodes()
bindingSeqs += Binding.BindingInstances.map(child)(bindableSeq.toBindingSeq(_))
this
}
@inline
def applyNext[AttributeObject](attributeBuilder: NodeBinding.Constant.AttributeBuilder.Untyped) = {
attributeBuilder.set(element)
this
}
@inline
def applyNext[AttributeObject](attributeBuilder: NodeBinding.Constant.AttributeBuilder.Typed[AttributeObject])(
implicit attributeSetter: Constant.AttributeSetter[E, AttributeObject]) = {
attributeSetter.setAttribute(element, attributeBuilder.value)
this
}
@inline
def applyNext(attributeBuilder: NodeBinding.Interpolated.AttributeBuilder)(
implicit dummyImplicit: DummyImplicit = DummyImplicit.dummyImplicit) = {
mountPoints += attributeBuilder.mountPoint(element)
this
}
@inline
def applyNext[Property, Expected](
attributeBuilder: NodeBinding.Interpolated.PropertyBuilder[Property, Binding[Expected]])(
implicit mountPointBuilder: MountPointBuilder[E, Property, Expected]
) = {
mountPoints += mountPointBuilder.mountProperty(element, attributeBuilder.value)
this
}
}
}
}
private[lrng] trait ChildBuilder {
def childNodes: js.Array[Node]
def mountPoints: js.Array[Binding[Unit]]
@inline
def applyNext(elementBuilder: NodeBinding.Constant.ElementBuilder[Element]): this.type = {
childNodes += elementBuilder.element
this
}
def applyNext(elementBuilder: NodeBinding.Interpolated.ElementBuilder[Element]): this.type = {
if (elementBuilder.bindingSeqs.isEmpty && elementBuilder.mountPoints.isEmpty) {
val childElement = elementBuilder.element
elementBuilder.childNodes.foreach(childElement.appendChild)
childNodes += childElement
} else {
elementBuilder.flush()
childNodes += elementBuilder.element
mountPoints.push(scalajs.runtime.toScalaVarArgs(elementBuilder.mountPoints): _*)
}
this
}
@inline
def applyNext(nodeBuilder: NodeBinding.Constant.NodeBuilder[Node]): this.type = {
childNodes += nodeBuilder.node
this
}
@inline
def applyNext(textBuilder: NodeBinding.Constant.TextBuilder): this.type = {
childNodes += document.createTextNode(textBuilder.data)
this
}
}
private[html] trait LowPriorityAutoImports {
// TODO: move to https://github.com/ThoughtWorksInc/bindable.scala
implicit def bindableBindableSeq[From, BindableValue, Value0](
implicit
bindableSeq: BindableSeq.Aux[From, BindableValue],
bindable: Bindable.Aux[BindableValue, Value0]): BindableSeq.Aux[From, Value0] =
new BindableSeq[From] {
type Value = Value0
def toBindingSeq(from: From): BindingSeq[Value] = {
bindableSeq.toBindingSeq(from).mapBinding(bindable.toBinding(_))
}
}
}
private[lrng] object elementTypes {
/** @todo Remove this type alias once scala-js-dom added the definition for this type */
type HTMLTimeElement <: HTMLElement
/** @todo Remove this type alias once scala-js-dom added the definition for this type */
type HTMLDataElement <: HTMLElement
/** @todo Remove this type alias once scala-js-dom added the definition for this type */
type HTMLPictureElement <: HTMLElement
/** @todo Remove this type alias once scala-js-dom added the definition for this type */
type HTMLOutputElement <: HTMLElement
/** @todo Remove this type alias once scala-js-dom added the definition for this type */
type HTMLMeterElement <: HTMLElement
/** @todo Remove this type alias once scala-js-dom added the definition for this type */
type HTMLDetailsElement <: HTMLElement
/** @todo Remove this type alias once scala-js-dom added the definition for this type */
type HTMLDialogElement <: HTMLElement
/** @todo Remove this type alias once scala-js-dom added the definition for this type */
type HTMLTemplateElement <: HTMLElement
/** @todo Remove this type alias once scala-js-dom added the definition for this type */
type HTMLSlotElement <: HTMLElement
}
object autoImports extends LowPriorityAutoImports {
object data {
@inline def entities = EntityBuilders
@inline def interpolation = Binding
object values extends AnyRefSelectDynamic[NodeBinding.Constant.TextBuilder] {
@inline def selectDynamic(data: String) = new NodeBinding.Constant.TextBuilder(data)
@inline def selectDynamic: NodeBinding.Constant.TextBuilder = selectDynamic("selectDynamic")
}
object attributes extends AnyRefApplyDynamic {
object applyDynamic {
@inline def apply(attributeName: String): AttributeFactory.Untyped =
new AttributeFactory.Untyped(attributeName)
@inline implicit def asUntyped(a: => applyDynamic.type): AttributeFactory.Untyped =
new AttributeFactory.Untyped("applyDynamic")
}
}
}
// TODO: move to https://github.com/ThoughtWorksInc/bindable.scala
implicit def jsFunctionBindable[A, R]: Bindable.Aux[Binding[A => R], js.Function1[A, R]] =
new Bindable[Binding[A => R]] {
type Value = js.Function1[A, R]
def toBinding(from: Binding[A => R]): Binding[js.Function1[A, R]] = {
Binding.BindingInstances.map(from)(f => f: js.Function1[A, R])
}
}
// TODO: move to https://github.com/ThoughtWorksInc/bindable.scala
implicit def bindingBindingSeqBindableSeq[BindableValue, Value0](
implicit bindable: Bindable.Aux[BindableValue, Value0]): BindableSeq.Aux[BindingSeq[BindableValue], Value0] =
new BindableSeq[BindingSeq[BindableValue]] {
type Value = Value0
def toBindingSeq(from: BindingSeq[BindableValue]): BindingSeq[Value] = {
from.mapBinding(bindable.toBinding(_))
}
}
object xml {
@inline def noPrefix[Uri](uri: Uri) = uri
object prefixes extends Dynamic {
@inline def getClass[Uri](uri: Uri) = uri
@inline def !=[Uri](uri: Uri) = uri
@inline def ##[Uri](uri: Uri) = uri
@inline def +[Uri](uri: Uri) = uri
@inline def ->[Uri](uri: Uri) = uri
@inline def ==[Uri](uri: Uri) = uri
@inline def asInstanceOf[Uri](uri: Uri) = uri
@inline def ensuring[Uri](uri: Uri) = uri
@inline def eq[Uri](uri: Uri) = uri
@inline def equals[Uri](uri: Uri) = uri
@inline def formatted[Uri](uri: Uri) = uri
@inline def hashCode[Uri](uri: Uri) = uri
@inline def isInstanceOf[Uri](uri: Uri) = uri
@inline def ne[Uri](uri: Uri) = uri
@inline def notify[Uri](uri: Uri) = uri
@inline def notifyAll[Uri](uri: Uri) = uri
@inline def synchronized[Uri](uri: Uri)(implicit dummyImplicit: DummyImplicit = DummyImplicit.dummyImplicit) =
uri
@inline def toString[Uri](uri: Uri) = uri
@inline def wait[Uri](uri: Uri) = uri
@inline def →[Uri](uri: Uri) = uri
object applyDynamic {
@inline def applyDynamic[Uri](uri: Uri) = uri
}
case class applyDynamic(prefix: String) extends AnyVal {
@inline def apply[Uri](uri: Uri) = uri
}
}
object uris {
@inline
def `http://www.w3.org/1999/xhtml` = xml
}
@inline def elements = ElementFactories
@inline def attributes = AttributeFactories
@inline def entities = EntityBuilders
@inline def cdata(data: String) = new NodeBinding.Constant.NodeBuilder(document.createCDATASection(data))
object values extends AnyRefSelectDynamic[NodeBinding.Constant.TextBuilder] {
@inline def selectDynamic: NodeBinding.Constant.TextBuilder = selectDynamic("selectDynamic")
@inline def selectDynamic(data: String) = new NodeBinding.Constant.TextBuilder(data)
}
/**
* @note All methods in [[AnyRef]] are overloaded, in case of name clash
* {{{
* import html.autoImports.xml.texts
* import html.NodeBinding.Constant.TextBuilder
* texts.selectDynamic should be(a[TextBuilder])
* texts.getClass should be(a[TextBuilder])
* texts.!= should be(a[TextBuilder])
* texts.## should be(a[TextBuilder])
* texts.+ should be(a[TextBuilder])
* texts.-> should be(a[TextBuilder])
* texts.== should be(a[TextBuilder])
* texts.asInstanceOf should be(a[TextBuilder])
* texts.ensuring should be(a[TextBuilder])
* texts.eq should be(a[TextBuilder])
* texts.equals should be(a[TextBuilder])
* texts.formatted should be(a[TextBuilder])
* texts.hashCode should be(a[TextBuilder])
* texts.isInstanceOf should be(a[TextBuilder])
* texts.ne should be(a[TextBuilder])
* texts.notify should be(a[TextBuilder])
* texts.notifyAll should be(a[TextBuilder])
* texts.synchronized should be(a[TextBuilder])
* texts.toString should be(a[TextBuilder])
* texts.wait should be(a[TextBuilder])
* texts.→ should be(a[TextBuilder])
* }}}
*/
object texts extends AnyRefSelectDynamic[NodeBinding.Constant.TextBuilder] {
@inline def selectDynamic: NodeBinding.Constant.TextBuilder = selectDynamic("selectDynamic")
@inline def selectDynamic(data: String) = new NodeBinding.Constant.TextBuilder(data)
}
@inline def comment(data: String) = new NodeBinding.Constant.NodeBuilder(document.createComment(data))
object processInstructions extends Dynamic {
@inline def getClass(data: String) = applyDynamic("getClass")(data)
@inline def !=(data: String) = applyDynamic("!=")(data)
@inline def ##(data: String) = applyDynamic("##")(data)
@inline def +(data: String) = applyDynamic("+")(data)
@inline def ->(data: String) = applyDynamic("->")(data)
@inline def ==(data: String) = applyDynamic("==")(data)
@inline def asInstanceOf(data: String) = applyDynamic("asInstanceOf")(data)
@inline def ensuring(data: String) = applyDynamic("ensuring")(data)
@inline def eq(data: String) = applyDynamic("eq")(data)
@inline def equals(data: String) = applyDynamic("equals")(data)
@inline def formatted(data: String) = applyDynamic("formatted")(data)
@inline def hashCode(data: String) = applyDynamic("hashCode")(data)
@inline def isInstanceOf(data: String) = applyDynamic("isInstanceOf")(data)
@inline def ne(data: String) = applyDynamic("ne")(data)
@inline def notify(data: String) = applyDynamic("notify")(data)
@inline def notifyAll(data: String) = applyDynamic("notifyAll")(data)
@inline def synchronized(data: String) = applyDynamic("synchronized")(data)
@inline def toString(data: String) = applyDynamic("toString")(data)
@inline def wait(data: String) = applyDynamic("wait")(data)
@inline def →(data: String) = applyDynamic("→")(data)
@inline def applyDynamic(target: String)(data: String) =
new NodeBinding.Constant.NodeBuilder(document.createProcessingInstruction(target, data))
}
@inline def interpolation = Binding
object literal extends Curried {
@inline def apply[Node](nodeBuilder: NodeBinding.Constant.NodeBuilder[Node]) = Constant(nodeBuilder.node)
@inline def apply[E <: Element](elementBuilder: NodeBinding.Constant.ElementBuilder[E]) =
Constant(elementBuilder.element)
def apply[E <: Element](elementBuilder: NodeBinding.Interpolated.ElementBuilder[E]): NodeBinding[E] = {
if (elementBuilder.mountPoints.isEmpty && elementBuilder.bindingSeqs.isEmpty) {
val element = elementBuilder.element
elementBuilder.childNodes.foreach(element.appendChild)
Constant(element)
} else {
elementBuilder.flush()
new NodeBinding.Interpolated(elementBuilder.element, elementBuilder.mountPoints)
}
}
@inline def applyBegin = new NodeBindingSeq.Builder
}
}
}
private[lrng] final class WhiteBoxMacros(context: whitebox.Context) extends nameBasedXml.Macros(context) {
import c.universe._
override protected def transformBody(tree: Tree): Tree = q"""
import _root_.org.lrng.binding.html.autoImports.{
!= => _,
## => _,
== => _,
eq => _,
equals => _,
getClass => _,
hashCode => _,
ne => _,
notify => _,
notifyAll => _,
synchronized => _,
toString => _,
wait => _,
_
}
${new NameBasedXmlTransformer().transform(tree)}
"""
}
}
/** An annotation to convert XHTML literals to data-bindable DOM nodes.
* @author 杨博 (Yang Bo) <pop.atry@gmail.com>
*
* @example XHTML literals with text attributes
* {{{
* @html
* val myDiv = <div class="my-class" tabindex="42"></div>
* myDiv.value.nodeName should be("DIV")
* myDiv.value.className should be("my-class")
* myDiv.value.tabIndex should be(42)
* }}}
*
* Nested XHTML literals with interpolation:
*
* {{{
* @html
* val myDiv2 = <div style="color: red;" tabIndex={99999} title="my title" class={"my-class"}><div>text</div><span style={"color: blue;"} tabIndex={99}></span><div innerHTML={"html"}></div><div></div>{myDiv.bind}</div>
* myDiv2.watch()
* myDiv2.value.outerHTML should be("""<div style="color: red;" tabindex="99999" title="my title" class="my-class"><div>text</div><span style="color: blue;" tabindex="99"></span><div>html</div><div></div><div class="my-class" tabindex="42"></div></div>""")
* }}}
*
* @example Special character in attribute names
* {{{
* @html
* val myMeta = <meta http-equiv="refresh" content="30"/>
* myMeta.watch()
* myMeta.value.outerHTML should be("""<meta http-equiv="refresh" content="30">""")
* }}}
*
* @example Opaque type aliases of HTMLInputElement
* {{{
* @html
* val myMeta = <input name="myInput" type="radio"/>
* myMeta.watch()
* myMeta.value.outerHTML should be("""<input name="myInput" type="radio">""")
* }}}
*
* @example Element list of XHTML literals
*
* {{{
* @html
* val myDivs = <div></div><div title={"my title"} class=""></div><div class="my-class"></div>
* myDivs.watch()
* import org.scalajs.dom.html.Div
* inside(myDivs.value) {
* case collection.Seq(div1: Div, div2: Div, div3: Div) =>
* div1.nodeName should be("DIV")
* div1.hasAttribute("class") should be(false)
* div1.className should be("")
* div2.title should be("my title")
* div2.hasAttribute("class") should be(true)
* div2.className should be("")
* div3.className should be("my-class")
* }
* }}}
*
* @example Text interpolation in an element
* {{{
* @html val monadicDiv = <div>{"text"}</div>
* monadicDiv.watch()
* assert(monadicDiv.value.outerHTML == "<div>text</div>")
* }}}
*
* @example Changing text
* {{{
* import com.thoughtworks.binding.Binding.Var
* val v0 = Var("original text")
* @html val monadicDiv = <div> <span> {v0.bind} </span> </div>
* monadicDiv.watch()
* assert(monadicDiv.value.outerHTML == "<div> <span> original text </span> </div>")
* v0.value = "changed"
* assert(monadicDiv.value.outerHTML == "<div> <span> changed </span> </div>")
* }}}
*
* @example `for` / `yield` expressions in XHTML interpolation
* {{{
* import com.thoughtworks.binding.Binding.Vars
* val v0 = Vars("original text 0","original text 1")
* @html val monadicDiv = <div> <span> { for (s <- v0) yield <b>{s}</b> } </span> </div>
* monadicDiv.watch()
* val div = monadicDiv.value
* assert(monadicDiv.value.outerHTML == "<div> <span> <b>original text 0</b><b>original text 1</b> </span> </div>")
* v0.value.prepend("prepended")
* assert(div eq monadicDiv.value)
* assert(monadicDiv.value.outerHTML == "<div> <span> <b>prepended</b><b>original text 0</b><b>original text 1</b> </span> </div>")
* v0.value.remove(1)
* assert(div eq monadicDiv.value)
* assert(monadicDiv.value.outerHTML == "<div> <span> <b>prepended</b><b>original text 1</b> </span> </div>")
* }}}
*
* @example `for` / `yield` / `if` expressions in XHTML interpolation
* {{{
* import com.thoughtworks.binding.Binding
* import com.thoughtworks.binding.Binding.Var
* import com.thoughtworks.binding.Binding.Vars
* final case class User(firstName: Var[String], lastName: Var[String], age: Var[Int])
* val filterPattern = Var("")
* val users = Vars(
* User(Var("Steve"), Var("Jobs"), Var(10)),
* User(Var("Tim"), Var("Cook"), Var(12)),
* User(Var("Jeff"), Var("Lauren"), Var(13))
* )
* def shouldShow(user: User): Binding[Boolean] = Binding {
* val pattern = filterPattern.bind
* if (pattern == "") {
* true
* } else if (user.firstName.bind.toLowerCase.contains(pattern)) {
* true
* } else if (user.lastName.bind.toLowerCase.contains(pattern)) {
* true
* } else {
* false
* }
* }
*
* @html
* def tbodyBinding = {
* <tbody>{
* for {
* user <- users
* if shouldShow(user).bind
* } yield <tr><td>{user.firstName.bind}</td><td>{user.lastName.bind}</td><td>{user.age.bind.toString}</td></tr>
* }</tbody>
* }
*
* @html
* val tableBinding = {
* <table class="my-table" title="My Tooltip"><thead><tr><td>First Name</td><td>Second Name</td><td>Age</td></tr></thead>{tbodyBinding.bind}</table>
* }
* tableBinding.watch()
* assert(tableBinding.value.outerHTML == """<table class="my-table" title="My Tooltip"><thead><tr><td>First Name</td><td>Second Name</td><td>Age</td></tr></thead><tbody><tr><td>Steve</td><td>Jobs</td><td>10</td></tr><tr><td>Tim</td><td>Cook</td><td>12</td></tr><tr><td>Jeff</td><td>Lauren</td><td>13</td></tr></tbody></table>""")
* filterPattern.value = "o"
* assert(tableBinding.value.outerHTML == """<table class="my-table" title="My Tooltip"><thead><tr><td>First Name</td><td>Second Name</td><td>Age</td></tr></thead><tbody><tr><td>Steve</td><td>Jobs</td><td>10</td></tr><tr><td>Tim</td><td>Cook</td><td>12</td></tr></tbody></table>""")
* }}}
*
* @example Dynamc attributes
* {{{
* @html
* val myBr = <br data:toString="+©" data:applyDynamic="value"/>
* myBr.watch()
* myBr.value.outerHTML should be("""<br tostring="+©" applydynamic="value">""")
* }}}
*
* @example Changing attribute values
* {{{
* import com.thoughtworks.binding.Binding.Var
* val id = Var("oldId")
* @html val myInput = <input data:applyDynamic={id.bind} data:custom={id.bind} name={id.bind} id={id.bind} onclick={ _: Any => id.value = "newId" }/>
* myInput.watch()
* assert(myInput.value.outerHTML == """<input applydynamic="oldId" custom="oldId" name="oldId" id="oldId">""")
* myInput.value.onclick(null)
* assert(myInput.value.outerHTML == """<input applydynamic="newId" custom="newId" name="newId" id="newId">""")
* }}}
*
* @example A child node must not be inserted more than once
* {{{
* an[IllegalStateException] should be thrownBy {
* @html
* val child = <hr/>
* @html
* val parent = <p><span>{child.bind}</span><span>{child.bind}</span></p>
* parent.watch()
* }
* }}}
*
*
* @example Seq in DOM
* {{{
* import org.scalajs.dom.document
* @html def myUl = {
* <ul>{Seq(<li>data1</li>, <li>data2</li>)}</ul>
* }
* val div = document.createElement("div")
* html.render(div, myUl)
* div.firstChild.childNodes.length should be(2)
* }}}
*
* @example XHTML comments
* {{{
* import org.scalajs.dom.document
* @html def comment = <div><!--my comment--></div>
* val div = document.createElement("div")
* html.render(div, comment)
* assert(div.innerHTML == "<div><!--my comment--></div>")
* }}}
*
* @example Escape
* {{{
* import org.scalajs.dom.document
* @html def escaped = <div> $minus</div>
* val div = document.createElement("div")
* html.render(div, escaped)
* assert(div.innerHTML == "<div> $minus</div>")
* }}}
* @example Entity references
* {{{
* import org.scalajs.dom.document
* @html def entity = <div class="< > © λ my-class">my text < > © λ</div>
* val div = document.createElement("div")
* html.render(div, entity)
* assert(div.innerHTML == """<div class="< > © λ my-class">my text < > © λ</div>""")
* }}}
* @example Process instructions
* {{{
* @html val myXmlStylesheet = <?my-instruction my data?>
* myXmlStylesheet.watch()
* myXmlStylesheet.value.target should be("my-instruction")
* myXmlStylesheet.value.data should be("my data")
* }}}
* @example CDATA sections are not supported in HTML documents
* {{{
* import scala.scalajs.js
* a[js.JavaScriptException] should be thrownBy {
* @html val myCData = <![CDATA[my data]]>
* myCData.watch()
* }
* }}}
*
* @example XML namespaces
* {{{
* import scala.language.dynamics
* import org.scalajs.dom.document
* import org.scalajs.dom.raw._
* import com.thoughtworks.binding.Binding
* import com.thoughtworks.binding.Binding.BindingInstances.monadSyntax._
* object svg {
* object texts extends Dynamic {
* @inline def selectDynamic(data: String) = new html.NodeBinding.Constant.TextBuilder(data)
* }
* object elements {
* object svg extends Curried {
* @inline def applyBegin = new html.NodeBinding.Constant.ElementBuilder(document.createElementNS("http://www.w3.org/2000/svg", "svg").asInstanceOf[SVGSVGElement])
* }
* object text extends Curried {
* @inline def applyBegin = new html.NodeBinding.Constant.ElementBuilder(document.createElementNS("http://www.w3.org/2000/svg", "text").asInstanceOf[SVGTextElement])
* }
* }
* @inline def interpolation = Binding
* object values {
* sealed trait FontStyle
* case object normal extends FontStyle
* case object italic extends FontStyle
* case object oblique extends FontStyle
* }
* object attributes {
* def font$minusstyle(value: values.FontStyle) = {
* new html.NodeBinding.Constant.AttributeBuilder.Untyped(_.setAttribute("font-style", value.toString))
* }
* def font$minusstyle(binding: Binding[values.FontStyle]) = {
* new html.NodeBinding.Interpolated.AttributeBuilder( element =>
* binding.map { value =>
* element.setAttribute("font-style", value.toString)
* }
* )
* }
* }
* }
* implicit final class SvgUriOps(uriFactory: html.autoImports.xml.uris.type) {
* @inline def http$colon$div$divwww$u002Ew3$u002Eorg$div2000$divsvg = svg
* }
* @html
* val mySvg1 = <svg xmlns="http://www.w3.org/2000/svg"><text font-style="normal">my text</text></svg>
* mySvg1.watch()
* mySvg1.value.outerHTML should be("""<svg><text font-style="normal">my text</text></svg>""")
*
* import svg.values.normal
* @html
* val mySvg2 = <svg:svg xmlns:svg="http://www.w3.org/2000/svg"><svg:text font-style={normal}>my text</svg:text></svg:svg>
* mySvg2.watch()
* mySvg2.value.outerHTML should be("""<svg><text font-style="normal">my text</text></svg>""")
* }}}
*
*/
@compileTimeOnly("enable macro paradise to expand macro annotations")
class html extends StaticAnnotation {
def macroTransform(annottees: Any*): Any = macro html.WhiteBoxMacros.macroTransform
}