Fix new element being referenced in Komponent instead of old not updated one (in DOM_DIFF strategy)

This commit is contained in:
2021-02-05 11:18:11 +01:00
parent 01a30c9645
commit 1c1cb8eaba
9 changed files with 106 additions and 88 deletions

View File

@@ -40,11 +40,23 @@ object DiffPatch {
)
}
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
}
@@ -55,6 +67,8 @@ object DiffPatch {
}
oldNode.textContent = newNode.textContent
}
updateKomponentOnNode(oldNode, newNode)
return oldNode
}
@@ -73,6 +87,8 @@ object DiffPatch {
}
updateChildren(oldNode, newNode)
oldNode.setKompHash(newNode.getKompHash())
updateKomponentOnNode(oldNode, newNode)
return oldNode
}
}

View File

@@ -9,6 +9,8 @@ import kotlinx.browser.window
import kotlinx.html.div
import kotlin.reflect.KProperty
const val KOMP_KOMPONENT = "komp-komponent"
typealias CssStyle = CSSStyleDeclaration.() -> Unit
class StateDelegate<T>(
@@ -72,7 +74,12 @@ abstract class Komponent {
consumer.render()
val result = consumer.finalize()
if (result.id.isBlank()) {
result.id = "komp_${createIndex}"
}
element = result
element.asDynamic()[KOMP_KOMPONENT] = this
dirty = false
@@ -101,6 +108,7 @@ abstract class Komponent {
internal fun refresh() {
val oldElement = element
if (logRenderEvent) {
console.log("Rendering", this)
}
@@ -126,6 +134,9 @@ abstract class Komponent {
@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!?")
@@ -176,14 +187,21 @@ abstract class Komponent {
}
todo.forEach { next ->
if (next.dirty) {
if (logRenderEvent) {
console.log("Update dirty ${next.createIndex}")
}
next.update()
} else {
if (logRenderEvent) {
console.log("Skip ${next.createIndex}")
val element = next.element
console.log("update element", element)
if (element is HTMLElement) {
console.log("by id", document.getElementById(element.id))
if (document.getElementById(element.id) != null) {
if (next.dirty) {
if (logRenderEvent) {
console.log("Update dirty ${next.createIndex}")
}
next.update()
} else {
if (logRenderEvent) {
console.log("Skip ${next.createIndex}")
}
}
}
}
}