All files / src/renderer Patcher.ts

90.7% Statements 117/129
85% Branches 51/60
93.33% Functions 14/15
90.16% Lines 110/122

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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 50110x 10x 10x 10x                                                                                                                         10x   10x   10x   10x                           18x   14x           46x   46x   46x       46x   20x           20x             46x   46x   81x   81x   81x   1x     80x           80x   80x       26x   26x                                                                                                                           29x   29x     25x   25x   25x   25x     25x               25x   25x                     18x   18x   14x     10x   68x   68x   68x   136x   136x   84x   84x   29x       55x     52x   43x       68x   68x         84x   84x   546x   84x     462x     84x     10x       52x   115x   9x       43x             64x       64x   64x     11x         11x   53x   26x       27x   27x   13x       27x   50x     27x             13x   13x   14x   14x   5x   5x           9x   4x   4x               13x         46x   46x   46x           87x   87x             46x         87x   87x   106x   106x     87x         29x               29x           29x   29x             29x         3x       26x           26x   26x   2x     26x         10x                                          
enum NodePatcherRuleTypes {
    PATCH_NODE = 1, // Patches either a single node or a collection of nodes
    PATCH_ATTRIBUTE,
    PATCH_EVENT
}
 
/**
 * The rule to "compile" to patch the DOM node
 */
 interface NodePatcherRule {
 
    /**
     * The type of patching to do to that node
     */
    type: NodePatcherRuleTypes,
 
    /**
     * The path to locate the node
     */
    path: number[],
 
    /**
     * The name of the attribute to patch
     * Only populated if it is an attribute or an event
     */
    name?: string,
}
 
interface CompiledNodePatcherRule {
 
    /**
     * The type of patching to do to that node
     */
    type: NodePatcherRuleTypes,
 
    /**
     * The node the rule is acting upon
     */
    node: Node,
 
    /**
     * The name of the attribute to patch
     * Only populated if it is an attribute or an event
     */
    name?: string,
}
 
/**
 * The patching data that gets attached to a node
 */
interface NodePatchingData {
 
    patcher: NodePatcher,
 
    rules: CompiledNodePatcherRule[],
 
    values: any[]
}
 
interface NodePatchingDataHolder {
 
    _$patchingData: NodePatchingData
}
 
const nodeMarker = "_$node_";
 
const attributeMarkerPrefix = "_$attr:";
 
const eventMarkerPrefix = "_$evt:";
 
export class NodePatcher {
 
    /**
     * The template to clone and generate the node from
     */
    private _template: HTMLTemplateElement;
 
    /**
     * The rules to be cloned (compiled)to execute the patching
     */
    private _rules: NodePatcherRule[];
 
    constructor(strings: TemplateStringsArray) {
 
        this._template = createTemplate(strings);
 
        this._rules = createNodePatcherRules(this._template.content);
    }
 
    createNode(oldValues: any[], newValues: any[]): Node {
 
        // The content of the template is a document fragment
        const node = this._template.content.cloneNode(/*deep*/true);
 
        const rules = compileRules(node, this._rules);
 
        const newValuesHolder = {
            newValues
        };
 
        this.patchNode(node, rules, oldValues, newValuesHolder);
 
        (node as unknown as NodePatchingDataHolder)._$patchingData  = {
            patcher: this,
            rules,
            values: newValuesHolder.newValues // Store the old values to compare
        };
 
        return node;
    }
 
