UNPKG

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