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 8d06df2..84492cc 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,27 +1,23 @@ plugins { - kotlin("multiplatform") version "1.4.32" + kotlin("multiplatform") version "1.5.21" `maven-publish` } group = "nl.astraeus" -version = "0.2.6-SNAPSHOT" +version = "0.5.7-SNAPSHOT" 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() + useChromiumHeadless() + //useChromeHeadless() } } } @@ -32,7 +28,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 +49,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 +60,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 72350c6..be266c6 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 719f2ec..b17b328 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 6f0c251..a9e480b 100644 --- a/komp.iml +++ b/komp.iml @@ -1,5 +1,5 @@ - + diff --git a/komp.ipr b/komp.ipr index aa6e2f4..86a4c44 100644 --- a/komp.ipr +++ b/komp.ipr @@ -55,6 +55,54 @@ + + $PROJECT_DIR$/build/libs + + + + + + $PROJECT_DIR$/build/libs + + + + + + $PROJECT_DIR$/build/libs + + + + + + $PROJECT_DIR$/build/libs + + + + + + $PROJECT_DIR$/build/libs + + + + + + $PROJECT_DIR$/build/libs + + + + + + $PROJECT_DIR$/build/libs + + + + + + $PROJECT_DIR$/build/libs + + + + + + @@ -304,6 +426,13 @@ + + + - - - - + - + - + + + - + - + - + - + - + - + - + - + - + - + - + - + - - - - - - - - - - - - - - - - - - - + diff --git a/komp.jsMain.iml b/komp.jsMain.iml index 59aae30..bae6a11 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 0741fb6..e1332c8 100644 --- a/komp.jsTest.iml +++ b/komp.jsTest.iml @@ -1,12 +1,12 @@ - + - + komp:commonTest - komp.jsMain komp.commonTest + komp.jsMain komp.commonMain COMPILATION_AND_SOURCE_SET_HOLDER @@ -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/DiffPatch.kt b/src/jsMain/kotlin/nl/astraeus/komp/DiffPatch.kt deleted file mode 100644 index 64b30fc..0000000 --- a/src/jsMain/kotlin/nl/astraeus/komp/DiffPatch.kt +++ /dev/null @@ -1,298 +0,0 @@ -package nl.astraeus.komp - -import org.w3c.dom.* -import org.w3c.dom.events.Event - -const val HASH_VALUE = "komp-hash-value" - -//const val HASH_ATTRIBUTE = "data-komp-hash" -const val EVENT_PROPERTY = "komp-events" - -fun Node.getKompHash(): Int = this.asDynamic()[HASH_VALUE] as? Int? ?: -1 - -fun Node.setKompHash(hash: Int) { - this.asDynamic()[HASH_VALUE] = hash -} - -private fun NodeList.findNodeHashIndex(hash: Int): Int { - for (index in 0..this.length) { - val node = this[index] - if (node is HTMLElement && node.getKompHash() == hash) { - return index - } - } - - return -1 -} - -object DiffPatch { - - fun hashesMatch(oldNode: Node, newNode: Node): Boolean { - return ( - oldNode is HTMLElement && - newNode is HTMLElement && - oldNode.nodeName == newNode.nodeName && - oldNode.getKompHash() != -1 && - newNode.getKompHash() != -1 && - oldNode.getKompHash() == newNode.getKompHash() - ) - } - - private fun updateKomponentOnNode(oldNode: Node, newNode: Node) { - val komponent = newNode.asDynamic()[KOMP_KOMPONENT] as? Komponent - if (komponent != null) { - if (Komponent.logReplaceEvent) { - console.log("Keeping oldNode, set oldNode element on Komponent", oldNode, komponent) - } - komponent.element = oldNode - } - } - - fun updateNode(oldNode: Node, newNode: Node): Node { - if (hashesMatch(oldNode, newNode)) { - if (Komponent.logReplaceEvent) { - console.log("Hashes match", oldNode, newNode, oldNode.getKompHash(), newNode.getKompHash()) - } - - updateKomponentOnNode(oldNode, newNode) - return oldNode - } - - if (oldNode.nodeType == newNode.nodeType && oldNode.nodeType == 3.toShort()) { - if (oldNode.textContent != newNode.textContent) { - if (Komponent.logReplaceEvent) { - console.log("Updating text content", oldNode, newNode) - } - oldNode.textContent = newNode.textContent - } - - updateKomponentOnNode(oldNode, newNode) - return oldNode - } - - if (oldNode is HTMLElement && newNode is HTMLElement) { - if (oldNode.nodeName == newNode.nodeName) { - if (Komponent.logReplaceEvent) { - console.log("Update attributes", oldNode.nodeName, newNode.nodeName) - } - updateAttributes(oldNode, newNode); - if (Komponent.logReplaceEvent) { - console.log("Update events", oldNode.nodeName, newNode.nodeName) - } - updateEvents(oldNode, newNode) - if (Komponent.logReplaceEvent) { - console.log("Update children", oldNode.nodeName, newNode.nodeName) - } - updateKomponentOnNode(oldNode, newNode) - updateChildren(oldNode, newNode) - oldNode.setKompHash(newNode.getKompHash()) - - return oldNode - } - } - - if (Komponent.logReplaceEvent) { - console.log("Replace node (type)", oldNode.nodeType, oldNode, newNode) - } - - oldNode.parentNode?.replaceChild(newNode, oldNode) - return newNode - } - - private fun updateAttributes(oldNode: HTMLElement, newNode: HTMLElement) { - // removed attributes - for (name in oldNode.getAttributeNames()) { - val attr = oldNode.attributes[name] - - if (attr != null && newNode.getAttribute(name) == null) { - oldNode.removeAttribute(name) - } - } - - for (name in newNode.getAttributeNames()) { - val value = newNode.getAttribute(name) - val oldValue = oldNode.getAttribute(name) - - if (value != oldValue) { - if (value != null) { - oldNode.setAttribute(name, value) - }else { - oldNode.removeAttribute(name) - } - } - } - - if (newNode is HTMLInputElement && oldNode is HTMLInputElement) { - oldNode.value = newNode.value - oldNode.checked = newNode.checked - } - } - - private fun updateChildren(oldNode: HTMLElement, newNode: HTMLElement) { - var oldIndex = 0 - var newIndex = 0 - - if (Komponent.logReplaceEvent) { - console.log( - "updateChildren HTML old(${oldNode.childNodes.length})", - oldNode.innerHTML - ) - console.log( - "updateChildren HTML new(${newNode.childNodes.length})", - newNode.innerHTML - ) - } - - while (newIndex < newNode.childNodes.length) { - if (Komponent.logReplaceEvent) { - console.log("Update Old/new", oldIndex, newIndex) - } - val newChildNode = newNode.childNodes[newIndex] - - if (oldIndex < oldNode.childNodes.length) { - val oldChildNode = oldNode.childNodes[oldIndex] - - if (oldChildNode != null && newChildNode != null) { - /* - if (Komponent.logReplaceEvent) { - console.log(">>> updateChildren old/new", oldChildNode, newChildNode) - } - */ - - if (Komponent.logReplaceEvent) { - console.log("Update node Old/new", oldChildNode, newChildNode) - } - - if (!hashesMatch(oldChildNode, newChildNode) && newChildNode is HTMLElement && oldChildNode is HTMLElement) { - if (Komponent.logReplaceEvent) { - console.log("Hashes don't match") - } - - val oldHash = oldChildNode.getKompHash() - val newHash = newChildNode.getKompHash() - - if (newHash >= 0) { - val oldNodeWithNewHashIndex = oldNode.childNodes.findNodeHashIndex(newHash) - - if (Komponent.logReplaceEvent) { - console.log("oldNodeWithNewHashIndex", newHash, oldNodeWithNewHashIndex) - } - - if (oldNodeWithNewHashIndex > oldIndex) { - if (oldHash >= 0) { - val newNodeWithOldHashIndex = newNode.childNodes.findNodeHashIndex(oldHash) - - // remove i.o. swap - if (newNodeWithOldHashIndex == -1) { - if (Komponent.logReplaceEvent) { - console.log("Old node missing in new tree, remove node", oldChildNode) - } - oldNode.removeChild(oldChildNode) - continue - } - } - val nodeWithHash = oldNode.childNodes[oldNodeWithNewHashIndex] - - if (Komponent.logReplaceEvent) { - console.log("nodeWithHash", nodeWithHash) - } - if (nodeWithHash != null) { - if (Komponent.logReplaceEvent) { - console.log(">-> swap nodes", oldNode) - } - - oldNode.insertBefore(nodeWithHash, oldNode.childNodes[oldIndex]) - - if (Komponent.logReplaceEvent) { - console.log(">-> swapped nodes", oldNode) - } - newIndex++ - oldIndex++ - continue - } - } else if (oldHash >= 0 && newNode.childNodes.findNodeHashIndex(oldHash) > newIndex) { - if (Komponent.logReplaceEvent) { - console.log("newNodeWithOldHashIndex", oldHash, newNode.childNodes.findNodeHashIndex(oldHash)) - } - - oldNode.insertBefore(newChildNode, oldChildNode) - oldIndex++ - continue - } - } - } - - val updatedNode = updateNode(oldChildNode, newChildNode) - if (updatedNode == newChildNode) { - if (oldChildNode is HTMLElement && newChildNode is HTMLElement) { - updateEvents(oldChildNode, newChildNode) - } - oldIndex++ - continue - } - } else { - if (Komponent.logReplaceEvent) { - console.log("Null node", oldChildNode, newChildNode) - } - } - - oldIndex++ - newIndex++ - } else { - if (Komponent.logReplaceEvent) { - console.log("Append Old/new/node", oldIndex, newIndex, newChildNode) - } - oldNode.append(newChildNode) - - oldIndex++ - } - - /* - if (Komponent.logReplaceEvent) { - console.log("<<< Updated Old/new", oldNode.innerHTML, newNode.innerHTML) - } - */ - } - - while (oldIndex < oldNode.childNodes.length) { - oldNode.childNodes[oldIndex]?.also { - if (Komponent.logReplaceEvent) { - console.log("Remove old node", it) - } - - oldNode.removeChild(it) - } - } - } - - private fun updateEvents(oldNode: HTMLElement, newNode: HTMLElement) { - val oldEvents = (oldNode.asDynamic()[EVENT_PROPERTY] as? MutableList) ?: mutableListOf() - val newEvents = (newNode.asDynamic()[EVENT_PROPERTY] as? MutableList) ?: mutableListOf() - - if (Komponent.logReplaceEvent) { - console.log("Update events", oldNode.getAttribute(EVENT_PROPERTY), newNode.getAttribute(EVENT_PROPERTY)) - } - - for (event in oldEvents) { - oldNode.removeKompEvent(event) - } - - for (event in newEvents) { - val newNodeEvent = newNode.asDynamic()["event-$event"] - - if (newNodeEvent != null) { - if (Komponent.logReplaceEvent) { - console.log("Set event $event on", oldNode) - } - oldNode.setKompEvent(event, newNodeEvent as ((Event) -> Unit)) - } - } - - if (newEvents.isEmpty()) { - oldNode.asDynamic()[EVENT_PROPERTY] = null - } else { - oldNode.asDynamic()[EVENT_PROPERTY] = newNode.asDynamic()[EVENT_PROPERTY] - } - } - -} diff --git a/src/jsMain/kotlin/nl/astraeus/komp/HtmlBuilder.kt b/src/jsMain/kotlin/nl/astraeus/komp/HtmlBuilder.kt index 415eeeb..4fd9cfa 100644 --- a/src/jsMain/kotlin/nl/astraeus/komp/HtmlBuilder.kt +++ b/src/jsMain/kotlin/nl/astraeus/komp/HtmlBuilder.kt @@ -1,256 +1,521 @@ package nl.astraeus.komp import kotlinx.browser.document -import kotlinx.html.* -import org.w3c.dom.* -import org.w3c.dom.css.CSSStyleDeclaration +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.HTMLInputElement +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 -@Suppress("NOTHING_TO_INLINE") -inline fun HTMLElement.setKompEvent(name: String, noinline callback: (Event) -> Unit) { - val eventName = if (name.startsWith("on")) { - name.substring(2) - } else { - name - } - addEventListener(eventName, callback, null) +private var currentElement: Element? = null - if (Komponent.updateStrategy == UpdateStrategy.DOM_DIFF) { - //asDynamic()[name] = callback - val events: MutableList = (asDynamic()[EVENT_PROPERTY] as? MutableList) ?: mutableListOf() - - events.add(eventName) - asDynamic()[EVENT_PROPERTY] = events - asDynamic()["event-$eventName"] = callback - } +interface HtmlConsumer : TagConsumer { + fun append(node: Element) + fun include(komponent: Komponent) + fun debug(block: HtmlConsumer.() -> Unit) } -@Suppress("NOTHING_TO_INLINE") -inline fun HTMLElement.removeKompEvent(name: String) { - val eventName = if (name.startsWith("on")) { - name.substring(2) - } else { - name - } - - removeEventListener(eventName, asDynamic()["event-$eventName"] as ((Event) -> Unit), null) - - if (Komponent.updateStrategy == UpdateStrategy.DOM_DIFF) { - //asDynamic()[name] = callback - val events: MutableList = (asDynamic()[EVENT_PROPERTY] as? MutableList) ?: mutableListOf() - - events.remove(eventName) - asDynamic()["event-$eventName"] = null +fun Int.asSpaces(): String { + val result = StringBuilder() + repeat(this) { + result.append(" ") } + return result.toString() } -fun HTMLElement.clearEvents() { - if (Komponent.updateStrategy == UpdateStrategy.DOM_DIFF) { - //asDynamic()[name] = callback - val events = getAttribute(EVENT_PROPERTY) ?: "" +fun FlowOrMetaDataOrPhrasingContent.currentElement(): Element = + currentElement ?: error("No current element defined!") - for (eventName in events.split(",")) { - if (eventName.isNotBlank()) { - val event: (Event) -> Unit = asDynamic()["event-$eventName"] - removeEventListener(eventName, event) +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() } -interface HtmlConsumer : TagConsumer { - fun append(node: Node) -} +private fun Element.clearKompAttributes() { + val attributes = this.asDynamic()["komp-attributes"] as MutableSet? -fun HTMLElement.setStyles(cssStyle: CSSStyleDeclaration) { - for (index in 0 until cssStyle.length) { - val propertyName = cssStyle.item(index) + if (attributes == null) { + this.asDynamic()["komp-attributes"] = mutableSetOf() + } else { + attributes.clear() + } - style.setProperty(propertyName, cssStyle.getPropertyValue(propertyName)) + if (this is HTMLInputElement) { + this.checked = false } } +private fun Element.getKompAttributes(): MutableSet { + var result: MutableSet? = this.asDynamic()["komp-attributes"] as MutableSet? + + if (result == null) { + result = mutableSetOf() + + this.asDynamic()["komp-attributes"] = result + } + + return result +} + +private fun Element.setKompAttribute(name: String, value: String) { + val setAttrs: MutableSet = getKompAttributes() + setAttrs.add(name) + + if (this is HTMLInputElement) { + when (name) { + "checked" -> { + this.checked = value == "checked" + } + "value" -> { + this.value = value + + } + else -> { + setAttribute(name, value) + } + } + } else if (this.getAttribute(name) != value) { + setAttribute(name, value) + } +} + +private fun Element.clearKompEvents() { + for ((name, event) in getKompEvents()) { + currentElement?.removeEventListener(name, event) + } + + val events = this.asDynamic()["komp-events"] as MutableMap Unit>? + + if (events == null) { + this.asDynamic()["komp-events"] = mutableMapOf Unit>() + } else { + events.clear() + } +} + +private 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 + + this.addEventListener(eventName, event) +} + +private fun Element.getKompEvents(): MutableMap Unit> { + return this.asDynamic()["komp-events"] ?: mutableMapOf() +} + +private data class ElementIndex( + val parent: Node, + var childIndex: Int +) + +private fun ArrayList.currentParent(): Node { + this.lastOrNull()?.let { + return it.parent + } + + throw IllegalStateException("currentParent should never be null!") +} + +private fun ArrayList.currentElement(): Node? { + this.lastOrNull()?.let { + return it.parent.childNodes[it.childIndex] + } + + return null +} + +private fun ArrayList.nextElement() { + this.lastOrNull()?.let { + it.childIndex++ + } +} + +private fun ArrayList.pop() { + this.removeLast() +} + +private fun ArrayList.push(element: Node) { + this.add(ElementIndex(element, 0)) +} + +private fun ArrayList.replace(new: Node) { + if (this.currentElement() != null) { + this.currentElement()?.parentElement?.replaceChild(new, this.currentElement()!!) + } else { + this.last().parent.appendChild(new) + } +} + +private fun Node.asElement() = this as? HTMLElement + class HtmlBuilder( - val komponent: Komponent, - val document: Document, - val baseHash: Int + val parent: Element, + var childIndex: Int = 0 ) : HtmlConsumer { - private val path = arrayListOf() - private var lastLeaved: HTMLElement? = null + private var currentPosition = arrayListOf() + private var inDebug = false + var currentNode: Node? = null + var root: Element? = null + val currentAttributes: MutableMap = mutableMapOf() + + init { + currentPosition.add(ElementIndex(parent, childIndex)) + } + + override fun include(komponent: Komponent) { + if ( + komponent.element != null && + !komponent.memoizeChanged() + ) { + currentPosition.replace(komponent.element!!) + if (Komponent.logRenderEvent) { + console.log("Skipped include $komponent, memoize hasn't changed") + } + } else { + komponent.create( + currentPosition.last().parent as Element, + currentPosition.last().childIndex + ) + } + currentPosition.nextElement() + } + + override fun append(node: Element) { + currentPosition.replace(node) + currentPosition.nextElement() + } + + override fun debug(block: HtmlConsumer.() -> Unit) { + inDebug = true + + try { + block.invoke(this) + } finally { + inDebug = false + } + } + + fun logReplace(msg: String) { + if (Komponent.logReplaceEvent && inDebug) { + console.log(msg) + } + } 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 + //logReplace"onTagStart, [${tag.tagName}, ${tag.namespace}], currentPosition: $currentPosition") + currentNode = currentPosition.currentElement() + + 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) + } else { + document.createElement(tag.tagName) + } + + 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.lowercase(), entry.value) + } + + if (tag.namespace != null) { + //logReplace"onTagStart, same node type") + + (currentNode as? Element)?.innerHTML = "" + } } - 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().tagName.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.lowercase()) + } else { + currentElement?.setKompAttribute(attribute.lowercase(), value) } } override fun onTagEvent(tag: Tag, event: String, value: (Event) -> Unit) { - when { - path.isEmpty() -> throw IllegalStateException("No current tag") - path.last().tagName.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.lowercase(), value) } override fun onTagEnd(tag: Tag) { - var hash = 0 - if (path.isEmpty() || path.last().tagName.toLowerCase() != tag.tagName.toLowerCase()) { - throw IllegalStateException("We haven't entered tag ${tag.tagName} but trying to leave") - } - - val element = path.last() - - if (Komponent.updateStrategy == UpdateStrategy.DOM_DIFF) { - for (index in 0 until element.childNodes.length) { - val child = element.childNodes[index] - if (child is HTMLElement) { - hash = hash * 37 + child.getKompHash() - } else { - hash = hash * 37 + (child?.textContent?.hashCode() ?: 0) - } + while (currentPosition.currentElement() != null) { + currentPosition.currentElement()?.let { + it.parentElement?.removeChild(it) } } - for ((key, value) in tag.attributesEntries) { - if (key == "class") { - val classes = value.split(Regex("\\s+")) - val classNames = StringBuilder() + checkTag(tag) - for (cls in classes) { - val cssStyle = komponent.declaredStyles[cls] + currentPosition.pop() - if (cssStyle != null) { - if (Komponent.updateStrategy == UpdateStrategy.DOM_DIFF) { - hash = hash * 37 + cssStyle.hashCode() - } + val setAttrs: List = currentElement.asDynamic()["komp-attributes"] ?: listOf() - if (cls.endsWith(":hover")) { - val oldOnMouseOver = element.onmouseover - val oldOnMouseOut = element.onmouseout + // remove attributes that where not set + val element = currentElement + if (element?.hasAttributes() == true) { + for (index in 0 until element.attributes.length) { + val attr = element.attributes[index] + if (attr != null) { - element.onmouseover = { - element.setStyles(cssStyle) + if (element is HTMLElement && attr.name == "data-has-focus" && "true" == attr.value) { + element.focus() + } - oldOnMouseOver?.invoke(it) - } - element.onmouseout = { - cls.split(':').firstOrNull()?.let { - komponent.declaredStyles[it]?.let { cssStyle -> - element.setStyles(cssStyle) - } - } - - oldOnMouseOut?.invoke(it) + if (!setAttrs.contains(attr.name)) { + if (element is HTMLInputElement) { + if (attr.name == "checkbox") { + element.checked = false + } else if (attr.name == "value") { + element.value = "" } } else { - element.setStyles(cssStyle) + if (Komponent.logReplaceEvent) { + console.log("Clear attribute [${attr.name}] on $element)") + } + element.removeAttribute(attr.name) } - } else { - if (Komponent.updateStrategy == UpdateStrategy.DOM_DIFF) { - hash = hash * 37 + cls.hashCode() - } - - classNames.append(cls) - classNames.append(" ") } } - - element.className = classNames.toString() - - if (Komponent.updateStrategy == UpdateStrategy.DOM_DIFF) { - val key_value = "${key}-${classNames}" - hash = hash * 37 + key_value.hashCode() - } - } else { - element.setAttribute(key, value) - - if (Komponent.updateStrategy == UpdateStrategy.DOM_DIFF) { - val key_value = "${key}-${value}" - hash = hash * 37 + key_value.hashCode() - } } } - if (Komponent.updateStrategy == UpdateStrategy.DOM_DIFF) { - element.setKompHash(baseHash * 53 + hash) - } - lastLeaved = path.removeAt(path.lastIndex) + 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(document.createTextNode(content.toString())) + //logReplace"Tag content: $content") + if ( + currentElement?.nodeType != Node.TEXT_NODE || + 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 - val s = document.createElement("span") as HTMLElement + val s = document.createElement("span") as HTMLSpanElement s.innerHTML = entity.text - path.last().appendChild(s.childNodes.asList().first { it.nodeType == Node.TEXT_NODE }) - - // other solution would be - // pathLast().innerHTML += entity.text - } - - override fun append(node: Node) { - path.last().appendChild(node) + currentPosition.replace( + s.childNodes.asList().firstOrNull() ?: document.createTextNode(entity.text) + ) + currentPosition.nextElement() } override fun onTagContentUnsafe(block: Unsafe.() -> Unit) { with(DefaultUnsafe()) { block() - path.last().innerHTML += toString() + 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(document.createComment(content.toString())) + check(currentElement != null) { + "No current DOM node" + } + currentElement?.appendChild( + document.createComment(content.toString()) + ) + + currentPosition.nextElement() } - override fun finalize(): HTMLElement = lastLeaved?.asR() ?: throw IllegalStateException("We can't finalize as there was no tags") - - @Suppress("UNCHECKED_CAST") - private fun HTMLElement.asR(): HTMLElement = this.asDynamic() + 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): HTMLElement { - val komponent = DummyKomponent() - val consumer = HtmlBuilder(komponent, document, 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 4262906..f251359 100644 --- a/src/jsMain/kotlin/nl/astraeus/komp/Komponent.kt +++ b/src/jsMain/kotlin/nl/astraeus/komp/Komponent.kt @@ -1,18 +1,13 @@ 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 -const val KOMP_KOMPONENT = "komp-komponent" - -typealias CssStyle = CSSStyleDeclaration.() -> Unit - class StateDelegate( val komponent: Komponent, initialValue: T @@ -33,144 +28,126 @@ class StateDelegate( inline fun Komponent.state(initialValue: T): StateDelegate = StateDelegate(this, initialValue) -fun HtmlConsumer.include(component: Komponent) { - if (Komponent.updateStrategy == UpdateStrategy.REPLACE) { - if (component.element != null) { - component.update() - } else { - component.refresh() - } - - component.element?.also { - append(it) - } - } else { - append(component.create()) - } -} - -class DummyKomponent: Komponent() { - override fun HtmlBuilder.render() { - div { - + "dummy" - } - } -} - -enum class UpdateStrategy { - REPLACE, - DOM_DIFF +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 + private var lastMemoizeHash: Int? = null var element: Node? = null val declaredStyles: MutableMap = HashMap() - open fun create(): HTMLElement { - val consumer = HtmlBuilder(this, document, this.createIndex) - try { - consumer.render() - } catch (e: Throwable) { - println("Exception occurred in ${this::class.simpleName}.render() call!") + open fun create(parent: Element, childIndex: Int? = null) { + onBeforeUpdate() + val builder = HtmlBuilder( + parent, + childIndex ?: parent.childElementCount + ) - throw e - } - val result = consumer.finalize() - - if (result.id.isBlank()) { - result.id = "komp_${createIndex}" - } - - element = result - element.asDynamic()[KOMP_KOMPONENT] = this - - dirty = false - - return result + builder.render() + element = builder.root + lastMemoizeHash = generateMemoizeHash() + onAfterUpdate() } + fun memoizeChanged() = lastMemoizeHash != null && lastMemoizeHash != generateMemoizeHash() + abstract fun HtmlBuilder.render() + /** + * This method is called after the Komponent is updated + * + * note: it's also called at first render + */ + open fun onAfterUpdate() {} + + /** + * This method is called before the Komponent is updated + * and before memoizeHash is checked + * + * note: it's also called at first render + */ + open fun onBeforeUpdate() {} + 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() } + /** + * If this function returns a value it will be stored and on the next render it will be compared. + * + * The render will only happen if the hash is not null and has changed + */ + open fun generateMemoizeHash(): Int? = null + internal fun refresh() { - val oldElement = element + val currentElement = element - if (logRenderEvent) { - console.log("Rendering", this) + check(currentElement != null) { + error("element is null") } - val newElement = create() - if (oldElement != null) { - element = if (updateStrategy == UpdateStrategy.REPLACE) { - if (logReplaceEvent) { - console.log("Replacing", oldElement, newElement) - } - oldElement.parentNode?.replaceChild(newElement, oldElement) - newElement - } else { - if (logReplaceEvent) { - console.log("DomDiffing", oldElement, newElement) - } - DiffPatch.updateNode(oldElement, 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 } } - + val consumer = HtmlBuilder(parent, childIndex) + consumer.root = null + consumer.render() + element = consumer.root dirty = false } - @JsName("remove") - fun remove() { - check(updateStrategy == UpdateStrategy.REPLACE) { - "remote only works with UpdateStrategy.REPLACE" - } - element?.let { - val parent = it.parentElement ?: throw IllegalArgumentException("Element has no parent!?") - - if (logReplaceEvent) { - console.log("Remove", it) - } - - parent.removeChild(it) - } + override fun toString(): String { + return "${this::class.simpleName}" } 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 updateStrategy = UpdateStrategy.DOM_DIFF + var unsafeMode = UnsafeMode.UNSAFE_DISABLED fun create(parent: HTMLElement, component: Komponent, insertAsFirst: Boolean = false) { - val element = component.create() + 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++ @@ -185,6 +162,11 @@ abstract class Komponent { } } + private fun runUpdateImmediately(komponent: Komponent) { + scheduledForUpdate.add(komponent) + runUpdate() + } + private fun runUpdate() { val todo = scheduledForUpdate.sortedBy { komponent -> komponent.createIndex } @@ -193,20 +175,31 @@ 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() + val memoizeHash = next.generateMemoizeHash() + + if (memoizeHash == null || next.lastMemoizeHash != memoizeHash) { + next.onBeforeUpdate() + next.update() + next.lastMemoizeHash = memoizeHash + next.onAfterUpdate() + } else if (logRenderEvent) { + console.log("Skipped render, memoizeHash is equal $next-[$memoizeHash]") + } } else { if (logRenderEvent) { console.log("Skip ${next.createIndex}") } } + } else { + console.log("Komponent element is null", next, element) } } } diff --git a/src/jsTest/kotlin/nl/astraeus/komp/TestUpdate.kt b/src/jsTest/kotlin/nl/astraeus/komp/TestUpdate.kt index 39da898..a6eb0e9 100644 --- a/src/jsTest/kotlin/nl/astraeus/komp/TestUpdate.kt +++ b/src/jsTest/kotlin/nl/astraeus/komp/TestUpdate.kt @@ -1,132 +1,238 @@ package nl.astraeus.komp -import kotlinx.html.* +import kotlinx.browser.document +import kotlinx.html.div +import kotlinx.html.i +import kotlinx.html.id import kotlinx.html.js.onClickFunction -import org.w3c.dom.HTMLElement -import org.w3c.dom.Node -import org.w3c.dom.get +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 kotlin.test.Test -import kotlin.test.assertTrue -fun nodesEqual(node1: Node, node2: Node): Boolean { - if (node1.childNodes.length != node1.childNodes.length) { - return false +class TestKomponent : Komponent() { + override fun HtmlBuilder.render() { + div { + +"Test" + } } - if (node1 is HTMLElement && node2 is HTMLElement) { - if (node1.attributes.length != node2.attributes.length) { - return false - } - for (index in 0 until node1.attributes.length) { - node1.attributes[index]?.also { attr1 -> - val attr2 = node2.getAttribute(attr1.name) +} - if (attr1.value != attr2) { - return false - } - } +class Child1 : Komponent() { + override fun HtmlBuilder.render() { + div { + +"Child 1" } - for (index in 0 until node1.childNodes.length) { - node1.childNodes[index]?.also { child1 -> - node2.childNodes[index]?.also { child2 -> - if (!nodesEqual(child1, child2)) { - return false + } +} + +class Child2 : Komponent() { + override fun HtmlBuilder.render() { + div { + +"Child 2" + } + } +} + +class SimpleKomponent : Komponent() { + var hello = true + var append = HtmlBuilder.create { + p { + +"Appended" + } + } + + override fun HtmlBuilder.render() { + div("div_class") { + span { + svg { + unsafe { + +""" +

