'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var reactIs = require('react-is'); var unitless = _interopDefault(require('@emotion/unitless')); var validAttr = _interopDefault(require('@emotion/is-prop-valid')); var React = require('react'); var React__default = _interopDefault(React); var Stylis = _interopDefault(require('stylis/stylis.min')); var _insertRulePlugin = _interopDefault(require('stylis-rule-sheet')); var PropTypes = _interopDefault(require('prop-types')); function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _construct(Parent, args, Class) { if (isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } // var interleave = (function (strings, interpolations) { var result = [strings[0]]; for (var i = 0, len = interpolations.length; i < len; i += 1) { result.push(interpolations[i], strings[i + 1]); } return result; }); // var isPlainObject = (function (x) { return typeof x === 'object' && x.constructor === Object; }); // var EMPTY_ARRAY = Object.freeze([]); var EMPTY_OBJECT = Object.freeze({}); // function isFunction(test) { return typeof test === 'function'; } // function getComponentName(target) { return (process.env.NODE_ENV !== 'production' ? typeof target === 'string' && target : false) || // $FlowFixMe target.displayName || // $FlowFixMe target.name || 'Component'; } // function isStatelessFunction(test) { return typeof test === 'function' && !(test.prototype && test.prototype.isReactComponent); } // function isStyledComponent(target) { return target && typeof target.styledComponentId === 'string'; } // var SC_ATTR = typeof process !== 'undefined' && process.env.SC_ATTR || 'data-styled'; var SC_ATTR_ACTIVE = 'active'; var SC_VERSION_ATTR = 'data-styled-version'; var SC_VERSION = "5.0.0-2.canary-sheet"; var IS_BROWSER = typeof window !== 'undefined' && 'HTMLElement' in window; var DISABLE_SPEEDY = typeof SC_DISABLE_SPEEDY === 'boolean' && SC_DISABLE_SPEEDY || process.env.NODE_ENV !== 'production'; // Shared empty execution context when generating static styles var STATIC_EXECUTION_CONTEXT = {}; // var ELEMENT_TYPE = 1; /* Node.ELEMENT_TYPE */ /** Find last style element if any inside target */ var findLastStyleTag = function findLastStyleTag(target) { var childNodes = target.childNodes; for (var i = childNodes.length; i >= 0; i--) { var child = childNodes[i]; if (child && child.nodeType === ELEMENT_TYPE && child.hasAttribute(SC_ATTR)) { return child; } } return undefined; }; /** Create a style element inside `target` or
after the last */ var makeStyleTag = function makeStyleTag(target) { var head = document.head; var parent = target || head; var style = document.createElement('style'); var prevStyle = findLastStyleTag(parent); var nextSibling = prevStyle !== undefined ? prevStyle.nextSibling : null; style.setAttribute(SC_ATTR, SC_ATTR_ACTIVE); style.setAttribute(SC_VERSION_ATTR, SC_VERSION); parent.insertBefore(style, nextSibling); return style; }; /** Get the CSSStyleSheet instance for a given style element */ var getSheet = function getSheet(tag) { if (tag.sheet) { return tag.sheet; } // Avoid Firefox quirk where the style element might not have a sheet property var _document = document, styleSheets = _document.styleSheets; for (var i = 0, l = styleSheets.length; i < l; i++) { var sheet = styleSheets[i]; if (sheet.ownerNode === tag) { return sheet; } } throw new TypeError("CSSStyleSheet could not be found on HTMLStyleElement"); }; // /** CSSStyleSheet-like Tag abstraction for CSS rules */ /** Create a CSSStyleSheet-like tag depending on the environment */ var makeTag = function makeTag(isServer, target) { if (!IS_BROWSER) { return new VirtualTag(target); } else if (DISABLE_SPEEDY) { return new TextTag(target); } else { return new SpeedyTag(target); } }; /** A Tag that wraps CSSOM's CSSStyleSheet API directly */ var SpeedyTag = /*#__PURE__*/ function () { function SpeedyTag(target) { var element = this.element = makeStyleTag(target); // Avoid Edge bug where empty style elements don't create sheets element.appendChild(document.createTextNode('')); this.sheet = getSheet(element); this.length = 0; } var _proto = SpeedyTag.prototype; _proto.insertRule = function insertRule(index, rule) { try { this.sheet.insertRule(rule, index); this.length++; return true; } catch (_error) { return false; } }; _proto.deleteRule = function deleteRule(index) { this.sheet.deleteRule(index); this.length--; }; _proto.getRule = function getRule(index) { if (index < this.length) { return this.sheet.cssRules[index].cssText; } else { return ''; } }; return SpeedyTag; }(); /** A Tag that emulates the CSSStyleSheet API but uses text nodes */ var TextTag = /*#__PURE__*/ function () { function TextTag(target) { var element = this.element = makeStyleTag(target); this.nodes = element.childNodes; this.length = 0; } var _proto2 = TextTag.prototype; _proto2.insertRule = function insertRule(index, rule) { if (index <= this.length && index >= 0) { var node = document.createTextNode(rule); var refNode = this.nodes[index]; this.element.insertBefore(node, refNode || null); this.length++; return true; } else { return false; } }; _proto2.deleteRule = function deleteRule(index) { this.element.removeChild(this.nodes[index]); this.length--; }; _proto2.getRule = function getRule(index) { if (index < this.length) { return this.nodes[index].textContent; } else { return ''; } }; return TextTag; }(); /** A completely virtual (server-side) Tag that doesn't manipulate the DOM */ var VirtualTag = /*#__PURE__*/ function () { function VirtualTag(_target) { this.rules = []; this.length = 0; } var _proto3 = VirtualTag.prototype; _proto3.insertRule = function insertRule(index, rule) { if (index <= this.length) { this.rules.splice(index, 0, rule); this.length++; return true; } else { return false; } }; _proto3.deleteRule = function deleteRule(index) { this.rules.splice(index, 1); this.length--; }; _proto3.getRule = function getRule(index) { if (index < this.length) { return this.rules[index]; } else { return ''; } }; return VirtualTag; }(); // /* eslint-disable no-use-before-define */ /** Group-aware Tag that sorts rules by indices */ /** Create a GroupedTag with an underlying Tag implementation */ var makeGroupedTag = function makeGroupedTag(tag) { return new DefaultGroupedTag(tag); }; var BASE_SIZE = 1 << 8; var DefaultGroupedTag = /*#__PURE__*/ function () { function DefaultGroupedTag(tag) { this.groupSizes = new Uint32Array(BASE_SIZE); this.length = BASE_SIZE; this.tag = tag; } var _proto = DefaultGroupedTag.prototype; _proto.indexOfGroup = function indexOfGroup(group) { var index = 0; for (var i = 0; i < group; i++) { index += this.groupSizes[i]; } return index; }; _proto.insertRules = function insertRules(group, rules) { if (group >= this.groupSizes.length) { var oldBuffer = this.groupSizes; var oldSize = oldBuffer.length; var newSize = BASE_SIZE << (group / BASE_SIZE | 0); this.groupSizes = new Uint32Array(newSize); this.groupSizes.set(oldBuffer); this.length = newSize; for (var i = oldSize; i < newSize; i++) { this.groupSizes[i] = 0; } } var startIndex = this.indexOfGroup(group + 1); for (var _i = 0, l = rules.length; _i < l; _i++) { if (this.tag.insertRule(startIndex + _i, rules[_i])) { this.groupSizes[group]++; } } }; _proto.clearGroup = function clearGroup(group) { if (group < this.length) { var length = this.groupSizes[group]; var startIndex = this.indexOfGroup(group); var endIndex = startIndex + length; this.groupSizes[group] = 0; for (var i = startIndex; i < endIndex; i++) { this.tag.deleteRule(startIndex); } } }; _proto.getGroup = function getGroup(group) { var css = ''; if (group >= this.length || this.groupSizes[group] === 0) { return css; } var length = this.groupSizes[group]; var startIndex = this.indexOfGroup(group); var endIndex = startIndex + length; for (var i = startIndex; i < endIndex; i++) { css += this.tag.getRule(i) + "\n"; } return css; }; return DefaultGroupedTag; }(); // var groupIDRegister = new Map(); var reverseRegister = new Map(); var nextFreeGroup = 1; var getGroupForId = function getGroupForId(id) { if (groupIDRegister.has(id)) { return groupIDRegister.get(id); } var group = nextFreeGroup++; groupIDRegister.set(id, group); reverseRegister.set(group, id); return group; }; var getIdForGroup = function getIdForGroup(group) { return reverseRegister.get(group); }; var setGroupForId = function setGroupForId(id, group) { if (group >= nextFreeGroup) { nextFreeGroup = group + 1; } groupIDRegister.set(id, group); reverseRegister.set(group, id); }; // var PLAIN_RULE_TYPE = 1; var SELECTOR = "style[" + SC_ATTR + "][" + SC_VERSION_ATTR + "=\"" + SC_VERSION + "\"]"; var MARKER_RE = new RegExp("^" + SC_ATTR + "\\.g(\\d+)\\[id=\"([\\w\\d-]+)\"\\]"); var outputSheet = function outputSheet(sheet) { var tag = sheet.getTag(); var length = tag.length; var css = ''; for (var group = 0; group < length; group++) { var id = getIdForGroup(group); if (id === undefined) continue; var names = sheet.names.get(id); var rules = tag.getGroup(group); if (names === undefined || rules.length === 0) continue; var selector = SC_ATTR + ".g" + group + "[id=\"" + id + "\"]"; var content = ''; if (names !== undefined) { names.forEach(function (name) { if (name.length > 0) { content += name + ","; } }); } // NOTE: It's easier to collect rules and have the marker // after the actual rules to simplify the rehydration css += rules + selector; if (content.length > 0) { css += "{content:\"" + content + "\"}\n"; } else { css += '{}\n'; } } return css; }; var rehydrateNamesFromContent = function rehydrateNamesFromContent(sheet, id, content) { var names = content.slice(1, -1).split(','); for (var i = 0, l = names.length; i < l; i++) { var name = names[i]; if (name.length > 0) { sheet.registerName(id, name); } } }; var rehydrateSheetFromTag = function rehydrateSheetFromTag(sheet, style) { var _getSheet = getSheet(style), cssRules = _getSheet.cssRules; var rules = []; for (var i = 0, l = cssRules.length; i < l; i++) { var cssRule = cssRules[i]; if (cssRule.type !== PLAIN_RULE_TYPE) { rules.push(cssRule.cssText); } else { var marker = cssRule.selectorText.match(MARKER_RE); if (marker !== null) { var group = parseInt(marker[1], 10) | 0; var id = marker[2]; var content = cssRule.style.content; if (group !== 0) { // Rehydrate componentId to group index mapping setGroupForId(id, group); // Rehydrate names and rules rehydrateNamesFromContent(sheet, id, content); sheet.getTag().insertRules(group, rules); } rules.length = 0; } else { rules.push(cssRule.cssText); } } } }; var rehydrateSheet = function rehydrateSheet(sheet) { var nodes = document.querySelectorAll(SELECTOR); for (var i = 0, l = nodes.length; i < l; i++) { var node = nodes[i]; if (node && node.getAttribute(SC_ATTR) !== SC_ATTR_ACTIVE) { rehydrateSheetFromTag(sheet, node); if (node.parentNode) { node.parentNode.removeChild(node); } } } }; // var SHOULD_REHYDRATE = IS_BROWSER; /** Contains the main stylesheet logic for stringification and caching */ var StyleSheet = /*#__PURE__*/ function () { /** Register a group ID to give it an index */ StyleSheet.registerId = function registerId(id) { return getGroupForId(id); }; function StyleSheet(isServer, target) { this.names = new Map(); this.isServer = isServer; this.target = target; // We rehydrate only once and use the sheet that is // created first if (!isServer && IS_BROWSER && SHOULD_REHYDRATE) { SHOULD_REHYDRATE = false; rehydrateSheet(this); } } /** Lazily initialises a GroupedTag for when it's actually needed */ var _proto = StyleSheet.prototype; _proto.getTag = function getTag() { if (this.tag === undefined) { var tag = makeTag(this.isServer, this.target); this.tag = makeGroupedTag(tag); } return this.tag; } /** Check whether a name is known for caching */ ; _proto.hasNameForId = function hasNameForId(id, name) { return this.names.has(id) && this.names.get(id).has(name); } /** Mark a group's name as known for caching */ ; _proto.registerName = function registerName(id, name) { getGroupForId(id); if (!this.names.has(id)) { var groupNames = new Set(); groupNames.add(name); this.names.set(id, groupNames); } else { this.names.get(id).add(name); } } /** Insert new rules which also marks the name as known */ ; _proto.insertRules = function insertRules(id, name, rules) { this.registerName(id, name); this.getTag().insertRules(getGroupForId(id), rules); } /** Clears all cached names for a given group ID */ ; _proto.clearNames = function clearNames(id) { if (this.names.has(id)) { this.names.get(id).clear(); } } /** Clears all rules for a given group ID */ ; _proto.clearRules = function clearRules(id) { this.getTag().clearGroup(getGroupForId(id)); this.clearNames(id); } /** Clears the entire tag which deletes all rules but not its names */ ; _proto.clearTag = function clearTag() { // NOTE: This does not clear the names, since it's only used during SSR // so that we can continuously output only new rules this.tag = undefined; } /** Outputs the current sheet as a CSS string with markers for SSR */ ; _proto.toString = function toString() { return outputSheet(this); }; return StyleSheet; }(); // // /** * Parse errors.md and turn it into a simple hash of code: message */ var ERRORS = process.env.NODE_ENV !== 'production' ? { "1": "Cannot create styled-component for component: %s.\n\n", "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", "3": "Streaming SSR is only supported in a Node.js environment; Please do not try to call this method in the browser.\n\n", "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", "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", "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", "7": "ThemeProvider: Please return an object from your \"theme\" prop function, e.g.\n\n```js\ntheme={() => ({})}\n```\n\n", "8": "ThemeProvider: Please make your \"theme\" prop an object.\n\n", "9": "Missing document ``\n\n", "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", "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", "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\n", "13": "%s 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.\n" } : {}; /** * super basic version of sprintf */ function format() { var a = arguments.length <= 0 ? undefined : arguments[0]; var b = []; for (var c = 1, len = arguments.length; c < len; c += 1) { b.push(c < 0 || arguments.length <= c ? undefined : arguments[c]); } b.forEach(function (d) { a = a.replace(/%[a-z]/, d); }); return a; } /** * Create an error file out of errors.md for development and a simple web link to the full errors * in production mode. */ var StyledComponentsError = /*#__PURE__*/ function (_Error) { _inheritsLoose(StyledComponentsError, _Error); function StyledComponentsError(code) { var _this; for (var _len = arguments.length, interpolations = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } if (process.env.NODE_ENV === 'production') { _this = _Error.call(this, "An error occurred. See https://github.com/styled-components/styled-components/blob/master/packages/styled-components/src/utils/errors.md#" + code + " for more information. " + (interpolations ? "Additional arguments: " + interpolations.join(', ') : '')) || this; } else { _this = _Error.call(this, format.apply(void 0, [ERRORS[code]].concat(interpolations)).trim()) || this; } return _assertThisInitialized(_this); } return StyledComponentsError; }(_wrapNativeSuper(Error)); // var Keyframes = /*#__PURE__*/ function () { function Keyframes(name, rules) { var _this = this; this.inject = function (styleSheet) { if (!styleSheet.hasNameForId(_this.id, _this.name)) { styleSheet.insertRules(_this.id, _this.name, _this.rules); } }; this.toString = function () { throw new StyledComponentsError(12, String(_this.name)); }; this.name = name; this.rules = rules; this.id = "sc-keyframes-" + name; } var _proto = Keyframes.prototype; _proto.getName = function getName() { return this.name; }; return Keyframes; }(); // /** * inlined version of * https://github.com/facebook/fbjs/blob/master/packages/fbjs/src/core/hyphenateStyleName.js */ var uppercasePattern = /([A-Z])/g; var msPattern = /^ms-/; /** * Hyphenates a camelcased CSS property name, for example: * * > hyphenateStyleName('backgroundColor') * < "background-color" * > hyphenateStyleName('MozTransition') * < "-moz-transition" * > hyphenateStyleName('msTransition') * < "-ms-transition" * * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix * is converted to `-ms-`. * * @param {string} string * @return {string} */ function hyphenateStyleName(string) { return string.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern, '-ms-'); } // function addUnitIfNeeded(name, value) { // https://github.com/amilajack/eslint-plugin-flowtype-errors/issues/133 // $FlowFixMe if (value == null || typeof value === 'boolean' || value === '') { return ''; } if (typeof value === 'number' && value !== 0 && !(name in unitless)) { return value + "px"; // Presumes implicit 'px' suffix for unitless numbers } return String(value).trim(); } // /** * It's falsish not falsy because 0 is allowed. */ var isFalsish = function isFalsish(chunk) { return chunk === undefined || chunk === null || chunk === false || chunk === ''; }; var objToCss = function objToCss(obj, prevKey) { var css = Object.keys(obj).filter(function (key) { return !isFalsish(obj[key]); }).map(function (key) { if (isPlainObject(obj[key])) return objToCss(obj[key], key); return hyphenateStyleName(key) + ": " + addUnitIfNeeded(key, obj[key]) + ";"; }).join(' '); return prevKey ? prevKey + " {\n " + css + "\n}" : css; }; function flatten(chunk, executionContext, styleSheet) { if (Array.isArray(chunk)) { var ruleSet = []; for (var i = 0, len = chunk.length, result; i < len; i += 1) { result = flatten(chunk[i], executionContext, styleSheet); if (result === '') continue;else if (Array.isArray(result)) ruleSet.push.apply(ruleSet, result);else ruleSet.push(result); } return ruleSet; } if (isFalsish(chunk)) { return ''; } /* Handle other components */ if (isStyledComponent(chunk)) { return "." + chunk.styledComponentId; } /* Either execute or defer the function */ if (isFunction(chunk)) { if (isStatelessFunction(chunk) && executionContext) { var _result = chunk(executionContext); if (process.env.NODE_ENV !== 'production' && reactIs.isElement(_result)) { // eslint-disable-next-line no-console 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."); } return flatten(_result, executionContext, styleSheet); } else return chunk; } if (chunk instanceof Keyframes) { if (styleSheet) { chunk.inject(styleSheet); return chunk.getName(); } else return chunk; } /* Handle objects */ return isPlainObject(chunk) ? objToCss(chunk) : chunk.toString(); } // function css(styles) { for (var _len = arguments.length, interpolations = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } if (isFunction(styles) || isPlainObject(styles)) { // $FlowFixMe return flatten(interleave(EMPTY_ARRAY, [styles].concat(interpolations))); } // $FlowFixMe return flatten(interleave(styles, interpolations)); } function constructWithOptions(componentConstructor, tag, options) { if (options === void 0) { options = EMPTY_OBJECT; } if (!reactIs.isValidElementType(tag)) { throw new StyledComponentsError(1, String(tag)); } /* This is callable directly as a template function */ // $FlowFixMe: Not typed to avoid destructuring arguments var templateFunction = function templateFunction() { return componentConstructor(tag, options, css.apply(void 0, arguments)); }; /* If config methods are called, wrap up a new template function and merge options */ templateFunction.withConfig = function (config) { return constructWithOptions(componentConstructor, tag, _extends({}, options, config)); }; /* Modify/inject new props at runtime */ templateFunction.attrs = function (attrs) { return constructWithOptions(componentConstructor, tag, _extends({}, options, { attrs: Array.prototype.concat(options.attrs, attrs).filter(Boolean) })); }; return templateFunction; } // /* eslint-disable no-bitwise */ /* This is the "capacity" of our alphabet i.e. 2x26 for all letters plus their capitalised * counterparts */ var charsLength = 52; /* start at 75 for 'a' until 'z' (25) and then start at 65 for capitalised letters */ var getAlphabeticChar = function getAlphabeticChar(code) { return String.fromCharCode(code + (code > 25 ? 39 : 97)); }; /* input a number, usually a hash and convert it to base-52 */ function generateAlphabeticName(code) { var name = ''; var x; /* get a char and divide by alphabet-length */ for (x = Math.abs(code); x > charsLength; x = x / charsLength | 0) { name = getAlphabeticChar(x % charsLength) + name; } return getAlphabeticChar(x % charsLength) + name; } // var hash = function hash(x) { /* prettier-ignore */ for (var h = 5381 | 0, i = 0, l = x.length | 0; i < l; i++) { h = (h << 5) + h + x.charCodeAt(i); } return h >>> 0; }; var hasher = function hasher(str) { return generateAlphabeticName(hash(str)); }; // var stylis = new Stylis({ global: false, cascade: true, keyframe: false, prefix: true, compress: false, semicolon: false // NOTE: This means "autocomplete missing semicolons" }); // Wrap `insertRulePlugin to build a list of rules, // and then make our own plugin to return the rules. This // makes it easier to hook into the existing SSR architecture var parsingRules = []; // eslint-disable-next-line consistent-return var returnRulesPlugin = function returnRulesPlugin(context) { if (context === -2) { var parsedRules = parsingRules; parsingRules = []; return parsedRules; } }; var parseRulesPlugin = _insertRulePlugin(function (rule) { parsingRules.push(rule); }); var _componentId; var _selector; var _selectorRegexp; var selfReferenceReplacer = function selfReferenceReplacer(match, offset, string) { if ( // the first self-ref is always untouched offset > 0 && // there should be at least two self-refs to do a replacement (.b > .b) string.slice(0, offset).indexOf(_selector) !== -1 && // no consecutive self refs (.b.b); that is a precedence boost and treated differently string.slice(offset - _selector.length, offset) !== _selector) { return "." + _componentId; } return match; }; /** * When writing a style like * * & + & { * color: red; * } * * The second ampersand should be a reference to the static component class. stylis * has no knowledge of static class so we have to intelligently replace the base selector. */ var selfReferenceReplacementPlugin = function selfReferenceReplacementPlugin(context, _, selectors) { if (context === 2 && selectors.length && selectors[0].lastIndexOf(_selector) > 0) { // eslint-disable-next-line no-param-reassign selectors[0] = selectors[0].replace(_selectorRegexp, selfReferenceReplacer); } }; stylis.use([selfReferenceReplacementPlugin, parseRulesPlugin, returnRulesPlugin]); var COMMENT_REGEX = /^\s*\/\/.*$/gm; function stringifyRules(css, selector, prefix, componentId) { if (componentId === void 0) { componentId = '&'; } var flatCSS = css.replace(COMMENT_REGEX, ''); var cssStr = selector && prefix ? prefix + " " + selector + " { " + flatCSS + " }" : flatCSS; // stylis has no concept of state to be passed to plugins // but since JS is single=threaded, we can rely on that to ensure // these properties stay in sync with the current stylis run _componentId = componentId; _selector = selector; _selectorRegexp = new RegExp("\\" + _selector + "\\b", 'g'); return stylis(prefix || !selector ? '' : selector, cssStr); } // function hasFunctionObjectKey(obj) { // eslint-disable-next-line guard-for-in, no-restricted-syntax for (var key in obj) { if (isFunction(obj[key])) { return true; } } return false; } function isStaticRules(rules, attrs) { for (var i = 0; i < rules.length; i += 1) { var rule = rules[i]; // recursive case if (Array.isArray(rule) && !isStaticRules(rule, attrs)) { return false; } else if (isFunction(rule) && !isStyledComponent(rule)) { // functions are allowed to be static if they're just being // used to get the classname of a nested styled component return false; } } if (attrs.some(function (x) { return isFunction(x) || hasFunctionObjectKey(x); })) return false; return true; } // var isHMREnabled = process.env.NODE_ENV !== 'production' && typeof module !== 'undefined' && module.hot; /* ComponentStyle is all the CSS-specific stuff, not the React-specific stuff. */ var ComponentStyle = /*#__PURE__*/ function () { function ComponentStyle(rules, attrs, componentId) { this.rules = rules; this.isStatic = !isHMREnabled && IS_BROWSER && isStaticRules(rules, attrs); this.componentId = componentId; this.baseHash = hash(componentId); // NOTE: This registers the componentId, which ensures a consistent order // for this component's styles compared to others StyleSheet.registerId(componentId); } /* * Flattens a rule set into valid CSS * Hashes it, wraps the whole chunk in a .hash1234 {} * Returns the hash to be injected on render() * */ var _proto = ComponentStyle.prototype; _proto.generateAndInjectStyles = function generateAndInjectStyles(executionContext, styleSheet) { var componentId = this.componentId; if (this.isStatic) { if (!styleSheet.hasNameForId(componentId, componentId)) { var cssStatic = flatten(this.rules, executionContext, styleSheet).join(''); var cssStaticFormatted = stringifyRules(cssStatic, "." + componentId, undefined, componentId); styleSheet.insertRules(componentId, componentId, cssStaticFormatted); } return componentId; } else { var length = this.rules.length; var i = 0; var dynamicHash = this.baseHash; var css = ''; for (i = 0; i < length; i++) { var partRule = this.rules[i]; if (typeof partRule === 'string') { css += partRule; } else { var partChunk = flatten(partRule, executionContext, styleSheet); var partString = Array.isArray(partChunk) ? partChunk.join('') : partChunk; dynamicHash ^= hash(partString + i); css += partString; } } var name = generateAlphabeticName(dynamicHash); if (!styleSheet.hasNameForId(componentId, name)) { var cssFormatted = stringifyRules(css, "." + name, undefined, componentId); styleSheet.insertRules(componentId, name, cssFormatted); } return name; } }; return ComponentStyle; }(); // var LIMIT = 200; var createWarnTooManyClasses = (function (displayName) { var generatedClasses = {}; var warningSeen = false; return function (className) { if (!warningSeen) { generatedClasses[className] = true; if (Object.keys(generatedClasses).length >= LIMIT) { // Unable to find latestRule in test environment. /* eslint-disable no-console, prefer-template */ console.warn("Over " + LIMIT + " classes were generated for component " + displayName + ". \n" + 'Consider using the attrs method, together with a style object for frequently changed styles.\n' + 'Example:\n' + ' const Component = styled.div.attrs({\n' + ' style: ({ background }) => ({\n' + ' background,\n' + ' }),\n' + ' })`width: 100%;`\n\n' + '