diff --git a/.gitignore b/.gitignore index 90b0368..bf11bb6 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,6 @@ # Created by .ignore support plugin (hsz.mobi) +build +.gradle web/js/generated gradle.properties local.properties diff --git a/build.gradle.kts b/build.gradle.kts index d1b0de8..54a0c16 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,24 +1,19 @@ plugins { - kotlin("multiplatform") version "1.4.32" + kotlin("multiplatform") version "1.5.20" `maven-publish` } group = "nl.astraeus" -version = "0.3.0-SNAPSHOT" +version = "0.4.1" repositories { mavenCentral() - jcenter() } kotlin { - /* Targets configuration omitted. - * To find out how to configure the targets, please follow the link: - * https://kotlinlang.org/docs/reference/building-mpp-with-gradle.html#setting-up-targets */ js(BOTH) { browser { - //produceKotlinLibrary() testTask { useKarma { useChromeHeadless() @@ -32,7 +27,7 @@ kotlin { dependencies { implementation(kotlin("stdlib-common")) - api("org.jetbrains.kotlinx:kotlinx-html-js:0.7.2") + api("org.jetbrains.kotlinx:kotlinx-html-js:0.7.3") } } val jsMain by getting { @@ -53,7 +48,7 @@ publishing { if (project.properties["nexusUsername"] != null) { maven { name = "releases" - url = uri("http://nexus.astraeus.nl/nexus/content/repositories/releases") + url = uri("https://nexus.astraeus.nl/nexus/content/repositories/releases") credentials { val nexusUsername: String by project val nexusPassword: String by project @@ -64,7 +59,7 @@ publishing { } maven { name = "snapshots" - url = uri("http://nexus.astraeus.nl/nexus/content/repositories/snapshots") + url = uri("https://nexus.astraeus.nl/nexus/content/repositories/snapshots") credentials { val nexusUsername: String by project val nexusPassword: String by project diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 6e17301..591af2e 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ #Wed Mar 04 13:29:12 CET 2020 -distributionUrl=https\://services.gradle.org/distributions/gradle-6.2-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-7.1-all.zip distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStorePath=wrapper/dists diff --git a/komp.commonMain.iml b/komp.commonMain.iml index bafe558..7458162 100644 --- a/komp.commonMain.iml +++ b/komp.commonMain.iml @@ -1,25 +1,25 @@ - + - + SOURCE_SET_HOLDER - \ No newline at end of file diff --git a/komp.commonTest.iml b/komp.commonTest.iml index 4cab7e0..f4a10e9 100644 --- a/komp.commonTest.iml +++ b/komp.commonTest.iml @@ -1,28 +1,28 @@ - + - + SOURCE_SET_HOLDER jsLegacyBrowserTest|komp:jsTest|jsLegacy - \ No newline at end of file diff --git a/komp.iml b/komp.iml index 6696c55..3f12e56 100644 --- a/komp.iml +++ b/komp.iml @@ -1,5 +1,5 @@ - + diff --git a/komp.ipr b/komp.ipr index 1d16b4e..3007d5e 100644 --- a/komp.ipr +++ b/komp.ipr @@ -61,6 +61,18 @@ + + $PROJECT_DIR$/build/libs + + + + + + $PROJECT_DIR$/build/libs + + + + + + @@ -380,122 +466,50 @@ - - - - + - + - + - + - + - + - + - + - + - + - + - + - + - + - - - - - - - - - - - - - - - - - - - + diff --git a/komp.jsMain.iml b/komp.jsMain.iml index 266512e..088f8eb 100644 --- a/komp.jsMain.iml +++ b/komp.jsMain.iml @@ -1,8 +1,8 @@ - + - + komp:commonMain komp.commonMain @@ -10,25 +10,25 @@ COMPILATION_AND_SOURCE_SET_HOLDER - - + - - + + - - - + + + \ No newline at end of file diff --git a/komp.jsTest.iml b/komp.jsTest.iml index 429f5ff..6524dbf 100644 --- a/komp.jsTest.iml +++ b/komp.jsTest.iml @@ -1,8 +1,8 @@ - + - + komp:commonTest komp.commonTest @@ -15,25 +15,25 @@ - - + @@ -58,13 +58,29 @@ - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/settings.gradle.kts b/settings.gradle.kts index 812c733..606c7d8 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -12,5 +12,3 @@ pluginManagement { } rootProject.name = "komp" - -enableFeaturePreview("GRADLE_METADATA") diff --git a/src/jsMain/kotlin/nl/astraeus/komp/HtmlBuilder.kt b/src/jsMain/kotlin/nl/astraeus/komp/HtmlBuilder.kt index 4b779c1..b7e3098 100644 --- a/src/jsMain/kotlin/nl/astraeus/komp/HtmlBuilder.kt +++ b/src/jsMain/kotlin/nl/astraeus/komp/HtmlBuilder.kt @@ -1,114 +1,458 @@ package nl.astraeus.komp +import kotlinx.browser.document import kotlinx.html.DefaultUnsafe import kotlinx.html.Entities +import kotlinx.html.FlowOrMetaDataOrPhrasingContent import kotlinx.html.Tag import kotlinx.html.TagConsumer import kotlinx.html.Unsafe +import org.w3c.dom.Element +import org.w3c.dom.HTMLElement +import org.w3c.dom.HTMLSpanElement +import org.w3c.dom.Node +import org.w3c.dom.asList import org.w3c.dom.events.Event +import org.w3c.dom.get -interface HtmlConsumer : TagConsumer { - fun append(node: VDOMElement) +private var currentElement: Element? = null + +interface HtmlConsumer : TagConsumer { + fun append(node: Element) + fun include(komponent: Komponent) } +fun Int.asSpaces(): String { + val result = StringBuilder() + repeat(this) { + result.append(" ") + } + return result.toString() +} + +fun FlowOrMetaDataOrPhrasingContent.currentElement(): Element = (currentElement as? Element) ?: error("No current element defined!") + +fun Element.printTree(indent: Int = 0): String { + val result = StringBuilder() + + result.append(indent.asSpaces()) + result.append(tagName) + if (this.namespaceURI != "http://www.w3.org/1999/xhtml") { + result.append(" [") + result.append(namespaceURI) + result.append("]") + } + result.append(" (") + var first = true + if (hasAttributes()) { + for (index in 0 until attributes.length) { + if (!first) { + result.append(", ") + } else { + first = false + } + result.append(attributes[index]?.localName) + result.append("=") + result.append(attributes[index]?.value) + } + } + result.append(") {") + result.append("\n") + for ((name, event) in getKompEvents()) { + result.append(indent.asSpaces()) + result.append("on") + result.append(name) + result.append(" -> ") + result.append(event) + result.append("\n") + } + for (index in 0 until childNodes.length) { + childNodes[index]?.let { + if (it is Element) { + result.append(it.printTree(indent + 2)) + } else { + result.append((indent + 2).asSpaces()) + result.append(it.textContent) + result.append("\n") + } + } + } + result.append(indent.asSpaces()) + result.append("}\n") + + return result.toString() +} + +fun Element.clearKompAttributes() { + this.asDynamic()["komp-attributes"] = mutableListOf() +} + +fun Element.getKompAttributes(): MutableList { + var result: MutableList? = this.asDynamic()["komp-attributes"] as MutableList? + + if (result == null) { + result = mutableListOf() + + this.asDynamic()["komp-attributes"] = result + } + + return result +} + +fun Element.setKompAttribute(name: String, value: String) { + val setAttrs: MutableList = getKompAttributes() + setAttrs.add(name) + + if (this.getAttribute(name) != value) { + if (Komponent.logReplaceEvent) { + console.log("Setting attribute [$name,$value] on $this (old: ${this.getAttribute(name)})") + } + + setAttribute(name, value) + } +} + +fun Element.clearKompEvents() { + for ((name, event) in getKompEvents()) { + currentElement?.removeEventListener(name, event) + } + + this.asDynamic()["komp-events"] = mutableMapOf Unit>() +} + +fun Element.setKompEvent(name: String, event: (Event) -> Unit) { + val eventName: String = if (name.startsWith("on")) { + name.substring(2) + } else { + name + } + + val events: MutableMap Unit> = getKompEvents() + + events[eventName]?.let { + println("Warn event already defined!") + currentElement?.removeEventListener(eventName, it) + } + + events[eventName] = event + + this.asDynamic()["komp-events"] = events + + if (Komponent.logReplaceEvent) { + console.log("Setting events [$eventName] on $this") + } + + this.addEventListener(eventName, event) +} + +fun Element.getKompEvents(): MutableMap Unit> { + return this.asDynamic()["komp-events"] ?: mutableMapOf() +} + +data class ElementIndex( + val parent: Node, + var childIndex: Int +) + +fun ArrayList.currentParent(): Node { + this.lastOrNull()?.let { + return it.parent + } + + throw IllegalStateException("currentParent should never be null!") +} + +fun ArrayList.currentElement(): Node? { + this.lastOrNull()?.let { + return it.parent.childNodes[it.childIndex] + } + + return null +} + +fun ArrayList.nextElement() { + this.lastOrNull()?.let { + it.childIndex++ + } +} + +fun ArrayList.pop() { + this.removeLast() +} + +fun ArrayList.push(element: Node) { + this.add(ElementIndex(element, 0)) +} + +fun ArrayList.replace(new: Node) { + if (this.currentElement() != null) { + this.currentElement()?.parentElement?.replaceChild(new, this.currentElement()!!) + } else { + this.last().parent.appendChild(new) + } +} + +fun Node.asElement() = this as? HTMLElement + class HtmlBuilder( - val baseHash: Int + val parent: Element, + var childIndex: Int = 0 ) : HtmlConsumer { - private val path = arrayListOf() - private var lastLeaved: VDOMElement? = null + private var currentPosition = arrayListOf() + var currentNode: Node? = null + var root: Element? = null + + init { + currentPosition.add(ElementIndex(parent, childIndex)) + } + + constructor(position: ElementIndex) : this(position.parent as Element, position.childIndex) + + override fun include(komponent: Komponent) { + komponent.create( + currentPosition.last().parent as Element, + currentPosition.last().childIndex + ) + currentPosition.nextElement() + } + + override fun append(node: Element) { + currentPosition.replace(node) + currentPosition.nextElement() + } + + fun logReplace(msg: String) { + if (Komponent.logReplaceEvent) { + console.log(msg) + } + } override fun onTagStart(tag: Tag) { - val element = VDOMElement(baseHash, tag.tagName, tag.namespace) + //logReplace"onTagStart, [${tag.tagName}, ${tag.namespace}], currentPosition: $currentPosition") + currentNode = currentPosition.currentElement() - for (entry in tag.attributesEntries) { - element.setAttribute(entry.key, entry.value) + if (currentNode == null) { + //logReplace"onTagStart, currentNode1: $currentNode") + currentNode = if (tag.namespace != null) { + document.createElementNS(tag.namespace, tag.tagName) + } else { + document.createElement(tag.tagName) + } + + //logReplace"onTagStart, currentElement1.1: $currentNode") + currentPosition.currentParent().appendChild(currentNode!!) + } else if ( + !currentNode?.asElement()?.tagName.equals(tag.tagName, true) || + ( + tag.namespace != null && + !currentNode?.asElement()?.namespaceURI.equals(tag.namespace, true) + ) + ) { + //logReplace"onTagStart, currentElement, namespace: ${currentNode?.asElement()?.namespaceURI} -> ${tag.namespace}") + //logReplace"onTagStart, currentElement, replace: ${currentNode?.asElement()?.tagName} -> ${tag.tagName}") + currentNode = if (tag.namespace != null) { + document.createElementNS(tag.namespace, tag.tagName) as Element + } else { + document.createElement(tag.tagName) as Element + } + + currentPosition.replace(currentNode!!) + } else { + //logReplace"onTagStart, same node type") } - if (path.isNotEmpty()) { - path.last().appendChild(element) + currentElement = currentNode as? Element ?: currentElement + + if (currentNode is Element) { + if (root == null) { + //logReplace"Setting root: $currentNode") + root = currentNode as Element + } + + currentElement?.clearKompAttributes() + currentElement?.clearKompEvents() + + for (entry in tag.attributesEntries) { + currentElement!!.setKompAttribute(entry.key, entry.value) + } } - path.add(element) + //logReplace"onTagStart, currentElement2: $currentNode") + + currentPosition.push(currentNode!!) + } + + private fun checkTag(tag: Tag) { + check(currentElement != null) { + js("debugger") + "No current tag" + } + check(currentElement?.tagName.equals(tag.tagName, ignoreCase = true)) { + js("debugger") + "Wrong current tag" + } } override fun onTagAttributeChange(tag: Tag, attribute: String, value: String?) { - when { - path.isEmpty() -> throw IllegalStateException("No current tag") - path.last().content.toLowerCase() != tag.tagName.toLowerCase() -> throw IllegalStateException("Wrong current tag") - else -> path.last().let { node -> - if (value == null) { - node.removeAttribute(attribute) - } else { - node.setAttribute(attribute, value) - } - } + //logReplace"onTagAttributeChange, ${tag.tagName} [$attribute, $value]") + checkTag(tag) + + if (value == null) { + currentElement?.removeAttribute(attribute) + } else { + currentElement?.setKompAttribute(attribute, value) } } override fun onTagEvent(tag: Tag, event: String, value: (Event) -> Unit) { - when { - path.isEmpty() -> throw IllegalStateException("No current tag") - path.last().content.toLowerCase() != tag.tagName.toLowerCase() -> throw IllegalStateException("Wrong current tag") - else -> path.last().setKompEvent(event, value) - } + //logReplace"onTagEvent, ${tag.tagName} [$event, $value]") + + checkTag(tag) + + currentElement?.setKompEvent(event, value) } override fun onTagEnd(tag: Tag) { - if (path.isEmpty() || path.last().content.toLowerCase() != tag.tagName.toLowerCase()) { - throw IllegalStateException("We haven't entered tag ${tag.tagName} but trying to leave") + //logReplace"onTagEnd: ${tag.tagName}, $currentElement") + //logReplace"onTagEnd: ${tag.tagName}, $currentPosition") + + while (currentPosition.currentElement() != null) { + currentPosition.currentElement()?.let { + //logReplace"Removing $it") + it.parentElement?.removeChild(it) + } } - lastLeaved = path.removeAt(path.lastIndex) - lastLeaved?.updateChildHash() + checkTag(tag) + + //logReplace"onTagEnd, pre-pop: $currentPosition") + + currentPosition.pop() + + //logReplace"onTagEnd, post-pop: $currentPosition") + + val setAttrs: List = currentElement.asDynamic()["komp-attributes"] ?: listOf() + + // remove attributes that where not set + if (currentElement?.hasAttributes() == true) { + for (index in 0 until (currentElement?.attributes?.length ?: 0)) { + val attr = currentElement?.attributes?.get(index) + if (attr != null) { + if (!setAttrs.contains(attr.name)) { + currentElement?.removeAttribute(attr.name) + } + } + } + } + + currentPosition.nextElement() + + currentElement = currentElement?.parentElement as? HTMLElement + + //logReplace"onTagEnd, popped: $currentElement") } override fun onTagContent(content: CharSequence) { - if (path.isEmpty()) { - throw IllegalStateException("No current DOM node") + //logReplace"onTagContent, [$content]") + + check(currentElement != null) { + "No current DOM node" } - path.last().appendChild(VDOMElement(baseHash, content.toString(), type = VDOMElementType.TEXT)) + //logReplace"Tag content: $content") + + if (currentElement?.textContent != content.toString()) { + currentElement?.textContent = content.toString() + } + + currentPosition.nextElement() } override fun onTagContentEntity(entity: Entities) { - if (path.isEmpty()) { - throw IllegalStateException("No current DOM node") + //logReplace"onTagContentEntity, [${entity.text}]") + + check(currentElement != null) { + "No current DOM node" } - // stupid hack as browsers don't support createEntityReference - path.last().appendChild(VDOMElement(baseHash, entity.text, type = VDOMElementType.ENTITY)) - } - - override fun append(node: VDOMElement) { - path.last().appendChild(node) + val s = document.createElement("span") as HTMLSpanElement + s.innerText = entity.text + currentPosition.replace( + s.childNodes.asList().firstOrNull() ?: document.createTextNode(entity.text) + ) + currentPosition.nextElement() } override fun onTagContentUnsafe(block: Unsafe.() -> Unit) { with(DefaultUnsafe()) { block() - path.last().appendChild(VDOMElement(baseHash, toString(), type = VDOMElementType.UNSAFE)) + val textContent = toString() + + //logReplace"onTagContentUnsafe, [$textContent]") + + var namespace: String? = null + + if (currentPosition.currentParent().nodeType == 1.toShort()) { + val element = currentPosition.currentParent() as Element + + namespace = when (Komponent.unsafeMode) { + UnsafeMode.UNSAFE_ALLOWED -> { + element.namespaceURI + } + UnsafeMode.UNSAFE_SVG_ONLY -> { + if (element.namespaceURI == "http://www.w3.org/2000/svg") { + element.namespaceURI + } else { + null + } + } + else -> { + null + } + } + } + + //logReplace"onTagContentUnsafe, namespace: [$namespace]") + + if (Komponent.unsafeMode == UnsafeMode.UNSAFE_ALLOWED || + (Komponent.unsafeMode == UnsafeMode.UNSAFE_SVG_ONLY && namespace == "http://www.w3.org/2000/svg") + ) { + if (currentElement?.innerHTML != textContent) { + currentElement?.innerHTML = textContent + } + } else if (currentElement?.textContent != textContent) { + currentElement?.textContent = textContent + } + + currentPosition.nextElement() } } override fun onTagComment(content: CharSequence) { - if (path.isEmpty()) { - throw IllegalStateException("No current DOM node") - } + //logReplace"onTagComment, [$content]") - path.last().appendChild(VDOMElement(baseHash, content.toString(), type = VDOMElementType.COMMENT)) + check(currentElement != null) { + "No current DOM node" + } + currentElement?.appendChild( + document.createComment(content.toString()) + ) + + currentPosition.nextElement() } - override fun finalize(): VDOMElement { - return lastLeaved ?: throw IllegalStateException("We can't finalize as there was no tags") + override fun finalize(): Element { + //logReplace"finalize, currentPosition: $currentPosition") + return root ?: throw IllegalStateException("We can't finalize as there was no tags") } companion object { - fun create(content: HtmlBuilder.() -> Unit): VDOMElement { - val komponent = DummyKomponent() - val consumer = HtmlBuilder(komponent.hashCode()) + fun create(content: HtmlBuilder.() -> Unit): Element { + val container = document.createElement("div") as HTMLElement + val consumer = HtmlBuilder(container, 0) content.invoke(consumer) - return consumer.finalize() + return consumer.root ?: error("error") } } } diff --git a/src/jsMain/kotlin/nl/astraeus/komp/Komponent.kt b/src/jsMain/kotlin/nl/astraeus/komp/Komponent.kt index 2bf0e6b..c7ab95d 100644 --- a/src/jsMain/kotlin/nl/astraeus/komp/Komponent.kt +++ b/src/jsMain/kotlin/nl/astraeus/komp/Komponent.kt @@ -1,16 +1,14 @@ package nl.astraeus.komp -import kotlinx.browser.document import kotlinx.browser.window import kotlinx.html.div -import org.w3c.dom.HTMLDivElement +import org.w3c.dom.Element import org.w3c.dom.HTMLElement import org.w3c.dom.Node import org.w3c.dom.css.CSSStyleDeclaration +import org.w3c.dom.get import kotlin.reflect.KProperty -typealias CssStyle = CSSStyleDeclaration.() -> Unit - class StateDelegate( val komponent: Komponent, initialValue: T @@ -31,112 +29,107 @@ class StateDelegate( inline fun Komponent.state(initialValue: T): StateDelegate = StateDelegate(this, initialValue) -fun HtmlConsumer.include(component: Komponent) { - append(component.create()) -} - -class DummyKomponent: Komponent() { +class DummyKomponent : Komponent() { override fun HtmlBuilder.render() { div { - + "dummy" + +"dummy" } } } +enum class UnsafeMode { + UNSAFE_ALLOWED, + UNSAFE_DISABLED, + UNSAFE_SVG_ONLY +} + abstract class Komponent { - private var createIndex = getNextCreateIndex() + val createIndex = getNextCreateIndex() private var dirty: Boolean = true - var vdom: VDOMElement? = null var element: Node? = null val declaredStyles: MutableMap = HashMap() - open fun create(): VDOMElement { - val consumer = HtmlBuilder(this.createIndex) - try { - consumer.render() - } catch (e: Throwable) { - println("Exception occurred in ${this::class.simpleName}.render() call!") + open fun create(parent: Element, childIndex: Int = 0) { + //parent.parentElement?.child + val builder = HtmlBuilder(parent, childIndex) - throw e - } - val result = consumer.finalize() - - if (result.id.isBlank()) { - result.id = "komp_${createIndex}" - } - - result.komponent = this - - vdom = result - - dirty = false - - return result + builder.render() + element = builder.root } abstract fun HtmlBuilder.render() + /** + * This method is called after the Komponent is updated + * + * note: it's not called at first render + */ + open fun onAfterUpdate() {} + fun requestUpdate() { dirty = true scheduleForUpdate(this) } - open fun style(className: String, vararg imports: CssStyle, block: CssStyle = {}) { - val style = (document.createElement("div") as HTMLDivElement).style - for (imp in imports) { - imp(style) - } - block(style) - declaredStyles[className] = style + /** + * Request an immediate update of this Komponent + * + * This will run immediately, make sure Komponents are not rendered multiple times + * Any scheduled updates will be run as well + */ + fun requestImmediateUpdate() { + dirty = true + runUpdateImmediately(this) } + /** + * This function can be overwritten if you know how to update the Komponent yourself + * + * HTMLBuilder.render() is called 1st time the component is rendered, after that this + * method will be called + */ open fun update() { refresh() } internal fun refresh() { - val oldElement = vdom + val currentElement = element - if (logRenderEvent) { - console.log("Rendering", this) - } - val newElement = create() - - element = if (oldElement != null && element != null) { - if (logReplaceEvent) { - console.log("DomDiffing", oldElement, newElement) - } - DiffPatch.updateNode(element!!, oldElement, newElement) + if (currentElement == null) { + error("element is null") } else { - if (logReplaceEvent) { - console.log("Create", newElement) + val parent = currentElement.parentElement as? HTMLElement ?: error("parent is null!?") + var childIndex = 0 + for (index in 0 until parent.children.length) { + if (parent.children[index] == currentElement) { + childIndex = index + } } - newElement.createElement() + val consumer = HtmlBuilder(parent, childIndex) + consumer.root = null + consumer.render() + element = consumer.root + dirty = false } - - vdom = newElement - dirty = false } companion object { private var nextCreateIndex: Int = 1 private var updateCallback: Int? = null private var scheduledForUpdate = mutableSetOf() + private var interceptor: (Komponent, () -> Unit) -> Unit = { _, block -> block() } var logRenderEvent = false var logReplaceEvent = false + var unsafeMode = UnsafeMode.UNSAFE_DISABLED fun create(parent: HTMLElement, component: Komponent, insertAsFirst: Boolean = false) { - val vdomElement = component.create() - val element = vdomElement.createElement() - component.element = element + component.create(parent) + } - if (insertAsFirst && parent.childElementCount > 0) { - parent.insertBefore(element, parent.firstChild) - } else { - parent.appendChild(element) - } + fun setUpdateInterceptor(block: (Komponent, () -> Unit) -> Unit) { + interceptor = block } private fun getNextCreateIndex() = nextCreateIndex++ @@ -151,6 +144,11 @@ abstract class Komponent { } } + private fun runUpdateImmediately(komponent: Komponent) { + scheduledForUpdate.add(komponent) + runUpdate() + } + private fun runUpdate() { val todo = scheduledForUpdate.sortedBy { komponent -> komponent.createIndex } @@ -159,25 +157,24 @@ abstract class Komponent { } todo.forEach { next -> - val element = next.element + interceptor(next) { + val element = next.element - if (element is HTMLElement) { - if (document.getElementById(element.id) != null) { + if (element is HTMLElement) { if (next.dirty) { if (logRenderEvent) { console.log("Update dirty ${next.createIndex}") } next.update() + next.onAfterUpdate() } else { if (logRenderEvent) { console.log("Skip ${next.createIndex}") } } } else { - console.log("Komponent element has no id, ", next, element) + console.log("Komponent element is null", next) } - } else { - console.log("Komponent element is null", next) } } diff --git a/src/jsTest/kotlin/nl/astraeus/komp/TestUpdate.kt b/src/jsTest/kotlin/nl/astraeus/komp/TestUpdate.kt index 6bb5610..c719938 100644 --- a/src/jsTest/kotlin/nl/astraeus/komp/TestUpdate.kt +++ b/src/jsTest/kotlin/nl/astraeus/komp/TestUpdate.kt @@ -1,12 +1,21 @@ package nl.astraeus.komp -import kotlinx.html.* +import kotlinx.browser.document +import kotlinx.html.div +import kotlinx.html.id import kotlinx.html.js.onClickFunction +import kotlinx.html.p +import kotlinx.html.span +import kotlinx.html.svg +import kotlinx.html.table +import kotlinx.html.td +import kotlinx.html.tr +import kotlinx.html.unsafe import org.w3c.dom.Element +import org.w3c.dom.HTMLDivElement import org.w3c.dom.HTMLElement import org.w3c.dom.get import kotlin.test.Test -import kotlin.test.assertTrue fun nodesEqual(element: Element, vdom: VDOMElement): Boolean { if (element.childNodes.length != vdom.childNodes.size) { @@ -41,104 +50,145 @@ fun nodesEqual(element: Element, vdom: VDOMElement): Boolean { return true } -class TestUpdate { - - @Test - fun testCompare() { - val dom1 = HtmlBuilder.create { - div { - div(classes = "bla") { - span { - +" Some Text " - } - table { - tr { - td { - +"Table column" - } - } - } - } - } +class TestKomponent : Komponent() { + override fun HtmlBuilder.render() { + div { + +"Test" } + } +} - val dom2 = HtmlBuilder.create { - div { - span { - id = "123" - - +"New dom!" - } - input { - value = "bla" - } - } +class Child1 : Komponent() { + override fun HtmlBuilder.render() { + div { + +"Child 1" } + } +} - var element = dom1.createElement() +class Child2 : Komponent() { + override fun HtmlBuilder.render() { + div { + +"Child 2" + } + } +} - assertTrue(nodesEqual(element as Element, dom1), "Created dom not equal to original") - - element = DiffPatch.updateNode(element, dom1, dom2) as HTMLElement - - assertTrue(nodesEqual(element, dom2), "Updated dom not equal to original") +class SimpleKomponent : Komponent() { + var hello = true + var append = HtmlBuilder.create { + p { + +"Appended" + } } - @Test - fun testCompare2() { - val dom1 = HtmlBuilder.create { - div { - div(classes = "bla") { - span { - +" Some Text " + + override fun HtmlBuilder.render() { + div("div_class") { + span { + svg { + unsafe { + +""" +

