-
Notifications
You must be signed in to change notification settings - Fork 133
/
dom-js.kt
193 lines (157 loc) · 6.35 KB
/
dom-js.kt
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
package kotlinx.html.dom
import kotlinx.html.*
import kotlinx.html.consumers.*
import kotlinx.html.org.w3c.dom.events.Event
import org.w3c.dom.*
private inline fun HTMLElement.setEvent(name: String, noinline callback : (Event) -> Unit) : Unit {
asDynamic()[name] = callback
}
class JSDOMBuilder<out R : HTMLElement>(val document : Document) : TagConsumer<R> {
private val path = arrayListOf<HTMLElement>()
private var lastLeaved : HTMLElement? = null
override fun onTagStart(tag: Tag) {
val element: HTMLElement = when {
tag.namespace != null -> document.createElementNS(tag.namespace!!, tag.tagName).asDynamic()
else -> document.createElement(tag.tagName) as HTMLElement
}
tag.attributesEntries.forEach {
element.setAttribute(it.key, it.value)
}
if (path.isNotEmpty()) {
path.last().appendChild(element)
}
path.add(element)
}
override fun onTagAttributeChange(tag: Tag, attribute: String, value: String?) {
when {
path.isEmpty() -> throw IllegalStateException("No current tag")
path.last().tagName.lowercase() != tag.tagName.lowercase() -> throw IllegalStateException("Wrong current tag")
else -> path.last().let { node ->
if (value == null) {
node.removeAttribute(attribute)
} else {
node.setAttribute(attribute, value)
}
}
}
}
override fun onTagEvent(tag: Tag, event: String, value: (Event) -> Unit) {
when {
path.isEmpty() -> throw IllegalStateException("No current tag")
path.last().tagName.lowercase() != tag.tagName.lowercase() -> throw IllegalStateException("Wrong current tag")
else -> path.last().setEvent(event, value)
}
}
override fun onTagEnd(tag: Tag) {
if (path.isEmpty() || path.last().tagName.lowercase() != tag.tagName.lowercase()) {
throw IllegalStateException("We haven't entered tag ${tag.tagName} but trying to leave")
}
lastLeaved = path.removeAt(path.lastIndex)
}
override fun onTagContent(content: CharSequence) {
if (path.isEmpty()) {
throw IllegalStateException("No current DOM node")
}
path.last().appendChild(document.createTextNode(content.toString()))
}
override fun onTagContentEntity(entity: Entities) {
if (path.isEmpty()) {
throw IllegalStateException("No current DOM node")
}
// stupid hack as browsers doesn't support createEntityReference
val s = document.createElement("span") as HTMLElement
s.innerHTML = entity.text
path.last().appendChild(s.childNodes.asList().filter { it.nodeType == Node.TEXT_NODE }.first())
// other solution would be
// pathLast().innerHTML += entity.text
}
override fun onTagContentUnsafe(block: Unsafe.() -> Unit) {
with(DefaultUnsafe()) {
block()
path.last().innerHTML += toString()
}
}
override fun onTagComment(content: CharSequence) {
if (path.isEmpty()) {
throw IllegalStateException("No current DOM node")
}
path.last().appendChild(document.createComment(content.toString()))
}
override fun finalize(): R = lastLeaved?.asR() ?: throw IllegalStateException("We can't finalize as there was no tags")
@Suppress("UnsafeCastFromDynamic")
private fun HTMLElement.asR(): R = this.asDynamic()
}
fun Document.createTree() : TagConsumer<HTMLElement> = JSDOMBuilder(this)
val Document.create : TagConsumer<HTMLElement>
get() = JSDOMBuilder(this)
fun Node.append(block: TagConsumer<HTMLElement>.() -> Unit): List<HTMLElement> =
ArrayList<HTMLElement>().let { result ->
ownerDocumentExt.createTree().onFinalize { it, partial ->
if (!partial) {
result.add(it); appendChild(it)
}
}.block()
result
}
fun Node.prepend(block: TagConsumer<HTMLElement>.() -> Unit): List<HTMLElement> =
ArrayList<HTMLElement>().let { result ->
ownerDocumentExt.createTree().onFinalize { it, partial ->
if (!partial) {
result.add(it)
insertBefore(it, firstChild)
}
}.block()
result
}
val HTMLElement.append: TagConsumer<HTMLElement>
get() = ownerDocumentExt.createTree().onFinalize { element, partial ->
if (!partial) {
this@append.appendChild(element)
}
}
val HTMLElement.prepend: TagConsumer<HTMLElement>
get() = ownerDocumentExt.createTree().onFinalize { element, partial ->
if (!partial) {
this@prepend.insertBefore(element, this@prepend.firstChild)
}
}
private val Node.ownerDocumentExt: Document
get() = when {
this is Document -> this
else -> ownerDocument ?: throw IllegalStateException("Node has no ownerDocument")
}
/**
* Provides a short access to document elements by ID via delegated
* property syntax. Received element is not cached and received
* directly from the [Document] by calling [Document.getElementById]
* function on every property access. Throws an exception if element
* is not found or has different type
*
* To access an element with `theId` ID use the following property declaration
* ```
* val theId by document.gettingElementById
* ```
*
* To access an element of specific type, just add it to the property declaration
* ```
* val theId: HTMLImageElement by document.gettingElementById
* ```
*/
inline val Document.gettingElementById get() = DocumentGettingElementById(this)
/**
* Implementation details of [Document.gettingElementById]
* @see Document.gettingElementById
*/
inline class DocumentGettingElementById(val document: Document) {
/**
* Implementation details of [Document.gettingElementById]. Delegated property
* @see Document.gettingElementById
*/
inline operator fun <reified T : Element> getValue(x: Any?, kProperty: KProperty<*>): T {
val id = kProperty.name
val element = document.getElementById(id) ?: throw NullPointerException("Element $id is not found")
return element as? T ?: throw ClassCastException(
"Element $id has type ${element::class.simpleName} which does not implement ${T::class.simpleName}"
)
}
}