generated from Atry/scala-project-template
/
ReactToBindingHtml.scala
74 lines (65 loc) · 2.09 KB
/
ReactToBindingHtml.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
package com.yang_bo
import com.thoughtworks.binding.Binding
import com.thoughtworks.binding.Binding.BindingSeq
import com.thoughtworks.binding.bindable.Bindable
import com.thoughtworks.binding.bindable.BindableSeq
import org.scalajs.dom._
import org.scalajs.dom.raw._
import slinky.core._
import slinky.core.facade._
import scala.scalajs.js
import slinky.web.ReactDOM
/** A [[https://github.com/ThoughtWorksInc/Binding.scala/ Binding.scala]]
* element that wraps a React component.
*
* @see
* [[ReactToBindingHtml.Implicits.reactElementBindable]] for inserting a
* React component into an `@html` literal or an `html"..."` interpolation.
*/
final class ReactToBindingHtml[WrapperElement <: Element](
reactElement: ReactElement,
wrapperElement: WrapperElement
) extends Binding[WrapperElement] {
protected def value = wrapperElement
private var listenerCount = 0
protected def addChangedListener(
listener: Binding.ChangedListener[WrapperElement]
): Unit = {
try {
if (listenerCount == 0) {
ReactDOM.render(reactElement, wrapperElement)
}
} finally {
listenerCount += 1
}
}
protected def removeChangedListener(
listener: Binding.ChangedListener[WrapperElement]
): Unit = {
listenerCount -= 1
if (listenerCount == 0) {
ReactDOM.unmountComponentAtNode(value)
}
}
}
object ReactToBindingHtml {
private[ReactToBindingHtml] trait LowPriorityImplicits1024 {}
object Implicits
extends ReactToBindingHtmlImplicits2Or3
with LowPriorityImplicits1024 {
implicit def reactElementBindable[From](implicit
toReactElement: From => ReactElement
): Bindable.Aux[From, Element] with BindableSeq.Aux[From, Element] =
new Bindable[From] with BindableSeq[From] {
type Value = Element
def toBinding(from: From): Binding[Value] =
new ReactToBindingHtml(
toReactElement(from),
document.createElement("span")
)
def toBindingSeq(
from: From
): BindingSeq[Value] = Binding.SingletonBindingSeq(toBinding(from))
}
}
}