All files / src/renderer NodeSharedPatchingData.ts

7.32% Statements 6/82
0% Branches 0/26
0% Functions 0/10
7.89% Lines 6/76

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 26316x                                               16x   16x         16x                                                                                                                   16x                                                                                                                                                                                                                                                               16x                                                                                          
import NodePatcher, { nodeMarker, 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[];
 
    /**
     * The cloned patching rules with the references to the nodes to act upon
     */
    rules;
}
 
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 rules = cloneRules(node, this._patcher.rules);
 
        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
            rules
        };
 
        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}<!--${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('');
}
 
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;
}
 
const regexSelfClosingTag  = /\/>/;
 
function noSelfClosingTagAfter(strings: TemplateStringsArray, i: number) : boolean {
   
    for (; i < strings.length; ++i) {
 
        if (regexSelfClosingTag.test(strings[i])) {
 
            return true;
        }
    }
 
    return false;
}
 
function cloneRules(content: Node, rules: NodePatcherRule[]) : NodePatcherRule[] {
 
    const clonedRules: NodePatcherRule[] = [];
 
    const length = rules.length;
 
    for (let i = 0; i < length; i++) {
 
        const clonedRule = { ...rules[i] };
 
        clonedRule.node = findNode(content, clonedRule.path);
        
        clonedRules.push(clonedRule);
    }
 
    return clonedRules;
}
 
function findNode(node: Node, path: number[]): Node {
 
    let p = path;
 
    for (let i = 0; i < p.length; ++i) {
 
        const index = p[i];
 
        node = node.childNodes[index];
    }
 
    return node;
}