All files / lib/node patch.js

97.57% Statements 362/371
98.59% Branches 70/71
100% Functions 4/4
97.57% Lines 362/371

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 3722x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 51x 51x 47x 44x 44x 44x 44x 44x 1x 1x 44x 98x 98x 98x 98x 98x 87x 87x 87x 87x 87x 98x 98x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 18x 18x 18x 18x 18x 5x 5x 5x 18x 11x 11x 11x 11x 11x 11x 2x 2x 11x 18x 18x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 151x 151x 151x 4x 4x 151x 151x 151x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 276x 276x 276x 276x 276x 276x 276x 832x 832x 832x 276x 276x 556x 556x 832x 832x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 6x 6x 6x 6x 6x 116x 116x 116x 116x 116x 116x 832x 832x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 10x 10x 10x 10x 10x 151x 151x 151x 151x 151x 151x 832x 832x 178x 178x 178x 178x 178x 178x 178x 16x 16x 162x 162x 162x 162x 162x 162x 162x 162x 162x 178x                   178x 178x 178x 178x 178x 178x 1x 178x 178x 178x 178x 178x 178x 178x 178x 178x 178x 178x 178x 178x 178x 832x 832x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 1x 1x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 60x 60x 60x 60x 60x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 3x 3x 3x 3x 69x 69x 69x 832x 832x 42x 42x 42x 42x 42x 42x 42x 1x 1x 41x 41x 41x 42x 3x 3x 3x 3x 3x 3x 3x 3x 3x 42x 42x 42x 42x 42x 42x 42x 832x 832x 276x 276x 276x  
import createNode from './create';
import { runTransitions } from '../transition';
import { protectVTree, unprotectVTree } from '../util/memory';
import decodeEntities from '../util/decode-entities';
import {
  PATCH_TYPE,
  ValidNode,
  VTree,
  EMPTY,
  TransactionState,
  NodeCache,
  TransitionCache,
} from '../util/types';
import { $$insertAfter } from '../util/symbols';
 
const { keys } = Object;
const blocklist = new Set();
const allowlist = new Set();
 
/**
 * Sets an attribute on an element.
 *
 * @param {VTree} vTree
 * @param {ValidNode} domNode
 * @param {string} name
 * @param {any} value
 *
 * @return {void}
 */
const setAttribute = (vTree, domNode, name, value) => {
  const isObject = typeof value === 'object' && value;
  const isFunction = typeof value === 'function';
  const isSymbol = typeof value === 'symbol';
  const isEvent = name.indexOf('on') === 0;
  const anyNode = /** @type {any} */ (domNode);
 
  // Events must be lowercased otherwise they will not be set correctly.
  const lowerName = isEvent ? name.toLowerCase() : name;
 
  // Runtime checking if the property can be set.
  const blocklistName = 's-' + vTree.nodeName + '-' + lowerName;
 
  /** @type {HTMLElement} */
  const htmlElement = /** @type {any} */ (domNode);
 
  // Since this is a property value it gets set directly on the node.
  if (allowlist.has(blocklistName)) {
    anyNode[lowerName] = value;
  }
  else if (!blocklist.has(blocklistName)) {
    try {
      anyNode[lowerName] = value;
      allowlist.add(blocklistName);
    }
    catch {
      blocklist.add(blocklistName);
    }
  }
 
  // If the value is not an object, function, or symbol, then attempt to
  // set as an attribute. If the value is one of the excluded types, they
  // will be set below.
  if (!isObject && !isFunction && !isSymbol) {
    // For boolean/empty attributes, do not try and set a value, just an empty
    // string.
    const emptyValue = value === null || value === undefined || value === true;
    htmlElement.setAttribute(lowerName, emptyValue ? EMPTY.STR : value);
  }
  // Support patching an object representation of the style object.
  else if (isObject && lowerName === 'style') {
    const valueKeys = /** @type {any} */ (keys(value));
 
    for (let i = 0; i < valueKeys.length; i++) {
      htmlElement.style[valueKeys[i]] = value[valueKeys[i]];
    }
  }
};
 
/**
 * Removes an attribute from an element.
 *
 * @param {VTree} vTree
 * @param {ValidNode} domNode
 * @param {string} name
 * @return {void}
 */
