text: 'use strict';
  
  exports.__esModule = true;
  
  var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  
  var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
  
  var _react = require('react');
  
  var _propTypes = require('prop-types');
  
  var _propTypes2 = _interopRequireDefault(_propTypes);
  
  var _createWarnTooManyClasses = require('../utils/createWarnTooManyClasses');
  
  var _createWarnTooManyClasses2 = _interopRequireDefault(_createWarnTooManyClasses);
  
  var _validAttr = require('../utils/validAttr');
  
  var _validAttr2 = _interopRequireDefault(_validAttr);
  
  var _isTag = require('../utils/isTag');
  
  var _isTag2 = _interopRequireDefault(_isTag);
  
  var _isStyledComponent = require('../utils/isStyledComponent');
  
  var _isStyledComponent2 = _interopRequireDefault(_isStyledComponent);
  
  var _getComponentName = require('../utils/getComponentName');
  
  var _getComponentName2 = _interopRequireDefault(_getComponentName);
  
  var _ThemeProvider = require('./ThemeProvider');
  
  var _StyleSheet = require('./StyleSheet');
  
  var _StyleSheet2 = _interopRequireDefault(_StyleSheet);
  
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  
  function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
  
  function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  
  function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  
  function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  
  var babelPluginFlowReactPropTypes_proptype_Theme = require('./ThemeProvider').babelPluginFlowReactPropTypes_proptype_Theme || require('prop-types').any;
  
  var babelPluginFlowReactPropTypes_proptype_Target = require('../types').babelPluginFlowReactPropTypes_proptype_Target || require('prop-types').any;
  
  var babelPluginFlowReactPropTypes_proptype_RuleSet = require('../types').babelPluginFlowReactPropTypes_proptype_RuleSet || require('prop-types').any;
  
  var escapeRegex = /[[\].#*$><+~=|^:(),"'`]/g;
  var multiDashRegex = /--+/g;
  
  // HACK for generating all static styles without needing to allocate
  // an empty execution context every single time...
  var STATIC_EXECUTION_CONTEXT = {};
  
  exports.default = function (ComponentStyle, constructWithOptions) {
    /* We depend on components having unique IDs */
    var identifiers = {};
    var generateId = function generateId(_displayName, parentComponentId) {
      var displayName = typeof _displayName !== 'string' ? 'sc' : _displayName.replace(escapeRegex, '-') // Replace all possible CSS selectors
      .replace(multiDashRegex, '-'); // Replace multiple -- with single -
  
      var nr = (identifiers[displayName] || 0) + 1;
      identifiers[displayName] = nr;
  
      var hash = ComponentStyle.generateName(displayName + nr);
      var componentId = displayName + '-' + hash;
      return parentComponentId !== undefined ? parentComponentId + '-' + componentId : componentId;
    };
  
    var BaseStyledComponent = function (_Component) {
      _inherits(BaseStyledComponent, _Component);
  
      function BaseStyledComponent() {
        var _temp, _this, _ret;
  
        _classCallCheck(this, BaseStyledComponent);
  
        for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
          args[_key] = arguments[_key];
        }
  
        return _ret = (_temp = (_this = _possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.attrs = {}, _this.state = {
          theme: null,
          generatedClassName: ''
        }, _this.unsubscribeId = -1, _temp), _possibleConstructorReturn(_this, _ret);
      }
  
      BaseStyledComponent.prototype.unsubscribeFromContext = function unsubscribeFromContext() {
        if (this.unsubscribeId !== -1) {
          this.context[_ThemeProvider.CHANNEL_NEXT].unsubscribe(this.unsubscribeId);
        }
      };
  
      BaseStyledComponent.prototype.buildExecutionContext = function buildExecutionContext(theme, props) {
        var attrs = this.constructor.attrs;
  
        var context = _extends({}, props, { theme: theme });
        if (attrs === undefined) {
          return context;
        }
  
        this.attrs = Object.keys(attrs).reduce(function (acc, key) {
          var attr = attrs[key];
          // eslint-disable-next-line no-param-reassign
          acc[key] = typeof attr === 'function' ? attr(context) : attr;
          return acc;
        }, {});
  
        return _extends({}, context, this.attrs);
      };
  
      BaseStyledComponent.prototype.generateAndInjectStyles = function generateAndInjectStyles(theme, props) {
        var _constructor = this.constructor,
            attrs = _constructor.attrs,
            componentStyle = _constructor.componentStyle,
            warnTooManyClasses = _constructor.warnTooManyClasses;
  
        var styleSheet = this.context[_StyleSheet.CONTEXT_KEY] || _StyleSheet2.default.instance;
  
        // staticaly styled-components don't need to build an execution context object,
        // and shouldn't be increasing the number of class names
        if (componentStyle.isStatic && attrs === undefined) {
          return componentStyle.generateAndInjectStyles(STATIC_EXECUTION_CONTEXT, styleSheet);
        } else {
          var executionContext = this.buildExecutionContext(theme, props);
          var className = componentStyle.generateAndInjectStyles(executionContext, styleSheet);
  
          if (warnTooManyClasses !== undefined) warnTooManyClasses(className);
  
          return className;
        }
      };
  
      BaseStyledComponent.prototype.componentWillMount = function componentWillMount() {
        var _this2 = this;
  
        var componentStyle = this.constructor.componentStyle;
  
        var styledContext = this.context[_ThemeProvider.CHANNEL_NEXT];
  
        // If this is a staticaly-styled component, we don't need to the theme
        // to generate or build styles.
        if (componentStyle.isStatic) {
          var generatedClassName = this.generateAndInjectStyles(STATIC_EXECUTION_CONTEXT, this.props);
          this.setState({ generatedClassName: generatedClassName });
          // If there is a theme in the context, subscribe to the event emitter. This
          // is necessary due to pure components blocking context updates, this circumvents
          // that by updating when an event is emitted
        } else if (styledContext !== undefined) {
          var subscribe = styledContext.subscribe;
  
          this.unsubscribeId = subscribe(function (nextTheme) {
            // This will be called once immediately
  
            // Props should take precedence over ThemeProvider, which should take precedence over
            // defaultProps, but React automatically puts defaultProps on props.
            var defaultProps = _this2.constructor.defaultProps;
            /* eslint-disable react/prop-types */
  
            var isDefaultTheme = defaultProps && _this2.props.theme === defaultProps.theme;
            var theme = _this2.props.theme && !isDefaultTheme ? _this2.props.theme : nextTheme;
            /* eslint-enable */
            var generatedClassName = _this2.generateAndInjectStyles(theme, _this2.props);
            _this2.setState({ theme: theme, generatedClassName: generatedClassName });
          });
        } else {
          // eslint-disable-next-line react/prop-types
          var _theme = this.props.theme || {};
          var _generatedClassName = this.generateAndInjectStyles(_theme, this.props);
          this.setState({ theme: _theme, generatedClassName: _generatedClassName });
        }
      };
  
      BaseStyledComponent.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
        var _this3 = this;
  
        // If this is a staticaly-styled component, we don't need to listen to
        // props changes to update styles
        var componentStyle = this.constructor.componentStyle;
  
        if (componentStyle.isStatic) {
          return;
        }
  
        this.setState(function (oldState) {
          // Props should take precedence over ThemeProvider, which should take precedence over
          // defaultProps, but React automatically puts defaultProps on props.
          var defaultProps = _this3.constructor.defaultProps;
          /* eslint-disable react/prop-types */
  
          var isDefaultTheme = defaultProps && nextProps.theme === defaultProps.theme;
          var theme = nextProps.theme && !isDefaultTheme ? nextProps.theme : oldState.theme;
          /* eslint-enable */
          var generatedClassName = _this3.generateAndInjectStyles(theme, nextProps);
  
          return { theme: theme, generatedClassName: generatedClassName };
        });
      };
  
      BaseStyledComponent.prototype.componentWillUnmount = function componentWillUnmount() {
        this.unsubscribeFromContext();
      };
  
      BaseStyledComponent.prototype.render = function render() {
        var _this4 = this;
  
        // eslint-disable-next-line react/prop-types
        var innerRef = this.props.innerRef;
        var generatedClassName = this.state.generatedClassName;
        var _constructor2 = this.constructor,
            styledComponentId = _constructor2.styledComponentId,
            target = _constructor2.target;
  
  
        var isTargetTag = (0, _isTag2.default)(target);
  
        var className = [
        // eslint-disable-next-line react/prop-types
        this.props.className, styledComponentId, this.attrs.className, generatedClassName].filter(Boolean).join(' ');
  
        var baseProps = _extends({}, this.attrs, {
          className: className
        });
  
        if ((0, _isStyledComponent2.default)(target)) {
          baseProps.innerRef = innerRef;
        } else {
          baseProps.ref = innerRef;
        }
  
        var propsForElement = Object.keys(this.props).reduce(function (acc, propName) {
          // Don't pass through non HTML tags through to HTML elements
          // always omit innerRef
          if (propName !== 'innerRef' && propName !== 'className' && (!isTargetTag || (0, _validAttr2.default)(propName))) {
            // eslint-disable-next-line no-param-reassign
            acc[propName] = _this4.props[propName];
          }
  
          return acc;
        }, baseProps);
  
        return (0, _react.createElement)(target, propsForElement);
      };
  
      return BaseStyledComponent;
    }(_react.Component);
  
    var createStyledComponent = function createStyledComponent(target, options, rules) {
      var _StyledComponent$cont;
  
      var _options$displayName = options.displayName,
          displayName = _options$displayName === undefined ? (0, _isTag2.default)(target) ? 'styled.' + target : 'Styled(' + (0, _getComponentName2.default)(target) + ')' : _options$displayName,
          _options$componentId = options.componentId,
          componentId = _options$componentId === undefined ? generateId(options.displayName, options.parentComponentId) : _options$componentId,
          _options$ParentCompon = options.ParentComponent,
          ParentComponent = _options$ParentCompon === undefined ? BaseStyledComponent : _options$ParentCompon,
          extendingRules = options.rules,
          attrs = options.attrs;
  
  
      var styledComponentId = options.displayName && options.componentId ? options.displayName + '-' + options.componentId : componentId;
  
      var warnTooManyClasses = void 0;
      if (process.env.NODE_ENV !== 'production') {
        warnTooManyClasses = (0, _createWarnTooManyClasses2.default)(displayName);
      }
  
      var componentStyle = new ComponentStyle(extendingRules === undefined ? rules : extendingRules.concat(rules), styledComponentId);
  
      var StyledComponent = function (_ParentComponent) {
        _inherits(StyledComponent, _ParentComponent);
  
        function StyledComponent() {
          _classCallCheck(this, StyledComponent);
  
          return _possibleConstructorReturn(this, _ParentComponent.apply(this, arguments));
        }
  
        StyledComponent.withComponent = function withComponent(tag) {
          var previousComponentId = options.componentId,
              optionsToCopy = _objectWithoutProperties(options, ['componentId']);
  
          var newComponentId = previousComponentId && previousComponentId + '-' + ((0, _isTag2.default)(tag) ? tag : (0, _getComponentName2.default)(tag));
  
          var newOptions = _extends({}, optionsToCopy, {
            componentId: newComponentId,
            ParentComponent: StyledComponent
          });
  
          return createStyledComponent(tag, newOptions, rules);
        };
  
        _createClass(StyledComponent, null, [{
          key: 'extend',
          get: function get() {
            var rulesFromOptions = options.rules,
                parentComponentId = options.componentId,
                optionsToCopy = _objectWithoutProperties(options, ['rules', 'componentId']);
  
            var newRules = rulesFromOptions === undefined ? rules : rulesFromOptions.concat(rules);
  
            var newOptions = _extends({}, optionsToCopy, {
              rules: newRules,
              parentComponentId: parentComponentId,
              ParentComponent: StyledComponent
            });
  
            return constructWithOptions(createStyledComponent, target, newOptions);
          }
        }]);
  
        return StyledComponent;
      }(ParentComponent);
  
      StyledComponent.contextTypes = (_StyledComponent$cont = {}, _StyledComponent$cont[_ThemeProvider.CHANNEL] = _propTypes2.default.func, _StyledComponent$cont[_ThemeProvider.CHANNEL_NEXT] = _ThemeProvider.CONTEXT_CHANNEL_SHAPE, _StyledComponent$cont[_StyleSheet.CONTEXT_KEY] = _propTypes2.default.instanceOf(_StyleSheet2.default), _StyledComponent$cont);
      StyledComponent.displayName = displayName;
      StyledComponent.styledComponentId = styledComponentId;
      StyledComponent.attrs = attrs;
      StyledComponent.componentStyle = componentStyle;
      StyledComponent.warnTooManyClasses = warnTooManyClasses;
      StyledComponent.target = target;
  
  
      return StyledComponent;
    };
  
    return createStyledComponent;
  };
  
  module.exports = exports['default'];