Initial commit

This commit is contained in:
rnentjes
2017-04-01 17:43:13 +02:00
commit c636542b9e
21 changed files with 616 additions and 0 deletions

View File

@@ -0,0 +1,39 @@
package nl.astraeus.komp
import kotlinx.html.DIV
import kotlinx.html.TagConsumer
import kotlinx.html.dom.create
import org.w3c.dom.HTMLElement
import kotlin.browser.document
fun DIV.include(component: HtmlComponent) {
val result = component.render(this.consumer as TagConsumer<HTMLElement>)
component.element = result
Komp.define(result, component)
}
abstract class HtmlComponent {
var element: HTMLElement? = null
fun create(): HTMLElement {
var elem =element
if (elem != null) {
Komp.remove(elem)
}
elem = render(document.create)
Komp.define(elem, this)
this.element = elem
return elem
}
abstract fun render(consumer: TagConsumer<HTMLElement>): HTMLElement
fun refresh() {
Komp.refresh(element)
}
}

View File

@@ -0,0 +1,57 @@
package nl.astraeus.komp
import org.w3c.dom.HTMLElement
/**
* User: rnentjes
* Date: 29-3-17
* Time: 15:46
*/
object Komp {
private val elements: MutableMap<HTMLElement, HtmlComponent> = HashMap()
fun define(element: HTMLElement, component: HtmlComponent) {
elements[element] = component
}
fun create(parent: HTMLElement, component: HtmlComponent) {
val element = component.create()
parent.appendChild(element)
elements[element] = component
}
fun remove(element: HTMLElement) {
elements.remove(element)
}
@JsName("remove")
fun remove(component: HtmlComponent) {
for ((key, value) in elements) {
if (value == component) {
elements.remove(key)
}
}
}
fun refresh(component: HtmlComponent) {
refresh(component.element)
}
fun refresh(element: HTMLElement?) {
if (element != null) {
val comp = elements[element]
if (element is HTMLElement && comp != null) {
val parent = element.parentElement
val newElement = comp.create()
parent?.replaceChild(newElement, element)
}
}
}
}