I'll create a simple virtual DOM implementation that covers the core concepts. Here's the code with step-by-step explanations:
// Step 1: Virtual Node Representation
class VNode {
constructor(tag, props = {}, children = []) {
this.tag = tag;
this.props = props;
this.children = children;
}
}
// Step 2: Helper function to create virtual nodes
function h(tag, props, ...children) {
return new VNode(tag, props, children.flat());
}
// Step 3: Render virtual DOM to real DOM
function render(vnode) {
// Handle text nodes
if (typeof vnode === 'string' || typeof vnode === 'number') {
return document.createTextNode(vnode);
}
// Create the element
const element = document.createElement(vnode.tag);
// Set properties/attributes
for (const [key, value] of Object.entries(vnode.props)) {
if (key.startsWith('on')) {
// Handle event listeners
const eventType = key.slice(2).toLowerCase();
element.addEventListener(eventType, value);
} else if (key === 'className') {
element.className = value;
} else {
element.setAttribute(key, value);
}
}
// Render and append children
vnode.children.forEach(child => {
element.appendChild(render(child));
});
return element;
}
// Step 4: Diff algorithm to compare virtual DOM trees
function diff(oldVNode, newVNode) {
// If nodes are completely different, replace
if (!oldVNode) {
return { type: 'CREATE', newVNode };
}
if (!newVNode) {
return { type: 'REMOVE' };
}
if (typeof oldVNode !== typeof newVNode ||
(typeof oldVNode === 'string' && oldVNode !== newVNode) ||
oldVNode.tag !== newVNode.tag) {
return { type: 'REPLACE', newVNode };
}
if (typeof oldVNode === 'string') {
return null; // No changes needed
}
// Compare props
const propPatches = diffProps(oldVNode.props, newVNode.props);
// Compare children
const childPatches = [];
const maxLength = Math.max(oldVNode.children.length, newVNode.children.length);
for (let i = 0; i < maxLength; i++) {
const childPatch = diff(oldVNode.children[i], newVNode.children[i]);
if (childPatch) {
childPatches.push({ index: i, patch: childPatch });
}
}
if (propPatches.length === 0 && childPatches.length === 0) {
return null;
}
return { type: 'UPDATE', propPatches, childPatches };
}
// Step 5: Helper function to diff properties
function diffProps(oldProps, newProps) {
const patches = [];
// Check for removed or changed props
for (const key in oldProps) {
if (!(key in newProps)) {
patches.push({ type: 'REMOVE_PROP', key });
} else if (oldProps[key] !== newProps[key]) {
patches.push({ type: 'SET_PROP', key, value: newProps[key] });
}
}
// Check for new props
for (const key in newProps) {
if (!(key in oldProps)) {
patches.push({ type: 'SET_PROP', key, value: newProps[key] });
}
}
return patches;
}
// Step 6: Apply patches to real DOM
function patch(element, patches) {
if (!patches) return element;
switch (patches.type) {
case 'CREATE':
return render(patches.newVNode);
case 'REMOVE':
element.parentNode?.removeChild(element);
return null;
case 'REPLACE':
const newElement = render(patches.newVNode);
element.parentNode?.replaceChild(newElement, element);
return newElement;
case 'UPDATE':
// Apply property patches
patches.propPatches.forEach(propPatch => {
switch (propPatch.type) {
case 'SET_PROP':
if (propPatch.key.startsWith('on')) {
const eventType = propPatch.key.slice(2).toLowerCase();
element.addEventListener(eventType, propPatch.value);
} else if (propPatch.key === 'className') {
element.className = propPatch.value;
} else {
element.setAttribute(propPatch.key, propPatch.value);
}
break;
case 'REMOVE_PROP':
element.removeAttribute(propPatch.key);
break;
}
});
// Apply child patches
patches.childPatches.forEach(childPatch => {
const childElement = element.childNodes[childPatch.index];
const patchedChild = patch(childElement, childPatch.patch);
if (childPatch.patch.type === 'CREATE') {
element.appendChild(patchedChild);
}
});
return element;
}
}
// Step 7: Main update function
function updateDOM(container, oldVTree, newVTree) {
const patches = diff(oldVTree, newVTree);
const newContainer = patch(container.firstChild, patches);
if (newContainer && newContainer !== container.firstChild) {
container.innerHTML = '';
container.appendChild(newContainer);
}
return newVTree;
}
Step-by-Step Explanation:
Step 1: Virtual Node Representation
I created a VNode class to represent DOM elements as JavaScript objects. Each virtual node has a tag name, properties/attributes, and children.
Step 2: Helper Function
The h function provides a convenient way to create virtual nodes, similar to React's createElement. It accepts a tag, props, and children.
Step 3: Rendering
The render function converts virtual DOM nodes into real DOM elements. It handles text nodes, creates elements, sets properties and event listeners, and recursively renders children.
Step 4: Diffing Algorithm
The diff function compares two virtual DOM trees and returns a patch object describing the differences. It handles node creation, removal, replacement, and updates.
Step 5: Property Diffing
diffProps specifically compares the properties of two nodes and returns patches for property changes, additions, and removals.
Step 6: Patching
The patch function applies the patches to the real DOM, making minimal changes to update the interface efficiently.
Step 7: Main Update Function
updateDOM ties everything together, performing the diff and patch operations to update the DOM.
Usage Example:
// Create virtual DOM
const vdom1 = h('div', { className: 'container' },
h('h1', {}, 'Hello World'),
h('p', {}, 'This is a paragraph')
);
const vdom2 = h('div', { className: 'container' },
h('h1', {}, 'Hello Virtual DOM!'),
h('p', {}, 'This paragraph was updated'),
h('button', { onClick: () => alert('Clicked!') }, 'Click me')
);
// Initial render
const container = document.getElementById('app');
container.appendChild(render(vdom1));
// Update (only changes the necessary parts)
let currentVTree = vdom1;
currentVTree = updateDOM(container, currentVTree, vdom2);
This implementation demonstrates the core principles of virtual DOM: representing UI as data structures, efficiently calculating differences, and applying minimal updates to the real DOM.