const removeAttribute = (vTree, domNode, name) => {
  // Runtime checking if the property can be set.
  const blocklistName = 'r-' + vTree.nodeName + '-' + name;
  const anyNode = /** @type {any} */ (domNode);
 
  if (allowlist.has(blocklistName)) {
    anyNode[name] = undefined;
    delete anyNode[name];
  }
  else if (!blocklist.has(blocklistName)) {
    try {
      anyNode[name] = undefined;
      delete anyNode[name];
      allowlist.add(blocklistName);
    }
    catch {
      blocklist.add(blocklistName);
    }
  }
 
  /** @type {HTMLElement} */ (domNode).removeAttribute(name);
};
 
/**
 * Changes the nodeValue (text) content of an element.
 *
 * @param {ValidNode} domNode
 * @param {string} nodeValue
 *
 * @return {void}
 */
const changeNodeValue = (domNode, nodeValue) => {
  const htmlElement = /** @type {HTMLElement} */ (domNode);
 
  if (nodeValue.includes('&')) {
    htmlElement.nodeValue = decodeEntities(nodeValue);
  }
  else {
    htmlElement.nodeValue = nodeValue;
  }
};
 
/**
 *
 * @param {*} patches
 * @param {TransactionState=} state
 *
 * @return {Promise<any>[]}
 */
