All files / renderer NodeSharedPatchingData.ts

100% Statements 67/67
100% Branches 26/26
100% Functions 8/8
100% Lines 63/63

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 22515x                                     15x   15x         15x                           31x   31x   31x           116x   116x       116x   116x         116x                     31x   31x   31x     15x   147x   147x   147x   298x   298x   165x   165x   29x       136x     133x   124x       147x   147x         165x   165x   933x   165x     768x     165x             111x       111x   111x     25x         25x   86x   22x       64x   64x   33x       64x   80x     64x             33x   33x   32x   32x   25x   25x           7x   4x   4x               33x     15x       133x   299x   9x       124x      
import NodePatcher, { commentMarker, NodePatcherRule, NodePatcherRuleTypes } from "./NodePatcher";
 
interface NodeInstancePatchingData {
    /**
     * The patching data shared among the nodes generated by the same template 
     */
    sharedPatchingData: NodeSharedPatchingData;
 
    /**
     * The values previously used to generate the node from the template
     */
    values: any[];
}
 
interface NodeInstancePatchingDataHolder {
 
    __instancePatchingData__: NodeInstancePatchingData;
}
 
export const attributeMarkerPrefix = "_$attr:";
 
export const eventMarkerPrefix = "_$evt:";
 
/**
 * The shared patching data of the nodes generated by the same template
 */
export default class NodeSharedPatchingData {
 
    /**
     * The patcher to patch the node
     */
    private _patcher: NodePatcher;
 
    /**
     * The template to clone and generate the node from
     */
    private _template: HTMLTemplateElement;
 
    constructor(strings: TemplateStringsArray) {
 
        this._template = createTemplate(strings);
 
        const rules: NodePatcherRule[] = createNodePatcherRules(this._template.content);
 
        this._patcher = new NodePatcher(rules);
    }
 
    createNode(oldValues: any[], newValues: any[]): Node {
 
        // The content of the template is a document fragment
        let node = this._template.content.cloneNode(/*deep*/true);
 
        const newValuesHolder = {
            newValues
        }
 
        this._patcher.patch(node, oldValues, newValuesHolder);
 
        (node as unknown as NodeInstancePatchingDataHolder).__instancePatchingData__ = {
            sharedPatchingData: this,
            values: newValuesHolder.newValues // Store the old values to compare
        };
 
        return node;
    }
 
    // patchNode(node: Node, oldValues, newValues): void {
 
    //     this._patcher.patch(node, oldValues, newValues);
    // }
}
 
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}<!--${commentMarker}-->`);
        }
    }
 
    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('');
}
 
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 === commentMarker) {
 
        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;
}
 
const regexSelfClosingTag  = /\/>/;
 
function noSelfClosingTagAfter(strings: TemplateStringsArray, i: number) : boolean {
   
    for (; i < strings.length; ++i) {
 
        if (regexSelfClosingTag.test(strings[i])) {
 
            return true;
        }
    }
 
    return false;
}