"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Scoped = void 0;
var _react = _interopRequireDefault(require("react"));
var _reactDom = _interopRequireDefault(require("react-dom"));
var _propTypes = require("prop-types");
var _styleElementUtils = require("./style-element-utils.js");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
var reactSupportsReturningArrays = !!_reactDom["default"].createPortal;
var Scoped = exports.Scoped = /*#__PURE__*/function (_React$Component) {
  _inherits(Scoped, _React$Component);
  var _super = _createSuper(Scoped);
  function Scoped(props) {
    var _this;
    _classCallCheck(this, Scoped);
    _this = _super.call(this, props);
    _defineProperty(_assertThisInitialized(_this), "addKremlingAttributeToChildren", function (children) {
      return _react["default"].Children.map(children, function (child) {
        if ( /*#__PURE__*/_react["default"].isValidElement(child)) {
          if (child.type === _react["default"].Fragment && _react["default"].Fragment) {
            var fragmentChildren = _this.addKremlingAttributeToChildren(child.props.children);
            return /*#__PURE__*/_react["default"].cloneElement(child, {}, fragmentChildren);
          } else {
            return /*#__PURE__*/_react["default"].cloneElement(child, _defineProperty({}, _this.state.kremlingAttr, _this.state.kremlingAttrValue));
          }
        } else {
          return child;
        }
      });
    });
    _defineProperty(_assertThisInitialized(_this), "doneWithCss", function () {
      if (_this.state.styleRef && --_this.state.styleRef.kremlings === 0) {
        delete _styleElementUtils.styleTags[_this.state.rawCss];
        _this.state.styleRef.parentNode.removeChild(_this.state.styleRef);
      }
    });
    _this.state = {};
    if (!props.css) throw Error("Kremling's <Scoped /> component requires the 'css' prop.");
    if (_typeof(props.css) === "object" && (typeof props.css.id !== "string" || typeof props.css.styles !== "string")) throw Error("Kremling's <Scoped /> component requires either a string or an object with \"id\" and \"styles\" properties.");
    _this.state = _this.newCssState(props);
    return _this;
  }
  _createClass(Scoped, [{
    key: "render",
    value: function render() {
      if (this.props.children === undefined || this.props.children === null || this.props.children === false || this.props.children === true) {
        return null;
      }
      var kremlingChildren = this.addKremlingAttributeToChildren(this.props.children);
      if (reactSupportsReturningArrays) {
        return kremlingChildren;
      } else {
        // React 15 or below
        if (kremlingChildren.length > 1) {
          throw new Error("kremling's <Scoped /> component requires exactly one child element unless you are using react@>=16");
        } else if (kremlingChildren.length === 1) {
          return kremlingChildren[0];
        } else {
          return null;
        }
      }
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps) {
      var oldCss = prevProps.postcss || prevProps.css;
      var newCss = this.props.postcss || this.props.css;
      if (oldCss !== newCss || oldCss.id !== newCss.id || oldCss.styles !== newCss.styles || oldCss.namespace !== newCss.namespace) {
        this.doneWithCss();
        this.setState(this.newCssState(this.props));
      }
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      this.doneWithCss();
    }
  }, {
    key: "newCssState",
    value: function newCssState(props) {
      var css = props.postcss || props.css;
      var isPostCss = Boolean(css && css.id);
      var namespace = (isPostCss ? css.namespace : props.namespace) || Scoped.defaultNamespace;
      var rawCss = isPostCss ? css.styles : css;
      var styleRef, kremlingAttr, kremlingAttrValue;
      if (!isPostCss) {
        if (typeof css !== "string") {
          return;
        }
        if (css.indexOf("&") < 0 && css.trim().length > 0) {
          var firstRule = css.substring(0, props.css.indexOf("{")).trim();
          console.warn("Kremling's <Scoped css=\"...\"> css prop should have the '&' character in it to scope the css classes: ".concat(firstRule));
        }
      }
      var existingDomEl = _styleElementUtils.styleTags[rawCss];
      if (existingDomEl) {
        styleRef = existingDomEl;
        existingDomEl.kremlings++;
        kremlingAttr = styleRef.kremlingAttr;
        kremlingAttrValue = styleRef.kremlingValue;
      } else {
        // The attribute for namespacing the css
        kremlingAttr = namespace;
        kremlingAttrValue = isPostCss ? css.id : (0, _styleElementUtils.incrementCounter)();

        // The css to append to the dom
        var kremlingSelector = "[".concat(kremlingAttr, "=\"").concat(kremlingAttrValue, "\"]");
        var transformedCSS = isPostCss ? rawCss : (0, _styleElementUtils.transformCss)(rawCss, kremlingSelector);

        // The dom element
        var el = document.createElement("style");
        el.setAttribute("type", "text/css");
        el.textContent = transformedCSS;
        el.kremlings = 1;
        el.kremlingAttr = kremlingAttr;
        el.kremlingValue = kremlingAttrValue;
        document.head.appendChild(el);
        _styleElementUtils.styleTags[rawCss] = el;
        styleRef = el;
      }
      return {
        isPostCss: isPostCss,
        rawCss: rawCss,
        styleRef: styleRef,
        kremlingAttr: kremlingAttr,
        kremlingAttrValue: kremlingAttrValue
      };
    }
  }]);
  return Scoped;
}(_react["default"].Component);
_defineProperty(Scoped, "propTypes", {
  css: (0, _propTypes.oneOfType)([_propTypes.string, _propTypes.object]),
  postcss: _propTypes.object,
  namespace: _propTypes.string
});
_defineProperty(Scoped, "defaultNamespace", "kremling");
//# sourceMappingURL=scoped.component.js.map