+ """.trimIndent() + } + } + if (hello) { + div { + +"Hello" + } + } else { + span { + +"Good bye" } } } + div { + if (hello) { + id = "123" + +"div text" + } else { + +"div text goodbye" + } + + 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) + } + } + +} + +class IncludeKomponent( + var text: String = "My Text" +) : Komponent() { + + override fun generateMemoizeHash(): Int = text.hashCode() + + override fun HtmlBuilder.render() { + span { + +text + } + } +} + +class ReplaceKomponent : Komponent() { + val includeKomponent = IncludeKomponent() + var includeSpan = true + + override fun generateMemoizeHash(): Int = includeSpan.hashCode() * 7 + includeKomponent.generateMemoizeHash() + + override fun HtmlBuilder.render() { + div { + +"Child 2" + + div { + if (includeSpan) { + span { + i("fas fa-eye") { + +"span1" + } + } + span { + i("fas fa-eye") { + +"span2" + } + } + span { + i("fas fa-eye") { + +"span3" + } + } + } + + include(includeKomponent) + } } } - return true } class TestUpdate { @Test - fun testCompare1() { - val dom1 = HtmlBuilder.create { - div { - div(classes = "bla") { - span { - +" Some Text " - } - table { - tr { - td { - +"Table column" - } - } - } - } - } - } + fun testUpdateWithEmpty() { + val div = document.createElement("div") as HTMLDivElement + val rk = ReplaceKomponent() - val dom2 = HtmlBuilder.create { - div { - span { - id = "123" + Komponent.logRenderEvent = true - +"New dom!" - } - input { - value = "bla" - } - } - } + Komponent.create(div, rk) - DiffPatch.updateNode(dom1, dom2) + println("ReplaceKomponent: ${div.printTree()}") - assertTrue(nodesEqual(dom1, dom2), "Updated dom not equal to original") + rk.requestImmediateUpdate() + + println("ReplaceKomponent: ${div.printTree()}") + + rk.requestImmediateUpdate() + + println("ReplaceKomponent: ${div.printTree()}") + + rk.includeSpan = false + rk.requestImmediateUpdate() + + println("ReplaceKomponent: ${div.printTree()}") + + rk.includeSpan = true + rk.includeKomponent.text = "New Text" + rk.requestImmediateUpdate() + + println("ReplaceKomponent: ${div.printTree()}") } @Test - fun testCompare2() { - val dom1 = HtmlBuilder.create { - div { - div(classes = "bla") { - span { - +" Some Text " - } - table { - tr { - th { - + "Header" - } + 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" } - tr { - td { - +"Table column" - } + td { + +"column 2" } } } } } - val dom2 = HtmlBuilder.create { - div { - div { - span { - + "Other text" - } - } - span { - id = "123" - - +"New dom!" - } - input { - value = "bla" - - onClickFunction = { - println("Clickerdyclick!") - } - } - } - } - - Komponent.logReplaceEvent = true - DiffPatch.updateNode(dom1, dom2) - - assertTrue(nodesEqual(dom1, dom2), "Updated dom not equal to original") + println("Element: ${element.printTree()}") + println("divTst: ${elemTest?.printTree()}") + println("span class: ${ + elemTest?.getAttributeNames()?.joinToString + { "," } + }" + ) } }