UNPKG

75.9 kBJavaScriptView Raw
1import Stylis from 'stylis/stylis.min';
2import _insertRulePlugin from 'stylis-rule-sheet';
3import React, { cloneElement, createContext, Component, createElement } from 'react';
4import { isElement, isValidElementType, ForwardRef } from 'react-is';
5import memoize from 'memoize-one';
6import PropTypes from 'prop-types';
7import ReactDOM from 'react-dom';
8import validAttr from '@emotion/is-prop-valid';
9
10//
11
12var interleave = (function (strings, interpolations) {
13 var result = [strings[0]];
14
15 for (var i = 0, len = interpolations.length; i < len; i += 1) {
16 result.push(interpolations[i], strings[i + 1]);
17 }
18
19 return result;
20});
21
22var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
23 return typeof obj;
24} : function (obj) {
25 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
26};
27
28var classCallCheck = function (instance, Constructor) {
29 if (!(instance instanceof Constructor)) {
30 throw new TypeError("Cannot call a class as a function");
31 }
32};
33
34var createClass = function () {
35 function defineProperties(target, props) {
36 for (var i = 0; i < props.length; i++) {
37 var descriptor = props[i];
38 descriptor.enumerable = descriptor.enumerable || false;
39 descriptor.configurable = true;
40 if ("value" in descriptor) descriptor.writable = true;
41 Object.defineProperty(target, descriptor.key, descriptor);
42 }
43 }
44
45 return function (Constructor, protoProps, staticProps) {
46 if (protoProps) defineProperties(Constructor.prototype, protoProps);
47 if (staticProps) defineProperties(Constructor, staticProps);
48 return Constructor;
49 };
50}();
51
52var _extends = Object.assign || function (target) {
53 for (var i = 1; i < arguments.length; i++) {
54 var source = arguments[i];
55
56 for (var key in source) {
57 if (Object.prototype.hasOwnProperty.call(source, key)) {
58 target[key] = source[key];
59 }
60 }
61 }
62
63 return target;
64};
65
66var inherits = function (subClass, superClass) {
67 if (typeof superClass !== "function" && superClass !== null) {
68 throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
69 }
70
71 subClass.prototype = Object.create(superClass && superClass.prototype, {
72 constructor: {
73 value: subClass,
74 enumerable: false,
75 writable: true,
76 configurable: true
77 }
78 });
79 if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
80};
81
82var objectWithoutProperties = function (obj, keys) {
83 var target = {};
84
85 for (var i in obj) {
86 if (keys.indexOf(i) >= 0) continue;
87 if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
88 target[i] = obj[i];
89 }
90
91 return target;
92};
93
94var possibleConstructorReturn = function (self, call) {
95 if (!self) {
96 throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
97 }
98
99 return call && (typeof call === "object" || typeof call === "function") ? call : self;
100};
101
102//
103var isPlainObject = (function (x) {
104 return (typeof x === 'undefined' ? 'undefined' : _typeof(x)) === 'object' && x.constructor === Object;
105});
106
107//
108var EMPTY_ARRAY = Object.freeze([]);
109var EMPTY_OBJECT = Object.freeze({});
110
111//
112function isFunction(test) {
113 return typeof test === 'function';
114}
115
116//
117
118function getComponentName(target) {
119 return target.displayName || target.name || 'Component';
120}
121
122//
123function isStyledComponent(target) {
124 return target && typeof target.styledComponentId === 'string';
125}
126
127//
128
129
130var SC_ATTR = typeof process !== 'undefined' && process.env.SC_ATTR || 'data-styled';
131
132var SC_VERSION_ATTR = 'data-styled-version';
133
134var SC_STREAM_ATTR = 'data-styled-streamed';
135
136var IS_BROWSER = typeof window !== 'undefined' && 'HTMLElement' in window;
137
138var DISABLE_SPEEDY = process.env.NODE_ENV !== 'production';
139
140// Shared empty execution context when generating static styles
141var STATIC_EXECUTION_CONTEXT = {};
142
143//
144
145
146/**
147 * Parse errors.md and turn it into a simple hash of code: message
148 */
149var ERRORS = process.env.NODE_ENV !== 'production' ? {
150 "1": "Cannot create styled-component for component: %s.\n\n",
151 "2": "Can't collect styles once you've consumed a `ServerStyleSheet`'s styles! `ServerStyleSheet` is a one off instance for each server-side render cycle.\n\n- Are you trying to reuse it across renders?\n- Are you accidentally calling collectStyles twice?\n\n",
152 "3": "Streaming SSR is only supported in a Node.js environment; Please do not try to call this method in the browser.\n\n",
153 "4": "The `StyleSheetManager` expects a valid target or sheet prop!\n\n- Does this error occur on the client and is your target falsy?\n- Does this error occur on the server and is the sheet falsy?\n\n",
154 "5": "The clone method cannot be used on the client!\n\n- Are you running in a client-like environment on the server?\n- Are you trying to run SSR on the client?\n\n",
155 "6": "Trying to insert a new style tag, but the given Node is unmounted!\n\n- Are you using a custom target that isn't mounted?\n- Does your document not have a valid head element?\n- Have you accidentally removed a style tag manually?\n\n",
156 "7": "ThemeProvider: Please return an object from your \"theme\" prop function, e.g.\n\n```js\ntheme={() => ({})}\n```\n\n",
157 "8": "ThemeProvider: Please make your \"theme\" prop an object.\n\n",
158 "9": "Missing document `<head>`\n\n",
159 "10": "Cannot find a StyleSheet instance. Usually this happens if there are multiple copies of styled-components loaded at once. Check out this issue for how to troubleshoot and fix the common cases where this situation can happen: https://github.com/styled-components/styled-components/issues/1941#issuecomment-417862021\n\n",
160 "11": "_This error was replaced with a dev-time warning, it will be deleted for v4 final._ [createGlobalStyle] received children which will not be rendered. Please use the component without passing children elements.\n\n",
161 "12": "It seems you are interpolating a keyframe declaration (%s) into an untagged string. This was supported in styled-components v3, but is not longer supported in v4 as keyframes are now injected on-demand. Please wrap your string in the css\\`\\` helper (see https://www.styled-components.com/docs/api#css), which ensures the styles are injected correctly.\n"
162} : {};
163
164/**
165 * super basic version of sprintf
166 */
167function format() {
168 for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
169 args[_key] = arguments[_key];
170 }
171
172 var a = args[0];
173 var b = [];
174 var c = void 0;
175
176 for (c = 1; c < args.length; c += 1) {
177 b.push(args[c]);
178 }
179
180 b.forEach(function (d) {
181 a = a.replace(/%[a-z]/, d);
182 });
183
184 return a;
185}
186
187/**
188 * Create an error file out of errors.md for development and a simple web link to the full errors
189 * in production mode.
190 */
191
192var StyledComponentsError = function (_Error) {
193 inherits(StyledComponentsError, _Error);
194
195 function StyledComponentsError(code) {
196 classCallCheck(this, StyledComponentsError);
197
198 for (var _len2 = arguments.length, interpolations = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
199 interpolations[_key2 - 1] = arguments[_key2];
200 }
201
202 if (process.env.NODE_ENV === 'production') {
203 var _this = possibleConstructorReturn(this, _Error.call(this, 'An error occurred. See https://github.com/styled-components/styled-components/blob/master/src/utils/errors.md#' + code + ' for more information. ' + (interpolations ? 'Additional arguments: ' + interpolations.join(', ') : '')));
204 } else {
205 var _this = possibleConstructorReturn(this, _Error.call(this, format.apply(undefined, [ERRORS[code]].concat(interpolations)).trim()));
206 }
207 return possibleConstructorReturn(_this);
208 }
209
210 return StyledComponentsError;
211}(Error);
212
213//
214var SC_COMPONENT_ID = /^[^\S\n]*?\/\* sc-component-id:\s*(\S+)\s+\*\//gm;
215
216var extractComps = (function (maybeCSS) {
217 var css = '' + (maybeCSS || ''); // Definitely a string, and a clone
218 var existingComponents = [];
219 css.replace(SC_COMPONENT_ID, function (match, componentId, matchIndex) {
220 existingComponents.push({ componentId: componentId, matchIndex: matchIndex });
221 return match;
222 });
223 return existingComponents.map(function (_ref, i) {
224 var componentId = _ref.componentId,
225 matchIndex = _ref.matchIndex;
226
227 var nextComp = existingComponents[i + 1];
228 var cssFromDOM = nextComp ? css.slice(matchIndex, nextComp.matchIndex) : css.slice(matchIndex);
229 return { componentId: componentId, cssFromDOM: cssFromDOM };
230 });
231});
232
233//
234
235var COMMENT_REGEX = /^\s*\/\/.*$/gm;
236
237// NOTE: This stylis instance is only used to split rules from SSR'd style tags
238var stylisSplitter = new Stylis({
239 global: false,
240 cascade: true,
241 keyframe: false,
242 prefix: false,
243 compress: false,
244 semicolon: true
245});
246
247var stylis = new Stylis({
248 global: false,
249 cascade: true,
250 keyframe: false,
251 prefix: true,
252 compress: false,
253 semicolon: false // NOTE: This means "autocomplete missing semicolons"
254});
255
256// Wrap `insertRulePlugin to build a list of rules,
257// and then make our own plugin to return the rules. This
258// makes it easier to hook into the existing SSR architecture
259
260var parsingRules = [];
261
262// eslint-disable-next-line consistent-return
263var returnRulesPlugin = function returnRulesPlugin(context) {
264 if (context === -2) {
265 var parsedRules = parsingRules;
266 parsingRules = [];
267 return parsedRules;
268 }
269};
270
271var parseRulesPlugin = _insertRulePlugin(function (rule) {
272 parsingRules.push(rule);
273});
274
275var _componentId = void 0;
276var _selector = void 0;
277var _selectorRegexp = void 0;
278
279var selfReferenceReplacer = function selfReferenceReplacer(match, offset, string) {
280 if (
281 // the first self-ref is always untouched
282 offset > 0 &&
283 // there should be at least two self-refs to do a replacement (.b > .b)
284 string.slice(0, offset).indexOf(_selector) !== -1 &&
285 // no consecutive self refs (.b.b); that is a precedence boost and treated differently
286 string.slice(offset - _selector.length, offset) !== _selector) {
287 return '.' + _componentId;
288 }
289
290 return match;
291};
292
293/**
294 * When writing a style like
295 *
296 * & + & {
297 * color: red;
298 * }
299 *
300 * The second ampersand should be a reference to the static component class. stylis
301 * has no knowledge of static class so we have to intelligently replace the base selector.
302 */
303var selfReferenceReplacementPlugin = function selfReferenceReplacementPlugin(context, _, selectors) {
304 if (context === 2 && selectors[0].lastIndexOf(_selector) > 0) {
305 // eslint-disable-next-line no-param-reassign
306 selectors[0] = selectors[0].replace(_selectorRegexp, selfReferenceReplacer);
307 }
308};
309
310stylis.use([selfReferenceReplacementPlugin, parseRulesPlugin, returnRulesPlugin]);
311stylisSplitter.use([parseRulesPlugin, returnRulesPlugin]);
312
313var splitByRules = function splitByRules(css) {
314 return stylisSplitter('', css);
315};
316
317function stringifyRules(rules, selector, prefix) {
318 var componentId = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '&';
319
320 var flatCSS = rules.join('').replace(COMMENT_REGEX, ''); // replace JS comments
321
322 var cssStr = selector && prefix ? prefix + ' ' + selector + ' { ' + flatCSS + ' }' : flatCSS;
323
324 // stylis has no concept of state to be passed to plugins
325 // but since JS is single=threaded, we can rely on that to ensure
326 // these properties stay in sync with the current stylis run
327 _componentId = componentId;
328 _selector = selector;
329 _selectorRegexp = new RegExp('\\' + _selector + '\\b', 'g');
330
331 return stylis(prefix || !selector ? '' : selector, cssStr);
332}
333
334//
335/* eslint-disable camelcase, no-undef */
336
337var getNonce = (function () {
338 return typeof __webpack_nonce__ !== 'undefined' ? __webpack_nonce__ : null;
339});
340
341//
342// Helper to call a given function, only once
343var once = (function (cb) {
344 var called = false;
345
346 return function () {
347 if (!called) {
348 called = true;
349 cb();
350 }
351 };
352});
353
354//
355/* These are helpers for the StyleTags to keep track of the injected
356 * rule names for each (component) ID that they're keeping track of.
357 * They're crucial for detecting whether a name has already been
358 * injected.
359 * (This excludes rehydrated names) */
360
361/* adds a new ID:name pairing to a names dictionary */
362var addNameForId = function addNameForId(names, id, name) {
363 if (name) {
364 // eslint-disable-next-line no-param-reassign
365 var namesForId = names[id] || (names[id] = Object.create(null));
366 namesForId[name] = true;
367 }
368};
369
370/* resets an ID entirely by overwriting it in the dictionary */
371var resetIdNames = function resetIdNames(names, id) {
372 // eslint-disable-next-line no-param-reassign
373 names[id] = Object.create(null);
374};
375
376/* factory for a names dictionary checking the existance of an ID:name pairing */
377var hasNameForId = function hasNameForId(names) {
378 return function (id, name) {
379 return names[id] !== undefined && names[id][name];
380 };
381};
382
383/* stringifies names for the html/element output */
384var stringifyNames = function stringifyNames(names) {
385 var str = '';
386 // eslint-disable-next-line guard-for-in
387 for (var id in names) {
388 str += Object.keys(names[id]).join(' ') + ' ';
389 }
390 return str.trim();
391};
392
393/* clones the nested names dictionary */
394var cloneNames = function cloneNames(names) {
395 var clone = Object.create(null);
396 // eslint-disable-next-line guard-for-in
397 for (var id in names) {
398 clone[id] = _extends({}, names[id]);
399 }
400 return clone;
401};
402
403//
404
405/* These are helpers that deal with the insertRule (aka speedy) API
406 * They are used in the StyleTags and specifically the speedy tag
407 */
408
409/* retrieve a sheet for a given style tag */
410var sheetForTag = function sheetForTag(tag) {
411 // $FlowFixMe
412 if (tag.sheet) return tag.sheet;
413
414 /* Firefox quirk requires us to step through all stylesheets to find one owned by the given tag */
415 var size = document.styleSheets.length;
416 for (var i = 0; i < size; i += 1) {
417 var sheet = document.styleSheets[i];
418 // $FlowFixMe
419 if (sheet.ownerNode === tag) return sheet;
420 }
421
422 /* we should always be able to find a tag */
423 throw new StyledComponentsError(10);
424};
425
426/* insert a rule safely and return whether it was actually injected */
427var safeInsertRule = function safeInsertRule(sheet, cssRule, index) {
428 /* abort early if cssRule string is falsy */
429 if (!cssRule) return false;
430
431 var maxIndex = sheet.cssRules.length;
432
433 try {
434 /* use insertRule and cap passed index with maxIndex (no of cssRules) */
435 sheet.insertRule(cssRule, index <= maxIndex ? index : maxIndex);
436 } catch (err) {
437 /* any error indicates an invalid rule */
438 return false;
439 }
440
441 return true;
442};
443
444/* deletes `size` rules starting from `removalIndex` */
445var deleteRules = function deleteRules(sheet, removalIndex, size) {
446 var lowerBound = removalIndex - size;
447 for (var i = removalIndex; i > lowerBound; i -= 1) {
448 sheet.deleteRule(i);
449 }
450};
451
452//
453
454/* this marker separates component styles and is important for rehydration */
455var makeTextMarker = function makeTextMarker(id) {
456 return '\n/* sc-component-id: ' + id + ' */\n';
457};
458
459/* add up all numbers in array up until and including the index */
460var addUpUntilIndex = function addUpUntilIndex(sizes, index) {
461 var totalUpToIndex = 0;
462 for (var i = 0; i <= index; i += 1) {
463 totalUpToIndex += sizes[i];
464 }
465
466 return totalUpToIndex;
467};
468
469/* create a new style tag after lastEl */
470var makeStyleTag = function makeStyleTag(target, tagEl, insertBefore) {
471 var el = document.createElement('style');
472 el.setAttribute(SC_ATTR, '');
473 el.setAttribute(SC_VERSION_ATTR, "4.0.1");
474
475 var nonce = getNonce();
476 if (nonce) {
477 el.setAttribute('nonce', nonce);
478 }
479
480 /* Work around insertRule quirk in EdgeHTML */
481 el.appendChild(document.createTextNode(''));
482
483 if (target && !tagEl) {
484 /* Append to target when no previous element was passed */
485 target.appendChild(el);
486 } else {
487 if (!tagEl || !target || !tagEl.parentNode) {
488 throw new StyledComponentsError(6);
489 }
490
491 /* Insert new style tag after the previous one */
492 tagEl.parentNode.insertBefore(el, insertBefore ? tagEl : tagEl.nextSibling);
493 }
494
495 return el;
496};
497
498/* takes a css factory function and outputs an html styled tag factory */
499var wrapAsHtmlTag = function wrapAsHtmlTag(css, names) {
500 return function (additionalAttrs) {
501 var nonce = getNonce();
502 var attrs = [nonce && 'nonce="' + nonce + '"', SC_ATTR + '="' + stringifyNames(names) + '"', SC_VERSION_ATTR + '="' + "4.0.1" + '"', additionalAttrs];
503
504 var htmlAttr = attrs.filter(Boolean).join(' ');
505 return '<style ' + htmlAttr + '>' + css() + '</style>';
506 };
507};
508
509/* takes a css factory function and outputs an element factory */
510var wrapAsElement = function wrapAsElement(css, names) {
511 return function () {
512 var _props;
513
514 var props = (_props = {}, _props[SC_ATTR] = stringifyNames(names), _props[SC_VERSION_ATTR] = "4.0.1", _props);
515
516 var nonce = getNonce();
517 if (nonce) {
518 // $FlowFixMe
519 props.nonce = nonce;
520 }
521
522 // eslint-disable-next-line react/no-danger
523 return React.createElement('style', _extends({}, props, { dangerouslySetInnerHTML: { __html: css() } }));
524 };
525};
526
527var getIdsFromMarkersFactory = function getIdsFromMarkersFactory(markers) {
528 return function () {
529 return Object.keys(markers);
530 };
531};
532
533/* speedy tags utilise insertRule */
534var makeSpeedyTag = function makeSpeedyTag(el, getImportRuleTag) {
535 var names = Object.create(null);
536 var markers = Object.create(null);
537 var sizes = [];
538
539 var extractImport = getImportRuleTag !== undefined;
540 /* indicates whther getImportRuleTag was called */
541 var usedImportRuleTag = false;
542
543 var insertMarker = function insertMarker(id) {
544 var prev = markers[id];
545 if (prev !== undefined) {
546 return prev;
547 }
548
549 markers[id] = sizes.length;
550 sizes.push(0);
551 resetIdNames(names, id);
552
553 return markers[id];
554 };
555
556 var insertRules = function insertRules(id, cssRules, name) {
557 var marker = insertMarker(id);
558 var sheet = sheetForTag(el);
559 var insertIndex = addUpUntilIndex(sizes, marker);
560
561 var injectedRules = 0;
562 var importRules = [];
563 var cssRulesSize = cssRules.length;
564
565 for (var i = 0; i < cssRulesSize; i += 1) {
566 var cssRule = cssRules[i];
567 var mayHaveImport = extractImport; /* @import rules are reordered to appear first */
568 if (mayHaveImport && cssRule.indexOf('@import') !== -1) {
569 importRules.push(cssRule);
570 } else if (safeInsertRule(sheet, cssRule, insertIndex + injectedRules)) {
571 mayHaveImport = false;
572 injectedRules += 1;
573 }
574 }
575
576 if (extractImport && importRules.length > 0) {
577 usedImportRuleTag = true;
578 // $FlowFixMe
579 getImportRuleTag().insertRules(id + '-import', importRules);
580 }
581
582 sizes[marker] += injectedRules; /* add up no of injected rules */
583 addNameForId(names, id, name);
584 };
585
586 var removeRules = function removeRules(id) {
587 var marker = markers[id];
588 if (marker === undefined) return;
589
590 var size = sizes[marker];
591 var sheet = sheetForTag(el);
592 var removalIndex = addUpUntilIndex(sizes, marker) - 1;
593 deleteRules(sheet, removalIndex, size);
594 sizes[marker] = 0;
595 resetIdNames(names, id);
596
597 if (extractImport && usedImportRuleTag) {
598 // $FlowFixMe
599 getImportRuleTag().removeRules(id + '-import');
600 }
601 };
602
603 var css = function css() {
604 var _sheetForTag = sheetForTag(el),
605 cssRules = _sheetForTag.cssRules;
606
607 var str = '';
608
609 // eslint-disable-next-line guard-for-in
610 for (var id in markers) {
611 str += makeTextMarker(id);
612 var marker = markers[id];
613 var end = addUpUntilIndex(sizes, marker);
614 var size = sizes[marker];
615 for (var i = end - size; i < end; i += 1) {
616 var rule = cssRules[i];
617 if (rule !== undefined) {
618 str += rule.cssText;
619 }
620 }
621 }
622
623 return str;
624 };
625
626 return {
627 clone: function clone() {
628 throw new StyledComponentsError(5);
629 },
630
631 css: css,
632 getIds: getIdsFromMarkersFactory(markers),
633 hasNameForId: hasNameForId(names),
634 insertMarker: insertMarker,
635 insertRules: insertRules,
636 removeRules: removeRules,
637 sealed: false,
638 styleTag: el,
639 toElement: wrapAsElement(css, names),
640 toHTML: wrapAsHtmlTag(css, names)
641 };
642};
643
644var makeTextNode = function makeTextNode(id) {
645 return document.createTextNode(makeTextMarker(id));
646};
647
648var makeBrowserTag = function makeBrowserTag(el, getImportRuleTag) {
649 var names = Object.create(null);
650 var markers = Object.create(null);
651
652 var extractImport = getImportRuleTag !== undefined;
653
654 /* indicates whther getImportRuleTag was called */
655 var usedImportRuleTag = false;
656
657 var insertMarker = function insertMarker(id) {
658 var prev = markers[id];
659 if (prev !== undefined) {
660 return prev;
661 }
662
663 markers[id] = makeTextNode(id);
664 el.appendChild(markers[id]);
665 names[id] = Object.create(null);
666
667 return markers[id];
668 };
669
670 var insertRules = function insertRules(id, cssRules, name) {
671 var marker = insertMarker(id);
672 var importRules = [];
673 var cssRulesSize = cssRules.length;
674
675 for (var i = 0; i < cssRulesSize; i += 1) {
676 var rule = cssRules[i];
677 var mayHaveImport = extractImport;
678 if (mayHaveImport && rule.indexOf('@import') !== -1) {
679 importRules.push(rule);
680 } else {
681 mayHaveImport = false;
682 var separator = i === cssRulesSize - 1 ? '' : ' ';
683 marker.appendData('' + rule + separator);
684 }
685 }
686
687 addNameForId(names, id, name);
688
689 if (extractImport && importRules.length > 0) {
690 usedImportRuleTag = true;
691 // $FlowFixMe
692 getImportRuleTag().insertRules(id + '-import', importRules);
693 }
694 };
695
696 var removeRules = function removeRules(id) {
697 var marker = markers[id];
698 if (marker === undefined) return;
699
700 /* create new empty text node and replace the current one */
701 var newMarker = makeTextNode(id);
702 el.replaceChild(newMarker, marker);
703 markers[id] = newMarker;
704 resetIdNames(names, id);
705
706 if (extractImport && usedImportRuleTag) {
707 // $FlowFixMe
708 getImportRuleTag().removeRules(id + '-import');
709 }
710 };
711
712 var css = function css() {
713 var str = '';
714
715 // eslint-disable-next-line guard-for-in
716 for (var id in markers) {
717 str += markers[id].data;
718 }
719
720 return str;
721 };
722
723 return {
724 clone: function clone() {
725 throw new StyledComponentsError(5);
726 },
727
728 css: css,
729 getIds: getIdsFromMarkersFactory(markers),
730 hasNameForId: hasNameForId(names),
731 insertMarker: insertMarker,
732 insertRules: insertRules,
733 removeRules: removeRules,
734 sealed: false,
735 styleTag: el,
736 toElement: wrapAsElement(css, names),
737 toHTML: wrapAsHtmlTag(css, names)
738 };
739};
740
741var makeServerTag = function makeServerTag(namesArg, markersArg) {
742 var names = namesArg === undefined ? Object.create(null) : namesArg;
743 var markers = markersArg === undefined ? Object.create(null) : markersArg;
744
745 var insertMarker = function insertMarker(id) {
746 var prev = markers[id];
747 if (prev !== undefined) {
748 return prev;
749 }
750
751 return markers[id] = [''];
752 };
753
754 var insertRules = function insertRules(id, cssRules, name) {
755 var marker = insertMarker(id);
756 marker[0] += cssRules.join(' ');
757 addNameForId(names, id, name);
758 };
759
760 var removeRules = function removeRules(id) {
761 var marker = markers[id];
762 if (marker === undefined) return;
763 marker[0] = '';
764 resetIdNames(names, id);
765 };
766
767 var css = function css() {
768 var str = '';
769 // eslint-disable-next-line guard-for-in
770 for (var id in markers) {
771 var cssForId = markers[id][0];
772 if (cssForId) {
773 str += makeTextMarker(id) + cssForId;
774 }
775 }
776 return str;
777 };
778
779 var clone = function clone() {
780 var namesClone = cloneNames(names);
781 var markersClone = Object.create(null);
782
783 // eslint-disable-next-line guard-for-in
784 for (var id in markers) {
785 markersClone[id] = [markers[id][0]];
786 }
787
788 return makeServerTag(namesClone, markersClone);
789 };
790
791 var tag = {
792 clone: clone,
793 css: css,
794 getIds: getIdsFromMarkersFactory(markers),
795 hasNameForId: hasNameForId(names),
796 insertMarker: insertMarker,
797 insertRules: insertRules,
798 removeRules: removeRules,
799 sealed: false,
800 styleTag: null,
801 toElement: wrapAsElement(css, names),
802 toHTML: wrapAsHtmlTag(css, names)
803 };
804
805 return tag;
806};
807
808var makeTag = function makeTag(target, tagEl, forceServer, insertBefore, getImportRuleTag) {
809 if (IS_BROWSER && !forceServer) {
810 var el = makeStyleTag(target, tagEl, insertBefore);
811
812 if (DISABLE_SPEEDY) {
813 return makeBrowserTag(el, getImportRuleTag);
814 } else {
815 return makeSpeedyTag(el, getImportRuleTag);
816 }
817 }
818
819 return makeServerTag();
820};
821
822/* wraps a given tag so that rehydration is performed once when necessary */
823var makeRehydrationTag = function makeRehydrationTag(tag, els, extracted, immediateRehydration) {
824 /* rehydration function that adds all rules to the new tag */
825 var rehydrate = once(function () {
826 /* add all extracted components to the new tag */
827 for (var i = 0, len = extracted.length; i < len; i += 1) {
828 var _extracted$i = extracted[i],
829 componentId = _extracted$i.componentId,
830 cssFromDOM = _extracted$i.cssFromDOM;
831
832 var cssRules = splitByRules(cssFromDOM);
833 tag.insertRules(componentId, cssRules);
834 }
835
836 /* remove old HTMLStyleElements, since they have been rehydrated */
837 for (var _i = 0, _len = els.length; _i < _len; _i += 1) {
838 var el = els[_i];
839 if (el.parentNode) {
840 el.parentNode.removeChild(el);
841 }
842 }
843 });
844
845 if (immediateRehydration) rehydrate();
846
847 return _extends({}, tag, {
848
849 /* add rehydration hook to methods */
850 insertMarker: function insertMarker(id) {
851 rehydrate();
852 return tag.insertMarker(id);
853 },
854
855 insertRules: function insertRules(id, cssRules, name) {
856 rehydrate();
857 return tag.insertRules(id, cssRules, name);
858 },
859
860 removeRules: function removeRules(id) {
861 rehydrate();
862 return tag.removeRules(id);
863 }
864 });
865};
866
867//
868
869var SPLIT_REGEX = /\s+/;
870
871/* determine the maximum number of components before tags are sharded */
872var MAX_SIZE = void 0;
873if (IS_BROWSER) {
874 /* in speedy mode we can keep a lot more rules in a sheet before a slowdown can be expected */
875 MAX_SIZE = DISABLE_SPEEDY ? 40 : 1000;
876} else {
877 /* for servers we do not need to shard at all */
878 MAX_SIZE = -1;
879}
880
881var sheetRunningId = 0;
882var master = void 0;
883
884var StyleSheet = function () {
885
886 /* a map from ids to tags */
887
888 /* deferred rules for a given id */
889
890 /* this is used for not reinjecting rules via hasNameForId() */
891
892 /* when rules for an id are removed using remove() we have to ignore rehydratedNames for it */
893
894 /* a list of tags belonging to this StyleSheet */
895
896 /* a tag for import rules */
897
898 /* current capacity until a new tag must be created */
899
900 /* children (aka clones) of this StyleSheet inheriting all and future injections */
901
902 function StyleSheet() {
903 var _this = this;
904
905 var target = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : IS_BROWSER ? document.head : null;
906 var forceServer = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
907 classCallCheck(this, StyleSheet);
908
909 this.getImportRuleTag = function () {
910 var importRuleTag = _this.importRuleTag;
911
912 if (importRuleTag !== undefined) {
913 return importRuleTag;
914 }
915
916 var firstTag = _this.tags[0];
917 var insertBefore = true;
918
919 return _this.importRuleTag = makeTag(_this.target, firstTag ? firstTag.styleTag : null, _this.forceServer, insertBefore);
920 };
921
922 sheetRunningId += 1;
923 this.id = sheetRunningId;
924 this.forceServer = forceServer;
925 this.target = forceServer ? null : target;
926 this.tagMap = {};
927 this.deferred = {};
928 this.rehydratedNames = {};
929 this.ignoreRehydratedNames = {};
930 this.tags = [];
931 this.capacity = 1;
932 this.clones = [];
933 }
934
935 /* rehydrate all SSR'd style tags */
936
937
938 StyleSheet.prototype.rehydrate = function rehydrate() {
939 if (!IS_BROWSER || this.forceServer) {
940 return this;
941 }
942 var els = [];
943 var extracted = [];
944 var isStreamed = false;
945
946 /* retrieve all of our SSR style elements from the DOM */
947 var nodes = document.querySelectorAll('style[' + SC_ATTR + '][' + SC_VERSION_ATTR + '="' + "4.0.1" + '"]');
948 var nodesSize = nodes.length;
949
950 /* abort rehydration if no previous style tags were found */
951 if (nodesSize === 0) {
952 return this;
953 }
954
955 for (var i = 0; i < nodesSize; i += 1) {
956 // $FlowFixMe: We can trust that all elements in this query are style elements
957 var el = nodes[i];
958
959 /* check if style tag is a streamed tag */
960 if (!isStreamed) isStreamed = !!el.getAttribute(SC_STREAM_ATTR);
961
962 /* retrieve all component names */
963 var elNames = (el.getAttribute(SC_ATTR) || '').trim().split(SPLIT_REGEX);
964 var elNamesSize = elNames.length;
965 for (var j = 0; j < elNamesSize; j += 1) {
966 var name = elNames[j];
967 /* add rehydrated name to sheet to avoid readding styles */
968 this.rehydratedNames[name] = true;
969 }
970
971 /* extract all components and their CSS */
972 extracted.push.apply(extracted, extractComps(el.textContent));
973
974 /* store original HTMLStyleElement */
975 els.push(el);
976 }
977
978 /* abort rehydration if nothing was extracted */
979 var extractedSize = extracted.length;
980 if (extractedSize === 0) {
981 return this;
982 }
983
984 /* create a tag to be used for rehydration */
985 var tag = this.makeTag(null);
986 var rehydrationTag = makeRehydrationTag(tag, els, extracted, isStreamed);
987
988 /* reset capacity and adjust MAX_SIZE by the initial size of the rehydration */
989 this.capacity = Math.max(1, MAX_SIZE - extractedSize);
990 this.tags.push(rehydrationTag);
991
992 /* retrieve all component ids */
993 for (var _j = 0; _j < extractedSize; _j += 1) {
994 this.tagMap[extracted[_j].componentId] = rehydrationTag;
995 }
996
997 return this;
998 };
999
1000 /* retrieve a "master" instance of StyleSheet which is typically used when no other is available
1001 * The master StyleSheet is targeted by createGlobalStyle, keyframes, and components outside of any
1002 * StyleSheetManager's context */
1003
1004
1005 /* reset the internal "master" instance */
1006 StyleSheet.reset = function reset() {
1007 var forceServer = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
1008
1009 master = new StyleSheet(undefined, forceServer).rehydrate();
1010 };
1011
1012 /* adds "children" to the StyleSheet that inherit all of the parents' rules
1013 * while their own rules do not affect the parent */
1014
1015
1016 StyleSheet.prototype.clone = function clone() {
1017 var sheet = new StyleSheet(this.target, this.forceServer);
1018
1019 /* add to clone array */
1020 this.clones.push(sheet);
1021
1022 /* clone all tags */
1023 sheet.tags = this.tags.map(function (tag) {
1024 var ids = tag.getIds();
1025 var newTag = tag.clone();
1026
1027 /* reconstruct tagMap */
1028 for (var i = 0; i < ids.length; i += 1) {
1029 sheet.tagMap[ids[i]] = newTag;
1030 }
1031
1032 return newTag;
1033 });
1034
1035 /* clone other maps */
1036 sheet.rehydratedNames = _extends({}, this.rehydratedNames);
1037 sheet.deferred = _extends({}, this.deferred);
1038
1039 return sheet;
1040 };
1041
1042 /* force StyleSheet to create a new tag on the next injection */
1043
1044
1045 StyleSheet.prototype.sealAllTags = function sealAllTags() {
1046 this.capacity = 1;
1047
1048 this.tags.forEach(function (tag) {
1049 // eslint-disable-next-line no-param-reassign
1050 tag.sealed = true;
1051 });
1052 };
1053
1054 StyleSheet.prototype.makeTag = function makeTag$$1(tag) {
1055 var lastEl = tag ? tag.styleTag : null;
1056 var insertBefore = false;
1057
1058 return makeTag(this.target, lastEl, this.forceServer, insertBefore, this.getImportRuleTag);
1059 };
1060
1061 /* get a tag for a given componentId, assign the componentId to one, or shard */
1062 StyleSheet.prototype.getTagForId = function getTagForId(id) {
1063 /* simply return a tag, when the componentId was already assigned one */
1064 var prev = this.tagMap[id];
1065 if (prev !== undefined && !prev.sealed) {
1066 return prev;
1067 }
1068
1069 var tag = this.tags[this.tags.length - 1];
1070
1071 /* shard (create a new tag) if the tag is exhausted (See MAX_SIZE) */
1072 this.capacity -= 1;
1073
1074 if (this.capacity === 0) {
1075 this.capacity = MAX_SIZE;
1076 tag = this.makeTag(tag);
1077 this.tags.push(tag);
1078 }
1079
1080 return this.tagMap[id] = tag;
1081 };
1082
1083 /* mainly for createGlobalStyle to check for its id */
1084
1085
1086 StyleSheet.prototype.hasId = function hasId(id) {
1087 return this.tagMap[id] !== undefined;
1088 };
1089
1090 /* caching layer checking id+name to already have a corresponding tag and injected rules */
1091
1092
1093 StyleSheet.prototype.hasNameForId = function hasNameForId(id, name) {
1094 /* exception for rehydrated names which are checked separately */
1095 if (this.ignoreRehydratedNames[id] === undefined && this.rehydratedNames[name]) {
1096 return true;
1097 }
1098
1099 var tag = this.tagMap[id];
1100 return tag !== undefined && tag.hasNameForId(id, name);
1101 };
1102
1103 /* registers a componentId and registers it on its tag */
1104
1105
1106 StyleSheet.prototype.deferredInject = function deferredInject(id, cssRules) {
1107 /* don't inject when the id is already registered */
1108 if (this.tagMap[id] !== undefined) return;
1109
1110 var clones = this.clones;
1111
1112 for (var i = 0; i < clones.length; i += 1) {
1113 clones[i].deferredInject(id, cssRules);
1114 }
1115
1116 this.getTagForId(id).insertMarker(id);
1117 this.deferred[id] = cssRules;
1118 };
1119
1120 /* injects rules for a given id with a name that will need to be cached */
1121
1122
1123 StyleSheet.prototype.inject = function inject(id, cssRules, name) {
1124 var clones = this.clones;
1125
1126
1127 for (var i = 0; i < clones.length; i += 1) {
1128 clones[i].inject(id, cssRules, name);
1129 }
1130
1131 var tag = this.getTagForId(id);
1132
1133 /* add deferred rules for component */
1134 if (this.deferred[id] !== undefined) {
1135 // Combine passed cssRules with previously deferred CSS rules
1136 // NOTE: We cannot mutate the deferred array itself as all clones
1137 // do the same (see clones[i].inject)
1138 var rules = this.deferred[id].concat(cssRules);
1139 tag.insertRules(id, rules, name);
1140
1141 this.deferred[id] = undefined;
1142 } else {
1143 tag.insertRules(id, cssRules, name);
1144 }
1145 };
1146
1147 /* removes all rules for a given id, which doesn't remove its marker but resets it */
1148
1149
1150 StyleSheet.prototype.remove = function remove(id) {
1151 var tag = this.tagMap[id];
1152 if (tag === undefined) return;
1153
1154 var clones = this.clones;
1155
1156 for (var i = 0; i < clones.length; i += 1) {
1157 clones[i].remove(id);
1158 }
1159
1160 /* remove all rules from the tag */
1161 tag.removeRules(id);
1162
1163 /* ignore possible rehydrated names */
1164 this.ignoreRehydratedNames[id] = true;
1165
1166 /* delete possible deferred rules */
1167 this.deferred[id] = undefined;
1168 };
1169
1170 StyleSheet.prototype.toHTML = function toHTML() {
1171 return this.tags.map(function (tag) {
1172 return tag.toHTML();
1173 }).join('');
1174 };
1175
1176 StyleSheet.prototype.toReactElements = function toReactElements() {
1177 var id = this.id;
1178
1179
1180 return this.tags.map(function (tag, i) {
1181 var key = 'sc-' + id + '-' + i;
1182 return cloneElement(tag.toElement(), { key: key });
1183 });
1184 };
1185
1186 createClass(StyleSheet, null, [{
1187 key: 'master',
1188 get: function get$$1() {
1189 return master || (master = new StyleSheet().rehydrate());
1190 }
1191
1192 /* NOTE: This is just for backwards-compatibility with jest-styled-components */
1193
1194 }, {
1195 key: 'instance',
1196 get: function get$$1() {
1197 return StyleSheet.master;
1198 }
1199 }]);
1200 return StyleSheet;
1201}();
1202
1203//
1204
1205var Keyframes = function () {
1206 function Keyframes(name, rules) {
1207 var _this = this;
1208
1209 classCallCheck(this, Keyframes);
1210
1211 this.inject = function (styleSheet) {
1212 if (!styleSheet.hasNameForId(_this.id, _this.name)) {
1213 styleSheet.inject(_this.id, _this.rules, _this.name);
1214 }
1215 };
1216
1217 this.toString = function () {
1218 throw new StyledComponentsError(12, String(_this.name));
1219 };
1220
1221 this.name = name;
1222 this.rules = rules;
1223
1224 this.id = 'sc-keyframes-' + name;
1225 }
1226
1227 Keyframes.prototype.getName = function getName() {
1228 return this.name;
1229 };
1230
1231 return Keyframes;
1232}();
1233
1234//
1235
1236/**
1237 * inlined version of
1238 * https://github.com/facebook/fbjs/blob/master/packages/fbjs/src/core/hyphenateStyleName.js
1239 */
1240
1241var uppercasePattern = /([A-Z])/g;
1242var msPattern = /^ms-/;
1243
1244/**
1245 * Hyphenates a camelcased CSS property name, for example:
1246 *
1247 * > hyphenateStyleName('backgroundColor')
1248 * < "background-color"
1249 * > hyphenateStyleName('MozTransition')
1250 * < "-moz-transition"
1251 * > hyphenateStyleName('msTransition')
1252 * < "-ms-transition"
1253 *
1254 * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
1255 * is converted to `-ms-`.
1256 *
1257 * @param {string} string
1258 * @return {string}
1259 */
1260function hyphenateStyleName(string) {
1261 return string.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern, '-ms-');
1262}
1263
1264//
1265
1266var objToCss = function objToCss(obj, prevKey) {
1267 var css = Object.keys(obj).filter(function (key) {
1268 var chunk = obj[key];
1269 return chunk !== undefined && chunk !== null && chunk !== false && chunk !== '';
1270 }).map(function (key) {
1271 if (isPlainObject(obj[key])) return objToCss(obj[key], key);
1272 return hyphenateStyleName(key) + ': ' + obj[key] + ';';
1273 }).join(' ');
1274 return prevKey ? prevKey + ' {\n ' + css + '\n}' : css;
1275};
1276
1277/**
1278 * It's falsish not falsy because 0 is allowed.
1279 */
1280var isFalsish = function isFalsish(chunk) {
1281 return chunk === undefined || chunk === null || chunk === false || chunk === '';
1282};
1283
1284function flatten(chunk, executionContext, styleSheet) {
1285 if (Array.isArray(chunk)) {
1286 var ruleSet = [];
1287
1288 for (var i = 0, len = chunk.length, result; i < len; i += 1) {
1289 result = flatten(chunk[i], executionContext, styleSheet);
1290
1291 if (result === null) continue;else if (Array.isArray(result)) ruleSet.push.apply(ruleSet, result);else ruleSet.push(result);
1292 }
1293
1294 return ruleSet;
1295 }
1296
1297 if (isFalsish(chunk)) {
1298 return null;
1299 }
1300
1301 /* Handle other components */
1302 if (isStyledComponent(chunk)) {
1303 return '.' + chunk.styledComponentId;
1304 }
1305
1306 /* Either execute or defer the function */
1307 if (isFunction(chunk)) {
1308 if (executionContext) {
1309 if (process.env.NODE_ENV !== 'production') {
1310 /* Warn if not referring styled component */
1311 try {
1312 // eslint-disable-next-line new-cap
1313 if (isElement(new chunk(executionContext))) {
1314 console.warn(getComponentName(chunk) + ' is not a styled component and cannot be referred to via component selector. See https://www.styled-components.com/docs/advanced#referring-to-other-components for more details.');
1315 }
1316 // eslint-disable-next-line no-empty
1317 } catch (e) {}
1318 }
1319
1320 return flatten(chunk(executionContext), executionContext, styleSheet);
1321 } else return chunk;
1322 }
1323
1324 if (chunk instanceof Keyframes) {
1325 if (styleSheet) {
1326 chunk.inject(styleSheet);
1327 return chunk.getName();
1328 } else return chunk;
1329 }
1330
1331 /* Handle objects */
1332 return isPlainObject(chunk) ? objToCss(chunk) : chunk.toString();
1333}
1334
1335//
1336
1337function css(styles) {
1338 for (var _len = arguments.length, interpolations = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
1339 interpolations[_key - 1] = arguments[_key];
1340 }
1341
1342 if (isFunction(styles) || isPlainObject(styles)) {
1343 // $FlowFixMe
1344 return flatten(interleave(EMPTY_ARRAY, [styles].concat(interpolations)));
1345 }
1346
1347 // $FlowFixMe
1348 return flatten(interleave(styles, interpolations));
1349}
1350
1351//
1352
1353function constructWithOptions(componentConstructor, tag) {
1354 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : EMPTY_OBJECT;
1355
1356 if (!isValidElementType(tag)) {
1357 throw new StyledComponentsError(1, String(tag));
1358 }
1359
1360 /* This is callable directly as a template function */
1361 // $FlowFixMe: Not typed to avoid destructuring arguments
1362 var templateFunction = function templateFunction() {
1363 return componentConstructor(tag, options, css.apply(undefined, arguments));
1364 };
1365
1366 /* If config methods are called, wrap up a new template function and merge options */
1367 templateFunction.withConfig = function (config) {
1368 return constructWithOptions(componentConstructor, tag, _extends({}, options, config));
1369 };
1370 templateFunction.attrs = function (attrs) {
1371 return constructWithOptions(componentConstructor, tag, _extends({}, options, {
1372 attrs: _extends({}, options.attrs || EMPTY_OBJECT, attrs)
1373 }));
1374 };
1375
1376 return templateFunction;
1377}
1378
1379//
1380// Source: https://github.com/garycourt/murmurhash-js/blob/master/murmurhash2_gc.js
1381function murmurhash(c) {
1382 for (var e = c.length | 0, a = e | 0, d = 0, b; e >= 4;) {
1383 b = c.charCodeAt(d) & 255 | (c.charCodeAt(++d) & 255) << 8 | (c.charCodeAt(++d) & 255) << 16 | (c.charCodeAt(++d) & 255) << 24, b = 1540483477 * (b & 65535) + ((1540483477 * (b >>> 16) & 65535) << 16), b ^= b >>> 24, b = 1540483477 * (b & 65535) + ((1540483477 * (b >>> 16) & 65535) << 16), a = 1540483477 * (a & 65535) + ((1540483477 * (a >>> 16) & 65535) << 16) ^ b, e -= 4, ++d;
1384 }
1385 switch (e) {
1386 case 3:
1387 a ^= (c.charCodeAt(d + 2) & 255) << 16;
1388 case 2:
1389 a ^= (c.charCodeAt(d + 1) & 255) << 8;
1390 case 1:
1391 a ^= c.charCodeAt(d) & 255, a = 1540483477 * (a & 65535) + ((1540483477 * (a >>> 16) & 65535) << 16);
1392 }
1393 a ^= a >>> 13;
1394 a = 1540483477 * (a & 65535) + ((1540483477 * (a >>> 16) & 65535) << 16);
1395 return (a ^ a >>> 15) >>> 0;
1396}
1397
1398//
1399/* eslint-disable no-bitwise */
1400
1401/* This is the "capacity" of our alphabet i.e. 2x26 for all letters plus their capitalised
1402 * counterparts */
1403var charsLength = 52;
1404
1405/* start at 75 for 'a' until 'z' (25) and then start at 65 for capitalised letters */
1406var getAlphabeticChar = function getAlphabeticChar(code) {
1407 return String.fromCharCode(code + (code > 25 ? 39 : 97));
1408};
1409
1410/* input a number, usually a hash and convert it to base-52 */
1411function generateAlphabeticName(code) {
1412 var name = '';
1413 var x = void 0;
1414
1415 /* get a char and divide by alphabet-length */
1416 for (x = code; x > charsLength; x = Math.floor(x / charsLength)) {
1417 name = getAlphabeticChar(x % charsLength) + name;
1418 }
1419
1420 return getAlphabeticChar(x % charsLength) + name;
1421}
1422
1423//
1424
1425function isStaticRules(rules, attrs) {
1426 for (var i = 0; i < rules.length; i += 1) {
1427 var rule = rules[i];
1428
1429 // recursive case
1430 if (Array.isArray(rule) && !isStaticRules(rule)) {
1431 return false;
1432 } else if (isFunction(rule) && !isStyledComponent(rule)) {
1433 // functions are allowed to be static if they're just being
1434 // used to get the classname of a nested styled component
1435 return false;
1436 }
1437 }
1438
1439 if (attrs !== undefined) {
1440 // eslint-disable-next-line guard-for-in, no-restricted-syntax
1441 for (var key in attrs) {
1442 var value = attrs[key];
1443 if (isFunction(value)) {
1444 return false;
1445 }
1446 }
1447 }
1448
1449 return true;
1450}
1451
1452//
1453
1454//
1455
1456var isHMREnabled = process.env.NODE_ENV !== 'production' && typeof module !== 'undefined' && module.hot;
1457
1458/* combines hashStr (murmurhash) and nameGenerator for convenience */
1459var hasher = function hasher(str) {
1460 return generateAlphabeticName(murmurhash(str));
1461};
1462
1463/*
1464 ComponentStyle is all the CSS-specific stuff, not
1465 the React-specific stuff.
1466 */
1467
1468var ComponentStyle = function () {
1469 function ComponentStyle(rules, attrs, componentId) {
1470 classCallCheck(this, ComponentStyle);
1471
1472 this.rules = rules;
1473 this.isStatic = !isHMREnabled && isStaticRules(rules, attrs);
1474 this.componentId = componentId;
1475
1476 if (!StyleSheet.master.hasId(componentId)) {
1477 var placeholder = process.env.NODE_ENV !== 'production' ? ['.' + componentId + ' {}'] : [];
1478
1479 StyleSheet.master.deferredInject(componentId, placeholder);
1480 }
1481 }
1482
1483 /*
1484 * Flattens a rule set into valid CSS
1485 * Hashes it, wraps the whole chunk in a .hash1234 {}
1486 * Returns the hash to be injected on render()
1487 * */
1488
1489
1490 ComponentStyle.prototype.generateAndInjectStyles = function generateAndInjectStyles(executionContext, styleSheet) {
1491 var isStatic = this.isStatic,
1492 componentId = this.componentId,
1493 lastClassName = this.lastClassName;
1494
1495 if (IS_BROWSER && isStatic && lastClassName !== undefined && styleSheet.hasNameForId(componentId, lastClassName)) {
1496 return lastClassName;
1497 }
1498
1499 var flatCSS = flatten(this.rules, executionContext, styleSheet);
1500 var name = hasher(this.componentId + flatCSS.join(''));
1501 if (!styleSheet.hasNameForId(componentId, name)) {
1502 styleSheet.inject(this.componentId, stringifyRules(flatCSS, '.' + name, undefined, componentId), name);
1503 }
1504
1505 this.lastClassName = name;
1506 return name;
1507 };
1508
1509 ComponentStyle.generateName = function generateName(str) {
1510 return hasher(str);
1511 };
1512
1513 return ComponentStyle;
1514}();
1515
1516//
1517
1518var LIMIT = 200;
1519
1520var createWarnTooManyClasses = (function (displayName) {
1521 var generatedClasses = {};
1522 var warningSeen = false;
1523
1524 return function (className) {
1525 if (!warningSeen) {
1526 generatedClasses[className] = true;
1527 if (Object.keys(generatedClasses).length >= LIMIT) {
1528 // Unable to find latestRule in test environment.
1529 /* eslint-disable no-console, prefer-template */
1530 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 />');
1531 warningSeen = true;
1532 generatedClasses = {};
1533 }
1534 }
1535 };
1536});
1537
1538//
1539
1540var determineTheme = (function (props, fallbackTheme) {
1541 var defaultProps = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : EMPTY_OBJECT;
1542
1543 // Props should take precedence over ThemeProvider, which should take precedence over
1544 // defaultProps, but React automatically puts defaultProps on props.
1545
1546 /* eslint-disable react/prop-types, flowtype-errors/show-errors */
1547 var isDefaultTheme = defaultProps ? props.theme === defaultProps.theme : false;
1548 var theme = props.theme && !isDefaultTheme ? props.theme : fallbackTheme || defaultProps.theme;
1549 /* eslint-enable */
1550
1551 return theme;
1552});
1553
1554//
1555var escapeRegex = /[[\].#*$><+~=|^:(),"'`-]+/g;
1556var dashesAtEnds = /(^-|-$)/g;
1557
1558/**
1559 * TODO: Explore using CSS.escape when it becomes more available
1560 * in evergreen browsers.
1561 */
1562function escape(str) {
1563 return str
1564 // Replace all possible CSS selectors
1565 .replace(escapeRegex, '-')
1566
1567 // Remove extraneous hyphens at the start and end
1568 .replace(dashesAtEnds, '');
1569}
1570
1571//
1572
1573function isTag(target) /* : %checks */{
1574 return typeof target === 'string';
1575}
1576
1577//
1578
1579function generateDisplayName(target) {
1580 return isTag(target) ? 'styled.' + target : 'Styled(' + getComponentName(target) + ')';
1581}
1582
1583var _TYPE_STATICS;
1584
1585var REACT_STATICS = {
1586 childContextTypes: true,
1587 contextTypes: true,
1588 defaultProps: true,
1589 displayName: true,
1590 getDerivedStateFromProps: true,
1591 propTypes: true,
1592 type: true
1593};
1594
1595var KNOWN_STATICS = {
1596 name: true,
1597 length: true,
1598 prototype: true,
1599 caller: true,
1600 callee: true,
1601 arguments: true,
1602 arity: true
1603};
1604
1605var TYPE_STATICS = (_TYPE_STATICS = {}, _TYPE_STATICS[ForwardRef] = {
1606 $$typeof: true,
1607 render: true
1608}, _TYPE_STATICS);
1609
1610var defineProperty$1 = Object.defineProperty,
1611 getOwnPropertyNames = Object.getOwnPropertyNames,
1612 _Object$getOwnPropert = Object.getOwnPropertySymbols,
1613 getOwnPropertySymbols = _Object$getOwnPropert === undefined ? function () {
1614 return [];
1615} : _Object$getOwnPropert,
1616 getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor,
1617 getPrototypeOf = Object.getPrototypeOf,
1618 objectPrototype = Object.prototype;
1619var arrayPrototype = Array.prototype;
1620
1621
1622function hoistNonReactStatics(targetComponent, sourceComponent, blacklist) {
1623 if (typeof sourceComponent !== 'string') {
1624 // don't hoist over string (html) components
1625
1626 var inheritedComponent = getPrototypeOf(sourceComponent);
1627
1628 if (inheritedComponent && inheritedComponent !== objectPrototype) {
1629 hoistNonReactStatics(targetComponent, inheritedComponent, blacklist);
1630 }
1631
1632 var keys = arrayPrototype.concat(getOwnPropertyNames(sourceComponent),
1633 // $FlowFixMe
1634 getOwnPropertySymbols(sourceComponent));
1635
1636 var targetStatics = TYPE_STATICS[targetComponent.$$typeof] || REACT_STATICS;
1637
1638 var sourceStatics = TYPE_STATICS[sourceComponent.$$typeof] || REACT_STATICS;
1639
1640 var i = keys.length;
1641 var descriptor = void 0;
1642 var key = void 0;
1643
1644 // eslint-disable-next-line no-plusplus
1645 while (i--) {
1646 key = keys[i];
1647
1648 if (
1649 // $FlowFixMe
1650 !KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) &&
1651 // $FlowFixMe
1652 !(targetStatics && targetStatics[key])) {
1653 descriptor = getOwnPropertyDescriptor(sourceComponent, key);
1654
1655 if (descriptor) {
1656 try {
1657 // Avoid failures from read-only properties
1658 defineProperty$1(targetComponent, key, descriptor);
1659 } catch (e) {
1660 /* fail silently */
1661 }
1662 }
1663 }
1664 }
1665
1666 return targetComponent;
1667 }
1668
1669 return targetComponent;
1670}
1671
1672//
1673function isDerivedReactComponent(fn) {
1674 return !!(fn && fn.prototype && fn.prototype.isReactComponent);
1675}
1676
1677//
1678
1679var ThemeContext = createContext();
1680
1681var ThemeConsumer = ThemeContext.Consumer;
1682
1683/**
1684 * Provide a theme to an entire react component tree via context
1685 */
1686
1687var ThemeProvider = function (_Component) {
1688 inherits(ThemeProvider, _Component);
1689
1690 function ThemeProvider(props) {
1691 classCallCheck(this, ThemeProvider);
1692
1693 var _this = possibleConstructorReturn(this, _Component.call(this, props));
1694
1695 _this.getContext = memoize(_this.getContext.bind(_this));
1696 _this.renderInner = _this.renderInner.bind(_this);
1697 return _this;
1698 }
1699
1700 ThemeProvider.prototype.render = function render() {
1701 if (!this.props.children) return null;
1702
1703 return React.createElement(
1704 ThemeContext.Consumer,
1705 null,
1706 this.renderInner
1707 );
1708 };
1709
1710 ThemeProvider.prototype.renderInner = function renderInner(outerTheme) {
1711 var context = this.getContext(this.props.theme, outerTheme);
1712
1713 return React.createElement(
1714 ThemeContext.Provider,
1715 { value: context },
1716 React.Children.only(this.props.children)
1717 );
1718 };
1719
1720 /**
1721 * Get the theme from the props, supporting both (outerTheme) => {}
1722 * as well as object notation
1723 */
1724
1725
1726 ThemeProvider.prototype.getTheme = function getTheme(theme, outerTheme) {
1727 if (isFunction(theme)) {
1728 var mergedTheme = theme(outerTheme);
1729
1730 if (process.env.NODE_ENV !== 'production' && (mergedTheme === null || Array.isArray(mergedTheme) || (typeof mergedTheme === 'undefined' ? 'undefined' : _typeof(mergedTheme)) !== 'object')) {
1731 throw new StyledComponentsError(7);
1732 }
1733
1734 return mergedTheme;
1735 }
1736
1737 if (theme === null || Array.isArray(theme) || (typeof theme === 'undefined' ? 'undefined' : _typeof(theme)) !== 'object') {
1738 throw new StyledComponentsError(8);
1739 }
1740
1741 return _extends({}, outerTheme, theme);
1742 };
1743
1744 ThemeProvider.prototype.getContext = function getContext(theme, outerTheme) {
1745 return this.getTheme(theme, outerTheme);
1746 };
1747
1748 return ThemeProvider;
1749}(Component);
1750
1751//
1752
1753var ServerStyleSheet = function () {
1754 function ServerStyleSheet() {
1755 classCallCheck(this, ServerStyleSheet);
1756
1757 /* The master sheet might be reset, so keep a reference here */
1758 this.masterSheet = StyleSheet.master;
1759 this.instance = this.masterSheet.clone();
1760 this.sealed = false;
1761 }
1762
1763 /**
1764 * Mark the ServerStyleSheet as being fully emitted and manually GC it from the
1765 * StyleSheet singleton.
1766 */
1767
1768
1769 ServerStyleSheet.prototype.seal = function seal() {
1770 if (!this.sealed) {
1771 /* Remove sealed StyleSheets from the master sheet */
1772 var index = this.masterSheet.clones.indexOf(this.instance);
1773 this.masterSheet.clones.splice(index, 1);
1774 this.sealed = true;
1775 }
1776 };
1777
1778 ServerStyleSheet.prototype.collectStyles = function collectStyles(children) {
1779 if (this.sealed) {
1780 throw new StyledComponentsError(2);
1781 }
1782
1783 return React.createElement(
1784 StyleSheetManager,
1785 { sheet: this.instance },
1786 children
1787 );
1788 };
1789
1790 ServerStyleSheet.prototype.getStyleTags = function getStyleTags() {
1791 this.seal();
1792 return this.instance.toHTML();
1793 };
1794
1795 ServerStyleSheet.prototype.getStyleElement = function getStyleElement() {
1796 this.seal();
1797 return this.instance.toReactElements();
1798 };
1799
1800 ServerStyleSheet.prototype.interleaveWithNodeStream = function interleaveWithNodeStream(readableStream) {
1801 var _this = this;
1802
1803 {
1804 throw new StyledComponentsError(3);
1805 }
1806
1807 /* the tag index keeps track of which tags have already been emitted */
1808 var instance = this.instance;
1809
1810 var instanceTagIndex = 0;
1811
1812 var streamAttr = SC_STREAM_ATTR + '="true"';
1813
1814 var transformer = new stream.Transform({
1815 transform: function appendStyleChunks(chunk, /* encoding */_, callback) {
1816 var tags = instance.tags;
1817
1818 var html = '';
1819
1820 /* retrieve html for each new style tag */
1821 for (; instanceTagIndex < tags.length; instanceTagIndex += 1) {
1822 var tag = tags[instanceTagIndex];
1823 html += tag.toHTML(streamAttr);
1824 }
1825
1826 /* force our StyleSheets to emit entirely new tags */
1827 instance.sealAllTags();
1828
1829 /* prepend style html to chunk */
1830 this.push(html + chunk);
1831 callback();
1832 }
1833 });
1834
1835 readableStream.on('end', function () {
1836 return _this.seal();
1837 });
1838 readableStream.on('error', function (err) {
1839 _this.seal();
1840
1841 // forward the error to the transform stream
1842 transformer.emit('error', err);
1843 });
1844
1845 return readableStream.pipe(transformer);
1846 };
1847
1848 return ServerStyleSheet;
1849}();
1850
1851//
1852
1853var StyleSheetContext = createContext();
1854
1855var StyleSheetConsumer = StyleSheetContext.Consumer;
1856
1857var StyleSheetManager = function (_Component) {
1858 inherits(StyleSheetManager, _Component);
1859
1860 function StyleSheetManager(props) {
1861 classCallCheck(this, StyleSheetManager);
1862
1863 var _this = possibleConstructorReturn(this, _Component.call(this, props));
1864
1865 _this.getContext = memoize(_this.getContext);
1866 return _this;
1867 }
1868
1869 StyleSheetManager.prototype.getContext = function getContext(sheet, target) {
1870 if (sheet) {
1871 return sheet;
1872 } else if (target) {
1873 return new StyleSheet(target);
1874 } else {
1875 throw new StyledComponentsError(4);
1876 }
1877 };
1878
1879 StyleSheetManager.prototype.render = function render() {
1880 var _props = this.props,
1881 children = _props.children,
1882 sheet = _props.sheet,
1883 target = _props.target;
1884
1885 var context = this.getContext(sheet, target);
1886 return React.createElement(
1887 StyleSheetContext.Provider,
1888 { value: context },
1889 React.Children.only(children)
1890 );
1891 };
1892
1893 return StyleSheetManager;
1894}(Component);
1895process.env.NODE_ENV !== "production" ? StyleSheetManager.propTypes = {
1896 sheet: PropTypes.oneOfType([PropTypes.instanceOf(StyleSheet), PropTypes.instanceOf(ServerStyleSheet)]),
1897
1898 target: PropTypes.shape({
1899 appendChild: PropTypes.func.isRequired
1900 })
1901} : void 0;
1902
1903//
1904
1905var classNameUseCheckInjector = (function (target) {
1906 var elementClassName = '';
1907
1908 var targetCDM = target.componentDidMount;
1909
1910 // eslint-disable-next-line no-param-reassign
1911 target.componentDidMount = function componentDidMount() {
1912 if (typeof targetCDM === 'function') {
1913 targetCDM.call(this);
1914 }
1915
1916 var classNames = elementClassName.replace(/ +/g, ' ').trim().split(' ');
1917 // eslint-disable-next-line react/no-find-dom-node
1918 var node = ReactDOM.findDOMNode(this);
1919 var selector = classNames.map(function (s) {
1920 return '.' + s;
1921 }).join('');
1922
1923 if (node && node.nodeType === 1 && !classNames.every(function (className) {
1924 return node.classList && node.classList.contains(className);
1925 }) && !node.querySelector(selector)) {
1926 console.warn('It looks like you\'ve wrapped styled() around your React component (' + getComponentName(this.props.forwardedClass.target) + '), but the className prop is not being passed down to a child. No styles will be rendered unless className is composed within your React component.');
1927 }
1928 };
1929
1930 var prevRenderInner = target.renderInner;
1931
1932 // eslint-disable-next-line no-param-reassign
1933 target.renderInner = function renderInner() {
1934 for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
1935 args[_key] = arguments[_key];
1936 }
1937
1938 var element = prevRenderInner.apply(this, args);
1939
1940 elementClassName = element.props.className;
1941
1942 return element;
1943 };
1944});
1945
1946//
1947
1948var identifiers = {};
1949
1950/* We depend on components having unique IDs */
1951function generateId(_ComponentStyle, _displayName, parentComponentId) {
1952 var displayName = typeof _displayName !== 'string' ? 'sc' : escape(_displayName);
1953
1954 /**
1955 * This ensures uniqueness if two components happen to share
1956 * the same displayName.
1957 */
1958 var nr = (identifiers[displayName] || 0) + 1;
1959 identifiers[displayName] = nr;
1960
1961 var componentId = displayName + '-' + _ComponentStyle.generateName(displayName + nr);
1962
1963 return parentComponentId ? parentComponentId + '-' + componentId : componentId;
1964}
1965
1966var warnInnerRef = once(function () {
1967 return (
1968 // eslint-disable-next-line no-console
1969 console.warn('The "innerRef" API has been removed in styled-components v4 in favor of React 16 ref forwarding, use "ref" instead like a typical component.')
1970 );
1971});
1972
1973// $FlowFixMe
1974
1975var StyledComponent = function (_Component) {
1976 inherits(StyledComponent, _Component);
1977
1978 function StyledComponent() {
1979 classCallCheck(this, StyledComponent);
1980
1981 var _this = possibleConstructorReturn(this, _Component.call(this));
1982
1983 _this.attrs = {};
1984
1985 _this.renderOuter = _this.renderOuter.bind(_this);
1986 _this.renderInner = _this.renderInner.bind(_this);
1987
1988 if (process.env.NODE_ENV !== 'production' && IS_BROWSER) {
1989 classNameUseCheckInjector(_this);
1990 }
1991 return _this;
1992 }
1993
1994 StyledComponent.prototype.render = function render() {
1995 return React.createElement(
1996 StyleSheetConsumer,
1997 null,
1998 this.renderOuter
1999 );
2000 };
2001
2002 StyledComponent.prototype.renderOuter = function renderOuter(styleSheet) {
2003 this.styleSheet = styleSheet;
2004
2005 return React.createElement(
2006 ThemeConsumer,
2007 null,
2008 this.renderInner
2009 );
2010 };
2011
2012 StyledComponent.prototype.renderInner = function renderInner(theme) {
2013 var _props$forwardedClass = this.props.forwardedClass,
2014 componentStyle = _props$forwardedClass.componentStyle,
2015 defaultProps = _props$forwardedClass.defaultProps,
2016 styledComponentId = _props$forwardedClass.styledComponentId,
2017 target = _props$forwardedClass.target;
2018
2019
2020 var generatedClassName = void 0;
2021 if (componentStyle.isStatic) {
2022 generatedClassName = this.generateAndInjectStyles(EMPTY_OBJECT, this.props, this.styleSheet);
2023 } else if (theme !== undefined) {
2024 generatedClassName = this.generateAndInjectStyles(determineTheme(this.props, theme, defaultProps), this.props, this.styleSheet);
2025 } else {
2026 generatedClassName = this.generateAndInjectStyles(this.props.theme || EMPTY_OBJECT, this.props, this.styleSheet);
2027 }
2028 var elementToBeCreated = this.props.as || this.attrs.as || target;
2029 var isTargetTag = isTag(elementToBeCreated);
2030
2031 var propsForElement = _extends({}, this.attrs);
2032
2033 var key = void 0;
2034 // eslint-disable-next-line guard-for-in
2035 for (key in this.props) {
2036 if (process.env.NODE_ENV !== 'production' && key === 'innerRef') {
2037 warnInnerRef();
2038 }
2039
2040 if (key === 'forwardedClass' || key === 'as') continue;else if (key === 'forwardedRef') propsForElement.ref = this.props[key];else if (!isTargetTag || validAttr(key)) {
2041 // Don't pass through non HTML tags through to HTML elements
2042 propsForElement[key] = key === 'style' && key in this.attrs ? _extends({}, this.attrs[key], this.props[key]) : this.props[key];
2043 }
2044 }
2045
2046 propsForElement.className = [this.props.className, styledComponentId, this.attrs.className, generatedClassName].filter(Boolean).join(' ');
2047
2048 return createElement(elementToBeCreated, propsForElement);
2049 };
2050
2051 StyledComponent.prototype.buildExecutionContext = function buildExecutionContext(theme, props, attrs) {
2052 var context = _extends({}, props, { theme: theme });
2053
2054 if (attrs === undefined) return context;
2055
2056 this.attrs = {};
2057
2058 var attr = void 0;
2059 var key = void 0;
2060
2061 /* eslint-disable guard-for-in */
2062 for (key in attrs) {
2063 attr = attrs[key];
2064
2065 this.attrs[key] = isFunction(attr) && !isDerivedReactComponent(attr) && !isStyledComponent(attr) ? attr(context) : attr;
2066 }
2067 /* eslint-enable */
2068
2069 return _extends({}, context, this.attrs);
2070 };
2071
2072 StyledComponent.prototype.generateAndInjectStyles = function generateAndInjectStyles(theme, props) {
2073 var styleSheet = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : StyleSheet.master;
2074 var _props$forwardedClass2 = props.forwardedClass,
2075 attrs = _props$forwardedClass2.attrs,
2076 componentStyle = _props$forwardedClass2.componentStyle,
2077 warnTooManyClasses = _props$forwardedClass2.warnTooManyClasses;
2078
2079 // statically styled-components don't need to build an execution context object,
2080 // and shouldn't be increasing the number of class names
2081
2082 if (componentStyle.isStatic && attrs === undefined) {
2083 return componentStyle.generateAndInjectStyles(EMPTY_OBJECT, styleSheet);
2084 }
2085
2086 var className = componentStyle.generateAndInjectStyles(this.buildExecutionContext(theme, props, props.forwardedClass.attrs), styleSheet);
2087
2088 if (warnTooManyClasses) {
2089 warnTooManyClasses(className);
2090 }
2091
2092 return className;
2093 };
2094
2095 return StyledComponent;
2096}(Component);
2097
2098function createStyledComponent(target, options, rules) {
2099 var isTargetStyledComp = isStyledComponent(target);
2100 var isClass = !isTag(target);
2101
2102 var _options$displayName = options.displayName,
2103 displayName = _options$displayName === undefined ? generateDisplayName(target) : _options$displayName,
2104 _options$componentId = options.componentId,
2105 componentId = _options$componentId === undefined ? generateId(ComponentStyle, options.displayName, options.parentComponentId) : _options$componentId,
2106 _options$ParentCompon = options.ParentComponent,
2107 ParentComponent = _options$ParentCompon === undefined ? StyledComponent : _options$ParentCompon,
2108 attrs = options.attrs;
2109
2110
2111 var styledComponentId = options.displayName && options.componentId ? escape(options.displayName) + '-' + options.componentId : options.componentId || componentId;
2112
2113 // fold the underlying StyledComponent attrs up (implicit extend)
2114 var finalAttrs =
2115 // $FlowFixMe
2116 isTargetStyledComp && target.attrs ? _extends({}, target.attrs, attrs) : attrs;
2117
2118 var componentStyle = new ComponentStyle(isTargetStyledComp ? // fold the underlying StyledComponent rules up (implicit extend)
2119 // $FlowFixMe
2120 target.componentStyle.rules.concat(rules) : rules, finalAttrs, styledComponentId);
2121
2122 /**
2123 * forwardRef creates a new interim component, which we'll take advantage of
2124 * instead of extending ParentComponent to create _another_ interim class
2125 */
2126 var WrappedStyledComponent = React.forwardRef(function (props, ref) {
2127 return React.createElement(ParentComponent, _extends({}, props, { forwardedClass: WrappedStyledComponent, forwardedRef: ref }));
2128 });
2129
2130 // $FlowFixMe
2131 WrappedStyledComponent.attrs = finalAttrs;
2132 // $FlowFixMe
2133 WrappedStyledComponent.componentStyle = componentStyle;
2134 WrappedStyledComponent.displayName = displayName;
2135 // $FlowFixMe
2136 WrappedStyledComponent.styledComponentId = styledComponentId;
2137
2138 // fold the underlying StyledComponent target up since we folded the styles
2139 // $FlowFixMe
2140 WrappedStyledComponent.target = isTargetStyledComp ? target.target : target;
2141
2142 // $FlowFixMe
2143 WrappedStyledComponent.withComponent = function withComponent(tag) {
2144 var previousComponentId = options.componentId,
2145 optionsToCopy = objectWithoutProperties(options, ['componentId']);
2146
2147
2148 var newComponentId = previousComponentId && previousComponentId + '-' + (isTag(tag) ? tag : escape(getComponentName(tag)));
2149
2150 var newOptions = _extends({}, optionsToCopy, {
2151 attrs: finalAttrs,
2152 componentId: newComponentId,
2153 ParentComponent: ParentComponent
2154 });
2155
2156 return createStyledComponent(tag, newOptions, rules);
2157 };
2158
2159 if (process.env.NODE_ENV !== 'production') {
2160 // $FlowFixMe
2161 WrappedStyledComponent.warnTooManyClasses = createWarnTooManyClasses(displayName);
2162 }
2163
2164 if (isClass) {
2165 hoistNonReactStatics(WrappedStyledComponent, target, {
2166 // all SC-specific things should not be hoisted
2167 attrs: true,
2168 componentStyle: true,
2169 displayName: true,
2170 styledComponentId: true,
2171 target: true,
2172 warnTooManyClasses: true,
2173 withComponent: true
2174 });
2175 }
2176
2177 return WrappedStyledComponent;
2178}
2179
2180//
2181// Thanks to ReactDOMFactories for this handy list!
2182
2183var domElements = ['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'big', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr',
2184
2185// SVG
2186'circle', 'clipPath', 'defs', 'ellipse', 'foreignObject', 'g', 'image', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'svg', 'text', 'tspan'];
2187
2188//
2189
2190var styled = function styled(tag) {
2191 return constructWithOptions(createStyledComponent, tag);
2192};
2193
2194// Shorthands for all valid HTML Elements
2195domElements.forEach(function (domElement) {
2196 styled[domElement] = styled(domElement);
2197});
2198
2199//
2200
2201var GlobalStyle = function () {
2202 function GlobalStyle(rules, componentId) {
2203 classCallCheck(this, GlobalStyle);
2204
2205 this.rules = rules;
2206 this.componentId = componentId;
2207 this.isStatic = isStaticRules(rules);
2208
2209 if (!StyleSheet.master.hasId(componentId)) {
2210 StyleSheet.master.deferredInject(componentId, []);
2211 }
2212 }
2213
2214 GlobalStyle.prototype.createStyles = function createStyles(executionContext, styleSheet) {
2215 var flatCSS = flatten(this.rules, executionContext, styleSheet);
2216 var css = stringifyRules(flatCSS, '');
2217
2218 styleSheet.inject(this.componentId, css);
2219 };
2220
2221 GlobalStyle.prototype.removeStyles = function removeStyles(styleSheet) {
2222 var componentId = this.componentId;
2223
2224 if (styleSheet.hasId(componentId)) {
2225 styleSheet.remove(componentId);
2226 }
2227 };
2228
2229 // TODO: overwrite in-place instead of remove+create?
2230
2231
2232 GlobalStyle.prototype.renderStyles = function renderStyles(executionContext, styleSheet) {
2233 this.removeStyles(styleSheet);
2234 this.createStyles(executionContext, styleSheet);
2235 };
2236
2237 return GlobalStyle;
2238}();
2239
2240//
2241
2242// place our cache into shared context so it'll persist between HMRs
2243if (IS_BROWSER) {
2244 window.scCGSHMRCache = {};
2245}
2246
2247function createGlobalStyle(strings) {
2248 for (var _len = arguments.length, interpolations = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
2249 interpolations[_key - 1] = arguments[_key];
2250 }
2251
2252 var rules = css.apply(undefined, [strings].concat(interpolations));
2253 var id = 'sc-global-' + murmurhash(JSON.stringify(rules));
2254 var style = new GlobalStyle(rules, id);
2255
2256 var GlobalStyleComponent = function (_React$Component) {
2257 inherits(GlobalStyleComponent, _React$Component);
2258
2259 function GlobalStyleComponent() {
2260 classCallCheck(this, GlobalStyleComponent);
2261
2262 var _this = possibleConstructorReturn(this, _React$Component.call(this));
2263
2264 var _this$constructor = _this.constructor,
2265 globalStyle = _this$constructor.globalStyle,
2266 styledComponentId = _this$constructor.styledComponentId;
2267
2268
2269 if (IS_BROWSER) {
2270 window.scCGSHMRCache[styledComponentId] = (window.scCGSHMRCache[styledComponentId] || 0) + 1;
2271 }
2272
2273 /**
2274 * This fixes HMR compatiblility. Don't ask me why, but this combination of
2275 * caching the closure variables via statics and then persisting the statics in
2276 * state works across HMR where no other combination did. ¯\_(ツ)_/¯
2277 */
2278 _this.state = {
2279 globalStyle: globalStyle,
2280 styledComponentId: styledComponentId
2281 };
2282 return _this;
2283 }
2284
2285 GlobalStyleComponent.prototype.componentDidMount = function componentDidMount() {
2286 if (process.env.NODE_ENV !== 'production' && IS_BROWSER && window.scCGSHMRCache[this.state.styledComponentId] > 1 && !this.props.suppressMultiMountWarning) {
2287 console.warn('The global style component ' + this.state.styledComponentId + ' was composed and rendered multiple times in your React component tree. Only the last-rendered copy will have its styles remain in <head> (or your StyleSheetManager target.)');
2288 }
2289 };
2290
2291 GlobalStyleComponent.prototype.componentWillUnmount = function componentWillUnmount() {
2292 if (window.scCGSHMRCache[this.state.styledComponentId]) {
2293 window.scCGSHMRCache[this.state.styledComponentId] -= 1;
2294 }
2295 /**
2296 * Depending on the order "render" is called this can cause the styles to be lost
2297 * until the next render pass of the remaining instance, which may
2298 * not be immediate.
2299 */
2300 if (window.scCGSHMRCache[this.state.styledComponentId] === 0) {
2301 this.state.globalStyle.removeStyles(this.styleSheet);
2302 }
2303 };
2304
2305 GlobalStyleComponent.prototype.render = function render() {
2306 var _this2 = this;
2307
2308 if (process.env.NODE_ENV !== 'production' && React.Children.count(this.props.children)) {
2309 console.warn('The global style component ' + this.state.styledComponentId + ' was given child JSX. createGlobalStyle does not render children.');
2310 }
2311
2312 return React.createElement(
2313 StyleSheetConsumer,
2314 null,
2315 function (styleSheet) {
2316 _this2.styleSheet = styleSheet || StyleSheet.master;
2317
2318 var globalStyle = _this2.state.globalStyle;
2319
2320
2321 if (globalStyle.isStatic) {
2322 globalStyle.renderStyles(STATIC_EXECUTION_CONTEXT, _this2.styleSheet);
2323
2324 return null;
2325 } else {
2326 return React.createElement(
2327 ThemeConsumer,
2328 null,
2329 function (theme) {
2330 var defaultProps = _this2.constructor.defaultProps;
2331
2332
2333 var context = _extends({}, _this2.props);
2334
2335 if (typeof theme !== 'undefined') {
2336 context.theme = determineTheme(_this2.props, theme, defaultProps);
2337 }
2338
2339 globalStyle.renderStyles(context, _this2.styleSheet);
2340
2341 return null;
2342 }
2343 );
2344 }
2345 }
2346 );
2347 };
2348
2349 return GlobalStyleComponent;
2350 }(React.Component);
2351
2352 GlobalStyleComponent.defaultProps = {
2353 suppressMultiMountWarning: false
2354 };
2355 GlobalStyleComponent.globalStyle = style;
2356 GlobalStyleComponent.styledComponentId = id;
2357 process.env.NODE_ENV !== "production" ? GlobalStyleComponent.propTypes = {
2358 suppressMultiMountWarning: PropTypes.bool
2359 } : void 0;
2360
2361
2362 return GlobalStyleComponent;
2363}
2364
2365//
2366
2367var replaceWhitespace = function replaceWhitespace(str) {
2368 return str.replace(/\s|\\n/g, '');
2369};
2370
2371function keyframes(strings) {
2372 /* Warning if you've used keyframes on React Native */
2373 if (process.env.NODE_ENV !== 'production' && typeof navigator !== 'undefined' && navigator.product === 'ReactNative') {
2374 console.warn('`keyframes` cannot be used on ReactNative, only on the web. To do animation in ReactNative please use Animated.');
2375 }
2376
2377 for (var _len = arguments.length, interpolations = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
2378 interpolations[_key - 1] = arguments[_key];
2379 }
2380
2381 var rules = css.apply(undefined, [strings].concat(interpolations));
2382
2383 var name = generateAlphabeticName(murmurhash(replaceWhitespace(JSON.stringify(rules))));
2384
2385 return new Keyframes(name, stringifyRules(rules, name, '@keyframes'));
2386}
2387
2388//
2389
2390var withTheme = (function (Component$$1) {
2391 var WithTheme = React.forwardRef(function (props, ref) {
2392 return React.createElement(
2393 ThemeConsumer,
2394 null,
2395 function (theme) {
2396 // $FlowFixMe
2397 var defaultProps = Component$$1.defaultProps;
2398
2399 var themeProp = determineTheme(props, theme, defaultProps);
2400
2401 if (process.env.NODE_ENV !== 'production' && themeProp === undefined) {
2402 // eslint-disable-next-line no-console
2403 console.warn('[withTheme] You are not using a ThemeProvider nor passing a theme prop or a theme in defaultProps in component class ' + getComponentName(Component$$1));
2404 }
2405
2406 return React.createElement(Component$$1, _extends({}, props, { theme: themeProp, ref: ref }));
2407 }
2408 );
2409 });
2410
2411 hoistNonReactStatics(WithTheme, Component$$1);
2412
2413 WithTheme.displayName = 'WithTheme(' + getComponentName(Component$$1) + ')';
2414
2415 return WithTheme;
2416});
2417
2418//
2419
2420/* eslint-disable */
2421var __DO_NOT_USE_OR_YOU_WILL_BE_HAUNTED_BY_SPOOKY_GHOSTS = {
2422 StyleSheet: StyleSheet
2423};
2424
2425//
2426
2427/* Warning if you've imported this file on React Native */
2428if (process.env.NODE_ENV !== 'production' && typeof navigator !== 'undefined' && navigator.product === 'ReactNative') {
2429 // eslint-disable-next-line no-console
2430 console.warn("It looks like you've imported 'styled-components' on React Native.\n" + "Perhaps you're looking to import 'styled-components/native'?\n" + 'Read more about this at https://www.styled-components.com/docs/basics#react-native');
2431}
2432
2433/* Warning if there are several instances of styled-components */
2434if (process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test' && typeof window !== 'undefined' && typeof navigator !== 'undefined' && typeof navigator.userAgent === 'string' && navigator.userAgent.indexOf('Node.js') === -1 && navigator.userAgent.indexOf('jsdom') === -1) {
2435 window['__styled-components-init__'] = window['__styled-components-init__'] || 0;
2436
2437 if (window['__styled-components-init__'] === 1) {
2438 // eslint-disable-next-line no-console
2439 console.warn("It looks like there are several instances of 'styled-components' initialized in this application. " + 'This may cause dynamic styles not rendering properly, errors happening during rehydration process ' + 'and makes your application bigger without a good reason.\n\n' + 'See https://s-c.sh/2BAXzed for more info.');
2440 }
2441
2442 window['__styled-components-init__'] += 1;
2443}
2444
2445//
2446
2447export default styled;
2448export { css, keyframes, createGlobalStyle, isStyledComponent, ThemeConsumer, ThemeProvider, withTheme, ServerStyleSheet, StyleSheetManager, __DO_NOT_USE_OR_YOU_WILL_BE_HAUNTED_BY_SPOOKY_GHOSTS };
2449//# sourceMappingURL=styled-components.browser.esm.js.map