Testing vdom

This commit is contained in:
2018-08-01 19:58:56 +02:00
parent 9b66633230
commit ae3820e86f
9 changed files with 573 additions and 131 deletions

View File

@@ -1,6 +1,5 @@
package nl.astraeus.komp
import org.w3c.dom.Element
import org.w3c.dom.Node
import org.w3c.dom.get
@@ -12,32 +11,74 @@ import org.w3c.dom.get
object DomDiffer {
fun replaceDiff(newElement: Element, oldElement: Element): Element {
if (!newElement.isEqualNode(oldElement)) {
replaceNode(newElement, oldElement)
fun replaceDiff(oldElement: KompElement, newElement: KompElement, element: Node): Node {
if (oldElement.isKomponent() && newElement.isKomponent()) {
if (oldElement.equals(newElement)) {
newElement.komponent?.update()
return newElement.komponent?.element!!
} else {
return Komponent.replaceNode(newElement, element)
}
} else if (!oldElement.isKomponent() && newElement.isKomponent()) {
return Komponent.replaceNode(newElement, element)
} else if (!oldElement.equals(newElement)) {
return Komponent.replaceNode(newElement, element)
} else {
if (oldElement.children == null && newElement.children != null) {
for (index in 0 until newElement.children.size) {
Komponent.appendElement(element, newElement.children[index])
}
} else if (oldElement.children != null && newElement.children == null) {
while(element.firstChild != null) {
element.removeChild(element.firstChild!!)
}
} else if (oldElement.children != null && newElement.children != null) {
if (oldElement.children.size > newElement.children.size) {
val toRemove = oldElement.children.size - newElement.children.size
var removed = 0
var index = 0
return newElement
} else {
// think of the children!
for (index in 0 until newElement.children.length) {
val newChild = newElement.children[index]
val oldChild = oldElement.children[index]
while(index < newElement.children.size) {
val childNode = element.childNodes[index]
if (newChild is Element && oldChild is Element) {
replaceDiff(newChild, oldChild)
} else {
throw IllegalStateException("Children are not nodes! $newChild, $oldChild")
}
if (childNode == null) {
println("Warn childNode is null!")
} else {
if (!oldElement.children[index + removed].equals(newElement.children[index]) && removed < toRemove) {
element.removeChild(childNode)
removed++
} else {
replaceDiff(oldElement.children[index + removed], newElement.children[index], childNode)
index++
}
}
}
while(removed < toRemove) {
element.lastChild?.also {
Komponent.removeElement(it)
}
return oldElement
removed++
}
} else {
for (index in 0 until newElement.children.size) {
val childNode = element.childNodes[index]
if (childNode == null) {
Komponent.appendElement(element, newElement.children[index])
//} else if (!oldElement.children[index + removed].equals(newElement.children[index]) && removed < toRemove) {
} else {
replaceDiff(oldElement.children[index], newElement.children[index], childNode)
}
}
}
}
}
private fun replaceNode(newElement: Node, oldElement: Node) {
val parent = oldElement.parentElement ?: throw IllegalStateException("oldElement has no parent! $oldElement")
parent.replaceChild(newElement, oldElement)
return element
}
}
}

View File

@@ -0,0 +1,324 @@
package nl.astraeus.komp
import kotlinx.html.Entities
import kotlinx.html.Tag
import kotlinx.html.TagConsumer
import kotlinx.html.Unsafe
import kotlinx.html.div
import kotlinx.html.h1
import kotlinx.html.hr
import kotlinx.html.js.onClickFunction
import kotlinx.html.span
import org.w3c.dom.Node
import org.w3c.dom.events.Event
import kotlin.browser.document
/**
* User: rnentjes
* Date: 8-5-18
* Time: 21:58
*/
class KompElement(
val komponent: Komponent?,
var text: String,
var unsafe: Boolean = false,
val attributes: MutableMap<String, String>? = null,
val children: MutableList<KompElement>? = null,
val events: MutableMap<String, (Event) -> Unit>? = null
) {
constructor(text: String, isText: Boolean = true) : this(
null,
text,
false,
if (isText) {
null
} else {
HashMap()
},
if (isText) {
null
} else {
ArrayList()
},
if (isText) {
null
} else {
HashMap()
}
)
constructor(komponent: Komponent) : this(
komponent,
"",
false,
null,
null,
null
)
/* shallow equals check */
fun equals(other: KompElement): Boolean {
if (komponent != null) {
return komponent == other.komponent
} else if (other.isText() || isText()) {
return other.text == text
} else {
if (other.attributes?.size != attributes?.size || other.events?.size != events?.size) {
return false
} else {
(attributes?.entries)?.forEach { entry ->
if (other.attributes?.get(entry.key) != entry.value) {
return false
}
}
(events?.entries)?.forEach { entry ->
if (other.events?.get(entry.key) != entry.value) {
return false
}
}
}
}
return true
}
fun isText() = attributes == null && komponent == null
fun isKomponent() = komponent != null
fun create(): Node = when {
komponent != null -> {
komponent.element?.also {
Komponent.remove(it)
}
val kompElement = komponent.kompElement ?: komponent.create()
val element = kompElement.create()
komponent.kompElement = kompElement
komponent.element = element
Komponent.define(element, komponent)
element
}
isText() -> document.createTextNode(text)
else -> {
val result = document.createElement(text)
(attributes?.entries)?.forEach { entry ->
result.setAttribute(entry.key, entry.value)
}
(events?.entries)?.forEach { event ->
val key = if (event.key.startsWith("on")) {
event.key.substring(2)
} else {
event.key
}
result.addEventListener(key, event.value)
}
children?.forEach { child ->
result.append(child.create())
}
result
}
}
override fun toString(): String {
return this.toString("")
}
fun toString(indent: String = ""): String {
val result = StringBuilder()
if (attributes != null) {
result.append(indent)
result.append("<")
}
result.append(text)
if (attributes != null) {
for (entry in attributes.entries) {
result.append("\n")
result.append(indent)
result.append(indent)
result.append(entry.key)
result.append("=\"")
result.append(entry.value)
result.append("\"")
}
events?.apply {
for (event in this.entries) {
result.append("\n")
result.append(indent)
result.append(indent)
result.append(event.key)
result.append("=")
result.append(event.value)
}
}
result.append("\n")
result.append(indent)
result.append(">")
children?.apply {
result.append("\n")
result.append(indent)
for (child in this) {
result.append(child.toString(" $indent"))
}
}
result.append("\n")
result.append(indent)
result.append("</")
result.append(text)
result.append(">")
}
return result.toString()
}
}
class KompConsumer : TagConsumer<KompElement> {
val stack = ArrayList<KompElement>()
var currentTag: KompElement? = null
override fun finalize(): KompElement {
return currentTag!!
}
override fun onTagAttributeChange(tag: Tag, attribute: String, value: String?) {
//console.log("KC.onTagAttributeChange", tag, attribute, value)
if (value != null) {
currentTag?.attributes?.put(attribute, value)
}
}
override fun onTagContent(content: CharSequence) {
//console.log("KC.onTagContent", content)
currentTag?.children?.add(KompElement(content.toString(), true))
}
override fun onTagContentEntity(entity: Entities) {
console.log("KC.onTagContentEntity", entity)
}
override fun onTagContentUnsafe(block: Unsafe.() -> Unit) {
//console.log("KC.onTagContentUnsafe", block)
throw IllegalStateException("unsafe blocks are not supported atm.")
}
override fun onTagEnd(tag: Tag) {
//console.log("KC.onTagEnd", tag)
check(currentTag != null)
check(currentTag?.children != null)
val ke = currentTag
if (stack.isNotEmpty()) {
currentTag = stack.removeAt(stack.lastIndex)
if (ke != null) {
currentTag?.children?.add(ke)
}
}
}
override fun onTagEvent(tag: Tag, event: String, value: (Event) -> Unit) {
//console.log("KC.onTagEvent", tag, event, value)
currentTag?.events?.put(event, value)
}
override fun onTagStart(tag: Tag) {
//console.log("KC.onTagStart", tag)
currentTag?.apply {
stack.add(this)
}
currentTag = KompElement(tag.tagName, false)
for (attr in tag.attributes.entries) {
currentTag?.attributes?.set(attr.key, attr.value)
}
}
fun appendKomponent(komponent: Komponent) {
currentTag?.children?.add(KompElement(komponent))
}
}
class KompTest : Komponent() {
var counter = 0
var show = false
var child: KompTest? = null
override fun render(consumer: KompConsumer) = consumer.div {
h1 {
+"Test"
}
hr { }
span {
+"Clicks $counter"
onClickFunction = {
println("click")
counter++
update()
}
}
if (show) {
hr {}
span {
+"Hide element"
onClickFunction = {
show = false
update()
}
}
if (child == null) {
child = KompTest()
}
include(child!!)
} else {
hr {}
span {
+"Show element"
onClickFunction = {
show = true
console.log("show", this)
update()
}
}
}
}
}
/*
fun main(args: Array<String>) {
val test = KompTest()
println(test.create())
Komponent.create(document.body!!, KompTest())
}
*/

View File

@@ -1,112 +1,168 @@
package nl.astraeus.komp
import kotlinx.html.HtmlBlockTag
import kotlinx.html.TagConsumer
import kotlinx.html.dom.create
import org.w3c.dom.Element
import org.w3c.dom.HTMLElement
import kotlin.browser.document
import org.w3c.dom.Node
import kotlin.collections.component1
import kotlin.collections.component2
import kotlin.collections.set
fun HtmlBlockTag.include(component: Komponent) {
val result = component.render(this.consumer as TagConsumer<HTMLElement>)
val consumer = this.consumer
if (consumer is KompConsumer) {
consumer.appendKomponent(component)
}
component.element = result
nl.astraeus.komp.Komponent.define(result, component)
/*
val kc = this.consumer
val result = component.render(kc as KompConsumer)
val element = result.create()
component.element = element
Komponent.define(element, component, result)
*/
}
abstract class Komponent {
var element: Element? = null
var rendered = false
var element: Node? = null
var kompElement: KompElement? = null
var rendered = false
open fun create(): HTMLElement {
var elem =element
if (elem != null) {
remove(elem)
}
open fun create(): KompElement {
val result = render(KompConsumer())
elem = render(document.create)
rendered = true
return result
}
define(elem, this)
abstract fun render(consumer: KompConsumer): KompElement
this.element = elem
open fun refresh() {
if (!rendered) {
refresh(element)
} else {
update()
}
}
return elem
open fun update() {
refresh(element)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class.js != other::class.js) return false
other as Komponent
if (kompElement != other.kompElement) return false
if (rendered != other.rendered) return false
return true
}
override fun hashCode(): Int {
var result = kompElement?.hashCode() ?: 0
result = 31 * result + rendered.hashCode()
return result
}
companion object {
private val elements: MutableMap<Node, Komponent> = HashMap()
fun replaceNode(newKomponent: KompElement, oldElement: Node): Node {
val newElement = newKomponent.create()
val parent = oldElement.parentElement ?: throw IllegalStateException("oldElement has no parent! $oldElement")
parent.replaceChild(newElement, oldElement)
elements[oldElement]?.also {
elements.remove(oldElement)
}
newKomponent.komponent?.also {
it.element = newElement
elements[newElement] = it
}
return newElement
}
abstract fun render(consumer: TagConsumer<HTMLElement>): HTMLElement
fun removeElement(element: Node) {
val parent = element.parentElement ?: throw IllegalArgumentException("Element has no parent!?")
open fun refresh() {
if (rendered) {
refresh(element)
parent.removeChild(element)
elements.remove(element)
}
fun appendElement(element: Node, kompElement: KompElement) {
element.appendChild(kompElement.create())
}
fun define(element: Node, component: Komponent) {
elements[element] = component
}
fun create(parent: HTMLElement, component: Komponent, insertAsFirst: Boolean = false) {
component.kompElement = component.create()
val element = component.kompElement?.create()
if (element != null) {
if (insertAsFirst && parent.childElementCount > 0) {
parent.insertBefore(element, parent.firstChild)
} else {
update()
parent.appendChild(element)
}
component.element = element
elements[element] = component
}
}
open fun update() {
refresh(element)
fun remove(element: Node) {
val component = elements[element]
elements.remove(element)
}
companion object {
private val elements: MutableMap<Element, Komponent> = HashMap()
private val elementList: MutableList<Komponent> = ArrayList()
fun define(element: HTMLElement, component: Komponent) {
elements[element] = component
elementList.add(component)
}
fun create(parent: HTMLElement, component: Komponent, insertAsFirst: Boolean = false) {
val element = component.create()
if (insertAsFirst && parent.childElementCount > 0) {
parent.insertBefore(element, parent.firstChild)
} else {
parent.appendChild(element)
}
elements[element] = component
elementList.add(component)
}
fun remove(element: Element) {
val component = elements[element]
elements.remove(element)
elementList.remove(component)
}
@JsName("remove")
fun remove(component: Komponent) {
for ((key, value) in elements) {
if (value == component) {
elements.remove(key)
}
}
elementList.remove(component)
}
fun refresh(component: Komponent) {
refresh(component.element)
}
fun refresh(element: Element?) {
if (element != null) {
elements[element]?.let {
//val parent = element.parentElement
val newElement = it.create()
//parent?.replaceChild(newElement, element)
val replacedElement = DomDiffer.replaceDiff(newElement, element)
it.element = replacedElement
elements.remove(replacedElement)
elements[replacedElement] = it
}
}
@JsName("remove")
fun remove(component: Komponent) {
for ((key, value) in elements) {
if (value == component) {
elements.remove(key)
}
}
}
fun refresh(component: Komponent) {
refresh(component.element)
}
fun refresh(element: Node?) {
if (element != null) {
elements[element]?.let {
//val parent = element.parentElement
val newElement = it.create()
val kompElement = it.kompElement
val replacedElement = if (kompElement != null) {
DomDiffer.replaceDiff(kompElement, newElement, element)
} else {
newElement.create()
}
it.kompElement = newElement
it.element = replacedElement
elements.remove(element)
elements[replacedElement] = it
it.rendered = true
}
}
}
}
}

View File

@@ -3,7 +3,6 @@ package nl.astraeus.komp
import kotlinx.html.dom.create
import kotlinx.html.js.div
import kotlinx.html.style
import org.w3c.dom.HTMLElement
import kotlin.browser.document
/**
@@ -37,16 +36,20 @@ abstract class SizedKomponent(
this.size = size
}
override fun create(): HTMLElement {
override fun create(): KompElement {
val innerResult = super.create()
val result = document.create.div {
style = "left: ${left}px; top: ${top}px; width: ${width}px; height: ${height}px;" // sizing here
}
/*
result.appendChild(innerResult)
this.element = result
return result
*/
return innerResult
}
}

View File

@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Bla</title>
</head>
<body>
<script src="../../kotlin-js-min/main/kotlin.js"></script>
<script src="../../kotlin-js-min/main/kotlinx-html-js.js"></script>
<script src="../../kotlin-js-min/main/komp.js"></script>
</body>
</html>