# All files / lib/tree sync.js

100% Statements 335/335
97.26% Branches 71/73
100% Functions 1/1
100% Lines 335/335

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
    3362x
    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
    868x
    868x
    868x
    868x
    868x
    868x
    868x
    868x
    868x
    868x
    868x
    868x
    868x
    868x
    868x
    868x
    863x
    868x
    868x
    868x
    868x
    868x
    868x
    868x
    868x
    868x
    868x
    868x
    82x
    82x
    82x
    82x
    82x
    82x
    82x
    82x
    82x
    3x
    3x
    79x
    79x
    79x
    4x
    4x
    75x
    75x
    1x
    1x
    82x
    82x
    868x
    868x
    7x
    7x
    868x
    868x
    868x
    868x
    174x
    20x
    20x
    20x
    20x
    20x
    20x
    20x
    20x
    20x
    20x
    20x
    20x
    20x
    174x
    174x
    129x
    129x
    129x
    129x
    129x
    129x
    129x
    129x
    129x
    174x
    868x
    868x
    868x
    868x
    868x
    616x
    616x
    616x
    616x
    616x
    131x
    131x
    131x
    35x
    35x
    96x
    131x
    33x
    33x
    131x
    131x
    131x
    131x
    131x
    131x
    131x
    2x
    2x
    94x
    94x
    94x
    131x
    131x
    131x
    131x
    131x
    616x
    616x
    616x
    418x
    79x
    11x
    11x
    11x
    418x
    616x
    712x
    712x
    868x
    249x
    249x
    67x
    67x
    67x
    67x
    249x
    249x
    249x
    868x
    868x
    868x
    868x
    868x
    868x
    926x
    926x
    926x
    926x
    926x
    926x
    613x
    822x
    822x
    822x
    73x
    70x
    1x
    1x
    70x
    73x
    73x
    73x
    822x
    612x
    926x
    868x
    868x
    868x
    868x
    868x
    868x
    868x
    868x
    868x
    868x
    868x
    546x
    546x
    546x
    546x
    546x
    6x
    6x
    546x
    546x
    546x
    546x
    546x
    52x
    1x
    1x
    52x
    52x
    52x
    546x
    546x
    546x
    184x
    184x
    184x
    184x
    184x
    184x
    184x
    184x
    184x
    184x
    184x
    184x
    184x
    184x
    546x
    546x
    546x
    546x
    546x
    546x
    546x
    546x
    46x
    46x
    7x
    7x
    7x
    7x
    7x
    7x
    7x
    7x
    7x
    46x
    8x
    8x
    8x
    8x
    8x
    8x
    31x
    31x
    31x
    46x
    5x
    5x
    5x
    5x
    1x
    1x
    1x
    5x
    5x
    5x
    5x
    5x
    5x
    5x
    5x
    5x
    5x
    5x
    5x
    5x
    5x
    5x
    5x
    5x
    46x
    290x
    290x
    290x
    290x
    546x
    3x
    3x
    3x
    3x
    546x
    546x
    546x
    546x
    64x
    64x
    64x
    64x
    64x
    64x
    2x
    2x
    64x
    64x
    64x
    546x
    868x
    868x
    868x
    868x
    25x
    41x
    41x
    25x
    25x
    25x
    868x
    868x
    868x
     import process from '../util/process';
    import {
      SyncTreeHookCache,
      TransactionState,
      PATCH_TYPE,
      NODE_TYPE,
      VTree,
      EMPTY,
    } from '../util/types';

    const { max } = Math;
    const keyNames = ['old', 'new'];
    const textName = '#text';

    /**
     * Compares how the new state should look to the old state and mutates it,
     * while recording the changes along the way.
     *
     * @param {Partial<VTree> | null} oldTree
     * @param {Partial<VTree> | null=} newTree
     * @param {any[]} patches
     * @param {Partial<TransactionState>} state
     * @param {boolean} attributesOnly
     *
     * @return {any[] | false | null}
     */
    export default function syncTree(
      oldTree,
      newTree,
      patches = [],
      state = {},
      attributesOnly = false,
    ) {
      if (!oldTree) oldTree = /** @type {VTree} */ (EMPTY.OBJ);
      if (!newTree) newTree = /** @type {VTree} */ (EMPTY.OBJ);

      const { svgElements = new Set() } = state;
      const oldNodeName = oldTree.nodeName;
      const newNodeName = newTree.nodeName;
      const isEmpty = oldTree === EMPTY.OBJ || attributesOnly;

      // Check for SVG in parent.
      const isSVG = newNodeName === 'svg' || svgElements.has(
        /** @type {VTree} */ (newTree)
      );

      let shortCircuit = null;

      // Invoke the SyncTree hooks which allow middleware to do their own custom
      // sync logic. This may mean short-circuiting the sync completely by
      // returning the previous tree. This effectively sandboxes an element in the
      // DOM from changes or diffs. Another useful way to use these hooks are to
      // take the new tree, and convert it into something else. This is how
      // components are implemented.
      if (SyncTreeHookCache.size) {
        SyncTreeHookCache.forEach(fn => {
          // Call the user provided middleware function for a single root node.
          // Allow the consumer to specify a return value of a different VTree
          // (useful for components).
          const entry = fn(oldTree, newTree);

          // If the value returned matches the original element, then short circuit
          // and do not dig further.
          if (entry && entry === oldTree) {
            shortCircuit = patches;
          }
          // Allow skipping an element for diffing. It will be preserved and kept
          // in the DOM.
          else if (entry === false) {
            shortCircuit = false;
          }
          // If the user has returned a value, treat it as the new tree.
          else if (entry) {
            newTree = entry;
          }
        });
      }

      if (shortCircuit !== null || !newTree) {
        return shortCircuit;
      }

      // Text nodes are low level and frequently change, so this path is accounted
      // for first.
      if (newNodeName === textName) {
        if (oldNodeName === textName && oldTree.nodeValue !== newTree.nodeValue) {
          // If both VTrees are text nodes and the values are different, change the
          // `Element#nodeValue`.
          patches.push(
            PATCH_TYPE.NODE_VALUE,
            oldTree,
            newTree.nodeValue,
            oldTree.nodeValue,
          );

          oldTree.nodeValue = newTree.nodeValue;

          return patches;
        }
        // Ensure new text nodes have decoded entities.
        else if (isEmpty) {
          patches.push(
            PATCH_TYPE.NODE_VALUE,
            newTree,
            newTree.nodeValue,
            null,
          );

          return patches;
        }
      }

      const newChildNodes = newTree.childNodes || [];

      // Seek out attribute changes first, but only from element Nodes.
      if (newTree.nodeType === NODE_TYPE.ELEMENT) {
        const oldAttributes = isEmpty ? EMPTY.OBJ : oldTree.attributes;
        const newAttributes = newTree.attributes || {};

        // Search for sets and changes.
        for (let key in newAttributes) {
          const value = newAttributes[key];

          if (key in oldAttributes && oldAttributes[key] === newAttributes[key]) {
            continue;
          }

          if (!isEmpty) {
            oldAttributes[key] = value;
          }

          // Skip script types as these are handled special by the transaction
          // patch and end tasks.
          if (
            // Do not block existing scripts being modified.
            (!oldTree || oldTree.nodeName !== 'script')
            && newTree.nodeName === 'script' && key === 'type') {
            continue;
          }

          patches.push(
            PATCH_TYPE.SET_ATTRIBUTE,
            isEmpty ? newTree : oldTree,
            key,
            value,
          );
        }

        // Search for removals.
        if (!isEmpty) {
          for (let key in oldAttributes) {
            if (key in newAttributes) { continue; }
            patches.push(PATCH_TYPE.REMOVE_ATTRIBUTE, oldTree, key);
            delete oldAttributes[key];
          }
        }
      }

      // Scan all childNodes for attribute changes.
      if (attributesOnly) {
        // Do a single pass over the new child nodes.
        for (let i = 0; i < newChildNodes.length; i++) {
          // Ensure all SVG elements are tracked.
          isSVG && svgElements.add(newChildNodes[i]);
          syncTree(null, newChildNodes[i], patches, state, true);
        }

        return patches;
      }

      /** @type {any} */
      const keysLookup = { old: new Map(), new: new Map() };

      // Reduce duplicate logic by condensing old and new operations in a loop.
      for (let i = 0; i < keyNames.length; i++) {
        const keyName = keyNames[i];
        const map = keysLookup[keyName];
        const vTree = arguments[i];
        const nodes = vTree && vTree.childNodes;

        if (nodes && nodes.length) {
          for (let i = 0; i < nodes.length; i++) {
            const vTree = nodes[i];

            if (vTree.key) {
              if (process.env.NODE_ENV !== 'production') {
                if (map.has(vTree.key)) {
                  throw new Error(`Key: ${vTree.key} cannot be duplicated`);
                }
              }

              map.set(vTree.key, vTree);
            }
          }
        }
      }

      /** @type {VTree[]} */
      const oldChildNodes = (oldTree.childNodes) || [];

      // Used when skipping over nodes during syncTreeHook.
      let maxLength = max(newChildNodes.length, oldChildNodes.length);

      // Always perform a full diff based on the largest set of nodes. The end user
      // may want to do something with any of them, so while it may be more
      // performant to only loop over the new nodes, we loop over all instead.
      for (let i = 0; i < maxLength; i++) {
        const oldChildNode = oldChildNodes && oldChildNodes[i];
        const newChildNode = newChildNodes[i];

        // Check for SVG in child as well.
        if (isSVG || (newChildNode && newChildNode.nodeName === 'svg')) {
          svgElements.add(newChildNode);
        }

        // If there is no new child node, we will skip this comparison. If the old
        // node is something we want to preserve, we can migrate it to the new
        // nodes.
        if (!newChildNode) {
          if (syncTree(oldChildNode, null, patches, state, true) === false) {
            newChildNodes.splice(i, 0, oldChildNode);
          }

          continue;
        }

        // If there is no old element to compare to, this is a simple addition.
        if (!oldChildNode) {
          oldChildNodes.push(newChildNode);

          // Crawl this Node for any changes to apply.
          syncTree(null, newChildNode, patches, state, true);

          patches.push(
            PATCH_TYPE.INSERT_BEFORE,
            oldTree,
            newChildNode,
            null,
          );

          continue;
        }

        const newKey = newChildNode.key;
        const oldKey = oldChildNode.key;
        const oldInNew = keysLookup.new.has(oldKey);
        const newInOld = keysLookup.old.has(newKey);

        // If we are working with keys, we can follow an optimized path.
        if (oldKey || newKey) {
          // Remove the old node instead of replacing.
          if (!oldInNew && !newInOld) {
            oldChildNodes.splice(oldChildNodes.indexOf(oldChildNode), 1, newChildNode);
            syncTree(null, newChildNode, patches, state, true);

            patches.push(PATCH_TYPE.REPLACE_CHILD, newChildNode, oldChildNode);

            i = i - 1;

            continue;
          }
          else if (!oldInNew) {
            patches.push(PATCH_TYPE.REMOVE_CHILD, oldChildNode);
            oldChildNodes.splice(oldChildNodes.indexOf(oldChildNode), 1);
            i = i - 1;

            continue;
          }

          // If there is a key set for this new element, use that to figure out
          // which element to use.
          if (newKey !== oldKey) {
            let optimalNewNode = newChildNode;

            // Prefer existing to new and remove from old position.
            if (newKey && newInOld) {
              optimalNewNode = keysLookup.old.get(newKey);
              oldChildNodes.splice(oldChildNodes.indexOf(optimalNewNode), 1);
            }
            else {
              optimalNewNode = newChildNode;
            }

            // Crawl this Node for any changes to apply.
            syncTree(null, optimalNewNode, patches, state, true);

            patches.push(
              PATCH_TYPE.INSERT_BEFORE,
              oldTree,
              optimalNewNode,
              oldChildNode,
            );

            oldChildNodes.splice(i, 0, optimalNewNode);
            continue;
          }
        }

        const sameType = oldChildNode.nodeName === newChildNode.nodeName;
        const retVal = syncTree(oldChildNode, newChildNode, patches, state, !sameType);

        if (retVal === false) {
          newChildNodes.splice(i, 0, oldChildNode);
          maxLength += 1;
          continue;
        }

        // If the element we're replacing is totally different from the previous
        // replace the entire element, don't bother investigating children.
        if (!sameType) {
          oldChildNodes[i] = newChildNode;

          // This only works if VTrees are identical.
          const lookupIndex = oldChildNodes.lastIndexOf(newChildNode);

          if (lookupIndex > i) {
            oldChildNodes.splice(lookupIndex, 1);
          }

          patches.push(PATCH_TYPE.REPLACE_CHILD, newChildNode, oldChildNode);
        }
      }

      // We've reconciled new changes, so we can remove any old nodes and adjust
      // lengths to be equal.
      if (oldChildNodes.length !== newChildNodes.length) {
        for (let i = newChildNodes.length; i < oldChildNodes.length; i++) {
          patches.push(PATCH_TYPE.REMOVE_CHILD, oldChildNodes[i]);
        }

        oldChildNodes.length = newChildNodes.length;
      }

      return patches;
    }