    patchNode(parentNode: Node, rules: CompiledNodePatcherRule[], oldValues: any[], newValuesHolder: { newValues: any[]; }) {
 
        const {
            length
        } = rules;
 
        for (let i = 0; i < length; ++i) { // The index of the values of the rules match 1 to 1 with the number of rules
 
            const oldValue = oldValues[i];
 
            const newValue = newValuesHolder.newValues[i];
 
            if (oldValue === newValue) {
 
                continue;
            }
 
            const rule = rules[i];
 
            const {
                type,
                name,
                node
            } = rule;
 
            switch (type) {
 
                case NodePatcherRuleTypes.PATCH_NODE:
                    {
                        Eif (type === NodePatcherRuleTypes.PATCH_NODE) {
 
                            throw new Error('patchNode not implemented');
                        }
                        
                        // if (childNode === undefined) { // The node does not have any child at that path
 
                        //     childNode = node as HTMLElement;
                        // }
 
                        // const parentNode = (childNode.parentNode !== null ?
                        //     childNode.parentNode :
                        //     childNode) as HTMLElement;
 
                        // let { childNodes } = parentNode;
 
                        // if (Array.isArray(newValue)) { // Collection of nodes
 
                        //     if (
                        //         childNode.nodeType === Node.COMMENT_NODE &&
                        //         (childNode as Comment).data === nodeMarker
                        //     ) {
 
                        //         parentNode.replaceChildren(...newValue); // Replace the marker with the children
 
                        //         // If the newValue is an array of document fragments, they will lose their children after replacement
                        //         // Ensure the children have the instance of the patching data
                        //         childNodes = parentNode.childNodes;
 
                        //         const length = childNodes.length;
 
                        //         for (let i = 0; i < length; ++i) {
 
                        //             const instancePatchingData = newValue[i].__instancePatchingData__;
 
                        //             if (instancePatchingData !== undefined) {
 
                        //                 (childNodes[i] as any).__instancePatchingData__ = instancePatchingData;
                        //             }
                        //         }
                        //         // Restore the values
                        //         newValuesHolder.newValues = [Array.from(childNodes)];
                        //     }
                        //     else { // Parent node has children
 
                        //         patchChildren(parentNode, newValue); // Patch the existing children
                        //     }
                        // }
                        // else { // Single value or node
 
                        //     if (newValue instanceof DocumentFragment) {
 
                        //         parentNode.replaceChild(newValue, childNode);
                        //     }
                        //     else {
 
                        //         parentNode.replaceChild(document.createTextNode(newValue), childNode);
                        //     }
                        // }
                        
                    }
                    break;
                case NodePatcherRuleTypes.PATCH_ATTRIBUTE:
                    {
                        patchAttribute(node as HTMLElement, name, oldValue, newValue);
                    }
                    break;
                case NodePatcherRuleTypes.PATCH_EVENT:
                    {
                        const eventName: string = name.slice(2).toLowerCase();
 
                        const nameParts = eventName.split('_'); // Just in case it has the capture parameter in the event
 
                        const useCapture: boolean = nameParts[1]?.toLowerCase() === 'capture'; // The convention is: eventName_capture for capture. Example onClick_capture
 
                        Eif (oldValue === undefined &&
                            newValue !== undefined) {
 
                            node.addEventListener(eventName, newValue, useCapture);
                        }
                        else {
 
                            node.removeEventListener(eventName, newValue, useCapture);
                        }
 
                        // Remove the attribute from the HTML
                        (node as HTMLElement).removeAttribute(name);
                    }
                    break;
                default: throw Error(`patch is not implemented for rule type: ${type}`);
            }
 
        }
    }
 
}
 
function createTemplate(strings: TemplateStringsArray): HTMLTemplateElement {
 
    const t = document.createElement('template');
 
    t.innerHTML = createTemplateString(strings);
 
    return t;
}
 
export function createTemplateString(strings: TemplateStringsArray): string {
 
    const parts: string[] = [];
 
    const length = strings.length - 1; // Exclude the last one
 
    for (let i = 0; i < length; ++i) {
 
        const s = strings[i];
 
        if (s.endsWith('=')) { // It is an attribute
 
            const name = getAttributeName(s);
 
            if (name[0] === 'o' && name[1] === 'n') { // It is an event handler
 
                parts.push(`${s}"${eventMarkerPrefix}${name}"`);
            }
            else {
 
                parts.push(`${s}"${attributeMarkerPrefix}${name}"`);
            }
        }
        else if (!noSelfClosingTagAfter(strings, i)) {
 
            parts.push(`${s}<!--${nodeMarker}-->`);
        }
    }
 
    parts.push(strings[length]); // Add the ending string
 
    return parts.join('');
}
 
function getAttributeName(s: string): string {
 
    let b: string[] = [];
 
    for (let i = s.lastIndexOf('=') - 1; i >= 0; --i) {
 
        if (s[i] === ' ') { // Finished with the name of the attribute
 
            break;
        }
 
        b = [s[i], ...b]; // Prepend
    }
 
    return b.join('');
}
 