+ """.trimIndent() } - table { - tr { - th { - +"Header" - } - } - tr { - td { - +"Table column" - } - } + } + if (hello) { + div { + +"Hello" + } + } else { + span { + +"Good bye" } } } - } - - val dom2 = HtmlBuilder.create { div { - div { - span { - +"Other text" - } - } - span { + if (hello) { id = "123" - - +"New dom!" + +"div text" + } else { + +"div text goodbye" } - input { - value = "bla" - onClickFunction = { - println("Clickerdyclick!") + onClickFunction = if (hello) { + { + println("onClick") + } + } else { + { + println("onClick 2") } } } + if (hello) { + span { + +"2nd span" + } + } + //append(append) + if (hello) { + include(Child1()) + } else { + include(Child2()) + } + //append(append) } - - Komponent.logRenderEvent = true - - var element = dom1.createElement() - - assertTrue(nodesEqual(element as Element, dom1), "Created dom not equal to original") - - element = DiffPatch.updateNode(element, dom1, dom2) as HTMLElement - - assertTrue(nodesEqual(element, dom2), "Updated dom not equal to original") + } + +} + +class TestUpdate { + + @Test + fun testSimpleKomponent() { + val sk = SimpleKomponent() + val div = document.createElement("div") as HTMLDivElement + + Komponent.create(div, sk) + + println("SimpleKomponent: ${div.printTree()}") + + sk.hello = false + sk.requestImmediateUpdate() + + println("SimpleKomponent updated: ${div.printTree()}") + } + + @Test + fun testCreate() { + var elemTest: Element? = null + val element = HtmlBuilder.create { + div("div_class") { + id = "123" + +"Test" + + span("span_class") { + +"Span" + + elemTest = currentElement() + } + + table { + tr { + td { + +"column 1" + } + td { + +"column 2" + } + } + } + } + } + + println("Element: ${element.printTree()}") + println("divTst: ${elemTest?.printTree()}") + println("span class: ${ + elemTest?.getAttributeNames()?.joinToString + { "," } + }" + ) } }