# All files / lib component.js

99.55% Statements 443/445
92.64% Branches 63/68
100% Functions 24/24
99.55% Lines 443/445

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
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    4462x
    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
    44x
    28x
    28x
    28x
    28x
    44x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    28x
    61x
    61x
    61x
    61x
    58x
    58x
    3x
    3x
    3x
    61x
    28x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    22x
    22x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    112x
    112x
    112x
    112x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    110x
    110x
    110x
    110x
    110x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    129x
    129x
    129x
    129x
    129x
    129x
    129x
    129x
    129x
    129x
    129x
    129x
    129x
    107x
    107x
    107x
    129x
    129x
    129x
    129x
    129x
    129x
    125x
    11x
    9x
    9x
    10x
    10x
    125x
    125x
    129x
    129x
    129x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    1x
    1x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    15x
    15x
    15x
    14x
    14x
    14x
    14x
    14x
    14x
    13x
    13x
    14x
    14x
    14x
    14x
    14x
    15x
    15x
    15x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    19x
    17x
    17x
    17x
    17x
    17x
    17x
    17x
    17x
    19x
    19x
    19x
    2x
    2x
    2x
    129x
    129x
    129x
    129x
    129x
    129x
    129x
    129x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    63x
    63x
    38x
    38x
    38x
    38x
    38x
    38x
    38x
    38x
    38x
    38x
    38x
    38x
    38x
    38x
    38x
    38x
    38x
    38x
    38x
    25x
    25x
    25x
    25x
    25x
    25x
    25x
    25x
    25x
    25x
    25x
    25x
    25x
    25x
    25x
    25x
    63x
    63x
    63x
    63x
    63x
    63x
    63x
    63x
    63x

    63x
    63x
    63x
    63x
    63x
    63x
    13x
    13x
    13x
    13x
    13x
    63x
    63x
    63x
    63x
    63x
    63x
    63x
    63x
    63x
    25x
    25x
    25x
    25x
    54x
    54x
    54x
    54x
    8x
    8x
    8x
    8x
    8x
    8x
    8x
    8x
    46x
    46x
    6x
    6x
    6x
    6x
    6x
    6x
    6x
    6x
    6x
    46x
    46x
    46x
    46x
    54x
    54x
    54x
    25x
    25x
    63x
    63x
    63x
    63x
    63x
    63x
    63x
    63x
    63x
    63x
    25x
    25x
    25x
    25x
    25x
    25x
    63x
    63x
    2x
    2x
    22x
    22x
    22x
    22x
    22x
    22x
    22x
    22x
    22x
    22x
    22x
    7x
    7x
    7x
    5x
    5x
    5x
    5x
    5x
    5x
    5x
    7x
    7x
    22x
    22x
    2x
    2x
    18x
    18x
    2x
    2x
    6x
    6x
    6x
    6x
    6x
    6x
    6x
    6x
    6x
    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
     import {
      EMPTY,
      ComponentTreeCache,
      InstanceCache,
      Props,
      Transaction,
      VTree,
      State,
      ActiveRenderState,
    } from './util/types';
    import {
      $$render,
      $$vTree,
      $$unsubscribe,
      $$type,
      $$hooks,
      $$insertAfter,
    } from './util/symbols';
    import diff from './util/binding';
    import middleware from './middleware';

    const { outerHTML, innerHTML, createTree, release, Internals } = diff;
    const { isArray } = Array;
    const { setPrototypeOf, defineProperty, keys, assign } = Object;
    const RenderDebounce = new WeakMap();

    /**
     * @param {Props} defaultProps
     * @returns {string[]}
     */
    const getObserved = ({ defaultProps }) =>
      defaultProps ? keys(defaultProps) : EMPTY.ARR;

    /**
     * Creates the `component.props` object.
     *
     * @param {any} domNode
     * @param {Props} existingProps
     */
    const createProps = (domNode, existingProps = {}) => {
      return getObserved(domNode.constructor).reduce((props, attr) => ({
        [attr]: (
          domNode.hasAttribute(attr) ? domNode.getAttribute(attr) : domNode[attr]
        ) || props[attr] || domNode.constructor.defaultProps[attr],
        ...props,
      }), existingProps);
    };

    /**
     * Creates the `component.state` object.
     *
     * @param {Component} domNode
     * @param {State} newState
     */
    const createState = (domNode, newState) => assign({}, domNode.state, newState);

    /**
     * Finds all VTrees associated with a component.
     *
     * @param {VTree[]} childTrees
     * @param {VTree} vTree
     */
    const getChildTrees = (childTrees, vTree) => {
      ComponentTreeCache.forEach((parentTree, childTree) => {
        if (parentTree === vTree) {
          ComponentTreeCache.delete(childTree);

          if (typeof childTree.rawNodeName !== 'function') {
            childTrees.push(childTree);
          }
          else {
            getChildTrees(childTrees, childTree);
          }
        }
      });
    };

    /**
     * Represents a vanilla JavaScript Component. This is a lightweight version of
     * what you'd find in most modern web application libraries. It provides a
     * React-inspired API.
     */
    export default class Component {
      static get observedAttributes() {
        return getObserved(this).map(key => key.toLowerCase());
      }

      /**
       * Allow tests to unbind this task, you would not typically need to do this in
       * a web application, as this code loads once and is not reloaded.
       *
       * @type {Function | null}
       */
      static [$$unsubscribe] = null;

      /**
       * Adds the Component middleware, but first unregisters any previous
       * Component middleware.
       *
       * @returns {void}
       */
      static subscribeMiddleware() {
        const unsubscribe = Component[$$unsubscribe];
        unsubscribe && unsubscribe();
        Component[$$unsubscribe] = diff.use(middleware());
      }

      /**
       * Removes the Component middleware and clears the internal caches.
       *
       * @returns {void}
       */
      static unsubscribeMiddleware() {
        const unsubscribe = Component[$$unsubscribe];
        unsubscribe && unsubscribe();
        ComponentTreeCache.clear();
        InstanceCache.clear();
      }

      /**
       * Creates a lightweight stateful JavaScript component. Takes the static
       * default props and applies them to the incoming initial props.
       *
       * @param {Props} initialProps
       */
      constructor(initialProps) {
        let instance = this;

        // This is how we detect if this is a Web Component or not. The class
        // must be registered ahead of time within the customElements global
        // registry. This will allow us to construct the HTMLElement and attach the
        // shadow root.
        try {
          instance = Reflect.construct(HTMLElement, [], new.target);

          /** @type {any} */ (instance).attachShadow({ mode: 'open' });
          /** @type {any} */ (instance)[$$type] = 'web';

        } catch (e) {
          // Not a Web Component.
          /** @type {any} */ (instance)[$$type] = 'class';
        }

        const props = instance.props = assign({}, initialProps);
        const { defaultProps = EMPTY.OBJ } = /** @type {any} */ (instance.constructor);

        // Merge default props into props object.
        if (typeof defaultProps === 'object' && !isArray(defaultProps)) {
          keys(defaultProps || EMPTY.OBJ).forEach(prop => {
            if (prop in props && props[prop] !== undefined) {
              return;
            }

            instance.props[prop] = defaultProps[prop];
          });
        }

        return instance;
      }

      /**
       * @param {Props} props
       * @param {State} state
       *
       * @returns {VTree[] | VTree | undefined}
       */
      // @ts-ignore
      render(props, state) {
        return undefined;
      }

      /**
       * Changes the component state synchronously by shallow merging the incoming
       * state into the previous state. Rendering will then be scheduled to the
       * next reachable tick. If this is called multiple times on a single tick
       * all that will happen is the state will be updated by no rendering will
       * occur until the next tick.
       *
       * You can await this method to know when rendering has completed.
       *
       * @param {State} state
       */
      setState(state) {
        this.state = assign({}, this.state, state);

        if (!RenderDebounce.has(this)) {
          RenderDebounce.set(this, new Promise(resolve => setTimeout(() => {
            RenderDebounce.delete(this);

            this.componentWillReceiveProps(this.props, this.state);

            if (this.shouldComponentUpdate(this.props, this.state)) {
              this[$$render]()?.then(resolve);
            }
            else {
              resolve(null);
            }
          })));
        }

        return RenderDebounce.get(this);
      }

      /**
       * Schedule a render to happen, bypassing shouldComponentUpdate. Bound to the
       * same tick logic as setState, allowing this to be called as many times as
       * you want.
       */
      forceUpdate() {
        if (!RenderDebounce.has(this)) {
          RenderDebounce.set(this, new Promise(resolve => setTimeout(() => {
            RenderDebounce.delete(this);

            this.componentWillReceiveProps(this.props, this.state);

            this[$$render]()?.then(resolve);
          })));
        }

        return RenderDebounce.get(this);
      }

      /** @type {State} */
      state = {};

      /** @type {'web'|'class'} */
      [$$type] = 'class';

      /** @type {VTree | null} */
      [$$vTree] = null;

      /** @type {Function[]} */
      [$$hooks] = [];

      /**
       * Stateful render. Used when a component changes and needs to re-render
       * itself. This is triggered on `setState` and `forceUpdate` calls.
       *
       * @return {Promise<Transaction> | undefined}
       */
      [$$render]() {
        // This is a WebComponent, so do something different.
        if (this[$$type] === 'web') {
          const oldProps = this.props;
          const oldState = this.state;

          this.props = createProps(this, this.props);
          this.state = createState(this, this.state);

          ActiveRenderState.push(this);

          /** @type {Promise<Transaction>} */
          const promise = (innerHTML(
            /** @type {any} */ (this).shadowRoot,
            this.render(this.props, this.state),
          ));

          ActiveRenderState.length = 0;

          this.componentDidUpdate(oldProps, oldState);
          return promise;
        }

        // Get the fragment tree associated with this component. This is used to
        // lookup rendered children.
        let vTree = this[$$vTree];

        /**
         * Find all previously rendered top-level children associated to this
         * component. This will be used to diff against the newly rendered
         * elements.
         *
         * @type {VTree[]}
         */
        const childTrees = [];

        // Lookup all DOM nodes that were associated at the top level with this
        // component.
        vTree && getChildTrees(childTrees, vTree);

        // Render directly from the Component.
        ActiveRenderState.push(this);
        let renderTree = this.render(this.props, this.state);
        ActiveRenderState.length = 0;

        // Do not render.
        if (!renderTree) {
          return;
        }

        const renderTreeAsVTree = /** @type {VTree} */ (renderTree);

        // Always compare a fragment to a fragment. If the renderTree was not
        // wrapped, ensure it is here.
        if (renderTreeAsVTree.nodeType !== 11) {
          const isList = 'length' in renderTree;
          const renderTreeAsList = /** @type {VTree[]} */ (renderTree);

          renderTree = createTree(isList ? renderTreeAsList : [renderTreeAsVTree]);
        }

        // Put all the nodes together into a fragment for diffing.
        const fragment = createTree(childTrees);
        const tasks = [...Internals.defaultTasks];
        const syncTreesIndex = tasks.indexOf(Internals.tasks.syncTrees);

        // Inject a custom task after syncing has finished, but before patching has
        // occured. This gives us time to add additional patch logic per render.
        tasks.splice(syncTreesIndex + 1, 0, (/** @type {Transaction} */transaction) => {
          let lastTree = null;

          // Reconcile all top-level replacements and additions.
          for (let i = 0; i < fragment.childNodes.length; i++) {
            const childTree = fragment.childNodes[i];

            // Replace if the nodes are different.
            if (childTree && childTrees[i] && childTrees[i] !== childTree) {
              transaction.patches.push(
                Internals.PATCH_TYPE.REPLACE_CHILD,
                childTree,
                childTrees[i],
              );

              lastTree = childTree;
            }
            // Add if there is no old Node.
            else if (lastTree && !childTrees[i]) {
              transaction.patches.push(
                Internals.PATCH_TYPE.INSERT_BEFORE,
                $$insertAfter,
                childTree,
                lastTree,
              );

              lastTree = childTree;
            }
            // Keep the old node.
            else {
              lastTree = childTrees[i];
            }

            ComponentTreeCache.set(childTree, vTree);
          }

          return transaction;
        });

        /**
         * Compare the existing component node(s) to the new node(s).
         *
         * @type {Promise<Transaction>}
         */
        const promise = (outerHTML(fragment, renderTree, { tasks }));

        return promise.then(transaction => {
          // Empty the fragment after using.
          fragment.childNodes.length = 0;
          release(fragment);

          this.componentDidUpdate(this.props, this.state);
          return transaction;
        });
      }

      connectedCallback() {
        const { defaultProps = {} } = /** @type {any} */ (this).constructor;

        // This callback gets called during replace operations, there is no point
        // in re-rendering or creating a new shadow root due to this.

        // Always do a full render when mounting, so that something is visible.
        this[$$render]();

        this.componentDidMount();

        keys(defaultProps).forEach(propName => {
          defineProperty(this, propName, {
            get: () => this.props[propName],
            set: (value) => {
              this.props[propName] = value;

              this.componentWillReceiveProps(this.props, this.state);

              if (this.shouldComponentUpdate(this.props, this.state)) {
                this[$$render]();
              }
            },
          });
        });
      }

      disconnectedCallback() {
        this.componentWillUnmount();
      }

      attributeChangedCallback() {
        const nextProps = createProps(this, this.props);
        const nextState = createState(this, this.state);

        this.componentWillReceiveProps(nextProps, nextState);

        if (this.shouldComponentUpdate(nextProps, nextState)) {
          this[$$render]();
        }
      }

      /**
       * @param {Props} props
       * @param {State} state
       *
       * @returns {boolean}
       */
      // @ts-ignore
      shouldComponentUpdate(props, state) { return true; }

      componentWillMount() {}
      componentDidMount() {}

      /**
       * @param {Props} props
       * @param {State} state
       */
      // @ts-ignore
      componentWillReceiveProps(props, state) {}

      /**
       * @param {Props} props
       * @param {State} state
       *
       * @returns {void}
       */
      // @ts-ignore
      componentDidUpdate(props, state) {}

      componentWillUnmount() {}
    }

    // TODO: Can this be done inside the constructor so that class components do not
    // need to inherit from HTMLElement?
    try {
      setPrototypeOf(Component.prototype, HTMLElement.prototype);
    } catch {}

    // Automatically subscribe the Component middleware.
    Component.subscribeMiddleware();