export default function patchNode(patches, state = EMPTY.OBJ) {
  const promises = [];
  const { ownerDocument, svgElements = new Set() } = state;
  const { length } = patches;
 
  let i = 0;
 
  while (true) {
    const patchType = patches[i];
 
    if (i === length) {
      break;
    }
 
    switch(patchType) {
      case PATCH_TYPE.REMOVE_ATTRIBUTE:
      case PATCH_TYPE.SET_ATTRIBUTE: {
        const isSet = patchType === PATCH_TYPE.SET_ATTRIBUTE;
        const vTree = patches[i + 1];
        const name = patches[i + 2];
        const value = isSet ? decodeEntities(patches[i + 3]) : null;
 
        i += isSet ? 4 : 3;
 
        const isSVG = svgElements.has(vTree);
        const domNode = /** @type {HTMLElement} */ (
          createNode(vTree, ownerDocument, isSVG)
        );
 
        const oldValue = domNode.getAttribute(name);
        const attributeChangedPromises = runTransitions(
          'attributeChanged', vTree, name, oldValue, value
        );
 
        protectVTree(vTree);
 
        const setOrRemove = isSet ? setAttribute : removeAttribute;
 
        if (attributeChangedPromises.length) {
          Promise.all(attributeChangedPromises)
            .then(() => setOrRemove(vTree, domNode, name, value));
 
          promises.push(...attributeChangedPromises);
        }
        else {
          setOrRemove(vTree, domNode, name, value);
        }
 
        break;
      }
 
      case PATCH_TYPE.NODE_VALUE: {
        const vTree = patches[i + 1];
        const nodeValue = patches[i + 2];
        const oldValue = patches[i + 3];
        const isSVG = svgElements.has(vTree);
 
        i += 4;
 
        const domNode = /** @type {Text} */ (
          createNode(vTree, ownerDocument, isSVG)
        );
 
        protectVTree(vTree);
 
        const textChangedPromises = runTransitions(
          'textChanged', vTree, oldValue, nodeValue
        );
 
        if (textChangedPromises.length) {
          Promise.all(textChangedPromises)
            .then(() => changeNodeValue(domNode, nodeValue));
 
          promises.push(...textChangedPromises);
        }
        else {
          changeNodeValue(domNode, nodeValue);
        }
 
        break;
      }
 
      case PATCH_TYPE.INSERT_BEFORE: {
        const vTree = patches[i + 1];
        const newTree = patches[i + 2];
        let refTree = patches[i + 3];
 
        i += 4;
 
        if (!NodeCache.has(vTree) && vTree !== $$insertAfter) {
          continue;
        }
 
        // First attempt to locate a pre-existing DOM Node. If one hasn't been
        // created there could be a few reasons.
        let domNode = /** @type {HTMLElement} */ (
          NodeCache.get(vTree)
        );
 
        // This allows turning insertBefore into insertAfter. It is only used
        // for Components, but could be used externally as well.
        if (vTree === $$insertAfter) {
          const refNode = NodeCache.get(refTree);

          // Try and find the parentNode if it exists.
          if (refNode) {
            domNode = refNode.parentNode;

            refTree = refNode.nextSibling ? refNode.nextSibling : null;
          }
        }
 
        const isSVG = svgElements.has(newTree);
 
        protectVTree(newTree);
 
        const refNode = refTree && /** @type {HTMLElement} */ (
          createNode(refTree, ownerDocument, isSVG)
        );
 
        const newNode = /** @type {HTMLElement} */ (
          createNode(newTree, ownerDocument, isSVG)
        );
 
        // If refNode is `undefined` then it will simply append like
        // `appendChild`.
        domNode.insertBefore(newNode, refNode || null);
 
        promises.push(...runTransitions('attached', newTree));
 
        break;
      }
 
      case PATCH_TYPE.REPLACE_CHILD: {
        const newTree = patches[i + 1];
        const oldTree = patches[i + 2];
 
        i += 3;
 
        const isSVG = svgElements.has(newTree);
 
        const oldDomNode = /** @type {HTMLElement} */ (NodeCache.get(oldTree));
        const newDomNode = /** @type {HTMLElement} */ (
          createNode(newTree, ownerDocument, isSVG)
        );
 
        // Patching without an existing DOM Node is a mistake, so we should not
        // attempt to do anything in this case.
        if (!oldDomNode || !oldDomNode.parentNode) {
          break;
        }
 
        // Ensure the `newTree` is protected before any DOM operations occur.
        // This is due to the `connectedCallback` in Web Components firing off,
        // and possibly causing a `gc()` to wipe this out.
        protectVTree(newTree);
 
        // Check if there are any transitions, if none, then we can skip
        // inserting and removing, and instead use a much faster replaceChild.
        const hasAttached = TransitionCache.get('attached')?.size;
        const hasDetached = TransitionCache.get('detached')?.size;
        const hasReplaced = TransitionCache.get('replaced')?.size;
 
        // In the hot path, ensure we always use the fastest operation given
        // the constraints. If there are no transitions, do not use the more
        // expensive, but more expressive path.
        if (!hasAttached && !hasDetached && !hasReplaced) {
          oldDomNode.parentNode.replaceChild(newDomNode, oldDomNode);
          unprotectVTree(oldTree);
 
          break;
        }
 
        // Always insert before to allow the element to transition.
        oldDomNode.parentNode.insertBefore(newDomNode, oldDomNode);
 
        const allPromises = [
          ...(hasAttached && runTransitions('attached', newTree) || EMPTY.ARR),
          ...(hasDetached && runTransitions('detached', oldTree) || EMPTY.ARR),
          ...(hasReplaced && runTransitions('replaced', oldTree, newTree) || EMPTY.ARR),
        ];
 
        if (allPromises.length) {
          // Do full replace and cleanup once transitions have completed.
          Promise.all(allPromises).then(() => {
            if (oldDomNode.parentNode) {
              oldDomNode.parentNode.removeChild(oldDomNode);
            }
            unprotectVTree(oldTree);
          });
 
          promises.push(...allPromises);
        }
        else {
          oldDomNode.parentNode.removeChild(oldDomNode);
          unprotectVTree(oldTree);
        }
 
        break;
      }
 
      case PATCH_TYPE.REMOVE_CHILD: {
        const vTree = patches[i + 1];
 
        i += 2;
 
        const domNode = /** @type {HTMLElement} */ (NodeCache.get(vTree));
 
        if (!domNode || !domNode.parentNode) {
          break;
        }
 
        const detachedPromises = runTransitions('detached', vTree);
 
        if (detachedPromises.length) {
          Promise.all(detachedPromises).then(() => {
            if (domNode.parentNode) {
              domNode.parentNode.removeChild(domNode);
            }
            unprotectVTree(vTree);
          });
 
          promises.push(...detachedPromises);
        }
        else {
          domNode.parentNode.removeChild(domNode);
          unprotectVTree(vTree);
        }
 
        break;
      }
    }
  }
 
  return promises;
}