react-svg-line-chart
Version:
A lightweight responsive line chart component for React using only SVG
1,245 lines (981 loc) ⢠149 kB
JavaScript
/*!
* react-svg-line-chart v2.0.2 - https://github.com/xuopled/react-svg-line-chart#readme
* MIT Licensed
*/
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("prop-types"), require("react"));
else if(typeof define === 'function' && define.amd)
define(["prop-types", "react"], factory);
else if(typeof exports === 'object')
exports["ReactDemoPage"] = factory(require("prop-types"), require("react"));
else
root["ReactDemoPage"] = factory(root["PropTypes"], root["React"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_0__, __WEBPACK_EXTERNAL_MODULE_1__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 3);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_0__;
/***/ }),
/* 1 */
/***/ (function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_1__;
/***/ }),
/* 2 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(module) {/* unused harmony export css */
/* unused harmony export keyframes */
/* unused harmony export injectGlobal */
/* unused harmony export ThemeProvider */
/* unused harmony export withTheme */
/* unused harmony export ServerStyleSheet */
/* unused harmony export StyleSheetManager */
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_is_plain_object__ = __webpack_require__(6);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_is_plain_object___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_is_plain_object__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_stylis__ = __webpack_require__(8);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_stylis___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1_stylis__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_react__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_react___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_2_react__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_prop_types__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_prop_types___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_3_prop_types__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4_hoist_non_react_statics__ = __webpack_require__(9);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4_hoist_non_react_statics___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_4_hoist_non_react_statics__);
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
var _uppercasePattern = /([A-Z])/g;
/**
* Hyphenates a camelcased string, for example:
*
* > hyphenate('backgroundColor')
* < "background-color"
*
* For CSS style names, use `hyphenateStyleName` instead which works properly
* with all vendor prefixes, including `ms`.
*
* @param {string} string
* @return {string}
*/
function hyphenate$2(string) {
return string.replace(_uppercasePattern, '-$1').toLowerCase();
}
var hyphenate_1 = hyphenate$2;
var hyphenate = hyphenate_1;
var msPattern = /^ms-/;
/**
* Hyphenates a camelcased CSS property name, for example:
*
* > hyphenateStyleName('backgroundColor')
* < "background-color"
* > hyphenateStyleName('MozTransition')
* < "-moz-transition"
* > hyphenateStyleName('msTransition')
* < "-ms-transition"
*
* As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
* is converted to `-ms-`.
*
* @param {string} string
* @return {string}
*/
function hyphenateStyleName(string) {
return hyphenate(string).replace(msPattern, '-ms-');
}
var hyphenateStyleName_1 = hyphenateStyleName;
//
var objToCss = function objToCss(obj, prevKey) {
var css = Object.keys(obj).filter(function (key) {
var chunk = obj[key];
return chunk !== undefined && chunk !== null && chunk !== false && chunk !== '';
}).map(function (key) {
if (__WEBPACK_IMPORTED_MODULE_0_is_plain_object___default()(obj[key])) return objToCss(obj[key], key);
return hyphenateStyleName_1(key) + ': ' + obj[key] + ';';
}).join(' ');
return prevKey ? prevKey + ' {\n ' + css + '\n}' : css;
};
var flatten = function flatten(chunks, executionContext) {
return chunks.reduce(function (ruleSet, chunk) {
/* Remove falsey values */
if (chunk === undefined || chunk === null || chunk === false || chunk === '') {
return ruleSet;
}
/* Flatten ruleSet */
if (Array.isArray(chunk)) {
return [].concat(ruleSet, flatten(chunk, executionContext));
}
/* Handle other components */
if (chunk.hasOwnProperty('styledComponentId')) {
// $FlowFixMe not sure how to make this pass
return [].concat(ruleSet, ['.' + chunk.styledComponentId]);
}
/* Either execute or defer the function */
if (typeof chunk === 'function') {
return executionContext ? ruleSet.concat.apply(ruleSet, flatten([chunk(executionContext)], executionContext)) : ruleSet.concat(chunk);
}
/* Handle objects */
return ruleSet.concat(
// $FlowFixMe have to add %checks somehow to isPlainObject
__WEBPACK_IMPORTED_MODULE_0_is_plain_object___default()(chunk) ? objToCss(chunk) : chunk.toString());
}, []);
};
//
var stylis = new __WEBPACK_IMPORTED_MODULE_1_stylis___default.a({
global: false,
cascade: true,
keyframe: false,
prefix: true,
compress: false,
semicolon: true
});
var stringifyRules = function stringifyRules(rules, selector, prefix) {
var flatCSS = rules.join('').replace(/^\s*\/\/.*$/gm, ''); // replace JS comments
var cssStr = selector && prefix ? prefix + ' ' + selector + ' { ' + flatCSS + ' }' : flatCSS;
return stylis(prefix || !selector ? '' : selector, cssStr);
};
//
var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
var charsLength = chars.length;
/* Some high number, usually 9-digit base-10. Map it to base-š */
var generateAlphabeticName = function generateAlphabeticName(code) {
var name = '';
var x = void 0;
for (x = code; x > charsLength; x = Math.floor(x / charsLength)) {
name = chars[x % charsLength] + name;
}
return chars[x % charsLength] + name;
};
//
var interleave = (function (strings, interpolations) {
return interpolations.reduce(function (array, interp, i) {
return array.concat(interp, strings[i + 1]);
}, [strings[0]]);
});
//
var css = (function (strings) {
for (var _len = arguments.length, interpolations = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
interpolations[_key - 1] = arguments[_key];
}
return flatten(interleave(strings, interpolations));
});
//
var SC_COMPONENT_ID = /^[^\S\n]*?\/\* sc-component-id:\s+(\S+)\s+\*\//gm;
var extractCompsFromCSS = (function (maybeCSS) {
var css = '' + (maybeCSS || ''); // Definitely a string, and a clone
var existingComponents = [];
css.replace(SC_COMPONENT_ID, function (match, componentId, matchIndex) {
existingComponents.push({ componentId: componentId, matchIndex: matchIndex });
return match;
});
return existingComponents.map(function (_ref, i) {
var componentId = _ref.componentId,
matchIndex = _ref.matchIndex;
var nextComp = existingComponents[i + 1];
var cssFromDOM = nextComp ? css.slice(matchIndex, nextComp.matchIndex) : css.slice(matchIndex);
return { componentId: componentId, cssFromDOM: cssFromDOM };
});
});
//
/* eslint-disable camelcase, no-undef */
var getNonce = (function () {
return true ? __webpack_require__.nc : null;
});
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
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 inherits = function (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 objectWithoutProperties = function (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;
};
var possibleConstructorReturn = function (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;
};
//
/* eslint-disable no-underscore-dangle */
/*
* Browser Style Sheet with Rehydration
*
* <style data-styled-components="x y z"
* data-styled-components-is-local="true">
* /Ā· sc-component-id: a Ā·/
* .sc-a { ... }
* .x { ... }
* /Ā· sc-component-id: b Ā·/
* .sc-b { ... }
* .y { ... }
* .z { ... }
* </style>
*
* Note: replace Ā· with * in the above snippet.
* */
var COMPONENTS_PER_TAG = 40;
var BrowserTag = function () {
function BrowserTag(el, isLocal) {
var existingSource = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
classCallCheck(this, BrowserTag);
this.el = el;
this.isLocal = isLocal;
this.ready = false;
var extractedComps = extractCompsFromCSS(existingSource);
this.size = extractedComps.length;
this.components = extractedComps.reduce(function (acc, obj) {
acc[obj.componentId] = obj; // eslint-disable-line no-param-reassign
return acc;
}, {});
}
BrowserTag.prototype.isFull = function isFull() {
return this.size >= COMPONENTS_PER_TAG;
};
BrowserTag.prototype.addComponent = function addComponent(componentId) {
if (!this.ready) this.replaceElement();
if ("development" !== 'production' && this.components[componentId]) {
throw new Error('Trying to add Component \'' + componentId + '\' twice!');
}
var comp = { componentId: componentId, textNode: document.createTextNode('') };
this.el.appendChild(comp.textNode);
this.size += 1;
this.components[componentId] = comp;
};
BrowserTag.prototype.inject = function inject(componentId, css, name) {
if (!this.ready) this.replaceElement();
var comp = this.components[componentId];
if ("development" !== 'production' && !comp) {
throw new Error('Must add a new component before you can inject css into it');
}
if (comp.textNode.data === '') {
comp.textNode.appendData('\n/* sc-component-id: ' + componentId + ' */\n');
}
comp.textNode.appendData(css);
if (name) {
var existingNames = this.el.getAttribute(SC_ATTR);
this.el.setAttribute(SC_ATTR, existingNames ? existingNames + ' ' + name : name);
}
var nonce = getNonce();
if (nonce) {
this.el.setAttribute('nonce', nonce);
}
};
BrowserTag.prototype.toHTML = function toHTML() {
return this.el.outerHTML;
};
BrowserTag.prototype.toReactElement = function toReactElement() {
throw new Error("BrowserTag doesn't implement toReactElement!");
};
BrowserTag.prototype.clone = function clone() {
throw new Error('BrowserTag cannot be cloned!');
};
/* Because we care about source order, before we can inject anything we need to
* create a text node for each component and replace the existing CSS. */
BrowserTag.prototype.replaceElement = function replaceElement() {
var _this = this;
this.ready = true;
// We have nothing to inject. Use the current el.
if (this.size === 0) return;
// Build up our replacement style tag
var newEl = this.el.cloneNode();
newEl.appendChild(document.createTextNode('\n'));
Object.keys(this.components).forEach(function (key) {
var comp = _this.components[key];
// eslint-disable-next-line no-param-reassign
comp.textNode = document.createTextNode(comp.cssFromDOM);
newEl.appendChild(comp.textNode);
});
if (!this.el.parentNode) {
throw new Error("Trying to replace an element that wasn't mounted!");
}
// The ol' switcheroo
this.el.parentNode.replaceChild(newEl, this.el);
this.el = newEl;
};
return BrowserTag;
}();
/* Factory function to separate DOM operations from logical ones*/
var BrowserStyleSheet = {
create: function create() {
var tags = [];
var names = {};
/* Construct existing state from DOM */
var nodes = document.querySelectorAll('[' + SC_ATTR + ']');
var nodesLength = nodes.length;
for (var i = 0; i < nodesLength; i += 1) {
var el = nodes[i];
tags.push(new BrowserTag(el, el.getAttribute(LOCAL_ATTR) === 'true', el.innerHTML));
var attr = el.getAttribute(SC_ATTR);
if (attr) {
attr.trim().split(/\s+/).forEach(function (name) {
names[name] = true;
});
}
}
/* Factory for making more tags */
var tagConstructor = function tagConstructor(isLocal) {
var el = document.createElement('style');
el.type = 'text/css';
el.setAttribute(SC_ATTR, '');
el.setAttribute(LOCAL_ATTR, isLocal ? 'true' : 'false');
if (!document.head) throw new Error('Missing document <head>');
document.head.appendChild(el);
return new BrowserTag(el, isLocal);
};
return new StyleSheet(tagConstructor, tags, names);
}
};
//
var SC_ATTR = 'data-styled-components';
var LOCAL_ATTR = 'data-styled-components-is-local';
var CONTEXT_KEY = '__styled-components-stylesheet__';
/* eslint-disable flowtype/object-type-delimiter */
/* eslint-enable flowtype/object-type-delimiter */
var instance = null;
// eslint-disable-next-line no-use-before-define
var clones = [];
var StyleSheet = function () {
function StyleSheet(tagConstructor) {
var tags = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
var names = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
classCallCheck(this, StyleSheet);
this.hashes = {};
this.deferredInjections = {};
this.stylesCacheable = typeof document !== 'undefined';
this.tagConstructor = tagConstructor;
this.tags = tags;
this.names = names;
this.constructComponentTagMap();
}
// helper for `ComponentStyle` to know when it cache static styles.
// staticly styled-component can not safely cache styles on the server
// without all `ComponentStyle` instances saving a reference to the
// the styleSheet instance they last rendered with,
// or listening to creation / reset events. otherwise you might create
// a component with one stylesheet and render it another api response
// with another, losing styles on from your server-side render.
StyleSheet.prototype.constructComponentTagMap = function constructComponentTagMap() {
var _this = this;
this.componentTags = {};
this.tags.forEach(function (tag) {
Object.keys(tag.components).forEach(function (componentId) {
_this.componentTags[componentId] = tag;
});
});
};
/* Best level of cachingāget the name from the hash straight away. */
StyleSheet.prototype.getName = function getName(hash) {
return this.hashes[hash.toString()];
};
/* Second level of cachingāif the name is already in the dom, don't
* inject anything and record the hash for getName next time. */
StyleSheet.prototype.alreadyInjected = function alreadyInjected(hash, name) {
if (!this.names[name]) return false;
this.hashes[hash.toString()] = name;
return true;
};
/* Third type of cachingādon't inject components' componentId twice. */
StyleSheet.prototype.hasInjectedComponent = function hasInjectedComponent(componentId) {
return !!this.componentTags[componentId];
};
StyleSheet.prototype.deferredInject = function deferredInject(componentId, isLocal, css) {
if (this === instance) {
clones.forEach(function (clone) {
clone.deferredInject(componentId, isLocal, css);
});
}
this.getOrCreateTag(componentId, isLocal);
this.deferredInjections[componentId] = css;
};
StyleSheet.prototype.inject = function inject(componentId, isLocal, css, hash, name) {
if (this === instance) {
clones.forEach(function (clone) {
clone.inject(componentId, isLocal, css);
});
}
var tag = this.getOrCreateTag(componentId, isLocal);
var deferredInjection = this.deferredInjections[componentId];
if (deferredInjection) {
tag.inject(componentId, deferredInjection);
delete this.deferredInjections[componentId];
}
tag.inject(componentId, css, name);
if (hash && name) {
this.hashes[hash.toString()] = name;
}
};
StyleSheet.prototype.toHTML = function toHTML() {
return this.tags.map(function (tag) {
return tag.toHTML();
}).join('');
};
StyleSheet.prototype.toReactElements = function toReactElements() {
return this.tags.map(function (tag, i) {
return tag.toReactElement('sc-' + i);
});
};
StyleSheet.prototype.getOrCreateTag = function getOrCreateTag(componentId, isLocal) {
var existingTag = this.componentTags[componentId];
if (existingTag) {
return existingTag;
}
var lastTag = this.tags[this.tags.length - 1];
var componentTag = !lastTag || lastTag.isFull() || lastTag.isLocal !== isLocal ? this.createNewTag(isLocal) : lastTag;
this.componentTags[componentId] = componentTag;
componentTag.addComponent(componentId);
return componentTag;
};
StyleSheet.prototype.createNewTag = function createNewTag(isLocal) {
var newTag = this.tagConstructor(isLocal);
this.tags.push(newTag);
return newTag;
};
StyleSheet.reset = function reset(isServer) {
instance = StyleSheet.create(isServer);
};
/* We can make isServer totally implicit once Jest 20 drops and we
* can change environment on a per-test basis. */
StyleSheet.create = function create() {
var isServer = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : typeof document === 'undefined';
return (isServer ? ServerStyleSheet : BrowserStyleSheet).create();
};
StyleSheet.clone = function clone(oldSheet) {
var newSheet = new StyleSheet(oldSheet.tagConstructor, oldSheet.tags.map(function (tag) {
return tag.clone();
}), _extends({}, oldSheet.names));
newSheet.hashes = _extends({}, oldSheet.hashes);
newSheet.deferredInjections = _extends({}, oldSheet.deferredInjections);
clones.push(newSheet);
return newSheet;
};
createClass(StyleSheet, null, [{
key: 'instance',
get: function get$$1() {
return instance || (instance = StyleSheet.create());
}
}]);
return StyleSheet;
}();
var _StyleSheetManager$ch;
//
var StyleSheetManager = function (_Component) {
inherits(StyleSheetManager, _Component);
function StyleSheetManager() {
classCallCheck(this, StyleSheetManager);
return possibleConstructorReturn(this, _Component.apply(this, arguments));
}
StyleSheetManager.prototype.getChildContext = function getChildContext() {
var _ref;
return _ref = {}, _ref[CONTEXT_KEY] = this.props.sheet, _ref;
};
StyleSheetManager.prototype.render = function render() {
/* eslint-disable react/prop-types */
// Flow v0.43.1 will report an error accessing the `children` property,
// but v0.47.0 will not. It is necessary to use a type cast instead of
// a "fixme" comment to satisfy both Flow versions.
return __WEBPACK_IMPORTED_MODULE_2_react___default.a.Children.only(this.props.children);
};
return StyleSheetManager;
}(__WEBPACK_IMPORTED_MODULE_2_react__["Component"]);
StyleSheetManager.childContextTypes = (_StyleSheetManager$ch = {}, _StyleSheetManager$ch[CONTEXT_KEY] = __WEBPACK_IMPORTED_MODULE_3_prop_types___default.a.oneOfType([__WEBPACK_IMPORTED_MODULE_3_prop_types___default.a.instanceOf(StyleSheet), __WEBPACK_IMPORTED_MODULE_3_prop_types___default.a.instanceOf(ServerStyleSheet)]).isRequired, _StyleSheetManager$ch);
StyleSheetManager.propTypes = {
sheet: __WEBPACK_IMPORTED_MODULE_3_prop_types___default.a.oneOfType([__WEBPACK_IMPORTED_MODULE_3_prop_types___default.a.instanceOf(StyleSheet), __WEBPACK_IMPORTED_MODULE_3_prop_types___default.a.instanceOf(ServerStyleSheet)]).isRequired
};
//
/* eslint-disable no-underscore-dangle */
var ServerTag = function () {
function ServerTag(isLocal) {
classCallCheck(this, ServerTag);
this.isLocal = isLocal;
this.components = {};
this.size = 0;
this.names = [];
}
ServerTag.prototype.isFull = function isFull() {
return false;
};
ServerTag.prototype.addComponent = function addComponent(componentId) {
if ("development" !== 'production' && this.components[componentId]) {
throw new Error('Trying to add Component \'' + componentId + '\' twice!');
}
this.components[componentId] = { componentId: componentId, css: '' };
this.size += 1;
};
ServerTag.prototype.concatenateCSS = function concatenateCSS() {
var _this = this;
return Object.keys(this.components).reduce(function (styles, k) {
return styles + _this.components[k].css;
}, '');
};
ServerTag.prototype.inject = function inject(componentId, css, name) {
var comp = this.components[componentId];
if ("development" !== 'production' && !comp) {
throw new Error('Must add a new component before you can inject css into it');
}
if (comp.css === '') comp.css = '/* sc-component-id: ' + componentId + ' */\n';
comp.css += css.replace(/\n*$/, '\n');
if (name) this.names.push(name);
};
ServerTag.prototype.toHTML = function toHTML() {
var attrs = ['type="text/css"', SC_ATTR + '="' + this.names.join(' ') + '"', LOCAL_ATTR + '="' + (this.isLocal ? 'true' : 'false') + '"'];
var nonce = getNonce();
if (nonce) {
attrs.push('nonce="' + nonce + '"');
}
return '<style ' + attrs.join(' ') + '>' + this.concatenateCSS() + '</style>';
};
ServerTag.prototype.toReactElement = function toReactElement(key) {
var _attrs;
var attrs = (_attrs = {}, _attrs[SC_ATTR] = this.names.join(' '), _attrs[LOCAL_ATTR] = this.isLocal.toString(), _attrs);
var nonce = getNonce();
if (nonce) {
attrs.nonce = nonce;
}
return __WEBPACK_IMPORTED_MODULE_2_react___default.a.createElement('style', _extends({
key: key,
type: 'text/css'
}, attrs, {
dangerouslySetInnerHTML: { __html: this.concatenateCSS() }
}));
};
ServerTag.prototype.clone = function clone() {
var _this2 = this;
var copy = new ServerTag(this.isLocal);
copy.names = [].concat(this.names);
copy.size = this.size;
copy.components = Object.keys(this.components).reduce(function (acc, key) {
acc[key] = _extends({}, _this2.components[key]); // eslint-disable-line no-param-reassign
return acc;
}, {});
return copy;
};
return ServerTag;
}();
var ServerStyleSheet = function () {
function ServerStyleSheet() {
classCallCheck(this, ServerStyleSheet);
this.instance = StyleSheet.clone(StyleSheet.instance);
}
ServerStyleSheet.prototype.collectStyles = function collectStyles(children) {
if (this.closed) {
throw new Error("Can't collect styles once you've called getStyleTags!");
}
return __WEBPACK_IMPORTED_MODULE_2_react___default.a.createElement(
StyleSheetManager,
{ sheet: this.instance },
children
);
};
ServerStyleSheet.prototype.getStyleTags = function getStyleTags() {
if (!this.closed) {
clones.splice(clones.indexOf(this.instance), 1);
this.closed = true;
}
return this.instance.toHTML();
};
ServerStyleSheet.prototype.getStyleElement = function getStyleElement() {
if (!this.closed) {
clones.splice(clones.indexOf(this.instance), 1);
this.closed = true;
}
return this.instance.toReactElements();
};
ServerStyleSheet.create = function create() {
return new StyleSheet(function (isLocal) {
return new ServerTag(isLocal);
});
};
return ServerStyleSheet;
}();
//
var LIMIT = 200;
var createWarnTooManyClasses = (function (displayName) {
var generatedClasses = {};
var warningSeen = false;
return function (className) {
if (!warningSeen) {
generatedClasses[className] = true;
if (Object.keys(generatedClasses).length >= LIMIT) {
// Unable to find latestRule in test environment.
/* eslint-disable no-console, prefer-template */
console.warn('Over ' + LIMIT + ' classes were generated for component ' + displayName + '. \n' + 'Consider using the attrs method, together with a style object for frequently changed styles.\n' + 'Example:\n' + ' const Component = styled.div.attrs({\n' + ' style: ({ background }) => ({\n' + ' background,\n' + ' }),\n' + ' })`width: 100%;`\n\n' + ' <Component />');
warningSeen = true;
generatedClasses = {};
}
}
};
});
//
/* eslint-disable max-len */
/**
* Trying to avoid the unknown-prop errors on styled components by filtering by
* React's attribute whitelist.
*
* To regenerate this regex:
*
* 1. `npm i -g regexgen` (https://github.com/devongovett/regexgen)
* 2. Run `regexgen` with the list of space-separated words below as input
* 3. Surround the emitted regex with this: `/^(GENERATED_REGEX)$/` -- this will ensure a full string match
* and no false positives from partials
**/
/*
children dangerouslySetInnerHTML key ref autoFocus defaultValue valueLink defaultChecked checkedLink innerHTML suppressContentEditableWarning onFocusIn onFocusOut className onCopy onCut onPaste onCompositionEnd onCompositionStart onCompositionUpdate onKeyDown onKeyPress onKeyUp onFocus onBlur onChange onInput onSubmit onReset onClick onContextMenu onDoubleClick onDrag onDragEnd onDragEnter onDragExit onDragLeave onDragOver onDragStart onDrop onMouseDown onMouseEnter onMouseLeave onMouseMove onMouseOut onMouseOver onMouseUp onSelect onTouchCancel onTouchEnd onTouchMove onTouchStart onScroll onWheel onAbort onCanPlay onCanPlayThrough onDurationChange onEmptied onEncrypted onEnded onError onLoadedData onLoadedMetadata onLoadStart onPause onPlay onPlaying onProgress onRateChange onSeeked onSeeking onStalled onSuspend onTimeUpdate onVolumeChange onWaiting onLoad onAnimationStart onAnimationEnd onAnimationIteration onTransitionEnd onCopyCapture onCutCapture onPasteCapture onCompositionEndCapture onCompositionStartCapture onCompositionUpdateCapture onKeyDownCapture onKeyPressCapture onKeyUpCapture onFocusCapture onBlurCapture onChangeCapture onInputCapture onSubmitCapture onResetCapture onClickCapture onContextMenuCapture onDoubleClickCapture onDragCapture onDragEndCapture onDragEnterCapture onDragExitCapture onDragLeaveCapture onDragOverCapture onDragStartCapture onDropCapture onMouseDownCapture onMouseEnterCapture onMouseLeaveCapture onMouseMoveCapture onMouseOutCapture onMouseOverCapture onMouseUpCapture onSelectCapture onTouchCancelCapture onTouchEndCapture onTouchMoveCapture onTouchStartCapture onScrollCapture onWheelCapture onAbortCapture onCanPlayCapture onCanPlayThroughCapture onDurationChangeCapture onEmptiedCapture onEncryptedCapture onEndedCapture onErrorCapture onLoadedDataCapture onLoadedMetadataCapture onLoadStartCapture onPauseCapture onPlayCapture onPlayingCapture onProgressCapture onRateChangeCapture onSeekedCapture onSeekingCapture onStalledCapture onSuspendCapture onTimeUpdateCapture onVolumeChangeCapture onWaitingCapture onLoadCapture onAnimationStartCapture onAnimationEndCapture onAnimationIterationCapture onTransitionEndCapture accept acceptCharset accessKey action allowFullScreen allowTransparency alt as async autoComplete autoPlay capture cellPadding cellSpacing charSet challenge checked cite classID className cols colSpan content contentEditable contextMenu controls coords crossOrigin data dateTime default defer dir disabled download draggable encType form formAction formEncType formMethod formNoValidate formTarget frameBorder headers height hidden high href hrefLang htmlFor httpEquiv icon id inputMode integrity is keyParams keyType kind label lang list loop low manifest marginHeight marginWidth max maxLength media mediaGroup method min minLength multiple muted name nonce noValidate open optimum pattern placeholder playsInline poster preload profile radioGroup readOnly referrerPolicy rel required reversed role rows rowSpan sandbox scope scoped scrolling seamless selected shape size sizes span spellCheck src srcDoc srcLang srcSet start step style summary tabIndex target title type useMap value width wmode wrap about datatype inlist prefix property resource typeof vocab autoCapitalize autoCorrect autoSave color itemProp itemScope itemType itemID itemRef results security unselectable accentHeight accumulate additive alignmentBaseline allowReorder alphabetic amplitude arabicForm ascent attributeName attributeType autoReverse azimuth baseFrequency baseProfile baselineShift bbox begin bias by calcMode capHeight clip clipPath clipRule clipPathUnits colorInterpolation colorInterpolationFilters colorProfile colorRendering contentScriptType contentStyleType cursor cx cy d decelerate descent diffuseConstant direction display divisor dominantBaseline dur dx dy edgeMode elevation enableBackground end exponent externalResourcesRequired fill fillOpacity fillRule filter filterRes filterUnits floodColor floodOpacity focusable fontFamily fontSize fontSizeAdjust fontStretch fontStyle fontVariant fontWeight format from fx fy g1 g2 glyphName glyphOrientationHorizontal glyphOrientationVertical glyphRef gradientTransform gradientUnits hanging horizAdvX horizOriginX ideographic imageRendering in in2 intercept k k1 k2 k3 k4 kernelMatrix kernelUnitLength kerning keyPoints keySplines keyTimes lengthAdjust letterSpacing lightingColor limitingConeAngle local markerEnd markerMid markerStart markerHeight markerUnits markerWidth mask maskContentUnits maskUnits mathematical mode numOctaves offset opacity operator order orient orientation origin overflow overlinePosition overlineThickness paintOrder panose1 pathLength patternContentUnits patternTransform patternUnits pointerEvents points pointsAtX pointsAtY pointsAtZ preserveAlpha preserveAspectRatio primitiveUnits r radius refX refY renderingIntent repeatCount repeatDur requiredExtensions requiredFeatures restart result rotate rx ry scale seed shapeRendering slope spacing specularConstant specularExponent speed spreadMethod startOffset stdDeviation stemh stemv stitchTiles stopColor stopOpacity strikethroughPosition strikethroughThickness string stroke strokeDasharray strokeDashoffset strokeLinecap strokeLinejoin strokeMiterlimit strokeOpacity strokeWidth surfaceScale systemLanguage tableValues targetX targetY textAnchor textDecoration textRendering textLength to transform u1 u2 underlinePosition underlineThickness unicode unicodeBidi unicodeRange unitsPerEm vAlphabetic vHanging vIdeographic vMathematical values vectorEffect version vertAdvY vertOriginX vertOriginY viewBox viewTarget visibility widths wordSpacing writingMode x xHeight x1 x2 xChannelSelector xlinkActuate xlinkArcrole xlinkHref xlinkRole xlinkShow xlinkTitle xlinkType xmlBase xmlns xmlnsXlink xmlLang xmlSpace y y1 y2 yChannelSelector z zoomAndPan
*/
/* eslint-enable max-len */
var ATTRIBUTE_REGEX = /^((?:s(?:uppressContentEditableWarn|croll|pac)|(?:shape|image|text)Render|(?:letter|word)Spac|vHang|hang)ing|(?:on(?:AnimationIteration|C(?:o(?:mposition(?:Update|Start|End)|ntextMenu|py)|anPlayThrough|anPlay|hange|lick|ut)|(?:(?:Duration|Volume|Rate)Chang|(?:MouseLea|(?:Touch|Mouse)Mo|DragLea)v|Paus)e|Loaded(?:Metad|D)ata|(?:Animation|Touch|Load|Drag)Start|(?:(?:T(?:ransition|ouch)|Animation)E|Suspe)nd|DoubleClick|(?:TouchCanc|Whe)el|(?:Mouse(?:Ent|Ov)e|Drag(?:Ent|Ov)e|Erro)r|TimeUpdate|(?:E(?:n(?:crypt|d)|mpti)|S(?:tall|eek))ed|MouseDown|P(?:rogress|laying)|(?:MouseOu|DragExi|S(?:elec|ubmi)|Rese|Inpu)t|KeyPress|DragEnd|Key(?:Down|Up)|(?:Wait|Seek)ing|(?:MouseU|Dro)p|Scroll|Paste|Focus|Abort|Drag|Play|Load|Blur)Captur|alignmentBaselin|(?:limitingConeAng|xlink(?:(?:Arcr|R)o|Tit)|s(?:urfaceSca|ty|ca)|unselectab|baseProfi|fontSty|(?:focus|dragg)ab|multip|profi|tit)l|d(?:ominantBaselin|efaultValu)|a(?:uto(?:Capitaliz|Revers|Sav)|dditiv)|(?:(?:formNoValid|xlinkActu|noValid|accumul|rot)a|autoComple|decelera)t|(?:(?:attribute|item)T|datat)yp|(?:attribute|glyph)Nam|playsInlin|(?:formE|e)ncTyp|(?:writing|input|edge)Mod|(?:xlinkTy|itemSco|keyTy|slo)p|(?:amplitu|mo)d|(?:xmlSpa|non)c|fillRul|(?:dateTi|na)m|r(?:esourc|ol)|xmlBas|wmod)e|(?:glyphOrientationHorizont|loc)al|(?:externalResourcesRequir|select|revers|mut)ed|c(?:o(?:lorInterpolationFilter|ntrol|ord)s|o(?:lor(?:Interpolation)?|ntent)|(?:ontentS(?:cript|tyle)Typ|o(?:ntentEditab|lorProfi)l|l(?:assNam|ipRul)|a(?:lcMod|ptur)|it)e|olorRendering|l(?:ipPathUnits|assID)|o(?:ntextMenu|ls)|h(?:eckedLink|a(?:llenge|rSet)|ildren|ecked)|ell(?:Spac|Padd)ing|(?:rossOrigi|olSpa)n|apHeight|lip(?:Path)?|ursor|[xy])|glyphOrientationVertical|d(?:angerouslySetInnerHTML|efaultChecked|ownload|isabled|isplay|[xy])|(?:s(?:trikethroughThickn|eaml)es|(?:und|ov)erlineThicknes|r(?:equiredExtension|adiu)|(?:requiredFeatur|tableValu|stitchTil|numOctav|filterR)e|key(?:(?:Splin|Tim)e|Param)|autoFocu|header|bia)s|(?:(?:st(?:rikethroughPosi|dDevia)|(?:und|ov)erlinePosi|(?:textDecor|elev)a|orienta)tio|(?:strokeLinejo|orig)i|formActio|zoomAndPa|onFocusI|directio|(?:vers|act)io|rowSpa|begi|ico)n|o(?:n(?:AnimationIteration|C(?:o(?:mposition(?:Update|Start|End)|ntextMenu|py)|anPlayThrough|anPlay|hange|lick|ut)|(?:(?:Duration|Volume|Rate)Chang|(?:MouseLea|(?:Touch|Mouse)Mo|DragLea)v|Paus)e|Loaded(?:Metad|D)ata|(?:Animation|Touch|Load|Drag)Start|(?:(?:T(?:ransition|ouch)|Animation)E|Suspe)nd|DoubleClick|(?:TouchCanc|Whe)el|(?:Mouse(?:Ent|Ov)e|Drag(?:Ent|Ov)e|Erro)r|TimeUpdate|(?:E(?:n(?:crypt|d)|mpti)|S(?:tall|eek))ed|MouseDown|P(?:rogress|laying)|(?:MouseOu|DragExi|S(?:elec|ubmi)|Rese|Inpu)t|KeyPress|DragEnd|Key(?:Down|Up)|(?:Wait|Seek)ing|(?:MouseU|Dro)p|Scroll|Paste|Focus|Abort|Drag|Play|Load|Blur)|rient)|p(?:reserveA(?:spectRatio|lpha)|ointsAt[X-Z]|anose1)|(?:patternContent|ma(?:sk(?:Content)?|rker)|primitive|gradient|pattern|filter)Units|(?:gradientT|patternT|t)ransform|(?:(?:allowTranspar|baseFrequ)enc|re(?:ferrerPolic|adOnl)|(?:(?:st(?:roke|op)O|floodO|fillO|o)pac|integr|secur)it|visibilit|fontFamil|accessKe|propert|summar)y|(?:strokeMiterlimi|(?:specularConsta|repeatCou|fontVaria)n|(?:(?:specularE|e)xpon|renderingInt|asc)en|d(?:iffuseConsta|esce)n|(?:fontSizeAdju|lengthAdju|manife)s|baselineShif|vectorEffec|(?:(?:mar(?:ker|gin)|x)H|accentH|fontW)eigh|a(?:utoCorrec|bou)|markerStar|onFocusOu|in(?:tercep|lis)|restar|forma|heigh|lis)t|(?:(?:st(?:rokeDasho|artO)|o)ffs|acceptChars|formTarg|viewTarg|srcS)et|(?:(?:enableBackgrou|markerE)n|s(?:p(?:readMetho|ee)|ee)|formMetho|m(?:arkerMi|etho)|preloa|kin)d|k(?:ernel(?:UnitLength|Matrix)|[1-4])|(?:[xy]ChannelSelect|lightingCol|textAnch|floodCol|stopCol|operat|htmlF)or|(?:allowFullScre|hidd)en|strokeDasharray|systemLanguage|(?:strokeLineca|itemPro|useMa|wra|loo)p|v(?:Mathematical|ert(?:Origin[XY]|AdvY)|alues|ocab)|(?:pointerEve|keyPoi)nts|unicodeRange|(?:(?:allowReord|placehold|frameBord|paintOrd|post|ord)e|repeatDu|d(?:efe|u))r|mathematical|(?:vI|i)deographic|h(?:oriz(?:Origin|Adv)X|ttpEquiv)|u(?:nicodeBidi|[12])|(?:fontStretc|hig)h|(?:(?:mar(?:ker|gin)W|strokeW)id|azimu)th|vAlphabetic|mediaGroup|spellCheck|(?:unitsPerE|optimu|fro)m|r(?:adioGroup|e(?:sults|f[XY]|l)|ows|[xy])|(?:xmlnsXl|valueL)ink|a(?:rabicForm|l(?:phabetic|t)|sync)|pathLength|(?:text|m(?:in|ax))Length|innerHTML|xlinkShow|(?:xlinkHr|glyphR)ef|r(?:e(?:quired|sult|f))?|o(?:verflow|pen)|(?:tabInde|(?:sand|b)bo|viewBo)x|(?:(?:href|xml|src)La|kerni)ng|f(?:o(?:ntSize|rm)|il(?:ter|l))|autoPlay|unicode|p(?:attern|oints)|t(?:arget[XY]|o)|i(?:temRef|n2|s)|divisor|d(?:efault|ata|ir)?|srcDoc|s(?:coped|te(?:m[hv]|p)|pan)|(?:width|size)s|(?:stri|la)ng|prefix|itemID|s(?:t(?:roke|art)|hape|cope|rc)|a(?:ccept|s)|t(?:arget|ype)|typeof|width|value|x(?:mlns)?|label|m(?:edia|a(?:sk|x)|in)|size|href|k(?:ey)?|end|low|x[12]|i[dn]|y[12]|g[12]|by|f[xy]|[yz])$/;
/* From DOMProperty */
var ATTRIBUTE_NAME_START_CHAR = ':A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD';
var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + '\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040';
var isCustomAttribute = RegExp.prototype.test.bind(new RegExp('^(data|aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$'));
var validAttr = (function (name) {
return ATTRIBUTE_REGEX.test(name) || isCustomAttribute(name.toLowerCase());
});
//
function isTag(target) /* : %checks */{
return typeof target === 'string';
}
//
function isStyledComponent(target) /* : %checks */{
return typeof target === 'function' && typeof target.styledComponentId === 'string';
}
//
/* eslint-disable no-undef */
function getComponentName(target) {
return target.displayName || target.name || 'Component';
}
//
var determineTheme = (function (props, fallbackTheme, defaultProps) {
// Props should take precedence over ThemeProvider, which should take precedence over
// defaultProps, but React automatically puts defaultProps on props.
/* eslint-disable react/prop-types */
var isDefaultTheme = defaultProps && props.theme === defaultProps.theme;
var theme = props.theme && !isDefaultTheme ? props.theme : fallbackTheme;
/* eslint-enable */
return theme;
});
//
var escapeRegex = /[[\].#*$><+~=|^:(),"'`-]+/g;
var dashesAtEnds = /(^-|-$)/g;
/**
* TODO: Explore using CSS.escape when it becomes more available
* in evergreen browsers.
*/
function escape(str) {
return str
// Replace all possible CSS selectors
.replace(escapeRegex, '-')
// Remove extraneous hyphens at the start and end
.replace(dashesAtEnds, '');
}
//
/**
* Creates a broadcast that can be listened to, i.e. simple event emitter
*
* @see https://github.com/ReactTraining/react-broadcast
*/
var createBroadcast = function createBroadcast(initialState) {
var listeners = {};
var id = 0;
var state = initialState;
function publish(nextState) {
state = nextState;
// eslint-disable-next-line guard-for-in, no-restricted-syntax
for (var key in listeners) {
var listener = listeners[key];
if (listener === undefined) {
// eslint-disable-next-line no-continue
continue;
}
listener(state);
}
}
function subscribe(listener) {
var currentId = id;
listeners[currentId] = listener;
id += 1;
listener(state);
return currentId;
}
function unsubscribe(unsubID) {
listeners[unsubID] = undefined;
}
return { publish: publish, subscribe: subscribe, unsubscribe: unsubscribe };
};
//
// Helper to call a given function, only once
var once = (function (cb) {
var called = false;
return function () {
if (!called) {
called = true;
cb();
}
};
});
var _ThemeProvider$childC;
var _ThemeProvider$contex;
//
/* globals React$Element */
// NOTE: DO NOT CHANGE, changing this is a semver major change!
var CHANNEL = '__styled-components__';
var CHANNEL_NEXT = CHANNEL + 'next__';
var CONTEXT_CHANNEL_SHAPE = __WEBPACK_IMPORTED_MODULE_3_prop_types___default.a.shape({
getTheme: __WEBPACK_IMPORTED_MODULE_3_prop_types___default.a.func,
subscribe: __WEBPACK_IMPORTED_MODULE_3_prop_types___default.a.func,
unsubscribe: __WEBPACK_IMPORTED_MODULE_3_prop_types___default.a.func
});
var warnChannelDeprecated = void 0;
if (true) {
warnChannelDeprecated = once(function () {
// eslint-disable-next-line no-console
console.error('Warning: Usage of `context.' + CHANNEL + '` as a function is deprecated. It will be replaced with the object on `.context.' + CHANNEL_NEXT + '` in a future version.');
});
}
var isFunction = function isFunction(test) {
return typeof test === 'function';
};
/**
* Provide a theme to an entire react component tree via context and event listeners (have to do
* both context and event emitter as pure components block context updates)
*/
var ThemeProvider = function (_Component) {
inherits(ThemeProvider, _Component);
function ThemeProvider() {
classCallCheck(this, ThemeProvider);
var _this = possibleConstructorReturn(this, _Component.call(this));
_this.unsubscribeToOuterId = -1;
_this.getTheme = _this.getTheme.bind(_this);
return _this;
}
ThemeProvider.prototype.componentWillMount = function componentWillMount() {
var _this2 = this;
// If there is a ThemeProvider wrapper anywhere around this theme provider, merge this theme
// with the outer theme
var outerContext = this.context[CHANNEL_NEXT];
if (outerContext !== undefined) {
this.unsubscribeToOuterId = outerContext.subscribe(function (theme) {
_this2.outerTheme = theme;
});
}
this.broadcast = createBroadcast(this.getTheme());
};
ThemeProvider.prototype.getChildContext = function getChildContext() {
var _this3 = this,
_babelHelpers$extends;
return _extends({}, this.context, (_babelHelpers$extends = {}, _babelHelpers$extends[CHANNEL_NEXT] = {
getTheme: this.getTheme,
subscribe: this.broadcast.subscribe,
unsubscribe: this.broadcast.unsubscribe
}, _babelHelpers$extends[CHANNEL] = function (subscriber) {
if (true) {
warnChannelDeprecated();
}
// Patch the old `subscribe` provide via `CHANNEL` for older clients.
var unsubscribeId = _this3.broadcast.subscribe(subscriber);
return function () {
return _this3.broadcast.unsubscribe(unsubscribeId);
};
}, _babelHelpers$extends));
};
ThemeProvider.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
if (this.props.theme !== nextProps.theme) {
this.broadcast.publish(this.getTheme(nextProps.theme));
}
};
ThemeProvider.prototype.componentWillUnmount = function componentWillUnmount() {
if (this.unsubscribeToOuterId !== -1) {
this.context[CHANNEL_NEXT].unsubscribe(this.unsubscribeToOuterId);
}
};
// Get the theme from the props, supporting both (outerTheme) => {} as well as object notation
ThemeProvider.prototype.getTheme = function getTheme(passedTheme) {
var theme = passedTheme || this.props.theme;
if (isFunction(theme)) {
var mergedTheme = theme(this.outerTheme);
if ("development" !== 'production' && !__WEBPACK_IMPORTED_MODULE_0_is_plain_object___default()(mergedTheme)) {
throw new Error('[ThemeProvider] Please return an object from your theme function, i.e. theme={() => ({})}!');
}
return mergedTheme;
}
if (!__WEBPACK_IMPORTED_MODULE_0_is_plain_object___default()(theme)) {
throw new Error('[ThemeProvider] Please make your theme prop a plain object');
}
return _extends({}, this.outerTheme, theme);
};
ThemeProvider.prototype.render = function render() {
if (!this.props.children) {
return null;
}
return __WEBPACK_IMPORTED_MODULE_2_react___default.a.Children.only(this.props.children);
};
return ThemeProvider;
}(__WEBPACK_IMPORTED_MODULE_2_react__["Component"]);
ThemeProvider.childContextTypes = (_ThemeProvider$childC = {}, _ThemeProvider$childC[CHANNEL] = __WEBPACK_IMPORTED_MODULE_3_prop_types___default.a.func, _ThemeProvider$childC[CHANNEL_NEXT] = CONTEXT_CHANNEL_SHAPE, _ThemeProvider$childC);
ThemeProvider.contextTypes = (_ThemeProvider$contex = {}, _ThemeProvider$contex[CHANNEL_NEXT] = CONTEXT_CHANNEL_SHAPE, _ThemeProvider$contex);
//
// HACK for generating all static styles without needing to allocate
// an empty execution context every single time...
var STATIC_EXECUTION_CONTEXT = {};
var _StyledComponent = (function (ComponentStyle, constructWithOptions) {
var identifiers = {};
/* We depend on components having unique IDs */
var generateId = function generateId(_displayName, parentComponentId) {
var displayName = typeof _displayName !== 'string' ? 'sc' : escape(_displayName);
var componentId = void 0;
/**
* only fall back to hashing the component injection order if
* a proper displayName isn't provided by the babel plugin
*/
if (!_displayName) {
var nr = (identifiers[displayName] || 0) + 1;
identifiers[displayName] = nr;
componentId = displayName + '-' + ComponentStyle.generateName(displayName + nr);
} else {
componentId = displayName + '-' + ComponentStyle.generateName(displayName);
}
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[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