# All files / lib transaction.js

100% Statements 336/336
94.73% Branches 36/38
100% Functions 11/11
100% Lines 336/336

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
    3372x
    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
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    265x
    265x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    249x
    249x
    249x
    249x
    249x
    2018x
    2018x
    3x
    3x
    2018x
    2018x
    2018x
    2018x
    2018x
    2018x
    2018x
    2018x
    2018x
    2018x
    232x
    232x
    2018x
    249x
    249x
    249x
    2x
    2x
    2x
    2x
    2x
    2x
    243x
    243x
    4x
    4x
    243x
    243x
    1x
    1x
    238x
    243x
    1x
    1x
    243x
    243x
    2x
    2x
    2x
    2x
    2x
    2x
    240x
    240x
    240x
    22x
    22x
    22x
    22x
    22x
    22x
    22x
    22x
    22x
    4x
    4x
    22x
    22x
    240x
    240x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    267x
    267x
    267x
    267x
    267x
    267x
    267x
    267x
    177x
    177x
    177x
    177x
    177x
    267x
    267x
    267x
    267x
    267x
    267x
    267x
    267x
    267x
    267x
    267x
    2x
    2x
    2x
    2x
    2x
    244x
    243x
    243x
    244x
    244x
    244x
    244x
    244x
    244x
    244x
    244x
    244x
    244x
    244x
    244x
    244x
    244x
    244x
    244x
    244x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    13x
    13x
    13x
    13x
    13x
    4x
    4x
    13x
    2x
    2x
    2x
    2x
    2x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    8x
    8x
    8x
    8x
    8x
    8x
    1x
    1x
    8x
    8x
    8x
    8x
    8x
    8x
    8x
    8x
    8x
    3x
    3x
    3x
    7x
    7x
    7x
    7x
    7x
    7x
    8x
    1x
    1x
    1x
    8x
    8x
    8x
    8x
    8x
    8x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    221x
    2x
    2x
    2x
    2x
    2x
    19x
    19x
    2x
    2x
    2x
    267x
    267x
    267x
    267x
    267x
    267x
    267x
    267x
    267x
    267x
    267x
    267x
    267x
    267x
    267x
    267x
    267x
    267x
    267x
    267x
    267x
    267x
    267x
    267x
    2x
     import {
      MiddlewareCache,
      StateCache,
      NodeCache,
      VTree,
      ValidInput,
      Mount,
      TransactionConfig,
      TransactionState,
      EMPTY,
    } from './util/types';
    import makeMeasure from './util/make-measure';
    import process from './util/process';
    import { protectVTree, gc } from './util/memory';
    import globalThis from './util/global';
    import schedule from './tasks/schedule';
    import shouldUpdate from './tasks/should-update';
    import reconcileTrees from './tasks/reconcile-trees';
    import syncTrees from './tasks/sync-trees';
    import patchNode from './tasks/patch-node';
    import endAsPromise from './tasks/end-as-promise';
    import release from './release';
    import getConfig from './util/config';
    import hasModule from './util/has-module';

    const { assign } = Object;

    export const defaultTasks = [
      schedule, shouldUpdate, reconcileTrees, syncTrees, patchNode, endAsPromise,
    ];

    export const tasks = {
      schedule, shouldUpdate, reconcileTrees, syncTrees, patchNode, endAsPromise,
    };

    export default class Transaction {
      /**
       *
       * @param {Mount} mount
       * @param {ValidInput} input
       * @param {TransactionConfig} options
       */
      static create(mount, input, options) {
        return new Transaction(mount, input, options);
      }

      /**
       * @param {Transaction} transaction
       * @param {any} tasks
       *
       * @return {Promise<Transaction> | unknown}
       */
      static flow(transaction, tasks) {
        let retVal = transaction;

        // Execute each "task" serially, passing the transaction as a baton that
        // can be used to share state across the tasks.
        for (let i = 0; i < tasks.length; i++) {
          // If aborted, don't execute any more tasks.
          if (transaction.aborted) {
            return retVal;
          }

          // Run the task.
          retVal = tasks[i](transaction);

          // The last `returnValue` is what gets sent to the consumer. This
          // mechanism is crucial for the `abort`, if you want to modify the "flow"
          // that's fine, but you must ensure that your last task provides a
          // mechanism to know when the transaction completes. Something like
          // callbacks or a Promise.
          if (retVal !== undefined && retVal !== transaction) {
            return retVal;
          }
        }

        return retVal;
      }

      /**
       *
       * @param {Transaction} transaction
       */
      static assert(transaction) {
        if (process.env.NODE_ENV !== 'production') {
          if (typeof transaction.mount !== 'object' || !transaction.mount) {
            throw new Error('Transaction requires a DOM Node mount point');
          }

          if (transaction.aborted && transaction.completed) {
            throw new Error('Transaction was previously aborted');
          }

          if (transaction.completed) {
            throw new Error('Transaction was previously completed');
          }
        }
      }

      /**
       *
       * @param {Transaction} transaction
       */
      static invokeMiddleware(transaction) {
        const { state: { measure }, tasks } = transaction;

        MiddlewareCache.forEach(fn => {
          const label = `invoke ${fn.name || 'anon'}`;
          measure(label);

          // Invoke all the middleware passing along this transaction as the only
          // argument. If they return a value (must be a function) it will be added
          // to the transaction task flow.
          const result = fn(transaction);

          if (result) {
            tasks.push(result);
          }

          measure(label);
        });
      }

      /**
       * @constructor
       * @param {Mount} mount
       * @param {ValidInput} input
       * @param {TransactionConfig} config
       */
      constructor(mount, input, config) {
        this.mount = mount;
        this.input = input;
        this.config = config;

        const isDirtyCheck = () => this.state.isDirty = true;
        const hasObserver = 'MutationObserver' in (globalThis.window || EMPTY.OBJ);

        this.state = StateCache.get(mount) || /** @type {TransactionState} */ ({
          measure: makeMeasure(this),
          svgElements: new Set(),
          scriptsToExecute: new Map(),
          activeTransaction: this,
          mutationObserver: hasObserver && new globalThis.window.MutationObserver(isDirtyCheck),
        });

        this.tasks = /** @type {Function[]} */ (
          getConfig('tasks', defaultTasks, undefined, config)
        ).slice();

        // Store calls to trigger after the transaction has ended.
        this.endedCallbacks = new Set();

        StateCache.set(mount, this.state);
      }

      /**
       * @return {Promise<Transaction> | unknown}
       */
      start() {
        if (process.env.NODE_ENV !== 'production') {
          Transaction.assert(this);
        }

        const { state: { measure }, tasks } = this;
        const takeLastTask = tasks.pop();

        // Start measuring a render for performance tracing.
        measure('render');

        this.aborted = false;

        // Add middleware in as tasks.
        Transaction.invokeMiddleware(this);

        // Push back the last task as part of ending the flow.
        takeLastTask && tasks.push(takeLastTask);

        return Transaction.flow(this, tasks);
      }

      /**
       * This will immediately call the last flow task and terminate the flow. We
       * call the last task to ensure that the control flow completes. This should
       * end psuedo-synchronously. Think `Promise.resolve()`, `callback()`, and
       * `return someValue` to provide the most accurate performance reading. This
       * doesn't matter practically besides that.
       *
       * @param {boolean=} isReturn
       */
      abort(isReturn) {
        this.aborted = true;

        // Grab the last task in the flow and return, this task will be responsible
        // for calling `transaction.end`.
        if (isReturn) {
          return this.tasks[this.tasks.length - 1](this);
        }
      }

      /**
       * @return {Transaction}
       */
      end() {
        const { state, config, mount } = this;
        const { mutationObserver, measure, svgElements, scriptsToExecute } = state;

        const mountAsHTMLEl = /** @type {HTMLElement} */ (mount);

        measure('finalize');

        this.completed = true;

        // Clean up SVG element list.
        svgElements.clear();

        // Rendering is complete.
        state.isRendering = false;
        state.isDirty = false;

        // If MutationObserver is available, look for changes.
        if (mountAsHTMLEl.ownerDocument && mutationObserver) {
          mutationObserver.observe(mountAsHTMLEl, {
            subtree: true,
            childList: true,
            attributes: true,
            characterData: true,
          });
        }
        // If there is no MutationObserver, then the DOM is dirty by default and
        // rescanned every time.
        else {
          state.isDirty = true;
        }

        // Only execute scripts if the configuration is set. By default this is set
        // to true. You can toggle this behavior for your app to disable script
        // execution.
        // Execute deferred scripts by cloning them and reattaching into the same
        // position.
        scriptsToExecute.forEach((type, vTree)=> {
          const oldNode = NodeCache.get(vTree);

          // Reset the type attribute back to the original.
          oldNode.type = type;

          if (!config.executeScripts || (hasModule() && type === 'nomodule')) {
            return;
          }

          // Copy over properties to the new script element.
          const newNode = assign(
            oldNode.ownerDocument.createElement('script'),
            oldNode,
          );

          // Copy over attributes.
          for (let key in vTree.attributes) {
            const value = vTree.attributes[key];
            newNode.setAttribute(key, value);
          }

          // Copy over body.
          newNode.textContent = oldNode.textContent;

          // If the script is now the root element, make sure we cleanup and
          // re-assign.
          if (StateCache.has(oldNode)) {
            release(oldNode);
            StateCache.set(newNode, state);
          }

          // Replace the node association.
          NodeCache.set(vTree, newNode);

          // Replace the scripts to trigger default browser behavior.
          oldNode.parentNode && oldNode.parentNode.replaceChild(newNode, oldNode);
        });

        // Empty the scripts to execute.
        scriptsToExecute.clear();

        // Trigger all `onceEnded` callbacks, so that middleware can know the
        // transaction has ended.
        this.endedCallbacks.forEach(callback => callback(this));
        this.endedCallbacks.clear();

        // Mark the end to rendering.
        measure('finalize');
        measure('render');

        // Ensure the tree is fully protected before ending the transaction.
        if (state.oldTree) protectVTree(state.oldTree);

        // Run garbage collection after every successful render. Ensure that the
        // oldTree (current state) is solidified to not accidentially deallocate
        // something required. This allows VTrees to be reused quicker and reduce
        // memory overload.
        gc();

        return this;
      }

      /**
       * @param {Function} callback
       */
      onceEnded(callback) {
        this.endedCallbacks.add(callback);
      }

      /** @type {TransactionState} */
      state = EMPTY.OBJ;

      /** @type {Mount} */
      mount = EMPTY.OBJ;

      /** @type {ValidInput} */
      input = EMPTY.OBJ;

      /** @type {VTree=} */
      oldTree = undefined;

      /** @type {VTree=} */
      newTree = undefined;

      /** @type {Promise<any>=} */
      promise = undefined

      /** @type {Promise<any>[]=} */
      promises = undefined

      /** @type {Function[]} */
      tasks = []

      /** @type any */
      patches = []
    }