const regexSelfClosingTag  = /\/>/;
 
function noSelfClosingTagAfter(strings: TemplateStringsArray, i: number) : boolean {
   
    for (; i < strings.length; ++i) {
 
        if (regexSelfClosingTag.test(strings[i])) {
 
            return true;
        }
    }
 
    return false;
}
 
function createNodePatcherRules(node: Node, path: number[] = [], rules: NodePatcherRule[] = []): NodePatcherRule[] {
 
    const {
        childNodes
    } = node;
 
    const {
        length
    } = childNodes;
 
    if (node.nodeType === Node.COMMENT_NODE &&
        (node as Text).data === nodeMarker) {
 
        rules.push({
            type: NodePatcherRuleTypes.PATCH_NODE,
            path: [...path]
        });
 
        return rules; // Comments do not have attributes and children so we are done
    }
    else if (node.nodeType === Node.TEXT_NODE) {
 
        return rules; // No need to create rules for a text literal
    }
    else {
 
        const attributes = (node as HTMLElement).attributes;
 
        if (attributes !== undefined) {
 
            rules = createAttributePatcherRules(attributes, path, rules);
        }
    }
 
    for (let i = 0; i < length; ++i) {
 
        rules = createNodePatcherRules(childNodes[i], [...path, i], rules);
    }
 
    return rules;
}
 
function createAttributePatcherRules(attributes: NamedNodeMap, path: number[], rules: NodePatcherRule[]): NodePatcherRule[] {
 
    const {
        length
    } = attributes;
 
    for (let i = 0; i < length; ++i) {
 
        const value = attributes[i].value;
 
        if (value.startsWith(attributeMarkerPrefix)) {
 
            const name = value.split(':')[1];
 
            rules.push({
                type: NodePatcherRuleTypes.PATCH_ATTRIBUTE,
                path,
                name
            });
        }
        else if (value.startsWith(eventMarkerPrefix)) {
 
            const name = value.split(':')[1];
 
            rules.push({
                type: NodePatcherRuleTypes.PATCH_EVENT,
                path,
                name
            });
        }
    }
 
    return rules;
}
 
function compileRules(node: Node, rules: NodePatcherRule[]) : CompiledNodePatcherRule[] {
 
    const compiledRules: CompiledNodePatcherRule[] = [];
 
    const length = rules.length;
 
    for (let i = 0; i < length; i++) {
 
        const {   
            type,
            path,
            name
        } = rules[i];
        
        compiledRules.push( {
            type,
            name,
            node: findNode(node, path)
        });
    }
 
    return compiledRules;
}
 
function findNode(node: Node, path: number[]): HTMLElement | Comment | Text {
 
    let p = path;
 
    for (let i = 0; i < p.length; ++i) {
 
        const index = p[i];
 
        node = node.childNodes[index];
    }
 
    return node as HTMLElement | Comment | Text;
}
 
function patchAttribute(node: HTMLElement, name: string, oldValue: string, newValue: string): boolean {
 
    Iif (newValue === undefined) { // It was removed in the new virtual node
 
        node.removeAttribute(name);
 
        return true;
    }
    else {
 
        Iif (newValue === oldValue) {
 
            return false;
        }
        else {
 
            setAttribute(node, name, newValue);
 
            return true;
        }
    }
}
 
function setAttribute(node: HTMLElement, key: string, value: string) {
 
    if (value === 'undefined' ||
        value === 'null' ||
        value === '' ||
        value === 'false') {
 
        node.removeAttribute(key);
    }
    else {
 
        Iif (value === 'true') {
 
            node.setAttribute(key, '');
        }
        else {
 
            const type = typeof value;
 
            if (type === 'object') {
 
                value = JSON.stringify(value);
            }
 
            node.setAttribute(key, value);
        }
    }
}
 
export default function patch(node: Node, newNode: Node) {
 
    const {
        patcher: oldPatcher,
        rules: oldRules,
        values: oldValues
    } = (node as any)._$patchingData;
 
    const {
        patcher: newPatcher,
        values: newValues
    } = (newNode as any)._$patchingData;
 
    if (oldPatcher === newPatcher) {
 
        oldPatcher.patchNode(node, oldRules, oldValues, { newValues });
    }
    else {
 
        throw new Error('Not implemented');
    }
}