From 8f48912e1b1f3cac895077a1ba69801928922a86 Mon Sep 17 00:00:00 2001 From: nayyaung9 Date: Tue, 31 Aug 2021 22:32:57 +0630 Subject: [PATCH] playaround with vdom --- index.html | 4 ++- index.js | 71 ++++++++++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 72 insertions(+), 3 deletions(-) diff --git a/index.html b/index.html index 87a0e42..64ff86a 100644 --- a/index.html +++ b/index.html @@ -7,7 +7,9 @@ vdom implementation -

Hello vdom

+

VDOM implementation in burmese

+ +
diff --git a/index.js b/index.js index 914125d..7827664 100644 --- a/index.js +++ b/index.js @@ -4,11 +4,78 @@ function h(type, props, ...children) { return { type, props, children }; } +/** + * a function createElement(…) that will take a virtual DOM node + * and return a real DOM node + */ +function createElement(node) { + if (typeof node === "string") { + return document.createTextNode(node); + } + + const $el = document.createElement(node.type); + + node.children.map(createElement).forEach($el.appendChild.bind($el)); + + return $el; +} + +/** + * compare two nodes (old and new) + */ +function changed(node1, node2) { + return ( + typeof node1 !== typeof node2 || + (typeof node1 === "string" && node1 !== node2) || + node1.type !== node2.type + ); +} + +/** + * updateElement is used to check old node are exist + * diff children + */ +function updateElement($parent, newNode, oldNode, index = 0) { + if (!oldNode) { + $parent.appendChild(createElement(newNode)); + } else if (!newNode) { + $parent.removeChild($parent.childNodes[index]); + } else if (changed(newNode, oldNode)) { + $parent.replaceChild(createElement(newNode), $parent.childNodes[index]); + } else if (newNode.type) { + const newLength = newNode.children.length; + const oldLength = oldNode.children.length; + for (let i = 0; i < newLength || i < oldLength; i++) { + updateElement( + $parent.childNodes[index], + newNode.children[i], + oldNode.children[i], + i + ); + } + } +} + +// --------------------------------------------------------------------- + const a = ( -