All files / virtual-dom/dom patchNode.ts

100% Statements 11/11
60% Branches 6/10
100% Functions 4/4
100% Lines 11/11

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43  9x   9x   8x   8x   7x   7x         1x   1x             7x   1x                       1x      
import { VirtualNode } from "../interfaces";
import createNode from "./createNode";
 
export default function patchNode(newVNode: VirtualNode, oldVNode: VirtualNode, container: Document | HTMLElement): void {
 
    const oldElement = oldVNode.$node;
 
    if (newVNode.tag === oldVNode.tag) { // Check if the attributes and children changed
 
        patchAttributes(oldElement as HTMLElement, newVNode.attributes || {}, oldVNode.attributes || {});
 
        patchChildren(oldElement, newVNode.children, oldVNode.children);
 
    }
    else { // Different tags, replace the element
 
        const newElement = createNode(newVNode);
 
        oldElement.parentNode.replaceChild(newElement, oldElement);
    }
 
}
 
function patchAttributes(element: HTMLElement, newAttributes: Record<string, any> = {}, oldAttributes: Record<string, any> = {}) {
 
    for (const [key, value] of Object.entries(newAttributes)) {
 
        setAttribute(element, key, value);
    }
 
}
 
function patchChildren(oldElement: Node, oldChildren: any[] = [], newChildren: any[] = []) {
 
    //throw new Error("Function not implemented.");
}
 
function setAttribute(element: HTMLElement, key: string, value: any) {
 
    element.setAttribute(key, value);
}