react-infinite-tree
Version:
The infinite-tree library for React.
1,495 lines (1,203 loc) ⢠1.25 MB
JavaScript
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 30);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(process) {
if (process.env.NODE_ENV === 'production') {
module.exports = __webpack_require__(38);
} else {
module.exports = __webpack_require__(39);
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1)))
/***/ }),
/* 1 */
/***/ (function(module, exports) {
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) { return [] }
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
function makeEmptyFunction(arg) {
return function () {
return arg;
};
}
/**
* This function accepts and discards inputs; it has no side effects. This is
* primarily useful idiomatically for overridable function endpoints which
* always need to be callable, since JS lacks a null-call idiom ala Cocoa.
*/
var emptyFunction = function emptyFunction() {};
emptyFunction.thatReturns = makeEmptyFunction;
emptyFunction.thatReturnsFalse = makeEmptyFunction(false);
emptyFunction.thatReturnsTrue = makeEmptyFunction(true);
emptyFunction.thatReturnsNull = makeEmptyFunction(null);
emptyFunction.thatReturnsThis = function () {
return this;
};
emptyFunction.thatReturnsArgument = function (arg) {
return arg;
};
module.exports = emptyFunction;
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
if (process.env.NODE_ENV !== 'production') {
var REACT_ELEMENT_TYPE = (typeof Symbol === 'function' &&
Symbol.for &&
Symbol.for('react.element')) ||
0xeac7;
var isValidElement = function(object) {
return typeof object === 'object' &&
object !== null &&
object.$$typeof === REACT_ELEMENT_TYPE;
};
// By explicitly using `prop-types` you are opting into new development behavior.
// http://fb.me/prop-types-in-prod
var throwOnDirectAccess = true;
module.exports = __webpack_require__(51)(isValidElement, throwOnDirectAccess);
} else {
// By explicitly using `prop-types` you are opting into new production behavior.
// http://fb.me/prop-types-in-prod
module.exports = __webpack_require__(52)();
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1)))
/***/ }),
/* 4 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* WEBPACK VAR INJECTION */(function(process, module) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "css", function() { return css; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "keyframes", function() { return keyframes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "injectGlobal", function() { return injectGlobal; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isStyledComponent", function() { return isStyledComponent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "consolidateStreamedStyles", function() { return consolidateStreamedStyles; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ThemeProvider", function() { return ThemeProvider; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "withTheme", function() { return wrapWithTheme; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ServerStyleSheet", function() { return ServerStyleSheet; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StyleSheetManager", function() { return StyleSheetManager; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_is_plain_object__ = __webpack_require__(82);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_is_plain_object___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_is_plain_object__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_stylis__ = __webpack_require__(84);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_stylis___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1_stylis__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_stylis_rule_sheet__ = __webpack_require__(85);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_stylis_rule_sheet___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_2_stylis_rule_sheet__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_react__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_react___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_3_react__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4_prop_types__ = __webpack_require__(3);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4_prop_types___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_4_prop_types__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5_hoist_non_react_statics__ = __webpack_require__(86);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5_hoist_non_react_statics___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_5_hoist_non_react_statics__);
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @typechecks
*/
var _uppercasePattern = /([A-Z])/g;
/**
* Hyphenates a camelcased string, for example:
*
* > hyphenate('backgroundColor')
* < "background-color"
*
* For CSS style names, use `hyphenateStyleName` instead which works properly
* with all vendor prefixes, including `ms`.
*
* @param {string} string
* @return {string}
*/
function hyphenate$2(string) {
return string.replace(_uppercasePattern, '-$1').toLowerCase();
}
var hyphenate_1 = hyphenate$2;
var hyphenate = hyphenate_1;
var msPattern = /^ms-/;
/**
* Hyphenates a camelcased CSS property name, for example:
*
* > hyphenateStyleName('backgroundColor')
* < "background-color"
* > hyphenateStyleName('MozTransition')
* < "-moz-transition"
* > hyphenateStyleName('msTransition')
* < "-ms-transition"
*
* As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
* is converted to `-ms-`.
*
* @param {string} string
* @return {string}
*/
function hyphenateStyleName(string) {
return hyphenate(string).replace(msPattern, '-ms-');
}
var hyphenateStyleName_1 = hyphenateStyleName;
//
var objToCss = function objToCss(obj, prevKey) {
var css = Object.keys(obj).filter(function (key) {
var chunk = obj[key];
return chunk !== undefined && chunk !== null && chunk !== false && chunk !== '';
}).map(function (key) {
if (__WEBPACK_IMPORTED_MODULE_0_is_plain_object___default()(obj[key])) return objToCss(obj[key], key);
return hyphenateStyleName_1(key) + ': ' + obj[key] + ';';
}).join(' ');
return prevKey ? prevKey + ' {\n ' + css + '\n}' : css;
};
var flatten = function flatten(chunks, executionContext) {
return chunks.reduce(function (ruleSet, chunk) {
/* Remove falsey values */
if (chunk === undefined || chunk === null || chunk === false || chunk === '') {
return ruleSet;
}
/* Flatten ruleSet */
if (Array.isArray(chunk)) {
return [].concat(ruleSet, flatten(chunk, executionContext));
}
/* Handle other components */
if (chunk.hasOwnProperty('styledComponentId')) {
// $FlowFixMe not sure how to make this pass
return [].concat(ruleSet, ['.' + chunk.styledComponentId]);
}
/* Either execute or defer the function */
if (typeof chunk === 'function') {
return executionContext ? ruleSet.concat.apply(ruleSet, flatten([chunk(executionContext)], executionContext)) : ruleSet.concat(chunk);
}
/* Handle objects */
return ruleSet.concat(
// $FlowFixMe have to add %checks somehow to isPlainObject
__WEBPACK_IMPORTED_MODULE_0_is_plain_object___default()(chunk) ? objToCss(chunk) : chunk.toString());
}, []);
};
//
var stylis = new __WEBPACK_IMPORTED_MODULE_1_stylis___default.a({
global: false,
cascade: true,
keyframe: false,
prefix: true,
compress: false,
semicolon: true
});
// 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 = __WEBPACK_IMPORTED_MODULE_2_stylis_rule_sheet___default()(function (rule) {
parsingRules.push(rule);
});
stylis.use([parseRulesPlugin, returnRulesPlugin]);
var stringifyRules = function stringifyRules(rules, selector, prefix) {
var flatCSS = rules.join('').replace(/^\s*\/\/.*$/gm, ''); // replace JS comments
var cssStr = selector && prefix ? prefix + ' ' + selector + ' { ' + flatCSS + ' }' : flatCSS;
return stylis(prefix || !selector ? '' : selector, cssStr);
};
//
function isStyledComponent(target) /* : %checks */{
return typeof target === 'function' && typeof target.styledComponentId === 'string';
}
//
/**
* When using streaming rendering, style blocks are emitted in chunks directly
* next to the HTML they reference. In order to prevent errors during rehydration
* (since React doesn't know about the style blocks we are interleaving) this
* method relocates all styled-component blocks to the end of `<head>`.
*
* NOTE: this method MUST be called before ReactDOM.hydrate().
*/
function consolidateStreamedStyles() {
var blocks = Array.from(document.querySelectorAll('style[data-styled-components]'));
if (blocks.length) {
var frag = document.createDocumentFragment();
for (var i = 0, len = blocks.length; i < len; i += 1) {
// $FlowFixMe
frag.appendChild(blocks[i].parentNode.removeChild(blocks[i]));
}
// $FlowFixMe
document.head.appendChild(frag);
}
}
//
var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
var charsLength = chars.length;
/* Some high number, usually 9-digit base-10. Map it to base-š */
var generateAlphabeticName = function generateAlphabeticName(code) {
var name = '';
var x = void 0;
for (x = code; x > charsLength; x = Math.floor(x / charsLength)) {
name = chars[x % charsLength] + name;
}
return chars[x % charsLength] + name;
};
//
var interleave = (function (strings, interpolations) {
return interpolations.reduce(function (array, interp, i) {
return array.concat(interp, strings[i + 1]);
}, [strings[0]]);
});
//
var css = (function (strings) {
for (var _len = arguments.length, interpolations = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
interpolations[_key - 1] = arguments[_key];
}
return flatten(interleave(strings, interpolations));
});
//
var SC_COMPONENT_ID = /^[^\S\n]*?\/\* sc-component-id:\s*(\S+)\s+\*\//gm;
var extractCompsFromCSS = (function (maybeCSS) {
var css = '' + (maybeCSS || ''); // Definitely a string, and a clone
var existingComponents = [];
css.replace(SC_COMPONENT_ID, function (match, componentId, matchIndex) {
existingComponents.push({ componentId: componentId, matchIndex: matchIndex });
return match;
});
return existingComponents.map(function (_ref, i) {
var componentId = _ref.componentId,
matchIndex = _ref.matchIndex;
var nextComp = existingComponents[i + 1];
var cssFromDOM = nextComp ? css.slice(matchIndex, nextComp.matchIndex) : css.slice(matchIndex);
return { componentId: componentId, cssFromDOM: cssFromDOM };
});
});
//
/* eslint-disable camelcase, no-undef */
var getNonce = (function () {
return true ? __webpack_require__.nc : null;
});
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
var createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var _extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
var inherits = function (subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
};
var objectWithoutProperties = function (obj, keys) {
var target = {};
for (var i in obj) {
if (keys.indexOf(i) >= 0) continue;
if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
target[i] = obj[i];
}
return target;
};
var possibleConstructorReturn = function (self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
};
//
/* eslint-disable no-underscore-dangle */
/*
* Browser Style Sheet with Rehydration
*
* <style data-styled-components="x y z"
* data-styled-components-is-local="true">
* /Ā· sc-component-id: a Ā·/
* .sc-a { ... }
* .x { ... }
* /Ā· sc-component-id: b Ā·/
* .sc-b { ... }
* .y { ... }
* .z { ... }
* </style>
*
* Note: replace Ā· with * in the above snippet.
* */
var DISABLE_SPEEDY = typeof false === 'boolean' && false || process.env.NODE_ENV !== 'production';
var COMPONENTS_PER_TAG = 40;
var SPEEDY_COMPONENTS_PER_TAG = 1000; // insertRule allows more injections before a perf slowdown
// Source: https://github.com/threepointone/glamor/blob/master/src/sheet.js#L32-L43
var sheetForTag = function sheetForTag(tag) {
if (tag.sheet) {
// $FlowFixMe
return tag.sheet;
}
for (var i = 0; i < document.styleSheets.length; i += 1) {
if (document.styleSheets[i].ownerNode === tag) {
// $FlowFixMe
return document.styleSheets[i];
}
}
// NOTE: This should never happen
throw new Error('');
};
// Safely (try/catch) injects rule at index and returns whether it was successful
var safeInsertRule = function safeInsertRule(sheet, cssRule, index) {
if (cssRule === undefined || cssRule.length === 0) {
return false;
}
var maxIndex = sheet.cssRules.length;
var cappedIndex = index <= maxIndex ? index : maxIndex;
try {
sheet.insertRule(cssRule, cappedIndex);
} catch (err) {
// NOTE: An invalid rule here means it's not supported by the browser or obviously malformed
return false;
}
return true;
};
// Counts up the number of rules inside the array until a specific component entry is found
// This is used to determine the necessary insertRule index
var sizeUpToComponentIndex = function sizeUpToComponentIndex(componentSizes, componentIndex) {
var cssRulesSize = 0;
for (var i = 0; i <= componentIndex; i += 1) {
cssRulesSize += componentSizes[i];
}
return cssRulesSize;
};
var BaseBrowserTag = function () {
function BaseBrowserTag() {
classCallCheck(this, BaseBrowserTag);
}
BaseBrowserTag.prototype.toReactElement = function toReactElement() {
throw new Error(process.env.NODE_ENV !== 'production' ? "BrowserTag doesn't implement toReactElement!" : '');
};
BaseBrowserTag.prototype.clone = function clone() {
throw new Error(process.env.NODE_ENV !== 'production' ? 'BrowserTag cannot be cloned!' : '');
};
BaseBrowserTag.prototype.getComponentIds = function getComponentIds() {
return Object.keys(this.components);
};
return BaseBrowserTag;
}();
var BrowserTag = void 0;
if (!DISABLE_SPEEDY) {
BrowserTag = function (_BaseBrowserTag) {
inherits(SpeedyBrowserTag, _BaseBrowserTag);
// Store component ruleSizes in an array per component (in order)
function SpeedyBrowserTag(el, isLocal, existingSource) {
classCallCheck(this, SpeedyBrowserTag);
var _this = possibleConstructorReturn(this, _BaseBrowserTag.call(this));
var nonce = getNonce();
if (nonce) {
el.setAttribute('nonce', nonce);
}
var extractedComps = extractCompsFromCSS(existingSource);
_this.el = el;
_this.isLocal = isLocal;
_this.ready = false;
_this.componentSizes = [];
_this.size = extractedComps.length;
_this.components = extractedComps.reduce(function (acc, obj) {
acc[obj.componentId] = obj; // eslint-disable-line no-param-reassign
return acc;
}, {});
return _this;
}
/* Because we care about source order, before we can inject anything we need to
* create a text node for each component and replace the existing CSS. */
SpeedyBrowserTag.prototype.replaceElement = function replaceElement() {
var _this2 = this;
// Build up our replacement style tag
var newEl = this.el.cloneNode(false);
if (!this.el.parentNode) {
throw new Error(process.env.NODE_ENV !== 'production' ? "Trying to replace an element that wasn't mounted!" : '');
}
// workaround for an IE/Edge bug: https://twitter.com/probablyup/status/958138927981977600
newEl.appendChild(document.createTextNode(''));
// $FlowFixMe
this.el.parentNode.replaceChild(newEl, this.el);
this.el = newEl;
this.ready = true;
// Retrieve the sheet for the new style tag
var sheet = sheetForTag(newEl);
Object.keys(this.components).forEach(function (componentId) {
var comp = _this2.components[componentId];
var cssFromDOM = comp.cssFromDOM;
var rules = stringifyRules([cssFromDOM]);
var rulesSize = rules.length;
var injectedRules = 0;
for (var j = 0; j < rulesSize; j += 1) {
if (safeInsertRule(sheet, rules[j], sheet.cssRules.length)) {
injectedRules += 1;
}
}
comp.componentIndex = _this2.componentSizes.length;
comp.css = rules.join(' ');
_this2.componentSizes.push(injectedRules);
});
};
SpeedyBrowserTag.prototype.isSealed = function isSealed() {
return this.size >= SPEEDY_COMPONENTS_PER_TAG;
};
SpeedyBrowserTag.prototype.addComponent = function addComponent(componentId) {
if (!this.ready) this.replaceElement();
if (process.env.NODE_ENV !== 'production' && this.components[componentId]) {
throw new Error('Trying to add Component \'' + componentId + '\' twice!');
}
this.components[componentId] = {
componentIndex: this.componentSizes.length,
css: ''
};
this.componentSizes.push(0);
this.size += 1;
};
SpeedyBrowserTag.prototype.inject = function inject(componentId, cssRules, name) {
if (!this.ready) this.replaceElement();
var comp = this.components[componentId];
if (process.env.NODE_ENV !== 'production' && !comp) {
throw new Error('Must add a new component before you can inject css into it');
}
var cssRulesSize = cssRules.length;
var sheet = sheetForTag(this.el);
var componentIndex = comp.componentIndex;
// Determine start index for injection
var insertIndex = sizeUpToComponentIndex(this.componentSizes, componentIndex);
// Inject each rule shifting index forward for each one (in-order injection)
var injectedRules = 0;
for (var i = 0; i < cssRulesSize; i += 1) {
var cssRule = cssRules[i];
if (safeInsertRule(sheet, cssRule, insertIndex + injectedRules)) {
comp.css += ' ' + cssRule;
injectedRules += 1;
}
}
// Update number of rules for component
this.componentSizes[componentIndex] += injectedRules;
if (name !== undefined && name !== null) {
var existingNames = this.el.getAttribute(SC_ATTR);
this.el.setAttribute(SC_ATTR, existingNames ? existingNames + ' ' + name : name);
}
};
SpeedyBrowserTag.prototype.toRawCSS = function toRawCSS() {
return ''; // NOTE: Unsupported in production mode (SpeedyBrowserTag)
};
SpeedyBrowserTag.prototype.toHTML = function toHTML() {
return ''; // NOTE: Unsupported in production mode (SpeedyBrowserTag)
};
return SpeedyBrowserTag;
}(BaseBrowserTag);
} else {
BrowserTag = function (_BaseBrowserTag2) {
inherits(TextNodeBrowserTag, _BaseBrowserTag2);
function TextNodeBrowserTag(el, isLocal) {
var existingSource = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
classCallCheck(this, TextNodeBrowserTag);
var _this3 = possibleConstructorReturn(this, _BaseBrowserTag2.call(this));
var nonce = getNonce();
if (nonce !== null) {
el.setAttribute('nonce', nonce);
}
var extractedComps = extractCompsFromCSS(existingSource);
_this3.el = el;
_this3.isLocal = isLocal;
_this3.ready = false;
_this3.size = extractedComps.length;
_this3.components = extractedComps.reduce(function (acc, obj) {
acc[obj.componentId] = obj; // eslint-disable-line no-param-reassign
return acc;
}, {});
return _this3;
}
TextNodeBrowserTag.prototype.isSealed = function isSealed() {
return this.size >= COMPONENTS_PER_TAG;
};
TextNodeBrowserTag.prototype.addComponent = function addComponent(componentId) {
if (!this.ready) this.replaceElement();
if (process.env.NODE_ENV !== 'production' && this.components[componentId]) {
throw new Error('Trying to add Component \'' + componentId + '\' twice!');
}
var comp = { componentId: componentId, textNode: document.createTextNode('') };
this.el.appendChild(comp.textNode);
this.size += 1;
this.components[componentId] = comp;
};
TextNodeBrowserTag.prototype.inject = function inject(componentId, css, name) {
if (!this.ready) this.replaceElement();
var comp = this.components[componentId];
if (process.env.NODE_ENV !== 'production' && !comp) {
throw new Error('Must add a new component before you can inject css into it');
}
if (comp.textNode.data === '') {
comp.textNode.appendData('\n/* sc-component-id: ' + componentId + ' */\n');
}
comp.textNode.appendData(css.join(' '));
if (name !== undefined && name !== null) {
var existingNames = this.el.getAttribute(SC_ATTR);
this.el.setAttribute(SC_ATTR, existingNames ? existingNames + ' ' + name : name);
}
};
TextNodeBrowserTag.prototype.toHTML = function toHTML() {
return this.el.outerHTML;
};
TextNodeBrowserTag.prototype.toReactElement = function toReactElement() {
throw new Error(process.env.NODE_ENV !== 'production' ? "BrowserTag doesn't implement toReactElement!" : '');
};
TextNodeBrowserTag.prototype.clone = function clone() {
throw new Error(process.env.NODE_ENV !== 'production' ? 'BrowserTag cannot be cloned!' : '');
};
/* Because we care about source order, before we can inject anything we need to
* create a text node for each component and replace the existing CSS. */
TextNodeBrowserTag.prototype.replaceElement = function replaceElement() {
var _this4 = this;
this.ready = true;
// We have nothing to inject. Use the current el.
if (this.size === 0) return;
// Build up our replacement style tag
var newEl = this.el.cloneNode(false);
newEl.appendChild(document.createTextNode('\n'));
Object.keys(this.components).forEach(function (key) {
var comp = _this4.components[key];
// eslint-disable-next-line no-param-reassign
comp.textNode = document.createTextNode(comp.cssFromDOM);
newEl.appendChild(comp.textNode);
});
if (!this.el.parentNode) {
throw new Error(process.env.NODE_ENV !== 'production' ? "Trying to replace an element that wasn't mounted!" : '');
}
// The ol' switcheroo
this.el.parentNode.replaceChild(newEl, this.el);
this.el = newEl;
};
return TextNodeBrowserTag;
}(BaseBrowserTag);
}
/* Factory function to separate DOM operations from logical ones*/
var BrowserStyleSheet = {
create: function create() {
var tags = [];
var names = {};
/* Construct existing state from DOM */
var nodes = document.querySelectorAll('[' + SC_ATTR + ']');
var nodesLength = nodes.length;
for (var i = 0; i < nodesLength; i += 1) {
// $FlowFixMe: We can trust that all elements in this query are style elements
var el = nodes[i];
var attr = el.getAttribute(SC_ATTR);
if (attr) {
attr.trim().split(/\s+/).forEach(function (name) {
names[name] = true;
});
}
tags.push(new BrowserTag(el, el.getAttribute(LOCAL_ATTR) === 'true', el.textContent));
}
/* Factory for making more tags */
var tagConstructor = function tagConstructor(isLocal) {
var el = document.createElement('style');
el.type = 'text/css';
el.setAttribute(SC_ATTR, '');
el.setAttribute(LOCAL_ATTR, isLocal ? 'true' : 'false');
if (!document.head) {
throw new Error(process.env.NODE_ENV !== 'production' ? 'Missing document <head>' : '');
}
document.head.appendChild(el);
return new BrowserTag(el, isLocal);
};
return new StyleSheet(tagConstructor, tags, names);
}
};
//
var SC_ATTR = 'data-styled-components';
var LOCAL_ATTR = 'data-styled-components-is-local';
var CONTEXT_KEY = '__styled-components-stylesheet__';
/* eslint-disable flowtype/object-type-delimiter */
/* eslint-enable flowtype/object-type-delimiter */
var instance = null;
// eslint-disable-next-line no-use-before-define
var clones = [];
var IS_BROWSER = typeof document !== 'undefined';
var StyleSheet = function () {
function StyleSheet(tagConstructor) {
var tags = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
var names = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
classCallCheck(this, StyleSheet);
this.hashes = {};
this.deferredInjections = {};
this.stylesCacheable = IS_BROWSER;
this.tagConstructor = tagConstructor;
this.tags = tags;
this.names = names;
this.constructComponentTagMap();
this.isStreaming = false;
}
// helper for `ComponentStyle` to know when it cache static styles.
// staticly styled-component can not safely cache styles on the server
// without all `ComponentStyle` instances saving a reference to the
// the styleSheet instance they last rendered with,
// or listening to creation / reset events. otherwise you might create
// a component with one stylesheet and render it another api response
// with another, losing styles on from your server-side render.
StyleSheet.prototype.constructComponentTagMap = function constructComponentTagMap() {
var _this = this;
this.componentTags = {};
this.tags.forEach(function (tag) {
tag.getComponentIds().forEach(function (componentId) {
_this.componentTags[componentId] = tag;
});
});
};
/* Best level of cachingāget the name from the hash straight away. */
StyleSheet.prototype.getName = function getName(hash) {
return this.hashes[hash.toString()];
};
/* Second level of cachingāif the name is already in the dom, don't
* inject anything and record the hash for getName next time. */
StyleSheet.prototype.alreadyInjected = function alreadyInjected(hash, name) {
if (!this.names[name]) return false;
this.hashes[hash.toString()] = name;
return true;
};
/* Third type of cachingādon't inject components' componentId twice. */
StyleSheet.prototype.hasInjectedComponent = function hasInjectedComponent(componentId) {
return !!this.componentTags[componentId];
};
StyleSheet.prototype.deferredInject = function deferredInject(componentId, isLocal, css) {
if (this === instance) {
clones.forEach(function (clone) {
clone.deferredInject(componentId, isLocal, css);
});
}
this.getOrCreateTag(componentId, isLocal);
this.deferredInjections[componentId] = css;
};
StyleSheet.prototype.inject = function inject(componentId, isLocal, css, hash, name) {
if (this === instance) {
clones.forEach(function (clone) {
clone.inject(componentId, isLocal, css);
});
}
var tag = this.getOrCreateTag(componentId, isLocal);
var deferredInjection = this.deferredInjections[componentId];
if (deferredInjection) {
tag.inject(componentId, deferredInjection);
delete this.deferredInjections[componentId];
}
tag.inject(componentId, css, name);
if (hash && name) {
this.hashes[hash.toString()] = name;
}
};
StyleSheet.prototype.toHTML = function toHTML() {
return this.tags.map(function (tag) {
return tag.toHTML();
}).join('');
};
StyleSheet.prototype.toReactElements = function toReactElements() {
return this.tags.map(function (tag, i) {
return tag.toReactElement('sc-' + i);
});
};
StyleSheet.prototype.getOrCreateTag = function getOrCreateTag(componentId, isLocal) {
var existingTag = this.componentTags[componentId];
/**
* in a streaming context, once a tag is sealed it can never be added to again
* or those styles will never make it to the client
*/
if (existingTag && this.isStreaming ? !existingTag.isSealed() : existingTag) {
return existingTag;
}
var lastTag = this.tags[this.tags.length - 1];
var componentTag = !lastTag || lastTag.isSealed() || lastTag.isLocal !== isLocal ? this.createNewTag(isLocal) : lastTag;
this.componentTags[componentId] = componentTag;
componentTag.addComponent(componentId);
return componentTag;
};
StyleSheet.prototype.createNewTag = function createNewTag(isLocal) {
var newTag = this.tagConstructor(isLocal);
this.tags.push(newTag);
return newTag;
};
StyleSheet.reset = function reset(isServer) {
instance = StyleSheet.create(isServer);
};
/* We can make isServer totally implicit once Jest 20 drops and we
* can change environment on a per-test basis. */
StyleSheet.create = function create() {
var isServer = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : !IS_BROWSER;
return (isServer ? ServerStyleSheet : BrowserStyleSheet).create();
};
StyleSheet.clone = function clone(oldSheet) {
var newSheet = new StyleSheet(oldSheet.tagConstructor, oldSheet.tags.map(function (tag) {
return tag.clone();
}), _extends({}, oldSheet.names));
newSheet.hashes = _extends({}, oldSheet.hashes);
newSheet.deferredInjections = _extends({}, oldSheet.deferredInjections);
clones.push(newSheet);
return newSheet;
};
createClass(StyleSheet, null, [{
key: 'instance',
get: function get$$1() {
return instance || (instance = StyleSheet.create());
}
}]);
return StyleSheet;
}();
var _StyleSheetManager$ch;
//
var StyleSheetManager = function (_Component) {
inherits(StyleSheetManager, _Component);
function StyleSheetManager() {
classCallCheck(this, StyleSheetManager);
return possibleConstructorReturn(this, _Component.apply(this, arguments));
}
StyleSheetManager.prototype.getChildContext = function getChildContext() {
var _ref;
return _ref = {}, _ref[CONTEXT_KEY] = this.props.sheet, _ref;
};
StyleSheetManager.prototype.render = function render() {
/* eslint-disable react/prop-types */
// Flow v0.43.1 will report an error accessing the `children` property,
// but v0.47.0 will not. It is necessary to use a type cast instead of
// a "fixme" comment to satisfy both Flow versions.
return __WEBPACK_IMPORTED_MODULE_3_react___default.a.Children.only(this.props.children);
};
return StyleSheetManager;
}(__WEBPACK_IMPORTED_MODULE_3_react__["Component"]);
StyleSheetManager.childContextTypes = (_StyleSheetManager$ch = {}, _StyleSheetManager$ch[CONTEXT_KEY] = __WEBPACK_IMPORTED_MODULE_4_prop_types___default.a.oneOfType([__WEBPACK_IMPORTED_MODULE_4_prop_types___default.a.instanceOf(StyleSheet), __WEBPACK_IMPORTED_MODULE_4_prop_types___default.a.instanceOf(ServerStyleSheet)]).isRequired, _StyleSheetManager$ch);
process.env.NODE_ENV !== "production" ? StyleSheetManager.propTypes = {
sheet: __WEBPACK_IMPORTED_MODULE_4_prop_types___default.a.oneOfType([__WEBPACK_IMPORTED_MODULE_4_prop_types___default.a.instanceOf(StyleSheet), __WEBPACK_IMPORTED_MODULE_4_prop_types___default.a.instanceOf(ServerStyleSheet)]).isRequired
} : void 0;
//
/* eslint-disable no-underscore-dangle */
var ServerTag = function () {
function ServerTag(isLocal) {
classCallCheck(this, ServerTag);
this.emitted = false;
this.isLocal = isLocal;
this.isProduction = process.env.NODE_ENV === 'production';
this.components = {};
this.size = 0;
this.names = [];
}
ServerTag.prototype.isSealed = function isSealed() {
return this.emitted;
};
ServerTag.prototype.getComponentIds = function getComponentIds() {
return Object.keys(this.components);
};
ServerTag.prototype.addComponent = function addComponent(componentId) {
if (this.components[componentId]) {
throw new Error(process.env.NODE_ENV !== 'production' ? 'Trying to add Component \'' + componentId + '\' twice!' : '');
}
this.components[componentId] = { componentId: componentId, css: '' };
this.size += 1;
};
ServerTag.prototype.concatenateCSS = function concatenateCSS() {
var _this = this;
return Object.keys(this.components).reduce(function (styles, k) {
return styles + _this.components[k].css;
}, '');
};
ServerTag.prototype.inject = function inject(componentId, css, name) {
var comp = this.components[componentId];
if (!comp) {
throw new Error(process.env.NODE_ENV !== 'production' ? 'Must add a new component before you can inject css into it' : '');
}
if (comp.css === '') {
comp.css = '/* sc-component-id: ' + componentId + ' */\n';
}
var cssRulesSize = css.length;
for (var i = 0; i < cssRulesSize; i += 1) {
var cssRule = css[i];
comp.css += (cssRule + '\n').replace(/\n*$/, '\n');
}
if (name) this.names.push(name);
};
ServerTag.prototype.toHTML = function toHTML() {
var attrs = ['type="text/css"', SC_ATTR + '="' + this.names.join(' ') + '"', LOCAL_ATTR + '="' + (this.isLocal ? 'true' : 'false') + '"'];
var nonce = getNonce();
if (nonce) {
attrs.push('nonce="' + nonce + '"');
}
this.emitted = true;
return '<style ' + attrs.join(' ') + '>' + this.concatenateCSS() + '</style>';
};
ServerTag.prototype.toReactElement = function toReactElement(key) {
var _attrs;
var attrs = (_attrs = {}, _attrs[SC_ATTR] = this.names.join(' '), _attrs[LOCAL_ATTR] = this.isLocal.toString(), _attrs);
var nonce = getNonce();
if (nonce) {
attrs.nonce = nonce;
}
this.emitted = true;
return __WEBPACK_IMPORTED_MODULE_3_react___default.a.createElement('style', _extends({
key: key,
type: 'text/css'
}, attrs, {
dangerouslySetInnerHTML: { __html: this.concatenateCSS() }
}));
};
ServerTag.prototype.clone = function clone() {
var _this2 = this;
var copy = new ServerTag(this.isLocal);
copy.names = [].concat(this.names);
copy.size = this.size;
copy.components = Object.keys(this.components).reduce(function (acc, key) {
acc[key] = _extends({}, _this2.components[key]); // eslint-disable-line no-param-reassign
return acc;
}, {});
return copy;
};
return ServerTag;
}();
var ServerStyleSheet = function () {
function ServerStyleSheet() {
classCallCheck(this, ServerStyleSheet);
this.instance = StyleSheet.clone(StyleSheet.instance);
this.instance.isStreaming = false;
}
ServerStyleSheet.prototype.collectStyles = function collectStyles(children) {
if (this.closed) {
throw new Error(process.env.NODE_ENV !== 'production' ? "Can't collect styles once you've called getStyleTags!" : '');
}
return __WEBPACK_IMPORTED_MODULE_3_react___default.a.createElement(
StyleSheetManager,
{ sheet: this.instance },
children
);
};
ServerStyleSheet.prototype.close = function close() {
clones.splice(clones.indexOf(this.instance), 1);
this.closed = true;
};
ServerStyleSheet.prototype.getStyleTags = function getStyleTags() {
if (!this.closed) {
this.close();
}
return this.instance.toHTML();
};
ServerStyleSheet.prototype.getStyleElement = function getStyleElement() {
if (!this.closed) {
this.close();
}
return this.instance.toReactElements();
};
ServerStyleSheet.prototype.interleaveWithNodeStream = function interleaveWithNodeStream(readableStream) {
{
throw new Error(process.env.NODE_ENV !== 'production' ? 'streaming only works in Node.js, please do not try to call this method in the browser' : '');
}
};
ServerStyleSheet.create = function create() {
return new StyleSheet(function (isLocal) {
return new ServerTag(isLocal);
});
};
return ServerStyleSheet;
}();
//
var LIMIT = 200;
var createWarnTooManyClasses = (function (displayName) {
var generatedClasses = {};
var warningSeen = false;
return function (className) {
if (!warningSeen) {
generatedClasses[className] = true;
if (Object.keys(generatedClasses).length >= LIMIT) {
// Unable to find latestRule in test environment.
/* eslint-disable no-console, prefer-template */
console.warn('Over ' + LIMIT + ' classes were generated for component ' + displayName + '. \n' + 'Consider using the attrs method, together with a style object for frequently changed styles.\n' + 'Example:\n' + ' const Component = styled.div.attrs({\n' + ' style: ({ background }) => ({\n' + ' background,\n' + ' }),\n' + ' })`width: 100%;`\n\n' + ' <Component />');
warningSeen = true;
generatedClasses = {};
}
}
};
});
//
/* eslint-disable max-len */
/**
* Trying to avoid the unknown-prop errors on styled components by filtering by
* React's attribute whitelist.
*
* To regenerate this regex:
*
* 1. `npm i -g regexgen` (https://github.com/devongovett/regexgen)
* 2. Run `regexgen` with the list of space-separated words below as input
* 3. Surround the emitted regex with this: `/^(GENERATED_REGEX)$/` -- this will ensure a full string match
* and no false positives from partials
**/
/*
children dangerouslySetInnerHTML key ref autoFocus defaultValue valueLink defaultChecked checkedLink innerHTML suppressContentEditableWarning onFocusIn onFocusOut className onCopy onCut onPaste onCompositionEnd onCompositionStart onCompositionUpdate onKeyDown onKeyPress onKeyUp onFocus onBlur onChange onInput onSubmit onReset onClick onContextMenu onDoubleClick onDrag onDragEnd onDragEnter onDragExit onDragLeave onDragOver onDragStart onDrop onMouseDown onMouseEnter onMouseLeave onMouseMove onMouseOut onMouseOver onMouseUp onSelect onTouchCancel onTouchEnd onTouchMove onTouchStart onScroll onWheel onAbort onCanPlay onCanPlayThrough onDurationChange onEmptied onEncrypted onEnded onError onLoadedData onLoadedMetadata onLoadStart onPause onPlay onPlaying onProgress onRateChange onSeeked onSeeking onStalled onSuspend onTimeUpdate onVolumeChange onWaiting onLoad onAnimationStart onAnimationEnd onAnimationIteration onTransitionEnd onCopyCapture onCutCapture onPasteCapture onCompositionEndCapture onCompositionStartCapture onCompositionUpdateCapture onKeyDownCapture onKeyPressCapture onKeyUpCapture onFocusCapture onBlurCapture onChangeCapture onInputCapture onSubmitCapture onResetCapture onClickCapture onContextMenuCapture onDoubleClickCapture onDragCapture onDragEndCapture onDragEnterCapture onDragExitCapture onDragLeaveCapture onDragOverCapture onDragStartCapture onDropCapture onMouseDownCapture onMouseEnterCapture onMouseLeaveCapture onMouseMoveCapture onMouseOutCapture onMouseOverCapture onMouseUpCapture onSelectCapture onTouchCancelCapture onTouchEndCapture onTouchMoveCapture onTouchStartCapture onScrollCapture onWheelCapture onAbortCapture onCanPlayCapture onCanPlayThroughCapture onDurationChangeCapture onEmptiedCapture onEncryptedCapture onEndedCapture onErrorCapture onLoadedDataCapture onLoadedMetadataCapture onLoadStartCapture onPauseCapture onPlayCapture onPlayingCapture onProgressCapture onRateChangeCapture onSeekedCapture onSeekingCapture onStalledCapture onSuspendCapture onTimeUpdateCapture onVolumeChangeCapture onWaitingCapture onLoadCapture onAnimationStartCapture onAnimationEndCapture onAnimationIterationCapture onTransitionEndCapture accept acce