All files / src/connect connect.js

93.94% Statements 93/99
83.67% Branches 41/49
95.24% Functions 20/21
94.44% Lines 85/90
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 2181x 1x 1x   1x 1x 1x 1x 1x 1x 1x       120x 162x 162x               1x       39x   130x 130x 130x 82x 82x 82x                 39x               40x 40x 40x   40x 40x   40x         40x       160x 40x       40x   40x             117x     39x 39x 39x 39x 39x   39x 39x               80x 80x       39x               31x 31x 31x       32x       48x       9x 9x 9x 9x 9x 9x       39x 39x 39x       39x       31x 31x               31x       29x   29x 10x   19x 19x                   18x 18x       4x       80x         5x 5x 5x 5x       80x 80x   80x     80x         40x 40x 40x 40x 40x     40x      
import hoistStatics from 'hoist-non-react-statics';
import { Component, createElement } from 'react';
import PropTypes from 'prop-types';
 
import defaultMapSendToPropsFactories from './mapSendToProps'
import defaultMapStateToPropsFactories from './mapStateToProps'
import defaultMergePropsFactories from './mergeProps'
import defaultSelectorFactory from './selectorFactory'
import Subscription from './utils/Subscription'
import { storeKey, subscriptionKey, streamKey } from "../constants";
import { storeShape, subscriptionShape } from './utils/PropTypes';
 
 
function match(arg, factories, name) {
  for (let i = factories.length - 1; i >= 0; i--) {
    const result = factories[i](arg)
    if (result) return result
  }
 
  return (send, options) => {
    throw new Error(`Invalid value of type ${typeof arg} for ${name} argument when connecting component ${options.wrappedComponentName}.`)
  }
}
 
const dummyState = {}
function noop() {}
function makeSelectorStateful(sourceSelector, store) {
  // wrap the selector in an object that tracks its results between runs.
  const selector = {
    run: function runComponentSelector(props) {
      try {
        const nextProps = sourceSelector(store.getState(), props)
        if (nextProps !== selector.props || selector.error) {
          selector.shouldComponentUpdate = true
          selector.props = nextProps
          selector.error = null
        }
      } catch (error) {
        selector.shouldComponentUpdate = true
        selector.error = error
      }
    }
  }
 
  return selector
}
 
export function connect(
  mapStateToProps,
  mapSendToProps,
  mergeProps,
) {
  const initMapStateToProps = match(mapStateToProps, defaultMapStateToPropsFactories, 'mapStateToProps')
  const initMapSendToProps = match(mapSendToProps, defaultMapSendToPropsFactories, 'mapSendToProps')
  const initMergeProps = match(mergeProps, defaultMergePropsFactories, 'mergeProps')
 
  const shouldHandleStateChanges = Boolean(mapStateToProps);
  const renderCountProp = undefined;
 
  const contextTypes = {
    [storeKey]: storeShape,
    [streamKey]: PropTypes.any,
    [subscriptionKey]: subscriptionShape,
  }
  const childContextTypes = {
    [subscriptionKey]: subscriptionShape,
  }
 
  return function wrapWithConnect(WrappedComponent) {
    const wrappedComponentName = WrappedComponent.displayName
      || WrappedComponent.name
      || 'Component';
 
    const displayName = `Connect(${wrappedComponentName})`;
 
    const selectorFactoryOptions = {
      initMapStateToProps,
      initMapSendToProps: initMapSendToProps,
      initMergeProps,
    }
 
    class Connect extends Component {
      constructor(props, context) {
        super(props, context)
 
        this.state = {}
        this.renderCount = 0
        this.store = props[storeKey] || context[storeKey];
        this.stream = props[streamKey] || context[streamKey];
        this.propsMode = Boolean(props[storeKey])
 
        this.initSelector()
        this.initSubscription()
      }
 
      getChildContext() {
        // If this component received store from props, its subscription should be transparent
        // to any descendants receiving store+subscription from context; it passes along
        // subscription passed to it. Otherwise, it shadows the parent subscription, which allows
        // Connect to control ordering of notifications to flow top-down.
        const subscription = this.propsMode ? null : this.subscription
        return { [subscriptionKey]: subscription || this.context[subscriptionKey] }
      }
 
      componentDidMount() {
        if (!shouldHandleStateChanges) return
 
        // componentWillMount fires during server side rendering, but componentDidMount and
        // componentWillUnmount do not. Because of this, trySubscribe happens during ...didMount.
        // Otherwise, unsubscription would never take place during SSR, causing a memory leak.
        // To handle the case where a child component may have triggered a state change by
        // dispatching an action in its componentWillMount, we have to re-run the select and maybe
        // re-render.
        this.subscription.trySubscribe()
        this.selector.run(this.props)
        if (this.selector.shouldComponentUpdate) this.forceUpdate()
      }
 
      componentWillReceiveProps(nextProps) {
        this.selector.run(nextProps)
      }
 
      shouldComponentUpdate() {
        return this.selector.shouldComponentUpdate
      }
 
      componentWillUnmount() {
        Eif (this.subscription) this.subscription.tryUnsubscribe()
        this.subscription = null
        this.notifyNestedSubs = noop
        this.store = null
        this.selector.run = noop
        this.selector.shouldComponentUpdate = false
      }
 
      initSelector() {
        const sourceSelector = defaultSelectorFactory(this.stream.send.bind(this.stream), selectorFactoryOptions)
        this.selector = makeSelectorStateful(sourceSelector, this.store)
        this.selector.run(this.props)
      }
 
      initSubscription() {
        if (!shouldHandleStateChanges) return
 
        // parentSub's source should match where store came from: props vs. context. A component
        // connected to the store via props shouldn't use subscription from context, or vice versa.
        const parentSub = (this.propsMode ? this.props : this.context)[subscriptionKey]
        this.subscription = new Subscription(this.store, parentSub, this.onStateChange.bind(this))
 
        // `notifyNestedSubs` is duplicated to handle the case where the component is  unmounted in
        // the middle of the notification loop, where `this.subscription` will then be null. An
        // extra null check every change can be avoided by copying the method onto `this` and then
        // replacing it with a no-op on unmount. This can probably be avoided if Subscription's
        // listeners logic is changed to not call listeners that have been unsubscribed in the
        // middle of the notification loop.
        this.notifyNestedSubs = this.subscription.notifyNestedSubs.bind(this.subscription)
      }
 
      onStateChange() {
        this.selector.run(this.props)
 
        if (!this.selector.shouldComponentUpdate) {
          this.notifyNestedSubs()
        } else {
          this.componentDidUpdate = this.notifyNestedSubsOnComponentDidUpdate
          this.setState(dummyState)
        }
      }
 
      notifyNestedSubsOnComponentDidUpdate() {
        // `componentDidUpdate` is conditionally implemented when `onStateChange` determines it
        // needs to notify nested subs. Once called, it unimplements itself until further state
        // changes occur. Doing it this way vs having a permanent `componentDidUpdate` that does
        // a boolean check every time avoids an extra method call most of the time, resulting
        // in some perf boost.
        this.componentDidUpdate = undefined
        this.notifyNestedSubs()
      }
 
      isSubscribed() {
        return Boolean(this.subscription) && this.subscription.isSubscribed()
      }
 
      addExtraProps(props) {
        if (!renderCountProp && !(this.propsMode && this.subscription)) return props
        // make a shallow copy so that fields added don't leak to the original selector.
        // this is especially important for 'ref' since that's a reference back to the component
        // instance. a singleton memoized selector would then be holding a reference to the
        // instance, preventing the instance from being garbage collected, and that would be bad
        const withExtras = { ...props }
        Iif (renderCountProp) withExtras[renderCountProp] = this.renderCount++
        Eif (this.propsMode && this.subscription) withExtras[subscriptionKey] = this.subscription
        return withExtras
      }
 
      render() {
        const selector = this.selector
        selector.shouldComponentUpdate = false
 
        Iif (selector.error) {
          throw selector.error
        } else {
          return createElement(WrappedComponent, this.addExtraProps(selector.props))
        }
      }
    }
 
    Connect.WrappedComponent = WrappedComponent
    Connect.displayName = displayName
    Connect.childContextTypes = childContextTypes
    Connect.contextTypes = contextTypes
    Connect.propTypes = contextTypes
 
 
    return hoistStatics(Connect, WrappedComponent)
  }
}